xref: /linux/kernel/bpf/verifier.c (revision a3f143c461444c0b56360bbf468615fa814a8372)
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 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
198 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
199 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
200 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
201 static int ref_set_non_owning(struct bpf_verifier_env *env,
202 			      struct bpf_reg_state *reg);
203 static void specialize_kfunc(struct bpf_verifier_env *env,
204 			     u32 func_id, u16 offset, unsigned long *addr);
205 static bool is_trusted_reg(const struct bpf_reg_state *reg);
206 
207 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
208 {
209 	return aux->map_ptr_state.poison;
210 }
211 
212 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
213 {
214 	return aux->map_ptr_state.unpriv;
215 }
216 
217 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
218 			      struct bpf_map *map,
219 			      bool unpriv, bool poison)
220 {
221 	unpriv |= bpf_map_ptr_unpriv(aux);
222 	aux->map_ptr_state.unpriv = unpriv;
223 	aux->map_ptr_state.poison = poison;
224 	aux->map_ptr_state.map_ptr = map;
225 }
226 
227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
228 {
229 	return aux->map_key_state & BPF_MAP_KEY_POISON;
230 }
231 
232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
233 {
234 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
235 }
236 
237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
238 {
239 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
240 }
241 
242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
243 {
244 	bool poisoned = bpf_map_key_poisoned(aux);
245 
246 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
247 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
248 }
249 
250 static bool bpf_helper_call(const struct bpf_insn *insn)
251 {
252 	return insn->code == (BPF_JMP | BPF_CALL) &&
253 	       insn->src_reg == 0;
254 }
255 
256 static bool bpf_pseudo_call(const struct bpf_insn *insn)
257 {
258 	return insn->code == (BPF_JMP | BPF_CALL) &&
259 	       insn->src_reg == BPF_PSEUDO_CALL;
260 }
261 
262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
263 {
264 	return insn->code == (BPF_JMP | BPF_CALL) &&
265 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
266 }
267 
268 struct bpf_call_arg_meta {
269 	struct bpf_map *map_ptr;
270 	bool raw_mode;
271 	bool pkt_access;
272 	u8 release_regno;
273 	int regno;
274 	int access_size;
275 	int mem_size;
276 	u64 msize_max_value;
277 	int ref_obj_id;
278 	int dynptr_id;
279 	int map_uid;
280 	int func_id;
281 	struct btf *btf;
282 	u32 btf_id;
283 	struct btf *ret_btf;
284 	u32 ret_btf_id;
285 	u32 subprogno;
286 	struct btf_field *kptr_field;
287 };
288 
289 struct bpf_kfunc_call_arg_meta {
290 	/* In parameters */
291 	struct btf *btf;
292 	u32 func_id;
293 	u32 kfunc_flags;
294 	const struct btf_type *func_proto;
295 	const char *func_name;
296 	/* Out parameters */
297 	u32 ref_obj_id;
298 	u8 release_regno;
299 	bool r0_rdonly;
300 	u32 ret_btf_id;
301 	u64 r0_size;
302 	u32 subprogno;
303 	struct {
304 		u64 value;
305 		bool found;
306 	} arg_constant;
307 
308 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
309 	 * generally to pass info about user-defined local kptr types to later
310 	 * verification logic
311 	 *   bpf_obj_drop/bpf_percpu_obj_drop
312 	 *     Record the local kptr type to be drop'd
313 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
314 	 *     Record the local kptr type to be refcount_incr'd and use
315 	 *     arg_owning_ref to determine whether refcount_acquire should be
316 	 *     fallible
317 	 */
318 	struct btf *arg_btf;
319 	u32 arg_btf_id;
320 	bool arg_owning_ref;
321 
322 	struct {
323 		struct btf_field *field;
324 	} arg_list_head;
325 	struct {
326 		struct btf_field *field;
327 	} arg_rbtree_root;
328 	struct {
329 		enum bpf_dynptr_type type;
330 		u32 id;
331 		u32 ref_obj_id;
332 	} initialized_dynptr;
333 	struct {
334 		u8 spi;
335 		u8 frameno;
336 	} iter;
337 	struct {
338 		struct bpf_map *ptr;
339 		int uid;
340 	} map;
341 	u64 mem_size;
342 };
343 
344 struct btf *btf_vmlinux;
345 
346 static const char *btf_type_name(const struct btf *btf, u32 id)
347 {
348 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
349 }
350 
351 static DEFINE_MUTEX(bpf_verifier_lock);
352 static DEFINE_MUTEX(bpf_percpu_ma_lock);
353 
354 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
355 {
356 	struct bpf_verifier_env *env = private_data;
357 	va_list args;
358 
359 	if (!bpf_verifier_log_needed(&env->log))
360 		return;
361 
362 	va_start(args, fmt);
363 	bpf_verifier_vlog(&env->log, fmt, args);
364 	va_end(args);
365 }
366 
367 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
368 				   struct bpf_reg_state *reg,
369 				   struct bpf_retval_range range, const char *ctx,
370 				   const char *reg_name)
371 {
372 	bool unknown = true;
373 
374 	verbose(env, "%s the register %s has", ctx, reg_name);
375 	if (reg->smin_value > S64_MIN) {
376 		verbose(env, " smin=%lld", reg->smin_value);
377 		unknown = false;
378 	}
379 	if (reg->smax_value < S64_MAX) {
380 		verbose(env, " smax=%lld", reg->smax_value);
381 		unknown = false;
382 	}
383 	if (unknown)
384 		verbose(env, " unknown scalar value");
385 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
386 }
387 
388 static bool reg_not_null(const struct bpf_reg_state *reg)
389 {
390 	enum bpf_reg_type type;
391 
392 	type = reg->type;
393 	if (type_may_be_null(type))
394 		return false;
395 
396 	type = base_type(type);
397 	return type == PTR_TO_SOCKET ||
398 		type == PTR_TO_TCP_SOCK ||
399 		type == PTR_TO_MAP_VALUE ||
400 		type == PTR_TO_MAP_KEY ||
401 		type == PTR_TO_SOCK_COMMON ||
402 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
403 		type == PTR_TO_MEM;
404 }
405 
406 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
407 {
408 	struct btf_record *rec = NULL;
409 	struct btf_struct_meta *meta;
410 
411 	if (reg->type == PTR_TO_MAP_VALUE) {
412 		rec = reg->map_ptr->record;
413 	} else if (type_is_ptr_alloc_obj(reg->type)) {
414 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
415 		if (meta)
416 			rec = meta->record;
417 	}
418 	return rec;
419 }
420 
421 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
422 {
423 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
424 
425 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
426 }
427 
428 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
429 {
430 	struct bpf_func_info *info;
431 
432 	if (!env->prog->aux->func_info)
433 		return "";
434 
435 	info = &env->prog->aux->func_info[subprog];
436 	return btf_type_name(env->prog->aux->btf, info->type_id);
437 }
438 
439 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
440 {
441 	struct bpf_subprog_info *info = subprog_info(env, subprog);
442 
443 	info->is_cb = true;
444 	info->is_async_cb = true;
445 	info->is_exception_cb = true;
446 }
447 
448 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
449 {
450 	return subprog_info(env, subprog)->is_exception_cb;
451 }
452 
453 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
454 {
455 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
456 }
457 
458 static bool type_is_rdonly_mem(u32 type)
459 {
460 	return type & MEM_RDONLY;
461 }
462 
463 static bool is_acquire_function(enum bpf_func_id func_id,
464 				const struct bpf_map *map)
465 {
466 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
467 
468 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
469 	    func_id == BPF_FUNC_sk_lookup_udp ||
470 	    func_id == BPF_FUNC_skc_lookup_tcp ||
471 	    func_id == BPF_FUNC_ringbuf_reserve ||
472 	    func_id == BPF_FUNC_kptr_xchg)
473 		return true;
474 
475 	if (func_id == BPF_FUNC_map_lookup_elem &&
476 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
477 	     map_type == BPF_MAP_TYPE_SOCKHASH))
478 		return true;
479 
480 	return false;
481 }
482 
483 static bool is_ptr_cast_function(enum bpf_func_id func_id)
484 {
485 	return func_id == BPF_FUNC_tcp_sock ||
486 		func_id == BPF_FUNC_sk_fullsock ||
487 		func_id == BPF_FUNC_skc_to_tcp_sock ||
488 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
489 		func_id == BPF_FUNC_skc_to_udp6_sock ||
490 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
491 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
492 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
493 }
494 
495 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_dynptr_data;
498 }
499 
500 static bool is_sync_callback_calling_kfunc(u32 btf_id);
501 static bool is_async_callback_calling_kfunc(u32 btf_id);
502 static bool is_callback_calling_kfunc(u32 btf_id);
503 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
504 
505 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
506 
507 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_for_each_map_elem ||
510 	       func_id == BPF_FUNC_find_vma ||
511 	       func_id == BPF_FUNC_loop ||
512 	       func_id == BPF_FUNC_user_ringbuf_drain;
513 }
514 
515 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
516 {
517 	return func_id == BPF_FUNC_timer_set_callback;
518 }
519 
520 static bool is_callback_calling_function(enum bpf_func_id func_id)
521 {
522 	return is_sync_callback_calling_function(func_id) ||
523 	       is_async_callback_calling_function(func_id);
524 }
525 
526 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
527 {
528 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
529 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
530 }
531 
532 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
533 {
534 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
535 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
536 }
537 
538 static bool is_may_goto_insn(struct bpf_insn *insn)
539 {
540 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
541 }
542 
543 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
544 {
545 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
546 }
547 
548 static bool is_storage_get_function(enum bpf_func_id func_id)
549 {
550 	return func_id == BPF_FUNC_sk_storage_get ||
551 	       func_id == BPF_FUNC_inode_storage_get ||
552 	       func_id == BPF_FUNC_task_storage_get ||
553 	       func_id == BPF_FUNC_cgrp_storage_get;
554 }
555 
556 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
557 					const struct bpf_map *map)
558 {
559 	int ref_obj_uses = 0;
560 
561 	if (is_ptr_cast_function(func_id))
562 		ref_obj_uses++;
563 	if (is_acquire_function(func_id, map))
564 		ref_obj_uses++;
565 	if (is_dynptr_ref_function(func_id))
566 		ref_obj_uses++;
567 
568 	return ref_obj_uses > 1;
569 }
570 
571 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
572 {
573 	return BPF_CLASS(insn->code) == BPF_STX &&
574 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
575 	       insn->imm == BPF_CMPXCHG;
576 }
577 
578 static int __get_spi(s32 off)
579 {
580 	return (-off - 1) / BPF_REG_SIZE;
581 }
582 
583 static struct bpf_func_state *func(struct bpf_verifier_env *env,
584 				   const struct bpf_reg_state *reg)
585 {
586 	struct bpf_verifier_state *cur = env->cur_state;
587 
588 	return cur->frame[reg->frameno];
589 }
590 
591 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
592 {
593        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
594 
595        /* We need to check that slots between [spi - nr_slots + 1, spi] are
596 	* within [0, allocated_stack).
597 	*
598 	* Please note that the spi grows downwards. For example, a dynptr
599 	* takes the size of two stack slots; the first slot will be at
600 	* spi and the second slot will be at spi - 1.
601 	*/
602        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
603 }
604 
605 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
606 			          const char *obj_kind, int nr_slots)
607 {
608 	int off, spi;
609 
610 	if (!tnum_is_const(reg->var_off)) {
611 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
612 		return -EINVAL;
613 	}
614 
615 	off = reg->off + reg->var_off.value;
616 	if (off % BPF_REG_SIZE) {
617 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
618 		return -EINVAL;
619 	}
620 
621 	spi = __get_spi(off);
622 	if (spi + 1 < nr_slots) {
623 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
624 		return -EINVAL;
625 	}
626 
627 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
628 		return -ERANGE;
629 	return spi;
630 }
631 
632 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
633 {
634 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
635 }
636 
637 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
638 {
639 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
640 }
641 
642 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
643 {
644 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
645 	case DYNPTR_TYPE_LOCAL:
646 		return BPF_DYNPTR_TYPE_LOCAL;
647 	case DYNPTR_TYPE_RINGBUF:
648 		return BPF_DYNPTR_TYPE_RINGBUF;
649 	case DYNPTR_TYPE_SKB:
650 		return BPF_DYNPTR_TYPE_SKB;
651 	case DYNPTR_TYPE_XDP:
652 		return BPF_DYNPTR_TYPE_XDP;
653 	default:
654 		return BPF_DYNPTR_TYPE_INVALID;
655 	}
656 }
657 
658 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
659 {
660 	switch (type) {
661 	case BPF_DYNPTR_TYPE_LOCAL:
662 		return DYNPTR_TYPE_LOCAL;
663 	case BPF_DYNPTR_TYPE_RINGBUF:
664 		return DYNPTR_TYPE_RINGBUF;
665 	case BPF_DYNPTR_TYPE_SKB:
666 		return DYNPTR_TYPE_SKB;
667 	case BPF_DYNPTR_TYPE_XDP:
668 		return DYNPTR_TYPE_XDP;
669 	default:
670 		return 0;
671 	}
672 }
673 
674 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
675 {
676 	return type == BPF_DYNPTR_TYPE_RINGBUF;
677 }
678 
679 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
680 			      enum bpf_dynptr_type type,
681 			      bool first_slot, int dynptr_id);
682 
683 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
684 				struct bpf_reg_state *reg);
685 
686 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
687 				   struct bpf_reg_state *sreg1,
688 				   struct bpf_reg_state *sreg2,
689 				   enum bpf_dynptr_type type)
690 {
691 	int id = ++env->id_gen;
692 
693 	__mark_dynptr_reg(sreg1, type, true, id);
694 	__mark_dynptr_reg(sreg2, type, false, id);
695 }
696 
697 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
698 			       struct bpf_reg_state *reg,
699 			       enum bpf_dynptr_type type)
700 {
701 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
702 }
703 
704 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
705 				        struct bpf_func_state *state, int spi);
706 
707 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
708 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
709 {
710 	struct bpf_func_state *state = func(env, reg);
711 	enum bpf_dynptr_type type;
712 	int spi, i, err;
713 
714 	spi = dynptr_get_spi(env, reg);
715 	if (spi < 0)
716 		return spi;
717 
718 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
719 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
720 	 * to ensure that for the following example:
721 	 *	[d1][d1][d2][d2]
722 	 * spi    3   2   1   0
723 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
724 	 * case they do belong to same dynptr, second call won't see slot_type
725 	 * as STACK_DYNPTR and will simply skip destruction.
726 	 */
727 	err = destroy_if_dynptr_stack_slot(env, state, spi);
728 	if (err)
729 		return err;
730 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
731 	if (err)
732 		return err;
733 
734 	for (i = 0; i < BPF_REG_SIZE; i++) {
735 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
736 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
737 	}
738 
739 	type = arg_to_dynptr_type(arg_type);
740 	if (type == BPF_DYNPTR_TYPE_INVALID)
741 		return -EINVAL;
742 
743 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
744 			       &state->stack[spi - 1].spilled_ptr, type);
745 
746 	if (dynptr_type_refcounted(type)) {
747 		/* The id is used to track proper releasing */
748 		int id;
749 
750 		if (clone_ref_obj_id)
751 			id = clone_ref_obj_id;
752 		else
753 			id = acquire_reference_state(env, insn_idx);
754 
755 		if (id < 0)
756 			return id;
757 
758 		state->stack[spi].spilled_ptr.ref_obj_id = id;
759 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
760 	}
761 
762 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
763 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
764 
765 	return 0;
766 }
767 
768 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
769 {
770 	int i;
771 
772 	for (i = 0; i < BPF_REG_SIZE; i++) {
773 		state->stack[spi].slot_type[i] = STACK_INVALID;
774 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
775 	}
776 
777 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
778 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
779 
780 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
781 	 *
782 	 * While we don't allow reading STACK_INVALID, it is still possible to
783 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
784 	 * helpers or insns can do partial read of that part without failing,
785 	 * but check_stack_range_initialized, check_stack_read_var_off, and
786 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
787 	 * the slot conservatively. Hence we need to prevent those liveness
788 	 * marking walks.
789 	 *
790 	 * This was not a problem before because STACK_INVALID is only set by
791 	 * default (where the default reg state has its reg->parent as NULL), or
792 	 * in clean_live_states after REG_LIVE_DONE (at which point
793 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
794 	 * verifier state exploration (like we did above). Hence, for our case
795 	 * parentage chain will still be live (i.e. reg->parent may be
796 	 * non-NULL), while earlier reg->parent was NULL, so we need
797 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
798 	 * done later on reads or by mark_dynptr_read as well to unnecessary
799 	 * mark registers in verifier state.
800 	 */
801 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
802 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
803 }
804 
805 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
806 {
807 	struct bpf_func_state *state = func(env, reg);
808 	int spi, ref_obj_id, i;
809 
810 	spi = dynptr_get_spi(env, reg);
811 	if (spi < 0)
812 		return spi;
813 
814 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
815 		invalidate_dynptr(env, state, spi);
816 		return 0;
817 	}
818 
819 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
820 
821 	/* If the dynptr has a ref_obj_id, then we need to invalidate
822 	 * two things:
823 	 *
824 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
825 	 * 2) Any slices derived from this dynptr.
826 	 */
827 
828 	/* Invalidate any slices associated with this dynptr */
829 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
830 
831 	/* Invalidate any dynptr clones */
832 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
833 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
834 			continue;
835 
836 		/* it should always be the case that if the ref obj id
837 		 * matches then the stack slot also belongs to a
838 		 * dynptr
839 		 */
840 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
841 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
842 			return -EFAULT;
843 		}
844 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
845 			invalidate_dynptr(env, state, i);
846 	}
847 
848 	return 0;
849 }
850 
851 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
852 			       struct bpf_reg_state *reg);
853 
854 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
855 {
856 	if (!env->allow_ptr_leaks)
857 		__mark_reg_not_init(env, reg);
858 	else
859 		__mark_reg_unknown(env, reg);
860 }
861 
862 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
863 				        struct bpf_func_state *state, int spi)
864 {
865 	struct bpf_func_state *fstate;
866 	struct bpf_reg_state *dreg;
867 	int i, dynptr_id;
868 
869 	/* We always ensure that STACK_DYNPTR is never set partially,
870 	 * hence just checking for slot_type[0] is enough. This is
871 	 * different for STACK_SPILL, where it may be only set for
872 	 * 1 byte, so code has to use is_spilled_reg.
873 	 */
874 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
875 		return 0;
876 
877 	/* Reposition spi to first slot */
878 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
879 		spi = spi + 1;
880 
881 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
882 		verbose(env, "cannot overwrite referenced dynptr\n");
883 		return -EINVAL;
884 	}
885 
886 	mark_stack_slot_scratched(env, spi);
887 	mark_stack_slot_scratched(env, spi - 1);
888 
889 	/* Writing partially to one dynptr stack slot destroys both. */
890 	for (i = 0; i < BPF_REG_SIZE; i++) {
891 		state->stack[spi].slot_type[i] = STACK_INVALID;
892 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
893 	}
894 
895 	dynptr_id = state->stack[spi].spilled_ptr.id;
896 	/* Invalidate any slices associated with this dynptr */
897 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
898 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
899 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
900 			continue;
901 		if (dreg->dynptr_id == dynptr_id)
902 			mark_reg_invalid(env, dreg);
903 	}));
904 
905 	/* Do not release reference state, we are destroying dynptr on stack,
906 	 * not using some helper to release it. Just reset register.
907 	 */
908 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
909 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
910 
911 	/* Same reason as unmark_stack_slots_dynptr above */
912 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
913 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
914 
915 	return 0;
916 }
917 
918 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
919 {
920 	int spi;
921 
922 	if (reg->type == CONST_PTR_TO_DYNPTR)
923 		return false;
924 
925 	spi = dynptr_get_spi(env, reg);
926 
927 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
928 	 * error because this just means the stack state hasn't been updated yet.
929 	 * We will do check_mem_access to check and update stack bounds later.
930 	 */
931 	if (spi < 0 && spi != -ERANGE)
932 		return false;
933 
934 	/* We don't need to check if the stack slots are marked by previous
935 	 * dynptr initializations because we allow overwriting existing unreferenced
936 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
937 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
938 	 * touching are completely destructed before we reinitialize them for a new
939 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
940 	 * instead of delaying it until the end where the user will get "Unreleased
941 	 * reference" error.
942 	 */
943 	return true;
944 }
945 
946 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
947 {
948 	struct bpf_func_state *state = func(env, reg);
949 	int i, spi;
950 
951 	/* This already represents first slot of initialized bpf_dynptr.
952 	 *
953 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
954 	 * check_func_arg_reg_off's logic, so we don't need to check its
955 	 * offset and alignment.
956 	 */
957 	if (reg->type == CONST_PTR_TO_DYNPTR)
958 		return true;
959 
960 	spi = dynptr_get_spi(env, reg);
961 	if (spi < 0)
962 		return false;
963 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
964 		return false;
965 
966 	for (i = 0; i < BPF_REG_SIZE; i++) {
967 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
968 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
969 			return false;
970 	}
971 
972 	return true;
973 }
974 
975 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
976 				    enum bpf_arg_type arg_type)
977 {
978 	struct bpf_func_state *state = func(env, reg);
979 	enum bpf_dynptr_type dynptr_type;
980 	int spi;
981 
982 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
983 	if (arg_type == ARG_PTR_TO_DYNPTR)
984 		return true;
985 
986 	dynptr_type = arg_to_dynptr_type(arg_type);
987 	if (reg->type == CONST_PTR_TO_DYNPTR) {
988 		return reg->dynptr.type == dynptr_type;
989 	} else {
990 		spi = dynptr_get_spi(env, reg);
991 		if (spi < 0)
992 			return false;
993 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
994 	}
995 }
996 
997 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
998 
999 static bool in_rcu_cs(struct bpf_verifier_env *env);
1000 
1001 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1002 
1003 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1004 				 struct bpf_kfunc_call_arg_meta *meta,
1005 				 struct bpf_reg_state *reg, int insn_idx,
1006 				 struct btf *btf, u32 btf_id, int nr_slots)
1007 {
1008 	struct bpf_func_state *state = func(env, reg);
1009 	int spi, i, j, id;
1010 
1011 	spi = iter_get_spi(env, reg, nr_slots);
1012 	if (spi < 0)
1013 		return spi;
1014 
1015 	id = acquire_reference_state(env, insn_idx);
1016 	if (id < 0)
1017 		return id;
1018 
1019 	for (i = 0; i < nr_slots; i++) {
1020 		struct bpf_stack_state *slot = &state->stack[spi - i];
1021 		struct bpf_reg_state *st = &slot->spilled_ptr;
1022 
1023 		__mark_reg_known_zero(st);
1024 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1025 		if (is_kfunc_rcu_protected(meta)) {
1026 			if (in_rcu_cs(env))
1027 				st->type |= MEM_RCU;
1028 			else
1029 				st->type |= PTR_UNTRUSTED;
1030 		}
1031 		st->live |= REG_LIVE_WRITTEN;
1032 		st->ref_obj_id = i == 0 ? id : 0;
1033 		st->iter.btf = btf;
1034 		st->iter.btf_id = btf_id;
1035 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1036 		st->iter.depth = 0;
1037 
1038 		for (j = 0; j < BPF_REG_SIZE; j++)
1039 			slot->slot_type[j] = STACK_ITER;
1040 
1041 		mark_stack_slot_scratched(env, spi - i);
1042 	}
1043 
1044 	return 0;
1045 }
1046 
1047 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1048 				   struct bpf_reg_state *reg, int nr_slots)
1049 {
1050 	struct bpf_func_state *state = func(env, reg);
1051 	int spi, i, j;
1052 
1053 	spi = iter_get_spi(env, reg, nr_slots);
1054 	if (spi < 0)
1055 		return spi;
1056 
1057 	for (i = 0; i < nr_slots; i++) {
1058 		struct bpf_stack_state *slot = &state->stack[spi - i];
1059 		struct bpf_reg_state *st = &slot->spilled_ptr;
1060 
1061 		if (i == 0)
1062 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1063 
1064 		__mark_reg_not_init(env, st);
1065 
1066 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1067 		st->live |= REG_LIVE_WRITTEN;
1068 
1069 		for (j = 0; j < BPF_REG_SIZE; j++)
1070 			slot->slot_type[j] = STACK_INVALID;
1071 
1072 		mark_stack_slot_scratched(env, spi - i);
1073 	}
1074 
1075 	return 0;
1076 }
1077 
1078 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1079 				     struct bpf_reg_state *reg, int nr_slots)
1080 {
1081 	struct bpf_func_state *state = func(env, reg);
1082 	int spi, i, j;
1083 
1084 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1085 	 * will do check_mem_access to check and update stack bounds later, so
1086 	 * return true for that case.
1087 	 */
1088 	spi = iter_get_spi(env, reg, nr_slots);
1089 	if (spi == -ERANGE)
1090 		return true;
1091 	if (spi < 0)
1092 		return false;
1093 
1094 	for (i = 0; i < nr_slots; i++) {
1095 		struct bpf_stack_state *slot = &state->stack[spi - i];
1096 
1097 		for (j = 0; j < BPF_REG_SIZE; j++)
1098 			if (slot->slot_type[j] == STACK_ITER)
1099 				return false;
1100 	}
1101 
1102 	return true;
1103 }
1104 
1105 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1106 				   struct btf *btf, u32 btf_id, int nr_slots)
1107 {
1108 	struct bpf_func_state *state = func(env, reg);
1109 	int spi, i, j;
1110 
1111 	spi = iter_get_spi(env, reg, nr_slots);
1112 	if (spi < 0)
1113 		return -EINVAL;
1114 
1115 	for (i = 0; i < nr_slots; i++) {
1116 		struct bpf_stack_state *slot = &state->stack[spi - i];
1117 		struct bpf_reg_state *st = &slot->spilled_ptr;
1118 
1119 		if (st->type & PTR_UNTRUSTED)
1120 			return -EPROTO;
1121 		/* only main (first) slot has ref_obj_id set */
1122 		if (i == 0 && !st->ref_obj_id)
1123 			return -EINVAL;
1124 		if (i != 0 && st->ref_obj_id)
1125 			return -EINVAL;
1126 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1127 			return -EINVAL;
1128 
1129 		for (j = 0; j < BPF_REG_SIZE; j++)
1130 			if (slot->slot_type[j] != STACK_ITER)
1131 				return -EINVAL;
1132 	}
1133 
1134 	return 0;
1135 }
1136 
1137 /* Check if given stack slot is "special":
1138  *   - spilled register state (STACK_SPILL);
1139  *   - dynptr state (STACK_DYNPTR);
1140  *   - iter state (STACK_ITER).
1141  */
1142 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1143 {
1144 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1145 
1146 	switch (type) {
1147 	case STACK_SPILL:
1148 	case STACK_DYNPTR:
1149 	case STACK_ITER:
1150 		return true;
1151 	case STACK_INVALID:
1152 	case STACK_MISC:
1153 	case STACK_ZERO:
1154 		return false;
1155 	default:
1156 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1157 		return true;
1158 	}
1159 }
1160 
1161 /* The reg state of a pointer or a bounded scalar was saved when
1162  * it was spilled to the stack.
1163  */
1164 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1165 {
1166 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1167 }
1168 
1169 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1170 {
1171 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1172 	       stack->spilled_ptr.type == SCALAR_VALUE;
1173 }
1174 
1175 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1176 {
1177 	return stack->slot_type[0] == STACK_SPILL &&
1178 	       stack->spilled_ptr.type == SCALAR_VALUE;
1179 }
1180 
1181 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1182  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1183  * more precise STACK_ZERO.
1184  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1185  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1186  */
1187 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1188 {
1189 	if (*stype == STACK_ZERO)
1190 		return;
1191 	if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1192 		return;
1193 	*stype = STACK_MISC;
1194 }
1195 
1196 static void scrub_spilled_slot(u8 *stype)
1197 {
1198 	if (*stype != STACK_INVALID)
1199 		*stype = STACK_MISC;
1200 }
1201 
1202 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1203  * small to hold src. This is different from krealloc since we don't want to preserve
1204  * the contents of dst.
1205  *
1206  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1207  * not be allocated.
1208  */
1209 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1210 {
1211 	size_t alloc_bytes;
1212 	void *orig = dst;
1213 	size_t bytes;
1214 
1215 	if (ZERO_OR_NULL_PTR(src))
1216 		goto out;
1217 
1218 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1219 		return NULL;
1220 
1221 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1222 	dst = krealloc(orig, alloc_bytes, flags);
1223 	if (!dst) {
1224 		kfree(orig);
1225 		return NULL;
1226 	}
1227 
1228 	memcpy(dst, src, bytes);
1229 out:
1230 	return dst ? dst : ZERO_SIZE_PTR;
1231 }
1232 
1233 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1234  * small to hold new_n items. new items are zeroed out if the array grows.
1235  *
1236  * Contrary to krealloc_array, does not free arr if new_n is zero.
1237  */
1238 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1239 {
1240 	size_t alloc_size;
1241 	void *new_arr;
1242 
1243 	if (!new_n || old_n == new_n)
1244 		goto out;
1245 
1246 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1247 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1248 	if (!new_arr) {
1249 		kfree(arr);
1250 		return NULL;
1251 	}
1252 	arr = new_arr;
1253 
1254 	if (new_n > old_n)
1255 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1256 
1257 out:
1258 	return arr ? arr : ZERO_SIZE_PTR;
1259 }
1260 
1261 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1262 {
1263 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1264 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1265 	if (!dst->refs)
1266 		return -ENOMEM;
1267 
1268 	dst->acquired_refs = src->acquired_refs;
1269 	return 0;
1270 }
1271 
1272 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1273 {
1274 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1275 
1276 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1277 				GFP_KERNEL);
1278 	if (!dst->stack)
1279 		return -ENOMEM;
1280 
1281 	dst->allocated_stack = src->allocated_stack;
1282 	return 0;
1283 }
1284 
1285 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1286 {
1287 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1288 				    sizeof(struct bpf_reference_state));
1289 	if (!state->refs)
1290 		return -ENOMEM;
1291 
1292 	state->acquired_refs = n;
1293 	return 0;
1294 }
1295 
1296 /* Possibly update state->allocated_stack to be at least size bytes. Also
1297  * possibly update the function's high-water mark in its bpf_subprog_info.
1298  */
1299 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1300 {
1301 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1302 
1303 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1304 	size = round_up(size, BPF_REG_SIZE);
1305 	n = size / BPF_REG_SIZE;
1306 
1307 	if (old_n >= n)
1308 		return 0;
1309 
1310 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1311 	if (!state->stack)
1312 		return -ENOMEM;
1313 
1314 	state->allocated_stack = size;
1315 
1316 	/* update known max for given subprogram */
1317 	if (env->subprog_info[state->subprogno].stack_depth < size)
1318 		env->subprog_info[state->subprogno].stack_depth = size;
1319 
1320 	return 0;
1321 }
1322 
1323 /* Acquire a pointer id from the env and update the state->refs to include
1324  * this new pointer reference.
1325  * On success, returns a valid pointer id to associate with the register
1326  * On failure, returns a negative errno.
1327  */
1328 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1329 {
1330 	struct bpf_func_state *state = cur_func(env);
1331 	int new_ofs = state->acquired_refs;
1332 	int id, err;
1333 
1334 	err = resize_reference_state(state, state->acquired_refs + 1);
1335 	if (err)
1336 		return err;
1337 	id = ++env->id_gen;
1338 	state->refs[new_ofs].id = id;
1339 	state->refs[new_ofs].insn_idx = insn_idx;
1340 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1341 
1342 	return id;
1343 }
1344 
1345 /* release function corresponding to acquire_reference_state(). Idempotent. */
1346 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1347 {
1348 	int i, last_idx;
1349 
1350 	last_idx = state->acquired_refs - 1;
1351 	for (i = 0; i < state->acquired_refs; i++) {
1352 		if (state->refs[i].id == ptr_id) {
1353 			/* Cannot release caller references in callbacks */
1354 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1355 				return -EINVAL;
1356 			if (last_idx && i != last_idx)
1357 				memcpy(&state->refs[i], &state->refs[last_idx],
1358 				       sizeof(*state->refs));
1359 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1360 			state->acquired_refs--;
1361 			return 0;
1362 		}
1363 	}
1364 	return -EINVAL;
1365 }
1366 
1367 static void free_func_state(struct bpf_func_state *state)
1368 {
1369 	if (!state)
1370 		return;
1371 	kfree(state->refs);
1372 	kfree(state->stack);
1373 	kfree(state);
1374 }
1375 
1376 static void clear_jmp_history(struct bpf_verifier_state *state)
1377 {
1378 	kfree(state->jmp_history);
1379 	state->jmp_history = NULL;
1380 	state->jmp_history_cnt = 0;
1381 }
1382 
1383 static void free_verifier_state(struct bpf_verifier_state *state,
1384 				bool free_self)
1385 {
1386 	int i;
1387 
1388 	for (i = 0; i <= state->curframe; i++) {
1389 		free_func_state(state->frame[i]);
1390 		state->frame[i] = NULL;
1391 	}
1392 	clear_jmp_history(state);
1393 	if (free_self)
1394 		kfree(state);
1395 }
1396 
1397 /* copy verifier state from src to dst growing dst stack space
1398  * when necessary to accommodate larger src stack
1399  */
1400 static int copy_func_state(struct bpf_func_state *dst,
1401 			   const struct bpf_func_state *src)
1402 {
1403 	int err;
1404 
1405 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1406 	err = copy_reference_state(dst, src);
1407 	if (err)
1408 		return err;
1409 	return copy_stack_state(dst, src);
1410 }
1411 
1412 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1413 			       const struct bpf_verifier_state *src)
1414 {
1415 	struct bpf_func_state *dst;
1416 	int i, err;
1417 
1418 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1419 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1420 					  GFP_USER);
1421 	if (!dst_state->jmp_history)
1422 		return -ENOMEM;
1423 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1424 
1425 	/* if dst has more stack frames then src frame, free them, this is also
1426 	 * necessary in case of exceptional exits using bpf_throw.
1427 	 */
1428 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1429 		free_func_state(dst_state->frame[i]);
1430 		dst_state->frame[i] = NULL;
1431 	}
1432 	dst_state->speculative = src->speculative;
1433 	dst_state->active_rcu_lock = src->active_rcu_lock;
1434 	dst_state->active_preempt_lock = src->active_preempt_lock;
1435 	dst_state->in_sleepable = src->in_sleepable;
1436 	dst_state->curframe = src->curframe;
1437 	dst_state->active_lock.ptr = src->active_lock.ptr;
1438 	dst_state->active_lock.id = src->active_lock.id;
1439 	dst_state->branches = src->branches;
1440 	dst_state->parent = src->parent;
1441 	dst_state->first_insn_idx = src->first_insn_idx;
1442 	dst_state->last_insn_idx = src->last_insn_idx;
1443 	dst_state->dfs_depth = src->dfs_depth;
1444 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1445 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1446 	dst_state->may_goto_depth = src->may_goto_depth;
1447 	for (i = 0; i <= src->curframe; i++) {
1448 		dst = dst_state->frame[i];
1449 		if (!dst) {
1450 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1451 			if (!dst)
1452 				return -ENOMEM;
1453 			dst_state->frame[i] = dst;
1454 		}
1455 		err = copy_func_state(dst, src->frame[i]);
1456 		if (err)
1457 			return err;
1458 	}
1459 	return 0;
1460 }
1461 
1462 static u32 state_htab_size(struct bpf_verifier_env *env)
1463 {
1464 	return env->prog->len;
1465 }
1466 
1467 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1468 {
1469 	struct bpf_verifier_state *cur = env->cur_state;
1470 	struct bpf_func_state *state = cur->frame[cur->curframe];
1471 
1472 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1473 }
1474 
1475 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1476 {
1477 	int fr;
1478 
1479 	if (a->curframe != b->curframe)
1480 		return false;
1481 
1482 	for (fr = a->curframe; fr >= 0; fr--)
1483 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1484 			return false;
1485 
1486 	return true;
1487 }
1488 
1489 /* Open coded iterators allow back-edges in the state graph in order to
1490  * check unbounded loops that iterators.
1491  *
1492  * In is_state_visited() it is necessary to know if explored states are
1493  * part of some loops in order to decide whether non-exact states
1494  * comparison could be used:
1495  * - non-exact states comparison establishes sub-state relation and uses
1496  *   read and precision marks to do so, these marks are propagated from
1497  *   children states and thus are not guaranteed to be final in a loop;
1498  * - exact states comparison just checks if current and explored states
1499  *   are identical (and thus form a back-edge).
1500  *
1501  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1502  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1503  * algorithm for loop structure detection and gives an overview of
1504  * relevant terminology. It also has helpful illustrations.
1505  *
1506  * [1] https://api.semanticscholar.org/CorpusID:15784067
1507  *
1508  * We use a similar algorithm but because loop nested structure is
1509  * irrelevant for verifier ours is significantly simpler and resembles
1510  * strongly connected components algorithm from Sedgewick's textbook.
1511  *
1512  * Define topmost loop entry as a first node of the loop traversed in a
1513  * depth first search starting from initial state. The goal of the loop
1514  * tracking algorithm is to associate topmost loop entries with states
1515  * derived from these entries.
1516  *
1517  * For each step in the DFS states traversal algorithm needs to identify
1518  * the following situations:
1519  *
1520  *          initial                     initial                   initial
1521  *            |                           |                         |
1522  *            V                           V                         V
1523  *           ...                         ...           .---------> hdr
1524  *            |                           |            |            |
1525  *            V                           V            |            V
1526  *           cur                     .-> succ          |    .------...
1527  *            |                      |    |            |    |       |
1528  *            V                      |    V            |    V       V
1529  *           succ                    '-- cur           |   ...     ...
1530  *                                                     |    |       |
1531  *                                                     |    V       V
1532  *                                                     |   succ <- cur
1533  *                                                     |    |
1534  *                                                     |    V
1535  *                                                     |   ...
1536  *                                                     |    |
1537  *                                                     '----'
1538  *
1539  *  (A) successor state of cur   (B) successor state of cur or it's entry
1540  *      not yet traversed            are in current DFS path, thus cur and succ
1541  *                                   are members of the same outermost loop
1542  *
1543  *                      initial                  initial
1544  *                        |                        |
1545  *                        V                        V
1546  *                       ...                      ...
1547  *                        |                        |
1548  *                        V                        V
1549  *                .------...               .------...
1550  *                |       |                |       |
1551  *                V       V                V       V
1552  *           .-> hdr     ...              ...     ...
1553  *           |    |       |                |       |
1554  *           |    V       V                V       V
1555  *           |   succ <- cur              succ <- cur
1556  *           |    |                        |
1557  *           |    V                        V
1558  *           |   ...                      ...
1559  *           |    |                        |
1560  *           '----'                       exit
1561  *
1562  * (C) successor state of cur is a part of some loop but this loop
1563  *     does not include cur or successor state is not in a loop at all.
1564  *
1565  * Algorithm could be described as the following python code:
1566  *
1567  *     traversed = set()   # Set of traversed nodes
1568  *     entries = {}        # Mapping from node to loop entry
1569  *     depths = {}         # Depth level assigned to graph node
1570  *     path = set()        # Current DFS path
1571  *
1572  *     # Find outermost loop entry known for n
1573  *     def get_loop_entry(n):
1574  *         h = entries.get(n, None)
1575  *         while h in entries and entries[h] != h:
1576  *             h = entries[h]
1577  *         return h
1578  *
1579  *     # Update n's loop entry if h's outermost entry comes
1580  *     # before n's outermost entry in current DFS path.
1581  *     def update_loop_entry(n, h):
1582  *         n1 = get_loop_entry(n) or n
1583  *         h1 = get_loop_entry(h) or h
1584  *         if h1 in path and depths[h1] <= depths[n1]:
1585  *             entries[n] = h1
1586  *
1587  *     def dfs(n, depth):
1588  *         traversed.add(n)
1589  *         path.add(n)
1590  *         depths[n] = depth
1591  *         for succ in G.successors(n):
1592  *             if succ not in traversed:
1593  *                 # Case A: explore succ and update cur's loop entry
1594  *                 #         only if succ's entry is in current DFS path.
1595  *                 dfs(succ, depth + 1)
1596  *                 h = get_loop_entry(succ)
1597  *                 update_loop_entry(n, h)
1598  *             else:
1599  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1600  *                 update_loop_entry(n, succ)
1601  *         path.remove(n)
1602  *
1603  * To adapt this algorithm for use with verifier:
1604  * - use st->branch == 0 as a signal that DFS of succ had been finished
1605  *   and cur's loop entry has to be updated (case A), handle this in
1606  *   update_branch_counts();
1607  * - use st->branch > 0 as a signal that st is in the current DFS path;
1608  * - handle cases B and C in is_state_visited();
1609  * - update topmost loop entry for intermediate states in get_loop_entry().
1610  */
1611 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1612 {
1613 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1614 
1615 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1616 		topmost = topmost->loop_entry;
1617 	/* Update loop entries for intermediate states to avoid this
1618 	 * traversal in future get_loop_entry() calls.
1619 	 */
1620 	while (st && st->loop_entry != topmost) {
1621 		old = st->loop_entry;
1622 		st->loop_entry = topmost;
1623 		st = old;
1624 	}
1625 	return topmost;
1626 }
1627 
1628 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1629 {
1630 	struct bpf_verifier_state *cur1, *hdr1;
1631 
1632 	cur1 = get_loop_entry(cur) ?: cur;
1633 	hdr1 = get_loop_entry(hdr) ?: hdr;
1634 	/* The head1->branches check decides between cases B and C in
1635 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1636 	 * head's topmost loop entry is not in current DFS path,
1637 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1638 	 * no need to update cur->loop_entry.
1639 	 */
1640 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1641 		cur->loop_entry = hdr;
1642 		hdr->used_as_loop_entry = true;
1643 	}
1644 }
1645 
1646 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1647 {
1648 	while (st) {
1649 		u32 br = --st->branches;
1650 
1651 		/* br == 0 signals that DFS exploration for 'st' is finished,
1652 		 * thus it is necessary to update parent's loop entry if it
1653 		 * turned out that st is a part of some loop.
1654 		 * This is a part of 'case A' in get_loop_entry() comment.
1655 		 */
1656 		if (br == 0 && st->parent && st->loop_entry)
1657 			update_loop_entry(st->parent, st->loop_entry);
1658 
1659 		/* WARN_ON(br > 1) technically makes sense here,
1660 		 * but see comment in push_stack(), hence:
1661 		 */
1662 		WARN_ONCE((int)br < 0,
1663 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1664 			  br);
1665 		if (br)
1666 			break;
1667 		st = st->parent;
1668 	}
1669 }
1670 
1671 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1672 		     int *insn_idx, bool pop_log)
1673 {
1674 	struct bpf_verifier_state *cur = env->cur_state;
1675 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1676 	int err;
1677 
1678 	if (env->head == NULL)
1679 		return -ENOENT;
1680 
1681 	if (cur) {
1682 		err = copy_verifier_state(cur, &head->st);
1683 		if (err)
1684 			return err;
1685 	}
1686 	if (pop_log)
1687 		bpf_vlog_reset(&env->log, head->log_pos);
1688 	if (insn_idx)
1689 		*insn_idx = head->insn_idx;
1690 	if (prev_insn_idx)
1691 		*prev_insn_idx = head->prev_insn_idx;
1692 	elem = head->next;
1693 	free_verifier_state(&head->st, false);
1694 	kfree(head);
1695 	env->head = elem;
1696 	env->stack_size--;
1697 	return 0;
1698 }
1699 
1700 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1701 					     int insn_idx, int prev_insn_idx,
1702 					     bool speculative)
1703 {
1704 	struct bpf_verifier_state *cur = env->cur_state;
1705 	struct bpf_verifier_stack_elem *elem;
1706 	int err;
1707 
1708 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1709 	if (!elem)
1710 		goto err;
1711 
1712 	elem->insn_idx = insn_idx;
1713 	elem->prev_insn_idx = prev_insn_idx;
1714 	elem->next = env->head;
1715 	elem->log_pos = env->log.end_pos;
1716 	env->head = elem;
1717 	env->stack_size++;
1718 	err = copy_verifier_state(&elem->st, cur);
1719 	if (err)
1720 		goto err;
1721 	elem->st.speculative |= speculative;
1722 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1723 		verbose(env, "The sequence of %d jumps is too complex.\n",
1724 			env->stack_size);
1725 		goto err;
1726 	}
1727 	if (elem->st.parent) {
1728 		++elem->st.parent->branches;
1729 		/* WARN_ON(branches > 2) technically makes sense here,
1730 		 * but
1731 		 * 1. speculative states will bump 'branches' for non-branch
1732 		 * instructions
1733 		 * 2. is_state_visited() heuristics may decide not to create
1734 		 * a new state for a sequence of branches and all such current
1735 		 * and cloned states will be pointing to a single parent state
1736 		 * which might have large 'branches' count.
1737 		 */
1738 	}
1739 	return &elem->st;
1740 err:
1741 	free_verifier_state(env->cur_state, true);
1742 	env->cur_state = NULL;
1743 	/* pop all elements and return */
1744 	while (!pop_stack(env, NULL, NULL, false));
1745 	return NULL;
1746 }
1747 
1748 #define CALLER_SAVED_REGS 6
1749 static const int caller_saved[CALLER_SAVED_REGS] = {
1750 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1751 };
1752 
1753 /* This helper doesn't clear reg->id */
1754 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1755 {
1756 	reg->var_off = tnum_const(imm);
1757 	reg->smin_value = (s64)imm;
1758 	reg->smax_value = (s64)imm;
1759 	reg->umin_value = imm;
1760 	reg->umax_value = imm;
1761 
1762 	reg->s32_min_value = (s32)imm;
1763 	reg->s32_max_value = (s32)imm;
1764 	reg->u32_min_value = (u32)imm;
1765 	reg->u32_max_value = (u32)imm;
1766 }
1767 
1768 /* Mark the unknown part of a register (variable offset or scalar value) as
1769  * known to have the value @imm.
1770  */
1771 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1772 {
1773 	/* Clear off and union(map_ptr, range) */
1774 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1775 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1776 	reg->id = 0;
1777 	reg->ref_obj_id = 0;
1778 	___mark_reg_known(reg, imm);
1779 }
1780 
1781 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1782 {
1783 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1784 	reg->s32_min_value = (s32)imm;
1785 	reg->s32_max_value = (s32)imm;
1786 	reg->u32_min_value = (u32)imm;
1787 	reg->u32_max_value = (u32)imm;
1788 }
1789 
1790 /* Mark the 'variable offset' part of a register as zero.  This should be
1791  * used only on registers holding a pointer type.
1792  */
1793 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1794 {
1795 	__mark_reg_known(reg, 0);
1796 }
1797 
1798 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1799 {
1800 	__mark_reg_known(reg, 0);
1801 	reg->type = SCALAR_VALUE;
1802 	/* all scalars are assumed imprecise initially (unless unprivileged,
1803 	 * in which case everything is forced to be precise)
1804 	 */
1805 	reg->precise = !env->bpf_capable;
1806 }
1807 
1808 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1809 				struct bpf_reg_state *regs, u32 regno)
1810 {
1811 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1812 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1813 		/* Something bad happened, let's kill all regs */
1814 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1815 			__mark_reg_not_init(env, regs + regno);
1816 		return;
1817 	}
1818 	__mark_reg_known_zero(regs + regno);
1819 }
1820 
1821 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1822 			      bool first_slot, int dynptr_id)
1823 {
1824 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1825 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1826 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1827 	 */
1828 	__mark_reg_known_zero(reg);
1829 	reg->type = CONST_PTR_TO_DYNPTR;
1830 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1831 	reg->id = dynptr_id;
1832 	reg->dynptr.type = type;
1833 	reg->dynptr.first_slot = first_slot;
1834 }
1835 
1836 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1837 {
1838 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1839 		const struct bpf_map *map = reg->map_ptr;
1840 
1841 		if (map->inner_map_meta) {
1842 			reg->type = CONST_PTR_TO_MAP;
1843 			reg->map_ptr = map->inner_map_meta;
1844 			/* transfer reg's id which is unique for every map_lookup_elem
1845 			 * as UID of the inner map.
1846 			 */
1847 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1848 				reg->map_uid = reg->id;
1849 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
1850 				reg->map_uid = reg->id;
1851 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1852 			reg->type = PTR_TO_XDP_SOCK;
1853 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1854 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1855 			reg->type = PTR_TO_SOCKET;
1856 		} else {
1857 			reg->type = PTR_TO_MAP_VALUE;
1858 		}
1859 		return;
1860 	}
1861 
1862 	reg->type &= ~PTR_MAYBE_NULL;
1863 }
1864 
1865 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1866 				struct btf_field_graph_root *ds_head)
1867 {
1868 	__mark_reg_known_zero(&regs[regno]);
1869 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1870 	regs[regno].btf = ds_head->btf;
1871 	regs[regno].btf_id = ds_head->value_btf_id;
1872 	regs[regno].off = ds_head->node_offset;
1873 }
1874 
1875 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1876 {
1877 	return type_is_pkt_pointer(reg->type);
1878 }
1879 
1880 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1881 {
1882 	return reg_is_pkt_pointer(reg) ||
1883 	       reg->type == PTR_TO_PACKET_END;
1884 }
1885 
1886 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1887 {
1888 	return base_type(reg->type) == PTR_TO_MEM &&
1889 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1890 }
1891 
1892 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1893 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1894 				    enum bpf_reg_type which)
1895 {
1896 	/* The register can already have a range from prior markings.
1897 	 * This is fine as long as it hasn't been advanced from its
1898 	 * origin.
1899 	 */
1900 	return reg->type == which &&
1901 	       reg->id == 0 &&
1902 	       reg->off == 0 &&
1903 	       tnum_equals_const(reg->var_off, 0);
1904 }
1905 
1906 /* Reset the min/max bounds of a register */
1907 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1908 {
1909 	reg->smin_value = S64_MIN;
1910 	reg->smax_value = S64_MAX;
1911 	reg->umin_value = 0;
1912 	reg->umax_value = U64_MAX;
1913 
1914 	reg->s32_min_value = S32_MIN;
1915 	reg->s32_max_value = S32_MAX;
1916 	reg->u32_min_value = 0;
1917 	reg->u32_max_value = U32_MAX;
1918 }
1919 
1920 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1921 {
1922 	reg->smin_value = S64_MIN;
1923 	reg->smax_value = S64_MAX;
1924 	reg->umin_value = 0;
1925 	reg->umax_value = U64_MAX;
1926 }
1927 
1928 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1929 {
1930 	reg->s32_min_value = S32_MIN;
1931 	reg->s32_max_value = S32_MAX;
1932 	reg->u32_min_value = 0;
1933 	reg->u32_max_value = U32_MAX;
1934 }
1935 
1936 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1937 {
1938 	struct tnum var32_off = tnum_subreg(reg->var_off);
1939 
1940 	/* min signed is max(sign bit) | min(other bits) */
1941 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1942 			var32_off.value | (var32_off.mask & S32_MIN));
1943 	/* max signed is min(sign bit) | max(other bits) */
1944 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1945 			var32_off.value | (var32_off.mask & S32_MAX));
1946 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1947 	reg->u32_max_value = min(reg->u32_max_value,
1948 				 (u32)(var32_off.value | var32_off.mask));
1949 }
1950 
1951 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1952 {
1953 	/* min signed is max(sign bit) | min(other bits) */
1954 	reg->smin_value = max_t(s64, reg->smin_value,
1955 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1956 	/* max signed is min(sign bit) | max(other bits) */
1957 	reg->smax_value = min_t(s64, reg->smax_value,
1958 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1959 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1960 	reg->umax_value = min(reg->umax_value,
1961 			      reg->var_off.value | reg->var_off.mask);
1962 }
1963 
1964 static void __update_reg_bounds(struct bpf_reg_state *reg)
1965 {
1966 	__update_reg32_bounds(reg);
1967 	__update_reg64_bounds(reg);
1968 }
1969 
1970 /* Uses signed min/max values to inform unsigned, and vice-versa */
1971 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1972 {
1973 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1974 	 * bits to improve our u32/s32 boundaries.
1975 	 *
1976 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1977 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1978 	 * [10, 20] range. But this property holds for any 64-bit range as
1979 	 * long as upper 32 bits in that entire range of values stay the same.
1980 	 *
1981 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1982 	 * in decimal) has the same upper 32 bits throughout all the values in
1983 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1984 	 * range.
1985 	 *
1986 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1987 	 * following the rules outlined below about u64/s64 correspondence
1988 	 * (which equally applies to u32 vs s32 correspondence). In general it
1989 	 * depends on actual hexadecimal values of 32-bit range. They can form
1990 	 * only valid u32, or only valid s32 ranges in some cases.
1991 	 *
1992 	 * So we use all these insights to derive bounds for subregisters here.
1993 	 */
1994 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1995 		/* u64 to u32 casting preserves validity of low 32 bits as
1996 		 * a range, if upper 32 bits are the same
1997 		 */
1998 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1999 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2000 
2001 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2002 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2003 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2004 		}
2005 	}
2006 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2007 		/* low 32 bits should form a proper u32 range */
2008 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2009 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2010 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2011 		}
2012 		/* low 32 bits should form a proper s32 range */
2013 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2014 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2015 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2016 		}
2017 	}
2018 	/* Special case where upper bits form a small sequence of two
2019 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2020 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2021 	 * going from negative numbers to positive numbers. E.g., let's say we
2022 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2023 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2024 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2025 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2026 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2027 	 * upper 32 bits. As a random example, s64 range
2028 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2029 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2030 	 */
2031 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2032 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2033 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2034 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2035 	}
2036 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2037 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2038 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2039 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2040 	}
2041 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2042 	 * try to learn from that
2043 	 */
2044 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2045 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2046 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2047 	}
2048 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2049 	 * are the same, so combine.  This works even in the negative case, e.g.
2050 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2051 	 */
2052 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2053 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2054 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2055 	}
2056 }
2057 
2058 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2059 {
2060 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2061 	 * try to learn from that. Let's do a bit of ASCII art to see when
2062 	 * this is happening. Let's take u64 range first:
2063 	 *
2064 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2065 	 * |-------------------------------|--------------------------------|
2066 	 *
2067 	 * Valid u64 range is formed when umin and umax are anywhere in the
2068 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2069 	 * straightforward. Let's see how s64 range maps onto the same range
2070 	 * of values, annotated below the line for comparison:
2071 	 *
2072 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2073 	 * |-------------------------------|--------------------------------|
2074 	 * 0                        S64_MAX S64_MIN                        -1
2075 	 *
2076 	 * So s64 values basically start in the middle and they are logically
2077 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2078 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2079 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2080 	 * more visually as mapped to sign-agnostic range of hex values.
2081 	 *
2082 	 *  u64 start                                               u64 end
2083 	 *  _______________________________________________________________
2084 	 * /                                                               \
2085 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2086 	 * |-------------------------------|--------------------------------|
2087 	 * 0                        S64_MAX S64_MIN                        -1
2088 	 *                                / \
2089 	 * >------------------------------   ------------------------------->
2090 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2091 	 *
2092 	 * What this means is that, in general, we can't always derive
2093 	 * something new about u64 from any random s64 range, and vice versa.
2094 	 *
2095 	 * But we can do that in two particular cases. One is when entire
2096 	 * u64/s64 range is *entirely* contained within left half of the above
2097 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2098 	 *
2099 	 * |-------------------------------|--------------------------------|
2100 	 *     ^                   ^            ^                 ^
2101 	 *     A                   B            C                 D
2102 	 *
2103 	 * [A, B] and [C, D] are contained entirely in their respective halves
2104 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2105 	 * will be non-negative both as u64 and s64 (and in fact it will be
2106 	 * identical ranges no matter the signedness). [C, D] treated as s64
2107 	 * will be a range of negative values, while in u64 it will be
2108 	 * non-negative range of values larger than 0x8000000000000000.
2109 	 *
2110 	 * Now, any other range here can't be represented in both u64 and s64
2111 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2112 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2113 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2114 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2115 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2116 	 * ranges as u64. Currently reg_state can't represent two segments per
2117 	 * numeric domain, so in such situations we can only derive maximal
2118 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2119 	 *
2120 	 * So we use these facts to derive umin/umax from smin/smax and vice
2121 	 * versa only if they stay within the same "half". This is equivalent
2122 	 * to checking sign bit: lower half will have sign bit as zero, upper
2123 	 * half have sign bit 1. Below in code we simplify this by just
2124 	 * casting umin/umax as smin/smax and checking if they form valid
2125 	 * range, and vice versa. Those are equivalent checks.
2126 	 */
2127 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2128 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2129 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2130 	}
2131 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2132 	 * are the same, so combine.  This works even in the negative case, e.g.
2133 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2134 	 */
2135 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2136 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2137 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2138 	}
2139 }
2140 
2141 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2142 {
2143 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2144 	 * values on both sides of 64-bit range in hope to have tighter range.
2145 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2146 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2147 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2148 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2149 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2150 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2151 	 * We just need to make sure that derived bounds we are intersecting
2152 	 * with are well-formed ranges in respective s64 or u64 domain, just
2153 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2154 	 */
2155 	__u64 new_umin, new_umax;
2156 	__s64 new_smin, new_smax;
2157 
2158 	/* u32 -> u64 tightening, it's always well-formed */
2159 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2160 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2161 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2162 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2163 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2164 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2165 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2166 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2167 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2168 
2169 	/* if s32 can be treated as valid u32 range, we can use it as well */
2170 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2171 		/* s32 -> u64 tightening */
2172 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2173 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2174 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2175 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2176 		/* s32 -> s64 tightening */
2177 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2178 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2179 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2180 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2181 	}
2182 
2183 	/* Here we would like to handle a special case after sign extending load,
2184 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2185 	 *
2186 	 * Upper bits are all 1s when register is in a range:
2187 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2188 	 * Upper bits are all 0s when register is in a range:
2189 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2190 	 * Together this forms are continuous range:
2191 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2192 	 *
2193 	 * Now, suppose that register range is in fact tighter:
2194 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2195 	 * Also suppose that it's 32-bit range is positive,
2196 	 * meaning that lower 32-bits of the full 64-bit register
2197 	 * are in the range:
2198 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2199 	 *
2200 	 * If this happens, then any value in a range:
2201 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2202 	 * is smaller than a lowest bound of the range (R):
2203 	 *   0xffff_ffff_8000_0000
2204 	 * which means that upper bits of the full 64-bit register
2205 	 * can't be all 1s, when lower bits are in range (W).
2206 	 *
2207 	 * Note that:
2208 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2209 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2210 	 * These relations are used in the conditions below.
2211 	 */
2212 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2213 		reg->smin_value = reg->s32_min_value;
2214 		reg->smax_value = reg->s32_max_value;
2215 		reg->umin_value = reg->s32_min_value;
2216 		reg->umax_value = reg->s32_max_value;
2217 		reg->var_off = tnum_intersect(reg->var_off,
2218 					      tnum_range(reg->smin_value, reg->smax_value));
2219 	}
2220 }
2221 
2222 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2223 {
2224 	__reg32_deduce_bounds(reg);
2225 	__reg64_deduce_bounds(reg);
2226 	__reg_deduce_mixed_bounds(reg);
2227 }
2228 
2229 /* Attempts to improve var_off based on unsigned min/max information */
2230 static void __reg_bound_offset(struct bpf_reg_state *reg)
2231 {
2232 	struct tnum var64_off = tnum_intersect(reg->var_off,
2233 					       tnum_range(reg->umin_value,
2234 							  reg->umax_value));
2235 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2236 					       tnum_range(reg->u32_min_value,
2237 							  reg->u32_max_value));
2238 
2239 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2240 }
2241 
2242 static void reg_bounds_sync(struct bpf_reg_state *reg)
2243 {
2244 	/* We might have learned new bounds from the var_off. */
2245 	__update_reg_bounds(reg);
2246 	/* We might have learned something about the sign bit. */
2247 	__reg_deduce_bounds(reg);
2248 	__reg_deduce_bounds(reg);
2249 	/* We might have learned some bits from the bounds. */
2250 	__reg_bound_offset(reg);
2251 	/* Intersecting with the old var_off might have improved our bounds
2252 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2253 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2254 	 */
2255 	__update_reg_bounds(reg);
2256 }
2257 
2258 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2259 				   struct bpf_reg_state *reg, const char *ctx)
2260 {
2261 	const char *msg;
2262 
2263 	if (reg->umin_value > reg->umax_value ||
2264 	    reg->smin_value > reg->smax_value ||
2265 	    reg->u32_min_value > reg->u32_max_value ||
2266 	    reg->s32_min_value > reg->s32_max_value) {
2267 		    msg = "range bounds violation";
2268 		    goto out;
2269 	}
2270 
2271 	if (tnum_is_const(reg->var_off)) {
2272 		u64 uval = reg->var_off.value;
2273 		s64 sval = (s64)uval;
2274 
2275 		if (reg->umin_value != uval || reg->umax_value != uval ||
2276 		    reg->smin_value != sval || reg->smax_value != sval) {
2277 			msg = "const tnum out of sync with range bounds";
2278 			goto out;
2279 		}
2280 	}
2281 
2282 	if (tnum_subreg_is_const(reg->var_off)) {
2283 		u32 uval32 = tnum_subreg(reg->var_off).value;
2284 		s32 sval32 = (s32)uval32;
2285 
2286 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2287 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2288 			msg = "const subreg tnum out of sync with range bounds";
2289 			goto out;
2290 		}
2291 	}
2292 
2293 	return 0;
2294 out:
2295 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2296 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2297 		ctx, msg, reg->umin_value, reg->umax_value,
2298 		reg->smin_value, reg->smax_value,
2299 		reg->u32_min_value, reg->u32_max_value,
2300 		reg->s32_min_value, reg->s32_max_value,
2301 		reg->var_off.value, reg->var_off.mask);
2302 	if (env->test_reg_invariants)
2303 		return -EFAULT;
2304 	__mark_reg_unbounded(reg);
2305 	return 0;
2306 }
2307 
2308 static bool __reg32_bound_s64(s32 a)
2309 {
2310 	return a >= 0 && a <= S32_MAX;
2311 }
2312 
2313 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2314 {
2315 	reg->umin_value = reg->u32_min_value;
2316 	reg->umax_value = reg->u32_max_value;
2317 
2318 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2319 	 * be positive otherwise set to worse case bounds and refine later
2320 	 * from tnum.
2321 	 */
2322 	if (__reg32_bound_s64(reg->s32_min_value) &&
2323 	    __reg32_bound_s64(reg->s32_max_value)) {
2324 		reg->smin_value = reg->s32_min_value;
2325 		reg->smax_value = reg->s32_max_value;
2326 	} else {
2327 		reg->smin_value = 0;
2328 		reg->smax_value = U32_MAX;
2329 	}
2330 }
2331 
2332 /* Mark a register as having a completely unknown (scalar) value. */
2333 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2334 {
2335 	/*
2336 	 * Clear type, off, and union(map_ptr, range) and
2337 	 * padding between 'type' and union
2338 	 */
2339 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2340 	reg->type = SCALAR_VALUE;
2341 	reg->id = 0;
2342 	reg->ref_obj_id = 0;
2343 	reg->var_off = tnum_unknown;
2344 	reg->frameno = 0;
2345 	reg->precise = false;
2346 	__mark_reg_unbounded(reg);
2347 }
2348 
2349 /* Mark a register as having a completely unknown (scalar) value,
2350  * initialize .precise as true when not bpf capable.
2351  */
2352 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2353 			       struct bpf_reg_state *reg)
2354 {
2355 	__mark_reg_unknown_imprecise(reg);
2356 	reg->precise = !env->bpf_capable;
2357 }
2358 
2359 static void mark_reg_unknown(struct bpf_verifier_env *env,
2360 			     struct bpf_reg_state *regs, u32 regno)
2361 {
2362 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2363 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2364 		/* Something bad happened, let's kill all regs except FP */
2365 		for (regno = 0; regno < BPF_REG_FP; regno++)
2366 			__mark_reg_not_init(env, regs + regno);
2367 		return;
2368 	}
2369 	__mark_reg_unknown(env, regs + regno);
2370 }
2371 
2372 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2373 				struct bpf_reg_state *regs,
2374 				u32 regno,
2375 				s32 s32_min,
2376 				s32 s32_max)
2377 {
2378 	struct bpf_reg_state *reg = regs + regno;
2379 
2380 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2381 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2382 
2383 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2384 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2385 
2386 	reg_bounds_sync(reg);
2387 
2388 	return reg_bounds_sanity_check(env, reg, "s32_range");
2389 }
2390 
2391 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2392 				struct bpf_reg_state *reg)
2393 {
2394 	__mark_reg_unknown(env, reg);
2395 	reg->type = NOT_INIT;
2396 }
2397 
2398 static void mark_reg_not_init(struct bpf_verifier_env *env,
2399 			      struct bpf_reg_state *regs, u32 regno)
2400 {
2401 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2402 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2403 		/* Something bad happened, let's kill all regs except FP */
2404 		for (regno = 0; regno < BPF_REG_FP; regno++)
2405 			__mark_reg_not_init(env, regs + regno);
2406 		return;
2407 	}
2408 	__mark_reg_not_init(env, regs + regno);
2409 }
2410 
2411 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2412 			    struct bpf_reg_state *regs, u32 regno,
2413 			    enum bpf_reg_type reg_type,
2414 			    struct btf *btf, u32 btf_id,
2415 			    enum bpf_type_flag flag)
2416 {
2417 	if (reg_type == SCALAR_VALUE) {
2418 		mark_reg_unknown(env, regs, regno);
2419 		return;
2420 	}
2421 	mark_reg_known_zero(env, regs, regno);
2422 	regs[regno].type = PTR_TO_BTF_ID | flag;
2423 	regs[regno].btf = btf;
2424 	regs[regno].btf_id = btf_id;
2425 	if (type_may_be_null(flag))
2426 		regs[regno].id = ++env->id_gen;
2427 }
2428 
2429 #define DEF_NOT_SUBREG	(0)
2430 static void init_reg_state(struct bpf_verifier_env *env,
2431 			   struct bpf_func_state *state)
2432 {
2433 	struct bpf_reg_state *regs = state->regs;
2434 	int i;
2435 
2436 	for (i = 0; i < MAX_BPF_REG; i++) {
2437 		mark_reg_not_init(env, regs, i);
2438 		regs[i].live = REG_LIVE_NONE;
2439 		regs[i].parent = NULL;
2440 		regs[i].subreg_def = DEF_NOT_SUBREG;
2441 	}
2442 
2443 	/* frame pointer */
2444 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2445 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2446 	regs[BPF_REG_FP].frameno = state->frameno;
2447 }
2448 
2449 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2450 {
2451 	return (struct bpf_retval_range){ minval, maxval };
2452 }
2453 
2454 #define BPF_MAIN_FUNC (-1)
2455 static void init_func_state(struct bpf_verifier_env *env,
2456 			    struct bpf_func_state *state,
2457 			    int callsite, int frameno, int subprogno)
2458 {
2459 	state->callsite = callsite;
2460 	state->frameno = frameno;
2461 	state->subprogno = subprogno;
2462 	state->callback_ret_range = retval_range(0, 0);
2463 	init_reg_state(env, state);
2464 	mark_verifier_state_scratched(env);
2465 }
2466 
2467 /* Similar to push_stack(), but for async callbacks */
2468 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2469 						int insn_idx, int prev_insn_idx,
2470 						int subprog, bool is_sleepable)
2471 {
2472 	struct bpf_verifier_stack_elem *elem;
2473 	struct bpf_func_state *frame;
2474 
2475 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2476 	if (!elem)
2477 		goto err;
2478 
2479 	elem->insn_idx = insn_idx;
2480 	elem->prev_insn_idx = prev_insn_idx;
2481 	elem->next = env->head;
2482 	elem->log_pos = env->log.end_pos;
2483 	env->head = elem;
2484 	env->stack_size++;
2485 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2486 		verbose(env,
2487 			"The sequence of %d jumps is too complex for async cb.\n",
2488 			env->stack_size);
2489 		goto err;
2490 	}
2491 	/* Unlike push_stack() do not copy_verifier_state().
2492 	 * The caller state doesn't matter.
2493 	 * This is async callback. It starts in a fresh stack.
2494 	 * Initialize it similar to do_check_common().
2495 	 */
2496 	elem->st.branches = 1;
2497 	elem->st.in_sleepable = is_sleepable;
2498 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2499 	if (!frame)
2500 		goto err;
2501 	init_func_state(env, frame,
2502 			BPF_MAIN_FUNC /* callsite */,
2503 			0 /* frameno within this callchain */,
2504 			subprog /* subprog number within this prog */);
2505 	elem->st.frame[0] = frame;
2506 	return &elem->st;
2507 err:
2508 	free_verifier_state(env->cur_state, true);
2509 	env->cur_state = NULL;
2510 	/* pop all elements and return */
2511 	while (!pop_stack(env, NULL, NULL, false));
2512 	return NULL;
2513 }
2514 
2515 
2516 enum reg_arg_type {
2517 	SRC_OP,		/* register is used as source operand */
2518 	DST_OP,		/* register is used as destination operand */
2519 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2520 };
2521 
2522 static int cmp_subprogs(const void *a, const void *b)
2523 {
2524 	return ((struct bpf_subprog_info *)a)->start -
2525 	       ((struct bpf_subprog_info *)b)->start;
2526 }
2527 
2528 static int find_subprog(struct bpf_verifier_env *env, int off)
2529 {
2530 	struct bpf_subprog_info *p;
2531 
2532 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2533 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2534 	if (!p)
2535 		return -ENOENT;
2536 	return p - env->subprog_info;
2537 
2538 }
2539 
2540 static int add_subprog(struct bpf_verifier_env *env, int off)
2541 {
2542 	int insn_cnt = env->prog->len;
2543 	int ret;
2544 
2545 	if (off >= insn_cnt || off < 0) {
2546 		verbose(env, "call to invalid destination\n");
2547 		return -EINVAL;
2548 	}
2549 	ret = find_subprog(env, off);
2550 	if (ret >= 0)
2551 		return ret;
2552 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2553 		verbose(env, "too many subprograms\n");
2554 		return -E2BIG;
2555 	}
2556 	/* determine subprog starts. The end is one before the next starts */
2557 	env->subprog_info[env->subprog_cnt++].start = off;
2558 	sort(env->subprog_info, env->subprog_cnt,
2559 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2560 	return env->subprog_cnt - 1;
2561 }
2562 
2563 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2564 {
2565 	struct bpf_prog_aux *aux = env->prog->aux;
2566 	struct btf *btf = aux->btf;
2567 	const struct btf_type *t;
2568 	u32 main_btf_id, id;
2569 	const char *name;
2570 	int ret, i;
2571 
2572 	/* Non-zero func_info_cnt implies valid btf */
2573 	if (!aux->func_info_cnt)
2574 		return 0;
2575 	main_btf_id = aux->func_info[0].type_id;
2576 
2577 	t = btf_type_by_id(btf, main_btf_id);
2578 	if (!t) {
2579 		verbose(env, "invalid btf id for main subprog in func_info\n");
2580 		return -EINVAL;
2581 	}
2582 
2583 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2584 	if (IS_ERR(name)) {
2585 		ret = PTR_ERR(name);
2586 		/* If there is no tag present, there is no exception callback */
2587 		if (ret == -ENOENT)
2588 			ret = 0;
2589 		else if (ret == -EEXIST)
2590 			verbose(env, "multiple exception callback tags for main subprog\n");
2591 		return ret;
2592 	}
2593 
2594 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2595 	if (ret < 0) {
2596 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2597 		return ret;
2598 	}
2599 	id = ret;
2600 	t = btf_type_by_id(btf, id);
2601 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2602 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2603 		return -EINVAL;
2604 	}
2605 	ret = 0;
2606 	for (i = 0; i < aux->func_info_cnt; i++) {
2607 		if (aux->func_info[i].type_id != id)
2608 			continue;
2609 		ret = aux->func_info[i].insn_off;
2610 		/* Further func_info and subprog checks will also happen
2611 		 * later, so assume this is the right insn_off for now.
2612 		 */
2613 		if (!ret) {
2614 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2615 			ret = -EINVAL;
2616 		}
2617 	}
2618 	if (!ret) {
2619 		verbose(env, "exception callback type id not found in func_info\n");
2620 		ret = -EINVAL;
2621 	}
2622 	return ret;
2623 }
2624 
2625 #define MAX_KFUNC_DESCS 256
2626 #define MAX_KFUNC_BTFS	256
2627 
2628 struct bpf_kfunc_desc {
2629 	struct btf_func_model func_model;
2630 	u32 func_id;
2631 	s32 imm;
2632 	u16 offset;
2633 	unsigned long addr;
2634 };
2635 
2636 struct bpf_kfunc_btf {
2637 	struct btf *btf;
2638 	struct module *module;
2639 	u16 offset;
2640 };
2641 
2642 struct bpf_kfunc_desc_tab {
2643 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2644 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2645 	 * available, therefore at the end of verification do_misc_fixups()
2646 	 * sorts this by imm and offset.
2647 	 */
2648 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2649 	u32 nr_descs;
2650 };
2651 
2652 struct bpf_kfunc_btf_tab {
2653 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2654 	u32 nr_descs;
2655 };
2656 
2657 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2658 {
2659 	const struct bpf_kfunc_desc *d0 = a;
2660 	const struct bpf_kfunc_desc *d1 = b;
2661 
2662 	/* func_id is not greater than BTF_MAX_TYPE */
2663 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2664 }
2665 
2666 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2667 {
2668 	const struct bpf_kfunc_btf *d0 = a;
2669 	const struct bpf_kfunc_btf *d1 = b;
2670 
2671 	return d0->offset - d1->offset;
2672 }
2673 
2674 static const struct bpf_kfunc_desc *
2675 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2676 {
2677 	struct bpf_kfunc_desc desc = {
2678 		.func_id = func_id,
2679 		.offset = offset,
2680 	};
2681 	struct bpf_kfunc_desc_tab *tab;
2682 
2683 	tab = prog->aux->kfunc_tab;
2684 	return bsearch(&desc, tab->descs, tab->nr_descs,
2685 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2686 }
2687 
2688 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2689 		       u16 btf_fd_idx, u8 **func_addr)
2690 {
2691 	const struct bpf_kfunc_desc *desc;
2692 
2693 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2694 	if (!desc)
2695 		return -EFAULT;
2696 
2697 	*func_addr = (u8 *)desc->addr;
2698 	return 0;
2699 }
2700 
2701 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2702 					 s16 offset)
2703 {
2704 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2705 	struct bpf_kfunc_btf_tab *tab;
2706 	struct bpf_kfunc_btf *b;
2707 	struct module *mod;
2708 	struct btf *btf;
2709 	int btf_fd;
2710 
2711 	tab = env->prog->aux->kfunc_btf_tab;
2712 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2713 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2714 	if (!b) {
2715 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2716 			verbose(env, "too many different module BTFs\n");
2717 			return ERR_PTR(-E2BIG);
2718 		}
2719 
2720 		if (bpfptr_is_null(env->fd_array)) {
2721 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2722 			return ERR_PTR(-EPROTO);
2723 		}
2724 
2725 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2726 					    offset * sizeof(btf_fd),
2727 					    sizeof(btf_fd)))
2728 			return ERR_PTR(-EFAULT);
2729 
2730 		btf = btf_get_by_fd(btf_fd);
2731 		if (IS_ERR(btf)) {
2732 			verbose(env, "invalid module BTF fd specified\n");
2733 			return btf;
2734 		}
2735 
2736 		if (!btf_is_module(btf)) {
2737 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2738 			btf_put(btf);
2739 			return ERR_PTR(-EINVAL);
2740 		}
2741 
2742 		mod = btf_try_get_module(btf);
2743 		if (!mod) {
2744 			btf_put(btf);
2745 			return ERR_PTR(-ENXIO);
2746 		}
2747 
2748 		b = &tab->descs[tab->nr_descs++];
2749 		b->btf = btf;
2750 		b->module = mod;
2751 		b->offset = offset;
2752 
2753 		/* sort() reorders entries by value, so b may no longer point
2754 		 * to the right entry after this
2755 		 */
2756 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2757 		     kfunc_btf_cmp_by_off, NULL);
2758 	} else {
2759 		btf = b->btf;
2760 	}
2761 
2762 	return btf;
2763 }
2764 
2765 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2766 {
2767 	if (!tab)
2768 		return;
2769 
2770 	while (tab->nr_descs--) {
2771 		module_put(tab->descs[tab->nr_descs].module);
2772 		btf_put(tab->descs[tab->nr_descs].btf);
2773 	}
2774 	kfree(tab);
2775 }
2776 
2777 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2778 {
2779 	if (offset) {
2780 		if (offset < 0) {
2781 			/* In the future, this can be allowed to increase limit
2782 			 * of fd index into fd_array, interpreted as u16.
2783 			 */
2784 			verbose(env, "negative offset disallowed for kernel module function call\n");
2785 			return ERR_PTR(-EINVAL);
2786 		}
2787 
2788 		return __find_kfunc_desc_btf(env, offset);
2789 	}
2790 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2791 }
2792 
2793 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2794 {
2795 	const struct btf_type *func, *func_proto;
2796 	struct bpf_kfunc_btf_tab *btf_tab;
2797 	struct bpf_kfunc_desc_tab *tab;
2798 	struct bpf_prog_aux *prog_aux;
2799 	struct bpf_kfunc_desc *desc;
2800 	const char *func_name;
2801 	struct btf *desc_btf;
2802 	unsigned long call_imm;
2803 	unsigned long addr;
2804 	int err;
2805 
2806 	prog_aux = env->prog->aux;
2807 	tab = prog_aux->kfunc_tab;
2808 	btf_tab = prog_aux->kfunc_btf_tab;
2809 	if (!tab) {
2810 		if (!btf_vmlinux) {
2811 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2812 			return -ENOTSUPP;
2813 		}
2814 
2815 		if (!env->prog->jit_requested) {
2816 			verbose(env, "JIT is required for calling kernel function\n");
2817 			return -ENOTSUPP;
2818 		}
2819 
2820 		if (!bpf_jit_supports_kfunc_call()) {
2821 			verbose(env, "JIT does not support calling kernel function\n");
2822 			return -ENOTSUPP;
2823 		}
2824 
2825 		if (!env->prog->gpl_compatible) {
2826 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2827 			return -EINVAL;
2828 		}
2829 
2830 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2831 		if (!tab)
2832 			return -ENOMEM;
2833 		prog_aux->kfunc_tab = tab;
2834 	}
2835 
2836 	/* func_id == 0 is always invalid, but instead of returning an error, be
2837 	 * conservative and wait until the code elimination pass before returning
2838 	 * error, so that invalid calls that get pruned out can be in BPF programs
2839 	 * loaded from userspace.  It is also required that offset be untouched
2840 	 * for such calls.
2841 	 */
2842 	if (!func_id && !offset)
2843 		return 0;
2844 
2845 	if (!btf_tab && offset) {
2846 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2847 		if (!btf_tab)
2848 			return -ENOMEM;
2849 		prog_aux->kfunc_btf_tab = btf_tab;
2850 	}
2851 
2852 	desc_btf = find_kfunc_desc_btf(env, offset);
2853 	if (IS_ERR(desc_btf)) {
2854 		verbose(env, "failed to find BTF for kernel function\n");
2855 		return PTR_ERR(desc_btf);
2856 	}
2857 
2858 	if (find_kfunc_desc(env->prog, func_id, offset))
2859 		return 0;
2860 
2861 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2862 		verbose(env, "too many different kernel function calls\n");
2863 		return -E2BIG;
2864 	}
2865 
2866 	func = btf_type_by_id(desc_btf, func_id);
2867 	if (!func || !btf_type_is_func(func)) {
2868 		verbose(env, "kernel btf_id %u is not a function\n",
2869 			func_id);
2870 		return -EINVAL;
2871 	}
2872 	func_proto = btf_type_by_id(desc_btf, func->type);
2873 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2874 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2875 			func_id);
2876 		return -EINVAL;
2877 	}
2878 
2879 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2880 	addr = kallsyms_lookup_name(func_name);
2881 	if (!addr) {
2882 		verbose(env, "cannot find address for kernel function %s\n",
2883 			func_name);
2884 		return -EINVAL;
2885 	}
2886 	specialize_kfunc(env, func_id, offset, &addr);
2887 
2888 	if (bpf_jit_supports_far_kfunc_call()) {
2889 		call_imm = func_id;
2890 	} else {
2891 		call_imm = BPF_CALL_IMM(addr);
2892 		/* Check whether the relative offset overflows desc->imm */
2893 		if ((unsigned long)(s32)call_imm != call_imm) {
2894 			verbose(env, "address of kernel function %s is out of range\n",
2895 				func_name);
2896 			return -EINVAL;
2897 		}
2898 	}
2899 
2900 	if (bpf_dev_bound_kfunc_id(func_id)) {
2901 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2902 		if (err)
2903 			return err;
2904 	}
2905 
2906 	desc = &tab->descs[tab->nr_descs++];
2907 	desc->func_id = func_id;
2908 	desc->imm = call_imm;
2909 	desc->offset = offset;
2910 	desc->addr = addr;
2911 	err = btf_distill_func_proto(&env->log, desc_btf,
2912 				     func_proto, func_name,
2913 				     &desc->func_model);
2914 	if (!err)
2915 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2916 		     kfunc_desc_cmp_by_id_off, NULL);
2917 	return err;
2918 }
2919 
2920 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2921 {
2922 	const struct bpf_kfunc_desc *d0 = a;
2923 	const struct bpf_kfunc_desc *d1 = b;
2924 
2925 	if (d0->imm != d1->imm)
2926 		return d0->imm < d1->imm ? -1 : 1;
2927 	if (d0->offset != d1->offset)
2928 		return d0->offset < d1->offset ? -1 : 1;
2929 	return 0;
2930 }
2931 
2932 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2933 {
2934 	struct bpf_kfunc_desc_tab *tab;
2935 
2936 	tab = prog->aux->kfunc_tab;
2937 	if (!tab)
2938 		return;
2939 
2940 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2941 	     kfunc_desc_cmp_by_imm_off, NULL);
2942 }
2943 
2944 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2945 {
2946 	return !!prog->aux->kfunc_tab;
2947 }
2948 
2949 const struct btf_func_model *
2950 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2951 			 const struct bpf_insn *insn)
2952 {
2953 	const struct bpf_kfunc_desc desc = {
2954 		.imm = insn->imm,
2955 		.offset = insn->off,
2956 	};
2957 	const struct bpf_kfunc_desc *res;
2958 	struct bpf_kfunc_desc_tab *tab;
2959 
2960 	tab = prog->aux->kfunc_tab;
2961 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2962 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2963 
2964 	return res ? &res->func_model : NULL;
2965 }
2966 
2967 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2968 {
2969 	struct bpf_subprog_info *subprog = env->subprog_info;
2970 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2971 	struct bpf_insn *insn = env->prog->insnsi;
2972 
2973 	/* Add entry function. */
2974 	ret = add_subprog(env, 0);
2975 	if (ret)
2976 		return ret;
2977 
2978 	for (i = 0; i < insn_cnt; i++, insn++) {
2979 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2980 		    !bpf_pseudo_kfunc_call(insn))
2981 			continue;
2982 
2983 		if (!env->bpf_capable) {
2984 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2985 			return -EPERM;
2986 		}
2987 
2988 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2989 			ret = add_subprog(env, i + insn->imm + 1);
2990 		else
2991 			ret = add_kfunc_call(env, insn->imm, insn->off);
2992 
2993 		if (ret < 0)
2994 			return ret;
2995 	}
2996 
2997 	ret = bpf_find_exception_callback_insn_off(env);
2998 	if (ret < 0)
2999 		return ret;
3000 	ex_cb_insn = ret;
3001 
3002 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3003 	 * marked using BTF decl tag to serve as the exception callback.
3004 	 */
3005 	if (ex_cb_insn) {
3006 		ret = add_subprog(env, ex_cb_insn);
3007 		if (ret < 0)
3008 			return ret;
3009 		for (i = 1; i < env->subprog_cnt; i++) {
3010 			if (env->subprog_info[i].start != ex_cb_insn)
3011 				continue;
3012 			env->exception_callback_subprog = i;
3013 			mark_subprog_exc_cb(env, i);
3014 			break;
3015 		}
3016 	}
3017 
3018 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3019 	 * logic. 'subprog_cnt' should not be increased.
3020 	 */
3021 	subprog[env->subprog_cnt].start = insn_cnt;
3022 
3023 	if (env->log.level & BPF_LOG_LEVEL2)
3024 		for (i = 0; i < env->subprog_cnt; i++)
3025 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3026 
3027 	return 0;
3028 }
3029 
3030 static int check_subprogs(struct bpf_verifier_env *env)
3031 {
3032 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3033 	struct bpf_subprog_info *subprog = env->subprog_info;
3034 	struct bpf_insn *insn = env->prog->insnsi;
3035 	int insn_cnt = env->prog->len;
3036 
3037 	/* now check that all jumps are within the same subprog */
3038 	subprog_start = subprog[cur_subprog].start;
3039 	subprog_end = subprog[cur_subprog + 1].start;
3040 	for (i = 0; i < insn_cnt; i++) {
3041 		u8 code = insn[i].code;
3042 
3043 		if (code == (BPF_JMP | BPF_CALL) &&
3044 		    insn[i].src_reg == 0 &&
3045 		    insn[i].imm == BPF_FUNC_tail_call) {
3046 			subprog[cur_subprog].has_tail_call = true;
3047 			subprog[cur_subprog].tail_call_reachable = true;
3048 		}
3049 		if (BPF_CLASS(code) == BPF_LD &&
3050 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3051 			subprog[cur_subprog].has_ld_abs = true;
3052 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3053 			goto next;
3054 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3055 			goto next;
3056 		if (code == (BPF_JMP32 | BPF_JA))
3057 			off = i + insn[i].imm + 1;
3058 		else
3059 			off = i + insn[i].off + 1;
3060 		if (off < subprog_start || off >= subprog_end) {
3061 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3062 			return -EINVAL;
3063 		}
3064 next:
3065 		if (i == subprog_end - 1) {
3066 			/* to avoid fall-through from one subprog into another
3067 			 * the last insn of the subprog should be either exit
3068 			 * or unconditional jump back or bpf_throw call
3069 			 */
3070 			if (code != (BPF_JMP | BPF_EXIT) &&
3071 			    code != (BPF_JMP32 | BPF_JA) &&
3072 			    code != (BPF_JMP | BPF_JA)) {
3073 				verbose(env, "last insn is not an exit or jmp\n");
3074 				return -EINVAL;
3075 			}
3076 			subprog_start = subprog_end;
3077 			cur_subprog++;
3078 			if (cur_subprog < env->subprog_cnt)
3079 				subprog_end = subprog[cur_subprog + 1].start;
3080 		}
3081 	}
3082 	return 0;
3083 }
3084 
3085 /* Parentage chain of this register (or stack slot) should take care of all
3086  * issues like callee-saved registers, stack slot allocation time, etc.
3087  */
3088 static int mark_reg_read(struct bpf_verifier_env *env,
3089 			 const struct bpf_reg_state *state,
3090 			 struct bpf_reg_state *parent, u8 flag)
3091 {
3092 	bool writes = parent == state->parent; /* Observe write marks */
3093 	int cnt = 0;
3094 
3095 	while (parent) {
3096 		/* if read wasn't screened by an earlier write ... */
3097 		if (writes && state->live & REG_LIVE_WRITTEN)
3098 			break;
3099 		if (parent->live & REG_LIVE_DONE) {
3100 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3101 				reg_type_str(env, parent->type),
3102 				parent->var_off.value, parent->off);
3103 			return -EFAULT;
3104 		}
3105 		/* The first condition is more likely to be true than the
3106 		 * second, checked it first.
3107 		 */
3108 		if ((parent->live & REG_LIVE_READ) == flag ||
3109 		    parent->live & REG_LIVE_READ64)
3110 			/* The parentage chain never changes and
3111 			 * this parent was already marked as LIVE_READ.
3112 			 * There is no need to keep walking the chain again and
3113 			 * keep re-marking all parents as LIVE_READ.
3114 			 * This case happens when the same register is read
3115 			 * multiple times without writes into it in-between.
3116 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3117 			 * then no need to set the weak REG_LIVE_READ32.
3118 			 */
3119 			break;
3120 		/* ... then we depend on parent's value */
3121 		parent->live |= flag;
3122 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3123 		if (flag == REG_LIVE_READ64)
3124 			parent->live &= ~REG_LIVE_READ32;
3125 		state = parent;
3126 		parent = state->parent;
3127 		writes = true;
3128 		cnt++;
3129 	}
3130 
3131 	if (env->longest_mark_read_walk < cnt)
3132 		env->longest_mark_read_walk = cnt;
3133 	return 0;
3134 }
3135 
3136 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3137 {
3138 	struct bpf_func_state *state = func(env, reg);
3139 	int spi, ret;
3140 
3141 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3142 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3143 	 * check_kfunc_call.
3144 	 */
3145 	if (reg->type == CONST_PTR_TO_DYNPTR)
3146 		return 0;
3147 	spi = dynptr_get_spi(env, reg);
3148 	if (spi < 0)
3149 		return spi;
3150 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3151 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3152 	 * read.
3153 	 */
3154 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3155 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3156 	if (ret)
3157 		return ret;
3158 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3159 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3160 }
3161 
3162 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3163 			  int spi, int nr_slots)
3164 {
3165 	struct bpf_func_state *state = func(env, reg);
3166 	int err, i;
3167 
3168 	for (i = 0; i < nr_slots; i++) {
3169 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3170 
3171 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3172 		if (err)
3173 			return err;
3174 
3175 		mark_stack_slot_scratched(env, spi - i);
3176 	}
3177 
3178 	return 0;
3179 }
3180 
3181 /* This function is supposed to be used by the following 32-bit optimization
3182  * code only. It returns TRUE if the source or destination register operates
3183  * on 64-bit, otherwise return FALSE.
3184  */
3185 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3186 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3187 {
3188 	u8 code, class, op;
3189 
3190 	code = insn->code;
3191 	class = BPF_CLASS(code);
3192 	op = BPF_OP(code);
3193 	if (class == BPF_JMP) {
3194 		/* BPF_EXIT for "main" will reach here. Return TRUE
3195 		 * conservatively.
3196 		 */
3197 		if (op == BPF_EXIT)
3198 			return true;
3199 		if (op == BPF_CALL) {
3200 			/* BPF to BPF call will reach here because of marking
3201 			 * caller saved clobber with DST_OP_NO_MARK for which we
3202 			 * don't care the register def because they are anyway
3203 			 * marked as NOT_INIT already.
3204 			 */
3205 			if (insn->src_reg == BPF_PSEUDO_CALL)
3206 				return false;
3207 			/* Helper call will reach here because of arg type
3208 			 * check, conservatively return TRUE.
3209 			 */
3210 			if (t == SRC_OP)
3211 				return true;
3212 
3213 			return false;
3214 		}
3215 	}
3216 
3217 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3218 		return false;
3219 
3220 	if (class == BPF_ALU64 || class == BPF_JMP ||
3221 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3222 		return true;
3223 
3224 	if (class == BPF_ALU || class == BPF_JMP32)
3225 		return false;
3226 
3227 	if (class == BPF_LDX) {
3228 		if (t != SRC_OP)
3229 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3230 		/* LDX source must be ptr. */
3231 		return true;
3232 	}
3233 
3234 	if (class == BPF_STX) {
3235 		/* BPF_STX (including atomic variants) has multiple source
3236 		 * operands, one of which is a ptr. Check whether the caller is
3237 		 * asking about it.
3238 		 */
3239 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3240 			return true;
3241 		return BPF_SIZE(code) == BPF_DW;
3242 	}
3243 
3244 	if (class == BPF_LD) {
3245 		u8 mode = BPF_MODE(code);
3246 
3247 		/* LD_IMM64 */
3248 		if (mode == BPF_IMM)
3249 			return true;
3250 
3251 		/* Both LD_IND and LD_ABS return 32-bit data. */
3252 		if (t != SRC_OP)
3253 			return  false;
3254 
3255 		/* Implicit ctx ptr. */
3256 		if (regno == BPF_REG_6)
3257 			return true;
3258 
3259 		/* Explicit source could be any width. */
3260 		return true;
3261 	}
3262 
3263 	if (class == BPF_ST)
3264 		/* The only source register for BPF_ST is a ptr. */
3265 		return true;
3266 
3267 	/* Conservatively return true at default. */
3268 	return true;
3269 }
3270 
3271 /* Return the regno defined by the insn, or -1. */
3272 static int insn_def_regno(const struct bpf_insn *insn)
3273 {
3274 	switch (BPF_CLASS(insn->code)) {
3275 	case BPF_JMP:
3276 	case BPF_JMP32:
3277 	case BPF_ST:
3278 		return -1;
3279 	case BPF_STX:
3280 		if ((BPF_MODE(insn->code) == BPF_ATOMIC ||
3281 		     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
3282 		    (insn->imm & BPF_FETCH)) {
3283 			if (insn->imm == BPF_CMPXCHG)
3284 				return BPF_REG_0;
3285 			else
3286 				return insn->src_reg;
3287 		} else {
3288 			return -1;
3289 		}
3290 	default:
3291 		return insn->dst_reg;
3292 	}
3293 }
3294 
3295 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3296 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3297 {
3298 	int dst_reg = insn_def_regno(insn);
3299 
3300 	if (dst_reg == -1)
3301 		return false;
3302 
3303 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3304 }
3305 
3306 static void mark_insn_zext(struct bpf_verifier_env *env,
3307 			   struct bpf_reg_state *reg)
3308 {
3309 	s32 def_idx = reg->subreg_def;
3310 
3311 	if (def_idx == DEF_NOT_SUBREG)
3312 		return;
3313 
3314 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3315 	/* The dst will be zero extended, so won't be sub-register anymore. */
3316 	reg->subreg_def = DEF_NOT_SUBREG;
3317 }
3318 
3319 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3320 			   enum reg_arg_type t)
3321 {
3322 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3323 	struct bpf_reg_state *reg;
3324 	bool rw64;
3325 
3326 	if (regno >= MAX_BPF_REG) {
3327 		verbose(env, "R%d is invalid\n", regno);
3328 		return -EINVAL;
3329 	}
3330 
3331 	mark_reg_scratched(env, regno);
3332 
3333 	reg = &regs[regno];
3334 	rw64 = is_reg64(env, insn, regno, reg, t);
3335 	if (t == SRC_OP) {
3336 		/* check whether register used as source operand can be read */
3337 		if (reg->type == NOT_INIT) {
3338 			verbose(env, "R%d !read_ok\n", regno);
3339 			return -EACCES;
3340 		}
3341 		/* We don't need to worry about FP liveness because it's read-only */
3342 		if (regno == BPF_REG_FP)
3343 			return 0;
3344 
3345 		if (rw64)
3346 			mark_insn_zext(env, reg);
3347 
3348 		return mark_reg_read(env, reg, reg->parent,
3349 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3350 	} else {
3351 		/* check whether register used as dest operand can be written to */
3352 		if (regno == BPF_REG_FP) {
3353 			verbose(env, "frame pointer is read only\n");
3354 			return -EACCES;
3355 		}
3356 		reg->live |= REG_LIVE_WRITTEN;
3357 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3358 		if (t == DST_OP)
3359 			mark_reg_unknown(env, regs, regno);
3360 	}
3361 	return 0;
3362 }
3363 
3364 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3365 			 enum reg_arg_type t)
3366 {
3367 	struct bpf_verifier_state *vstate = env->cur_state;
3368 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3369 
3370 	return __check_reg_arg(env, state->regs, regno, t);
3371 }
3372 
3373 static int insn_stack_access_flags(int frameno, int spi)
3374 {
3375 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3376 }
3377 
3378 static int insn_stack_access_spi(int insn_flags)
3379 {
3380 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3381 }
3382 
3383 static int insn_stack_access_frameno(int insn_flags)
3384 {
3385 	return insn_flags & INSN_F_FRAMENO_MASK;
3386 }
3387 
3388 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3389 {
3390 	env->insn_aux_data[idx].jmp_point = true;
3391 }
3392 
3393 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3394 {
3395 	return env->insn_aux_data[insn_idx].jmp_point;
3396 }
3397 
3398 #define LR_FRAMENO_BITS	3
3399 #define LR_SPI_BITS	6
3400 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3401 #define LR_SIZE_BITS	4
3402 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3403 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3404 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3405 #define LR_SPI_OFF	LR_FRAMENO_BITS
3406 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3407 #define LINKED_REGS_MAX	6
3408 
3409 struct linked_reg {
3410 	u8 frameno;
3411 	union {
3412 		u8 spi;
3413 		u8 regno;
3414 	};
3415 	bool is_reg;
3416 };
3417 
3418 struct linked_regs {
3419 	int cnt;
3420 	struct linked_reg entries[LINKED_REGS_MAX];
3421 };
3422 
3423 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3424 {
3425 	if (s->cnt < LINKED_REGS_MAX)
3426 		return &s->entries[s->cnt++];
3427 
3428 	return NULL;
3429 }
3430 
3431 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3432  * number of elements currently in stack.
3433  * Pack one history entry for linked registers as 10 bits in the following format:
3434  * - 3-bits frameno
3435  * - 6-bits spi_or_reg
3436  * - 1-bit  is_reg
3437  */
3438 static u64 linked_regs_pack(struct linked_regs *s)
3439 {
3440 	u64 val = 0;
3441 	int i;
3442 
3443 	for (i = 0; i < s->cnt; ++i) {
3444 		struct linked_reg *e = &s->entries[i];
3445 		u64 tmp = 0;
3446 
3447 		tmp |= e->frameno;
3448 		tmp |= e->spi << LR_SPI_OFF;
3449 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3450 
3451 		val <<= LR_ENTRY_BITS;
3452 		val |= tmp;
3453 	}
3454 	val <<= LR_SIZE_BITS;
3455 	val |= s->cnt;
3456 	return val;
3457 }
3458 
3459 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3460 {
3461 	int i;
3462 
3463 	s->cnt = val & LR_SIZE_MASK;
3464 	val >>= LR_SIZE_BITS;
3465 
3466 	for (i = 0; i < s->cnt; ++i) {
3467 		struct linked_reg *e = &s->entries[i];
3468 
3469 		e->frameno =  val & LR_FRAMENO_MASK;
3470 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3471 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3472 		val >>= LR_ENTRY_BITS;
3473 	}
3474 }
3475 
3476 /* for any branch, call, exit record the history of jmps in the given state */
3477 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3478 			    int insn_flags, u64 linked_regs)
3479 {
3480 	u32 cnt = cur->jmp_history_cnt;
3481 	struct bpf_jmp_history_entry *p;
3482 	size_t alloc_size;
3483 
3484 	/* combine instruction flags if we already recorded this instruction */
3485 	if (env->cur_hist_ent) {
3486 		/* atomic instructions push insn_flags twice, for READ and
3487 		 * WRITE sides, but they should agree on stack slot
3488 		 */
3489 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3490 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3491 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3492 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3493 		env->cur_hist_ent->flags |= insn_flags;
3494 		WARN_ONCE(env->cur_hist_ent->linked_regs != 0,
3495 			  "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n",
3496 			  env->insn_idx, env->cur_hist_ent->linked_regs);
3497 		env->cur_hist_ent->linked_regs = linked_regs;
3498 		return 0;
3499 	}
3500 
3501 	cnt++;
3502 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3503 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3504 	if (!p)
3505 		return -ENOMEM;
3506 	cur->jmp_history = p;
3507 
3508 	p = &cur->jmp_history[cnt - 1];
3509 	p->idx = env->insn_idx;
3510 	p->prev_idx = env->prev_insn_idx;
3511 	p->flags = insn_flags;
3512 	p->linked_regs = linked_regs;
3513 	cur->jmp_history_cnt = cnt;
3514 	env->cur_hist_ent = p;
3515 
3516 	return 0;
3517 }
3518 
3519 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3520 						        u32 hist_end, int insn_idx)
3521 {
3522 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3523 		return &st->jmp_history[hist_end - 1];
3524 	return NULL;
3525 }
3526 
3527 /* Backtrack one insn at a time. If idx is not at the top of recorded
3528  * history then previous instruction came from straight line execution.
3529  * Return -ENOENT if we exhausted all instructions within given state.
3530  *
3531  * It's legal to have a bit of a looping with the same starting and ending
3532  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3533  * instruction index is the same as state's first_idx doesn't mean we are
3534  * done. If there is still some jump history left, we should keep going. We
3535  * need to take into account that we might have a jump history between given
3536  * state's parent and itself, due to checkpointing. In this case, we'll have
3537  * history entry recording a jump from last instruction of parent state and
3538  * first instruction of given state.
3539  */
3540 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3541 			     u32 *history)
3542 {
3543 	u32 cnt = *history;
3544 
3545 	if (i == st->first_insn_idx) {
3546 		if (cnt == 0)
3547 			return -ENOENT;
3548 		if (cnt == 1 && st->jmp_history[0].idx == i)
3549 			return -ENOENT;
3550 	}
3551 
3552 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3553 		i = st->jmp_history[cnt - 1].prev_idx;
3554 		(*history)--;
3555 	} else {
3556 		i--;
3557 	}
3558 	return i;
3559 }
3560 
3561 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3562 {
3563 	const struct btf_type *func;
3564 	struct btf *desc_btf;
3565 
3566 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3567 		return NULL;
3568 
3569 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3570 	if (IS_ERR(desc_btf))
3571 		return "<error>";
3572 
3573 	func = btf_type_by_id(desc_btf, insn->imm);
3574 	return btf_name_by_offset(desc_btf, func->name_off);
3575 }
3576 
3577 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3578 {
3579 	bt->frame = frame;
3580 }
3581 
3582 static inline void bt_reset(struct backtrack_state *bt)
3583 {
3584 	struct bpf_verifier_env *env = bt->env;
3585 
3586 	memset(bt, 0, sizeof(*bt));
3587 	bt->env = env;
3588 }
3589 
3590 static inline u32 bt_empty(struct backtrack_state *bt)
3591 {
3592 	u64 mask = 0;
3593 	int i;
3594 
3595 	for (i = 0; i <= bt->frame; i++)
3596 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3597 
3598 	return mask == 0;
3599 }
3600 
3601 static inline int bt_subprog_enter(struct backtrack_state *bt)
3602 {
3603 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3604 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3605 		WARN_ONCE(1, "verifier backtracking bug");
3606 		return -EFAULT;
3607 	}
3608 	bt->frame++;
3609 	return 0;
3610 }
3611 
3612 static inline int bt_subprog_exit(struct backtrack_state *bt)
3613 {
3614 	if (bt->frame == 0) {
3615 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3616 		WARN_ONCE(1, "verifier backtracking bug");
3617 		return -EFAULT;
3618 	}
3619 	bt->frame--;
3620 	return 0;
3621 }
3622 
3623 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3624 {
3625 	bt->reg_masks[frame] |= 1 << reg;
3626 }
3627 
3628 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3629 {
3630 	bt->reg_masks[frame] &= ~(1 << reg);
3631 }
3632 
3633 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3634 {
3635 	bt_set_frame_reg(bt, bt->frame, reg);
3636 }
3637 
3638 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3639 {
3640 	bt_clear_frame_reg(bt, bt->frame, reg);
3641 }
3642 
3643 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3644 {
3645 	bt->stack_masks[frame] |= 1ull << slot;
3646 }
3647 
3648 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3649 {
3650 	bt->stack_masks[frame] &= ~(1ull << slot);
3651 }
3652 
3653 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3654 {
3655 	return bt->reg_masks[frame];
3656 }
3657 
3658 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3659 {
3660 	return bt->reg_masks[bt->frame];
3661 }
3662 
3663 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3664 {
3665 	return bt->stack_masks[frame];
3666 }
3667 
3668 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3669 {
3670 	return bt->stack_masks[bt->frame];
3671 }
3672 
3673 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3674 {
3675 	return bt->reg_masks[bt->frame] & (1 << reg);
3676 }
3677 
3678 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
3679 {
3680 	return bt->reg_masks[frame] & (1 << reg);
3681 }
3682 
3683 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3684 {
3685 	return bt->stack_masks[frame] & (1ull << slot);
3686 }
3687 
3688 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3689 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3690 {
3691 	DECLARE_BITMAP(mask, 64);
3692 	bool first = true;
3693 	int i, n;
3694 
3695 	buf[0] = '\0';
3696 
3697 	bitmap_from_u64(mask, reg_mask);
3698 	for_each_set_bit(i, mask, 32) {
3699 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3700 		first = false;
3701 		buf += n;
3702 		buf_sz -= n;
3703 		if (buf_sz < 0)
3704 			break;
3705 	}
3706 }
3707 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3708 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3709 {
3710 	DECLARE_BITMAP(mask, 64);
3711 	bool first = true;
3712 	int i, n;
3713 
3714 	buf[0] = '\0';
3715 
3716 	bitmap_from_u64(mask, stack_mask);
3717 	for_each_set_bit(i, mask, 64) {
3718 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3719 		first = false;
3720 		buf += n;
3721 		buf_sz -= n;
3722 		if (buf_sz < 0)
3723 			break;
3724 	}
3725 }
3726 
3727 /* If any register R in hist->linked_regs is marked as precise in bt,
3728  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3729  */
3730 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3731 {
3732 	struct linked_regs linked_regs;
3733 	bool some_precise = false;
3734 	int i;
3735 
3736 	if (!hist || hist->linked_regs == 0)
3737 		return;
3738 
3739 	linked_regs_unpack(hist->linked_regs, &linked_regs);
3740 	for (i = 0; i < linked_regs.cnt; ++i) {
3741 		struct linked_reg *e = &linked_regs.entries[i];
3742 
3743 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3744 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3745 			some_precise = true;
3746 			break;
3747 		}
3748 	}
3749 
3750 	if (!some_precise)
3751 		return;
3752 
3753 	for (i = 0; i < linked_regs.cnt; ++i) {
3754 		struct linked_reg *e = &linked_regs.entries[i];
3755 
3756 		if (e->is_reg)
3757 			bt_set_frame_reg(bt, e->frameno, e->regno);
3758 		else
3759 			bt_set_frame_slot(bt, e->frameno, e->spi);
3760 	}
3761 }
3762 
3763 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3764 
3765 /* For given verifier state backtrack_insn() is called from the last insn to
3766  * the first insn. Its purpose is to compute a bitmask of registers and
3767  * stack slots that needs precision in the parent verifier state.
3768  *
3769  * @idx is an index of the instruction we are currently processing;
3770  * @subseq_idx is an index of the subsequent instruction that:
3771  *   - *would be* executed next, if jump history is viewed in forward order;
3772  *   - *was* processed previously during backtracking.
3773  */
3774 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3775 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3776 {
3777 	const struct bpf_insn_cbs cbs = {
3778 		.cb_call	= disasm_kfunc_name,
3779 		.cb_print	= verbose,
3780 		.private_data	= env,
3781 	};
3782 	struct bpf_insn *insn = env->prog->insnsi + idx;
3783 	u8 class = BPF_CLASS(insn->code);
3784 	u8 opcode = BPF_OP(insn->code);
3785 	u8 mode = BPF_MODE(insn->code);
3786 	u32 dreg = insn->dst_reg;
3787 	u32 sreg = insn->src_reg;
3788 	u32 spi, i, fr;
3789 
3790 	if (insn->code == 0)
3791 		return 0;
3792 	if (env->log.level & BPF_LOG_LEVEL2) {
3793 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3794 		verbose(env, "mark_precise: frame%d: regs=%s ",
3795 			bt->frame, env->tmp_str_buf);
3796 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3797 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3798 		verbose(env, "%d: ", idx);
3799 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3800 	}
3801 
3802 	/* If there is a history record that some registers gained range at this insn,
3803 	 * propagate precision marks to those registers, so that bt_is_reg_set()
3804 	 * accounts for these registers.
3805 	 */
3806 	bt_sync_linked_regs(bt, hist);
3807 
3808 	if (class == BPF_ALU || class == BPF_ALU64) {
3809 		if (!bt_is_reg_set(bt, dreg))
3810 			return 0;
3811 		if (opcode == BPF_END || opcode == BPF_NEG) {
3812 			/* sreg is reserved and unused
3813 			 * dreg still need precision before this insn
3814 			 */
3815 			return 0;
3816 		} else if (opcode == BPF_MOV) {
3817 			if (BPF_SRC(insn->code) == BPF_X) {
3818 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3819 				 * dreg needs precision after this insn
3820 				 * sreg needs precision before this insn
3821 				 */
3822 				bt_clear_reg(bt, dreg);
3823 				if (sreg != BPF_REG_FP)
3824 					bt_set_reg(bt, sreg);
3825 			} else {
3826 				/* dreg = K
3827 				 * dreg needs precision after this insn.
3828 				 * Corresponding register is already marked
3829 				 * as precise=true in this verifier state.
3830 				 * No further markings in parent are necessary
3831 				 */
3832 				bt_clear_reg(bt, dreg);
3833 			}
3834 		} else {
3835 			if (BPF_SRC(insn->code) == BPF_X) {
3836 				/* dreg += sreg
3837 				 * both dreg and sreg need precision
3838 				 * before this insn
3839 				 */
3840 				if (sreg != BPF_REG_FP)
3841 					bt_set_reg(bt, sreg);
3842 			} /* else dreg += K
3843 			   * dreg still needs precision before this insn
3844 			   */
3845 		}
3846 	} else if (class == BPF_LDX) {
3847 		if (!bt_is_reg_set(bt, dreg))
3848 			return 0;
3849 		bt_clear_reg(bt, dreg);
3850 
3851 		/* scalars can only be spilled into stack w/o losing precision.
3852 		 * Load from any other memory can be zero extended.
3853 		 * The desire to keep that precision is already indicated
3854 		 * by 'precise' mark in corresponding register of this state.
3855 		 * No further tracking necessary.
3856 		 */
3857 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3858 			return 0;
3859 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3860 		 * that [fp - off] slot contains scalar that needs to be
3861 		 * tracked with precision
3862 		 */
3863 		spi = insn_stack_access_spi(hist->flags);
3864 		fr = insn_stack_access_frameno(hist->flags);
3865 		bt_set_frame_slot(bt, fr, spi);
3866 	} else if (class == BPF_STX || class == BPF_ST) {
3867 		if (bt_is_reg_set(bt, dreg))
3868 			/* stx & st shouldn't be using _scalar_ dst_reg
3869 			 * to access memory. It means backtracking
3870 			 * encountered a case of pointer subtraction.
3871 			 */
3872 			return -ENOTSUPP;
3873 		/* scalars can only be spilled into stack */
3874 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3875 			return 0;
3876 		spi = insn_stack_access_spi(hist->flags);
3877 		fr = insn_stack_access_frameno(hist->flags);
3878 		if (!bt_is_frame_slot_set(bt, fr, spi))
3879 			return 0;
3880 		bt_clear_frame_slot(bt, fr, spi);
3881 		if (class == BPF_STX)
3882 			bt_set_reg(bt, sreg);
3883 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3884 		if (bpf_pseudo_call(insn)) {
3885 			int subprog_insn_idx, subprog;
3886 
3887 			subprog_insn_idx = idx + insn->imm + 1;
3888 			subprog = find_subprog(env, subprog_insn_idx);
3889 			if (subprog < 0)
3890 				return -EFAULT;
3891 
3892 			if (subprog_is_global(env, subprog)) {
3893 				/* check that jump history doesn't have any
3894 				 * extra instructions from subprog; the next
3895 				 * instruction after call to global subprog
3896 				 * should be literally next instruction in
3897 				 * caller program
3898 				 */
3899 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3900 				/* r1-r5 are invalidated after subprog call,
3901 				 * so for global func call it shouldn't be set
3902 				 * anymore
3903 				 */
3904 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3905 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3906 					WARN_ONCE(1, "verifier backtracking bug");
3907 					return -EFAULT;
3908 				}
3909 				/* global subprog always sets R0 */
3910 				bt_clear_reg(bt, BPF_REG_0);
3911 				return 0;
3912 			} else {
3913 				/* static subprog call instruction, which
3914 				 * means that we are exiting current subprog,
3915 				 * so only r1-r5 could be still requested as
3916 				 * precise, r0 and r6-r10 or any stack slot in
3917 				 * the current frame should be zero by now
3918 				 */
3919 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3920 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3921 					WARN_ONCE(1, "verifier backtracking bug");
3922 					return -EFAULT;
3923 				}
3924 				/* we are now tracking register spills correctly,
3925 				 * so any instance of leftover slots is a bug
3926 				 */
3927 				if (bt_stack_mask(bt) != 0) {
3928 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3929 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3930 					return -EFAULT;
3931 				}
3932 				/* propagate r1-r5 to the caller */
3933 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3934 					if (bt_is_reg_set(bt, i)) {
3935 						bt_clear_reg(bt, i);
3936 						bt_set_frame_reg(bt, bt->frame - 1, i);
3937 					}
3938 				}
3939 				if (bt_subprog_exit(bt))
3940 					return -EFAULT;
3941 				return 0;
3942 			}
3943 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3944 			/* exit from callback subprog to callback-calling helper or
3945 			 * kfunc call. Use idx/subseq_idx check to discern it from
3946 			 * straight line code backtracking.
3947 			 * Unlike the subprog call handling above, we shouldn't
3948 			 * propagate precision of r1-r5 (if any requested), as they are
3949 			 * not actually arguments passed directly to callback subprogs
3950 			 */
3951 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3952 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3953 				WARN_ONCE(1, "verifier backtracking bug");
3954 				return -EFAULT;
3955 			}
3956 			if (bt_stack_mask(bt) != 0) {
3957 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3958 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3959 				return -EFAULT;
3960 			}
3961 			/* clear r1-r5 in callback subprog's mask */
3962 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3963 				bt_clear_reg(bt, i);
3964 			if (bt_subprog_exit(bt))
3965 				return -EFAULT;
3966 			return 0;
3967 		} else if (opcode == BPF_CALL) {
3968 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3969 			 * catch this error later. Make backtracking conservative
3970 			 * with ENOTSUPP.
3971 			 */
3972 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3973 				return -ENOTSUPP;
3974 			/* regular helper call sets R0 */
3975 			bt_clear_reg(bt, BPF_REG_0);
3976 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3977 				/* if backtracing was looking for registers R1-R5
3978 				 * they should have been found already.
3979 				 */
3980 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3981 				WARN_ONCE(1, "verifier backtracking bug");
3982 				return -EFAULT;
3983 			}
3984 		} else if (opcode == BPF_EXIT) {
3985 			bool r0_precise;
3986 
3987 			/* Backtracking to a nested function call, 'idx' is a part of
3988 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3989 			 * In case of a regular function call, instructions giving
3990 			 * precision to registers R1-R5 should have been found already.
3991 			 * In case of a callback, it is ok to have R1-R5 marked for
3992 			 * backtracking, as these registers are set by the function
3993 			 * invoking callback.
3994 			 */
3995 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3996 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3997 					bt_clear_reg(bt, i);
3998 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3999 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
4000 				WARN_ONCE(1, "verifier backtracking bug");
4001 				return -EFAULT;
4002 			}
4003 
4004 			/* BPF_EXIT in subprog or callback always returns
4005 			 * right after the call instruction, so by checking
4006 			 * whether the instruction at subseq_idx-1 is subprog
4007 			 * call or not we can distinguish actual exit from
4008 			 * *subprog* from exit from *callback*. In the former
4009 			 * case, we need to propagate r0 precision, if
4010 			 * necessary. In the former we never do that.
4011 			 */
4012 			r0_precise = subseq_idx - 1 >= 0 &&
4013 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4014 				     bt_is_reg_set(bt, BPF_REG_0);
4015 
4016 			bt_clear_reg(bt, BPF_REG_0);
4017 			if (bt_subprog_enter(bt))
4018 				return -EFAULT;
4019 
4020 			if (r0_precise)
4021 				bt_set_reg(bt, BPF_REG_0);
4022 			/* r6-r9 and stack slots will stay set in caller frame
4023 			 * bitmasks until we return back from callee(s)
4024 			 */
4025 			return 0;
4026 		} else if (BPF_SRC(insn->code) == BPF_X) {
4027 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4028 				return 0;
4029 			/* dreg <cond> sreg
4030 			 * Both dreg and sreg need precision before
4031 			 * this insn. If only sreg was marked precise
4032 			 * before it would be equally necessary to
4033 			 * propagate it to dreg.
4034 			 */
4035 			bt_set_reg(bt, dreg);
4036 			bt_set_reg(bt, sreg);
4037 		} else if (BPF_SRC(insn->code) == BPF_K) {
4038 			 /* dreg <cond> K
4039 			  * Only dreg still needs precision before
4040 			  * this insn, so for the K-based conditional
4041 			  * there is nothing new to be marked.
4042 			  */
4043 		}
4044 	} else if (class == BPF_LD) {
4045 		if (!bt_is_reg_set(bt, dreg))
4046 			return 0;
4047 		bt_clear_reg(bt, dreg);
4048 		/* It's ld_imm64 or ld_abs or ld_ind.
4049 		 * For ld_imm64 no further tracking of precision
4050 		 * into parent is necessary
4051 		 */
4052 		if (mode == BPF_IND || mode == BPF_ABS)
4053 			/* to be analyzed */
4054 			return -ENOTSUPP;
4055 	}
4056 	/* Propagate precision marks to linked registers, to account for
4057 	 * registers marked as precise in this function.
4058 	 */
4059 	bt_sync_linked_regs(bt, hist);
4060 	return 0;
4061 }
4062 
4063 /* the scalar precision tracking algorithm:
4064  * . at the start all registers have precise=false.
4065  * . scalar ranges are tracked as normal through alu and jmp insns.
4066  * . once precise value of the scalar register is used in:
4067  *   .  ptr + scalar alu
4068  *   . if (scalar cond K|scalar)
4069  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4070  *   backtrack through the verifier states and mark all registers and
4071  *   stack slots with spilled constants that these scalar regisers
4072  *   should be precise.
4073  * . during state pruning two registers (or spilled stack slots)
4074  *   are equivalent if both are not precise.
4075  *
4076  * Note the verifier cannot simply walk register parentage chain,
4077  * since many different registers and stack slots could have been
4078  * used to compute single precise scalar.
4079  *
4080  * The approach of starting with precise=true for all registers and then
4081  * backtrack to mark a register as not precise when the verifier detects
4082  * that program doesn't care about specific value (e.g., when helper
4083  * takes register as ARG_ANYTHING parameter) is not safe.
4084  *
4085  * It's ok to walk single parentage chain of the verifier states.
4086  * It's possible that this backtracking will go all the way till 1st insn.
4087  * All other branches will be explored for needing precision later.
4088  *
4089  * The backtracking needs to deal with cases like:
4090  *   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)
4091  * r9 -= r8
4092  * r5 = r9
4093  * if r5 > 0x79f goto pc+7
4094  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4095  * r5 += 1
4096  * ...
4097  * call bpf_perf_event_output#25
4098  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4099  *
4100  * and this case:
4101  * r6 = 1
4102  * call foo // uses callee's r6 inside to compute r0
4103  * r0 += r6
4104  * if r0 == 0 goto
4105  *
4106  * to track above reg_mask/stack_mask needs to be independent for each frame.
4107  *
4108  * Also if parent's curframe > frame where backtracking started,
4109  * the verifier need to mark registers in both frames, otherwise callees
4110  * may incorrectly prune callers. This is similar to
4111  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4112  *
4113  * For now backtracking falls back into conservative marking.
4114  */
4115 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4116 				     struct bpf_verifier_state *st)
4117 {
4118 	struct bpf_func_state *func;
4119 	struct bpf_reg_state *reg;
4120 	int i, j;
4121 
4122 	if (env->log.level & BPF_LOG_LEVEL2) {
4123 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4124 			st->curframe);
4125 	}
4126 
4127 	/* big hammer: mark all scalars precise in this path.
4128 	 * pop_stack may still get !precise scalars.
4129 	 * We also skip current state and go straight to first parent state,
4130 	 * because precision markings in current non-checkpointed state are
4131 	 * not needed. See why in the comment in __mark_chain_precision below.
4132 	 */
4133 	for (st = st->parent; st; st = st->parent) {
4134 		for (i = 0; i <= st->curframe; i++) {
4135 			func = st->frame[i];
4136 			for (j = 0; j < BPF_REG_FP; j++) {
4137 				reg = &func->regs[j];
4138 				if (reg->type != SCALAR_VALUE || reg->precise)
4139 					continue;
4140 				reg->precise = true;
4141 				if (env->log.level & BPF_LOG_LEVEL2) {
4142 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4143 						i, j);
4144 				}
4145 			}
4146 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4147 				if (!is_spilled_reg(&func->stack[j]))
4148 					continue;
4149 				reg = &func->stack[j].spilled_ptr;
4150 				if (reg->type != SCALAR_VALUE || reg->precise)
4151 					continue;
4152 				reg->precise = true;
4153 				if (env->log.level & BPF_LOG_LEVEL2) {
4154 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4155 						i, -(j + 1) * 8);
4156 				}
4157 			}
4158 		}
4159 	}
4160 }
4161 
4162 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4163 {
4164 	struct bpf_func_state *func;
4165 	struct bpf_reg_state *reg;
4166 	int i, j;
4167 
4168 	for (i = 0; i <= st->curframe; i++) {
4169 		func = st->frame[i];
4170 		for (j = 0; j < BPF_REG_FP; j++) {
4171 			reg = &func->regs[j];
4172 			if (reg->type != SCALAR_VALUE)
4173 				continue;
4174 			reg->precise = false;
4175 		}
4176 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4177 			if (!is_spilled_reg(&func->stack[j]))
4178 				continue;
4179 			reg = &func->stack[j].spilled_ptr;
4180 			if (reg->type != SCALAR_VALUE)
4181 				continue;
4182 			reg->precise = false;
4183 		}
4184 	}
4185 }
4186 
4187 /*
4188  * __mark_chain_precision() backtracks BPF program instruction sequence and
4189  * chain of verifier states making sure that register *regno* (if regno >= 0)
4190  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4191  * SCALARS, as well as any other registers and slots that contribute to
4192  * a tracked state of given registers/stack slots, depending on specific BPF
4193  * assembly instructions (see backtrack_insns() for exact instruction handling
4194  * logic). This backtracking relies on recorded jmp_history and is able to
4195  * traverse entire chain of parent states. This process ends only when all the
4196  * necessary registers/slots and their transitive dependencies are marked as
4197  * precise.
4198  *
4199  * One important and subtle aspect is that precise marks *do not matter* in
4200  * the currently verified state (current state). It is important to understand
4201  * why this is the case.
4202  *
4203  * First, note that current state is the state that is not yet "checkpointed",
4204  * i.e., it is not yet put into env->explored_states, and it has no children
4205  * states as well. It's ephemeral, and can end up either a) being discarded if
4206  * compatible explored state is found at some point or BPF_EXIT instruction is
4207  * reached or b) checkpointed and put into env->explored_states, branching out
4208  * into one or more children states.
4209  *
4210  * In the former case, precise markings in current state are completely
4211  * ignored by state comparison code (see regsafe() for details). Only
4212  * checkpointed ("old") state precise markings are important, and if old
4213  * state's register/slot is precise, regsafe() assumes current state's
4214  * register/slot as precise and checks value ranges exactly and precisely. If
4215  * states turn out to be compatible, current state's necessary precise
4216  * markings and any required parent states' precise markings are enforced
4217  * after the fact with propagate_precision() logic, after the fact. But it's
4218  * important to realize that in this case, even after marking current state
4219  * registers/slots as precise, we immediately discard current state. So what
4220  * actually matters is any of the precise markings propagated into current
4221  * state's parent states, which are always checkpointed (due to b) case above).
4222  * As such, for scenario a) it doesn't matter if current state has precise
4223  * markings set or not.
4224  *
4225  * Now, for the scenario b), checkpointing and forking into child(ren)
4226  * state(s). Note that before current state gets to checkpointing step, any
4227  * processed instruction always assumes precise SCALAR register/slot
4228  * knowledge: if precise value or range is useful to prune jump branch, BPF
4229  * verifier takes this opportunity enthusiastically. Similarly, when
4230  * register's value is used to calculate offset or memory address, exact
4231  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4232  * what we mentioned above about state comparison ignoring precise markings
4233  * during state comparison, BPF verifier ignores and also assumes precise
4234  * markings *at will* during instruction verification process. But as verifier
4235  * assumes precision, it also propagates any precision dependencies across
4236  * parent states, which are not yet finalized, so can be further restricted
4237  * based on new knowledge gained from restrictions enforced by their children
4238  * states. This is so that once those parent states are finalized, i.e., when
4239  * they have no more active children state, state comparison logic in
4240  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4241  * required for correctness.
4242  *
4243  * To build a bit more intuition, note also that once a state is checkpointed,
4244  * the path we took to get to that state is not important. This is crucial
4245  * property for state pruning. When state is checkpointed and finalized at
4246  * some instruction index, it can be correctly and safely used to "short
4247  * circuit" any *compatible* state that reaches exactly the same instruction
4248  * index. I.e., if we jumped to that instruction from a completely different
4249  * code path than original finalized state was derived from, it doesn't
4250  * matter, current state can be discarded because from that instruction
4251  * forward having a compatible state will ensure we will safely reach the
4252  * exit. States describe preconditions for further exploration, but completely
4253  * forget the history of how we got here.
4254  *
4255  * This also means that even if we needed precise SCALAR range to get to
4256  * finalized state, but from that point forward *that same* SCALAR register is
4257  * never used in a precise context (i.e., it's precise value is not needed for
4258  * correctness), it's correct and safe to mark such register as "imprecise"
4259  * (i.e., precise marking set to false). This is what we rely on when we do
4260  * not set precise marking in current state. If no child state requires
4261  * precision for any given SCALAR register, it's safe to dictate that it can
4262  * be imprecise. If any child state does require this register to be precise,
4263  * we'll mark it precise later retroactively during precise markings
4264  * propagation from child state to parent states.
4265  *
4266  * Skipping precise marking setting in current state is a mild version of
4267  * relying on the above observation. But we can utilize this property even
4268  * more aggressively by proactively forgetting any precise marking in the
4269  * current state (which we inherited from the parent state), right before we
4270  * checkpoint it and branch off into new child state. This is done by
4271  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4272  * finalized states which help in short circuiting more future states.
4273  */
4274 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4275 {
4276 	struct backtrack_state *bt = &env->bt;
4277 	struct bpf_verifier_state *st = env->cur_state;
4278 	int first_idx = st->first_insn_idx;
4279 	int last_idx = env->insn_idx;
4280 	int subseq_idx = -1;
4281 	struct bpf_func_state *func;
4282 	struct bpf_reg_state *reg;
4283 	bool skip_first = true;
4284 	int i, fr, err;
4285 
4286 	if (!env->bpf_capable)
4287 		return 0;
4288 
4289 	/* set frame number from which we are starting to backtrack */
4290 	bt_init(bt, env->cur_state->curframe);
4291 
4292 	/* Do sanity checks against current state of register and/or stack
4293 	 * slot, but don't set precise flag in current state, as precision
4294 	 * tracking in the current state is unnecessary.
4295 	 */
4296 	func = st->frame[bt->frame];
4297 	if (regno >= 0) {
4298 		reg = &func->regs[regno];
4299 		if (reg->type != SCALAR_VALUE) {
4300 			WARN_ONCE(1, "backtracing misuse");
4301 			return -EFAULT;
4302 		}
4303 		bt_set_reg(bt, regno);
4304 	}
4305 
4306 	if (bt_empty(bt))
4307 		return 0;
4308 
4309 	for (;;) {
4310 		DECLARE_BITMAP(mask, 64);
4311 		u32 history = st->jmp_history_cnt;
4312 		struct bpf_jmp_history_entry *hist;
4313 
4314 		if (env->log.level & BPF_LOG_LEVEL2) {
4315 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4316 				bt->frame, last_idx, first_idx, subseq_idx);
4317 		}
4318 
4319 		if (last_idx < 0) {
4320 			/* we are at the entry into subprog, which
4321 			 * is expected for global funcs, but only if
4322 			 * requested precise registers are R1-R5
4323 			 * (which are global func's input arguments)
4324 			 */
4325 			if (st->curframe == 0 &&
4326 			    st->frame[0]->subprogno > 0 &&
4327 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4328 			    bt_stack_mask(bt) == 0 &&
4329 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4330 				bitmap_from_u64(mask, bt_reg_mask(bt));
4331 				for_each_set_bit(i, mask, 32) {
4332 					reg = &st->frame[0]->regs[i];
4333 					bt_clear_reg(bt, i);
4334 					if (reg->type == SCALAR_VALUE)
4335 						reg->precise = true;
4336 				}
4337 				return 0;
4338 			}
4339 
4340 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4341 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4342 			WARN_ONCE(1, "verifier backtracking bug");
4343 			return -EFAULT;
4344 		}
4345 
4346 		for (i = last_idx;;) {
4347 			if (skip_first) {
4348 				err = 0;
4349 				skip_first = false;
4350 			} else {
4351 				hist = get_jmp_hist_entry(st, history, i);
4352 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4353 			}
4354 			if (err == -ENOTSUPP) {
4355 				mark_all_scalars_precise(env, env->cur_state);
4356 				bt_reset(bt);
4357 				return 0;
4358 			} else if (err) {
4359 				return err;
4360 			}
4361 			if (bt_empty(bt))
4362 				/* Found assignment(s) into tracked register in this state.
4363 				 * Since this state is already marked, just return.
4364 				 * Nothing to be tracked further in the parent state.
4365 				 */
4366 				return 0;
4367 			subseq_idx = i;
4368 			i = get_prev_insn_idx(st, i, &history);
4369 			if (i == -ENOENT)
4370 				break;
4371 			if (i >= env->prog->len) {
4372 				/* This can happen if backtracking reached insn 0
4373 				 * and there are still reg_mask or stack_mask
4374 				 * to backtrack.
4375 				 * It means the backtracking missed the spot where
4376 				 * particular register was initialized with a constant.
4377 				 */
4378 				verbose(env, "BUG backtracking idx %d\n", i);
4379 				WARN_ONCE(1, "verifier backtracking bug");
4380 				return -EFAULT;
4381 			}
4382 		}
4383 		st = st->parent;
4384 		if (!st)
4385 			break;
4386 
4387 		for (fr = bt->frame; fr >= 0; fr--) {
4388 			func = st->frame[fr];
4389 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4390 			for_each_set_bit(i, mask, 32) {
4391 				reg = &func->regs[i];
4392 				if (reg->type != SCALAR_VALUE) {
4393 					bt_clear_frame_reg(bt, fr, i);
4394 					continue;
4395 				}
4396 				if (reg->precise)
4397 					bt_clear_frame_reg(bt, fr, i);
4398 				else
4399 					reg->precise = true;
4400 			}
4401 
4402 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4403 			for_each_set_bit(i, mask, 64) {
4404 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4405 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4406 						i, func->allocated_stack / BPF_REG_SIZE);
4407 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4408 					return -EFAULT;
4409 				}
4410 
4411 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4412 					bt_clear_frame_slot(bt, fr, i);
4413 					continue;
4414 				}
4415 				reg = &func->stack[i].spilled_ptr;
4416 				if (reg->precise)
4417 					bt_clear_frame_slot(bt, fr, i);
4418 				else
4419 					reg->precise = true;
4420 			}
4421 			if (env->log.level & BPF_LOG_LEVEL2) {
4422 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4423 					     bt_frame_reg_mask(bt, fr));
4424 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4425 					fr, env->tmp_str_buf);
4426 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4427 					       bt_frame_stack_mask(bt, fr));
4428 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4429 				print_verifier_state(env, func, true);
4430 			}
4431 		}
4432 
4433 		if (bt_empty(bt))
4434 			return 0;
4435 
4436 		subseq_idx = first_idx;
4437 		last_idx = st->last_insn_idx;
4438 		first_idx = st->first_insn_idx;
4439 	}
4440 
4441 	/* if we still have requested precise regs or slots, we missed
4442 	 * something (e.g., stack access through non-r10 register), so
4443 	 * fallback to marking all precise
4444 	 */
4445 	if (!bt_empty(bt)) {
4446 		mark_all_scalars_precise(env, env->cur_state);
4447 		bt_reset(bt);
4448 	}
4449 
4450 	return 0;
4451 }
4452 
4453 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4454 {
4455 	return __mark_chain_precision(env, regno);
4456 }
4457 
4458 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4459  * desired reg and stack masks across all relevant frames
4460  */
4461 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4462 {
4463 	return __mark_chain_precision(env, -1);
4464 }
4465 
4466 static bool is_spillable_regtype(enum bpf_reg_type type)
4467 {
4468 	switch (base_type(type)) {
4469 	case PTR_TO_MAP_VALUE:
4470 	case PTR_TO_STACK:
4471 	case PTR_TO_CTX:
4472 	case PTR_TO_PACKET:
4473 	case PTR_TO_PACKET_META:
4474 	case PTR_TO_PACKET_END:
4475 	case PTR_TO_FLOW_KEYS:
4476 	case CONST_PTR_TO_MAP:
4477 	case PTR_TO_SOCKET:
4478 	case PTR_TO_SOCK_COMMON:
4479 	case PTR_TO_TCP_SOCK:
4480 	case PTR_TO_XDP_SOCK:
4481 	case PTR_TO_BTF_ID:
4482 	case PTR_TO_BUF:
4483 	case PTR_TO_MEM:
4484 	case PTR_TO_FUNC:
4485 	case PTR_TO_MAP_KEY:
4486 	case PTR_TO_ARENA:
4487 		return true;
4488 	default:
4489 		return false;
4490 	}
4491 }
4492 
4493 /* Does this register contain a constant zero? */
4494 static bool register_is_null(struct bpf_reg_state *reg)
4495 {
4496 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4497 }
4498 
4499 /* check if register is a constant scalar value */
4500 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4501 {
4502 	return reg->type == SCALAR_VALUE &&
4503 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4504 }
4505 
4506 /* assuming is_reg_const() is true, return constant value of a register */
4507 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4508 {
4509 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4510 }
4511 
4512 static bool __is_pointer_value(bool allow_ptr_leaks,
4513 			       const struct bpf_reg_state *reg)
4514 {
4515 	if (allow_ptr_leaks)
4516 		return false;
4517 
4518 	return reg->type != SCALAR_VALUE;
4519 }
4520 
4521 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4522 					struct bpf_reg_state *src_reg)
4523 {
4524 	if (src_reg->type != SCALAR_VALUE)
4525 		return;
4526 
4527 	if (src_reg->id & BPF_ADD_CONST) {
4528 		/*
4529 		 * The verifier is processing rX = rY insn and
4530 		 * rY->id has special linked register already.
4531 		 * Cleared it, since multiple rX += const are not supported.
4532 		 */
4533 		src_reg->id = 0;
4534 		src_reg->off = 0;
4535 	}
4536 
4537 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4538 		/* Ensure that src_reg has a valid ID that will be copied to
4539 		 * dst_reg and then will be used by sync_linked_regs() to
4540 		 * propagate min/max range.
4541 		 */
4542 		src_reg->id = ++env->id_gen;
4543 }
4544 
4545 /* Copy src state preserving dst->parent and dst->live fields */
4546 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4547 {
4548 	struct bpf_reg_state *parent = dst->parent;
4549 	enum bpf_reg_liveness live = dst->live;
4550 
4551 	*dst = *src;
4552 	dst->parent = parent;
4553 	dst->live = live;
4554 }
4555 
4556 static void save_register_state(struct bpf_verifier_env *env,
4557 				struct bpf_func_state *state,
4558 				int spi, struct bpf_reg_state *reg,
4559 				int size)
4560 {
4561 	int i;
4562 
4563 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4564 	if (size == BPF_REG_SIZE)
4565 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4566 
4567 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4568 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4569 
4570 	/* size < 8 bytes spill */
4571 	for (; i; i--)
4572 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4573 }
4574 
4575 static bool is_bpf_st_mem(struct bpf_insn *insn)
4576 {
4577 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4578 }
4579 
4580 static int get_reg_width(struct bpf_reg_state *reg)
4581 {
4582 	return fls64(reg->umax_value);
4583 }
4584 
4585 /* See comment for mark_fastcall_pattern_for_call() */
4586 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
4587 					  struct bpf_func_state *state, int insn_idx, int off)
4588 {
4589 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4590 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
4591 	int i;
4592 
4593 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
4594 		return;
4595 	/* access to the region [max_stack_depth .. fastcall_stack_off)
4596 	 * from something that is not a part of the fastcall pattern,
4597 	 * disable fastcall rewrites for current subprogram by setting
4598 	 * fastcall_stack_off to a value smaller than any possible offset.
4599 	 */
4600 	subprog->fastcall_stack_off = S16_MIN;
4601 	/* reset fastcall aux flags within subprogram,
4602 	 * happens at most once per subprogram
4603 	 */
4604 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
4605 		aux[i].fastcall_spills_num = 0;
4606 		aux[i].fastcall_pattern = 0;
4607 	}
4608 }
4609 
4610 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4611  * stack boundary and alignment are checked in check_mem_access()
4612  */
4613 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4614 				       /* stack frame we're writing to */
4615 				       struct bpf_func_state *state,
4616 				       int off, int size, int value_regno,
4617 				       int insn_idx)
4618 {
4619 	struct bpf_func_state *cur; /* state of the current function */
4620 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4621 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4622 	struct bpf_reg_state *reg = NULL;
4623 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4624 
4625 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4626 	 * so it's aligned access and [off, off + size) are within stack limits
4627 	 */
4628 	if (!env->allow_ptr_leaks &&
4629 	    is_spilled_reg(&state->stack[spi]) &&
4630 	    size != BPF_REG_SIZE) {
4631 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4632 		return -EACCES;
4633 	}
4634 
4635 	cur = env->cur_state->frame[env->cur_state->curframe];
4636 	if (value_regno >= 0)
4637 		reg = &cur->regs[value_regno];
4638 	if (!env->bypass_spec_v4) {
4639 		bool sanitize = reg && is_spillable_regtype(reg->type);
4640 
4641 		for (i = 0; i < size; i++) {
4642 			u8 type = state->stack[spi].slot_type[i];
4643 
4644 			if (type != STACK_MISC && type != STACK_ZERO) {
4645 				sanitize = true;
4646 				break;
4647 			}
4648 		}
4649 
4650 		if (sanitize)
4651 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4652 	}
4653 
4654 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4655 	if (err)
4656 		return err;
4657 
4658 	check_fastcall_stack_contract(env, state, insn_idx, off);
4659 	mark_stack_slot_scratched(env, spi);
4660 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4661 		bool reg_value_fits;
4662 
4663 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4664 		/* Make sure that reg had an ID to build a relation on spill. */
4665 		if (reg_value_fits)
4666 			assign_scalar_id_before_mov(env, reg);
4667 		save_register_state(env, state, spi, reg, size);
4668 		/* Break the relation on a narrowing spill. */
4669 		if (!reg_value_fits)
4670 			state->stack[spi].spilled_ptr.id = 0;
4671 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4672 		   env->bpf_capable) {
4673 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
4674 
4675 		memset(tmp_reg, 0, sizeof(*tmp_reg));
4676 		__mark_reg_known(tmp_reg, insn->imm);
4677 		tmp_reg->type = SCALAR_VALUE;
4678 		save_register_state(env, state, spi, tmp_reg, size);
4679 	} else if (reg && is_spillable_regtype(reg->type)) {
4680 		/* register containing pointer is being spilled into stack */
4681 		if (size != BPF_REG_SIZE) {
4682 			verbose_linfo(env, insn_idx, "; ");
4683 			verbose(env, "invalid size of register spill\n");
4684 			return -EACCES;
4685 		}
4686 		if (state != cur && reg->type == PTR_TO_STACK) {
4687 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4688 			return -EINVAL;
4689 		}
4690 		save_register_state(env, state, spi, reg, size);
4691 	} else {
4692 		u8 type = STACK_MISC;
4693 
4694 		/* regular write of data into stack destroys any spilled ptr */
4695 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4696 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4697 		if (is_stack_slot_special(&state->stack[spi]))
4698 			for (i = 0; i < BPF_REG_SIZE; i++)
4699 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4700 
4701 		/* only mark the slot as written if all 8 bytes were written
4702 		 * otherwise read propagation may incorrectly stop too soon
4703 		 * when stack slots are partially written.
4704 		 * This heuristic means that read propagation will be
4705 		 * conservative, since it will add reg_live_read marks
4706 		 * to stack slots all the way to first state when programs
4707 		 * writes+reads less than 8 bytes
4708 		 */
4709 		if (size == BPF_REG_SIZE)
4710 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4711 
4712 		/* when we zero initialize stack slots mark them as such */
4713 		if ((reg && register_is_null(reg)) ||
4714 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4715 			/* STACK_ZERO case happened because register spill
4716 			 * wasn't properly aligned at the stack slot boundary,
4717 			 * so it's not a register spill anymore; force
4718 			 * originating register to be precise to make
4719 			 * STACK_ZERO correct for subsequent states
4720 			 */
4721 			err = mark_chain_precision(env, value_regno);
4722 			if (err)
4723 				return err;
4724 			type = STACK_ZERO;
4725 		}
4726 
4727 		/* Mark slots affected by this stack write. */
4728 		for (i = 0; i < size; i++)
4729 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4730 		insn_flags = 0; /* not a register spill */
4731 	}
4732 
4733 	if (insn_flags)
4734 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
4735 	return 0;
4736 }
4737 
4738 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4739  * known to contain a variable offset.
4740  * This function checks whether the write is permitted and conservatively
4741  * tracks the effects of the write, considering that each stack slot in the
4742  * dynamic range is potentially written to.
4743  *
4744  * 'off' includes 'regno->off'.
4745  * 'value_regno' can be -1, meaning that an unknown value is being written to
4746  * the stack.
4747  *
4748  * Spilled pointers in range are not marked as written because we don't know
4749  * what's going to be actually written. This means that read propagation for
4750  * future reads cannot be terminated by this write.
4751  *
4752  * For privileged programs, uninitialized stack slots are considered
4753  * initialized by this write (even though we don't know exactly what offsets
4754  * are going to be written to). The idea is that we don't want the verifier to
4755  * reject future reads that access slots written to through variable offsets.
4756  */
4757 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4758 				     /* func where register points to */
4759 				     struct bpf_func_state *state,
4760 				     int ptr_regno, int off, int size,
4761 				     int value_regno, int insn_idx)
4762 {
4763 	struct bpf_func_state *cur; /* state of the current function */
4764 	int min_off, max_off;
4765 	int i, err;
4766 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4767 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4768 	bool writing_zero = false;
4769 	/* set if the fact that we're writing a zero is used to let any
4770 	 * stack slots remain STACK_ZERO
4771 	 */
4772 	bool zero_used = false;
4773 
4774 	cur = env->cur_state->frame[env->cur_state->curframe];
4775 	ptr_reg = &cur->regs[ptr_regno];
4776 	min_off = ptr_reg->smin_value + off;
4777 	max_off = ptr_reg->smax_value + off + size;
4778 	if (value_regno >= 0)
4779 		value_reg = &cur->regs[value_regno];
4780 	if ((value_reg && register_is_null(value_reg)) ||
4781 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4782 		writing_zero = true;
4783 
4784 	for (i = min_off; i < max_off; i++) {
4785 		int spi;
4786 
4787 		spi = __get_spi(i);
4788 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4789 		if (err)
4790 			return err;
4791 	}
4792 
4793 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
4794 	/* Variable offset writes destroy any spilled pointers in range. */
4795 	for (i = min_off; i < max_off; i++) {
4796 		u8 new_type, *stype;
4797 		int slot, spi;
4798 
4799 		slot = -i - 1;
4800 		spi = slot / BPF_REG_SIZE;
4801 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4802 		mark_stack_slot_scratched(env, spi);
4803 
4804 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4805 			/* Reject the write if range we may write to has not
4806 			 * been initialized beforehand. If we didn't reject
4807 			 * here, the ptr status would be erased below (even
4808 			 * though not all slots are actually overwritten),
4809 			 * possibly opening the door to leaks.
4810 			 *
4811 			 * We do however catch STACK_INVALID case below, and
4812 			 * only allow reading possibly uninitialized memory
4813 			 * later for CAP_PERFMON, as the write may not happen to
4814 			 * that slot.
4815 			 */
4816 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4817 				insn_idx, i);
4818 			return -EINVAL;
4819 		}
4820 
4821 		/* If writing_zero and the spi slot contains a spill of value 0,
4822 		 * maintain the spill type.
4823 		 */
4824 		if (writing_zero && *stype == STACK_SPILL &&
4825 		    is_spilled_scalar_reg(&state->stack[spi])) {
4826 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4827 
4828 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4829 				zero_used = true;
4830 				continue;
4831 			}
4832 		}
4833 
4834 		/* Erase all other spilled pointers. */
4835 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4836 
4837 		/* Update the slot type. */
4838 		new_type = STACK_MISC;
4839 		if (writing_zero && *stype == STACK_ZERO) {
4840 			new_type = STACK_ZERO;
4841 			zero_used = true;
4842 		}
4843 		/* If the slot is STACK_INVALID, we check whether it's OK to
4844 		 * pretend that it will be initialized by this write. The slot
4845 		 * might not actually be written to, and so if we mark it as
4846 		 * initialized future reads might leak uninitialized memory.
4847 		 * For privileged programs, we will accept such reads to slots
4848 		 * that may or may not be written because, if we're reject
4849 		 * them, the error would be too confusing.
4850 		 */
4851 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4852 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4853 					insn_idx, i);
4854 			return -EINVAL;
4855 		}
4856 		*stype = new_type;
4857 	}
4858 	if (zero_used) {
4859 		/* backtracking doesn't work for STACK_ZERO yet. */
4860 		err = mark_chain_precision(env, value_regno);
4861 		if (err)
4862 			return err;
4863 	}
4864 	return 0;
4865 }
4866 
4867 /* When register 'dst_regno' is assigned some values from stack[min_off,
4868  * max_off), we set the register's type according to the types of the
4869  * respective stack slots. If all the stack values are known to be zeros, then
4870  * so is the destination reg. Otherwise, the register is considered to be
4871  * SCALAR. This function does not deal with register filling; the caller must
4872  * ensure that all spilled registers in the stack range have been marked as
4873  * read.
4874  */
4875 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4876 				/* func where src register points to */
4877 				struct bpf_func_state *ptr_state,
4878 				int min_off, int max_off, int dst_regno)
4879 {
4880 	struct bpf_verifier_state *vstate = env->cur_state;
4881 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4882 	int i, slot, spi;
4883 	u8 *stype;
4884 	int zeros = 0;
4885 
4886 	for (i = min_off; i < max_off; i++) {
4887 		slot = -i - 1;
4888 		spi = slot / BPF_REG_SIZE;
4889 		mark_stack_slot_scratched(env, spi);
4890 		stype = ptr_state->stack[spi].slot_type;
4891 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4892 			break;
4893 		zeros++;
4894 	}
4895 	if (zeros == max_off - min_off) {
4896 		/* Any access_size read into register is zero extended,
4897 		 * so the whole register == const_zero.
4898 		 */
4899 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4900 	} else {
4901 		/* have read misc data from the stack */
4902 		mark_reg_unknown(env, state->regs, dst_regno);
4903 	}
4904 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4905 }
4906 
4907 /* Read the stack at 'off' and put the results into the register indicated by
4908  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4909  * spilled reg.
4910  *
4911  * 'dst_regno' can be -1, meaning that the read value is not going to a
4912  * register.
4913  *
4914  * The access is assumed to be within the current stack bounds.
4915  */
4916 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4917 				      /* func where src register points to */
4918 				      struct bpf_func_state *reg_state,
4919 				      int off, int size, int dst_regno)
4920 {
4921 	struct bpf_verifier_state *vstate = env->cur_state;
4922 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4923 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4924 	struct bpf_reg_state *reg;
4925 	u8 *stype, type;
4926 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4927 
4928 	stype = reg_state->stack[spi].slot_type;
4929 	reg = &reg_state->stack[spi].spilled_ptr;
4930 
4931 	mark_stack_slot_scratched(env, spi);
4932 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
4933 
4934 	if (is_spilled_reg(&reg_state->stack[spi])) {
4935 		u8 spill_size = 1;
4936 
4937 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4938 			spill_size++;
4939 
4940 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4941 			if (reg->type != SCALAR_VALUE) {
4942 				verbose_linfo(env, env->insn_idx, "; ");
4943 				verbose(env, "invalid size of register fill\n");
4944 				return -EACCES;
4945 			}
4946 
4947 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4948 			if (dst_regno < 0)
4949 				return 0;
4950 
4951 			if (size <= spill_size &&
4952 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4953 				/* The earlier check_reg_arg() has decided the
4954 				 * subreg_def for this insn.  Save it first.
4955 				 */
4956 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4957 
4958 				copy_register_state(&state->regs[dst_regno], reg);
4959 				state->regs[dst_regno].subreg_def = subreg_def;
4960 
4961 				/* Break the relation on a narrowing fill.
4962 				 * coerce_reg_to_size will adjust the boundaries.
4963 				 */
4964 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4965 					state->regs[dst_regno].id = 0;
4966 			} else {
4967 				int spill_cnt = 0, zero_cnt = 0;
4968 
4969 				for (i = 0; i < size; i++) {
4970 					type = stype[(slot - i) % BPF_REG_SIZE];
4971 					if (type == STACK_SPILL) {
4972 						spill_cnt++;
4973 						continue;
4974 					}
4975 					if (type == STACK_MISC)
4976 						continue;
4977 					if (type == STACK_ZERO) {
4978 						zero_cnt++;
4979 						continue;
4980 					}
4981 					if (type == STACK_INVALID && env->allow_uninit_stack)
4982 						continue;
4983 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4984 						off, i, size);
4985 					return -EACCES;
4986 				}
4987 
4988 				if (spill_cnt == size &&
4989 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4990 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4991 					/* this IS register fill, so keep insn_flags */
4992 				} else if (zero_cnt == size) {
4993 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4994 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4995 					insn_flags = 0; /* not restoring original register state */
4996 				} else {
4997 					mark_reg_unknown(env, state->regs, dst_regno);
4998 					insn_flags = 0; /* not restoring original register state */
4999 				}
5000 			}
5001 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5002 		} else if (dst_regno >= 0) {
5003 			/* restore register state from stack */
5004 			copy_register_state(&state->regs[dst_regno], reg);
5005 			/* mark reg as written since spilled pointer state likely
5006 			 * has its liveness marks cleared by is_state_visited()
5007 			 * which resets stack/reg liveness for state transitions
5008 			 */
5009 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5010 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5011 			/* If dst_regno==-1, the caller is asking us whether
5012 			 * it is acceptable to use this value as a SCALAR_VALUE
5013 			 * (e.g. for XADD).
5014 			 * We must not allow unprivileged callers to do that
5015 			 * with spilled pointers.
5016 			 */
5017 			verbose(env, "leaking pointer from stack off %d\n",
5018 				off);
5019 			return -EACCES;
5020 		}
5021 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5022 	} else {
5023 		for (i = 0; i < size; i++) {
5024 			type = stype[(slot - i) % BPF_REG_SIZE];
5025 			if (type == STACK_MISC)
5026 				continue;
5027 			if (type == STACK_ZERO)
5028 				continue;
5029 			if (type == STACK_INVALID && env->allow_uninit_stack)
5030 				continue;
5031 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5032 				off, i, size);
5033 			return -EACCES;
5034 		}
5035 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5036 		if (dst_regno >= 0)
5037 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5038 		insn_flags = 0; /* we are not restoring spilled register */
5039 	}
5040 	if (insn_flags)
5041 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5042 	return 0;
5043 }
5044 
5045 enum bpf_access_src {
5046 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5047 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5048 };
5049 
5050 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5051 					 int regno, int off, int access_size,
5052 					 bool zero_size_allowed,
5053 					 enum bpf_access_src type,
5054 					 struct bpf_call_arg_meta *meta);
5055 
5056 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5057 {
5058 	return cur_regs(env) + regno;
5059 }
5060 
5061 /* Read the stack at 'ptr_regno + off' and put the result into the register
5062  * 'dst_regno'.
5063  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5064  * but not its variable offset.
5065  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5066  *
5067  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5068  * filling registers (i.e. reads of spilled register cannot be detected when
5069  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5070  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5071  * offset; for a fixed offset check_stack_read_fixed_off should be used
5072  * instead.
5073  */
5074 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5075 				    int ptr_regno, int off, int size, int dst_regno)
5076 {
5077 	/* The state of the source register. */
5078 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5079 	struct bpf_func_state *ptr_state = func(env, reg);
5080 	int err;
5081 	int min_off, max_off;
5082 
5083 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5084 	 */
5085 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5086 					    false, ACCESS_DIRECT, NULL);
5087 	if (err)
5088 		return err;
5089 
5090 	min_off = reg->smin_value + off;
5091 	max_off = reg->smax_value + off;
5092 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5093 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5094 	return 0;
5095 }
5096 
5097 /* check_stack_read dispatches to check_stack_read_fixed_off or
5098  * check_stack_read_var_off.
5099  *
5100  * The caller must ensure that the offset falls within the allocated stack
5101  * bounds.
5102  *
5103  * 'dst_regno' is a register which will receive the value from the stack. It
5104  * can be -1, meaning that the read value is not going to a register.
5105  */
5106 static int check_stack_read(struct bpf_verifier_env *env,
5107 			    int ptr_regno, int off, int size,
5108 			    int dst_regno)
5109 {
5110 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5111 	struct bpf_func_state *state = func(env, reg);
5112 	int err;
5113 	/* Some accesses are only permitted with a static offset. */
5114 	bool var_off = !tnum_is_const(reg->var_off);
5115 
5116 	/* The offset is required to be static when reads don't go to a
5117 	 * register, in order to not leak pointers (see
5118 	 * check_stack_read_fixed_off).
5119 	 */
5120 	if (dst_regno < 0 && var_off) {
5121 		char tn_buf[48];
5122 
5123 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5124 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5125 			tn_buf, off, size);
5126 		return -EACCES;
5127 	}
5128 	/* Variable offset is prohibited for unprivileged mode for simplicity
5129 	 * since it requires corresponding support in Spectre masking for stack
5130 	 * ALU. See also retrieve_ptr_limit(). The check in
5131 	 * check_stack_access_for_ptr_arithmetic() called by
5132 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5133 	 * with variable offsets, therefore no check is required here. Further,
5134 	 * just checking it here would be insufficient as speculative stack
5135 	 * writes could still lead to unsafe speculative behaviour.
5136 	 */
5137 	if (!var_off) {
5138 		off += reg->var_off.value;
5139 		err = check_stack_read_fixed_off(env, state, off, size,
5140 						 dst_regno);
5141 	} else {
5142 		/* Variable offset stack reads need more conservative handling
5143 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5144 		 * branch.
5145 		 */
5146 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5147 					       dst_regno);
5148 	}
5149 	return err;
5150 }
5151 
5152 
5153 /* check_stack_write dispatches to check_stack_write_fixed_off or
5154  * check_stack_write_var_off.
5155  *
5156  * 'ptr_regno' is the register used as a pointer into the stack.
5157  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5158  * 'value_regno' is the register whose value we're writing to the stack. It can
5159  * be -1, meaning that we're not writing from a register.
5160  *
5161  * The caller must ensure that the offset falls within the maximum stack size.
5162  */
5163 static int check_stack_write(struct bpf_verifier_env *env,
5164 			     int ptr_regno, int off, int size,
5165 			     int value_regno, int insn_idx)
5166 {
5167 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5168 	struct bpf_func_state *state = func(env, reg);
5169 	int err;
5170 
5171 	if (tnum_is_const(reg->var_off)) {
5172 		off += reg->var_off.value;
5173 		err = check_stack_write_fixed_off(env, state, off, size,
5174 						  value_regno, insn_idx);
5175 	} else {
5176 		/* Variable offset stack reads need more conservative handling
5177 		 * than fixed offset ones.
5178 		 */
5179 		err = check_stack_write_var_off(env, state,
5180 						ptr_regno, off, size,
5181 						value_regno, insn_idx);
5182 	}
5183 	return err;
5184 }
5185 
5186 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5187 				 int off, int size, enum bpf_access_type type)
5188 {
5189 	struct bpf_reg_state *regs = cur_regs(env);
5190 	struct bpf_map *map = regs[regno].map_ptr;
5191 	u32 cap = bpf_map_flags_to_cap(map);
5192 
5193 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5194 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5195 			map->value_size, off, size);
5196 		return -EACCES;
5197 	}
5198 
5199 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5200 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5201 			map->value_size, off, size);
5202 		return -EACCES;
5203 	}
5204 
5205 	return 0;
5206 }
5207 
5208 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5209 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5210 			      int off, int size, u32 mem_size,
5211 			      bool zero_size_allowed)
5212 {
5213 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5214 	struct bpf_reg_state *reg;
5215 
5216 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5217 		return 0;
5218 
5219 	reg = &cur_regs(env)[regno];
5220 	switch (reg->type) {
5221 	case PTR_TO_MAP_KEY:
5222 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5223 			mem_size, off, size);
5224 		break;
5225 	case PTR_TO_MAP_VALUE:
5226 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5227 			mem_size, off, size);
5228 		break;
5229 	case PTR_TO_PACKET:
5230 	case PTR_TO_PACKET_META:
5231 	case PTR_TO_PACKET_END:
5232 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5233 			off, size, regno, reg->id, off, mem_size);
5234 		break;
5235 	case PTR_TO_MEM:
5236 	default:
5237 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5238 			mem_size, off, size);
5239 	}
5240 
5241 	return -EACCES;
5242 }
5243 
5244 /* check read/write into a memory region with possible variable offset */
5245 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5246 				   int off, int size, u32 mem_size,
5247 				   bool zero_size_allowed)
5248 {
5249 	struct bpf_verifier_state *vstate = env->cur_state;
5250 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5251 	struct bpf_reg_state *reg = &state->regs[regno];
5252 	int err;
5253 
5254 	/* We may have adjusted the register pointing to memory region, so we
5255 	 * need to try adding each of min_value and max_value to off
5256 	 * to make sure our theoretical access will be safe.
5257 	 *
5258 	 * The minimum value is only important with signed
5259 	 * comparisons where we can't assume the floor of a
5260 	 * value is 0.  If we are using signed variables for our
5261 	 * index'es we need to make sure that whatever we use
5262 	 * will have a set floor within our range.
5263 	 */
5264 	if (reg->smin_value < 0 &&
5265 	    (reg->smin_value == S64_MIN ||
5266 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5267 	      reg->smin_value + off < 0)) {
5268 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5269 			regno);
5270 		return -EACCES;
5271 	}
5272 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5273 				 mem_size, zero_size_allowed);
5274 	if (err) {
5275 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5276 			regno);
5277 		return err;
5278 	}
5279 
5280 	/* If we haven't set a max value then we need to bail since we can't be
5281 	 * sure we won't do bad things.
5282 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5283 	 */
5284 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5285 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5286 			regno);
5287 		return -EACCES;
5288 	}
5289 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5290 				 mem_size, zero_size_allowed);
5291 	if (err) {
5292 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5293 			regno);
5294 		return err;
5295 	}
5296 
5297 	return 0;
5298 }
5299 
5300 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5301 			       const struct bpf_reg_state *reg, int regno,
5302 			       bool fixed_off_ok)
5303 {
5304 	/* Access to this pointer-typed register or passing it to a helper
5305 	 * is only allowed in its original, unmodified form.
5306 	 */
5307 
5308 	if (reg->off < 0) {
5309 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5310 			reg_type_str(env, reg->type), regno, reg->off);
5311 		return -EACCES;
5312 	}
5313 
5314 	if (!fixed_off_ok && reg->off) {
5315 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5316 			reg_type_str(env, reg->type), regno, reg->off);
5317 		return -EACCES;
5318 	}
5319 
5320 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5321 		char tn_buf[48];
5322 
5323 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5324 		verbose(env, "variable %s access var_off=%s disallowed\n",
5325 			reg_type_str(env, reg->type), tn_buf);
5326 		return -EACCES;
5327 	}
5328 
5329 	return 0;
5330 }
5331 
5332 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5333 		             const struct bpf_reg_state *reg, int regno)
5334 {
5335 	return __check_ptr_off_reg(env, reg, regno, false);
5336 }
5337 
5338 static int map_kptr_match_type(struct bpf_verifier_env *env,
5339 			       struct btf_field *kptr_field,
5340 			       struct bpf_reg_state *reg, u32 regno)
5341 {
5342 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5343 	int perm_flags;
5344 	const char *reg_name = "";
5345 
5346 	if (btf_is_kernel(reg->btf)) {
5347 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5348 
5349 		/* Only unreferenced case accepts untrusted pointers */
5350 		if (kptr_field->type == BPF_KPTR_UNREF)
5351 			perm_flags |= PTR_UNTRUSTED;
5352 	} else {
5353 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5354 		if (kptr_field->type == BPF_KPTR_PERCPU)
5355 			perm_flags |= MEM_PERCPU;
5356 	}
5357 
5358 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5359 		goto bad_type;
5360 
5361 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5362 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5363 
5364 	/* For ref_ptr case, release function check should ensure we get one
5365 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5366 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5367 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5368 	 * reg->off and reg->ref_obj_id are not needed here.
5369 	 */
5370 	if (__check_ptr_off_reg(env, reg, regno, true))
5371 		return -EACCES;
5372 
5373 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5374 	 * we also need to take into account the reg->off.
5375 	 *
5376 	 * We want to support cases like:
5377 	 *
5378 	 * struct foo {
5379 	 *         struct bar br;
5380 	 *         struct baz bz;
5381 	 * };
5382 	 *
5383 	 * struct foo *v;
5384 	 * v = func();	      // PTR_TO_BTF_ID
5385 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5386 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5387 	 *                    // first member type of struct after comparison fails
5388 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5389 	 *                    // to match type
5390 	 *
5391 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5392 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5393 	 * the struct to match type against first member of struct, i.e. reject
5394 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5395 	 * strict mode to true for type match.
5396 	 */
5397 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5398 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5399 				  kptr_field->type != BPF_KPTR_UNREF))
5400 		goto bad_type;
5401 	return 0;
5402 bad_type:
5403 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5404 		reg_type_str(env, reg->type), reg_name);
5405 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5406 	if (kptr_field->type == BPF_KPTR_UNREF)
5407 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5408 			targ_name);
5409 	else
5410 		verbose(env, "\n");
5411 	return -EINVAL;
5412 }
5413 
5414 static bool in_sleepable(struct bpf_verifier_env *env)
5415 {
5416 	return env->prog->sleepable ||
5417 	       (env->cur_state && env->cur_state->in_sleepable);
5418 }
5419 
5420 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5421  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5422  */
5423 static bool in_rcu_cs(struct bpf_verifier_env *env)
5424 {
5425 	return env->cur_state->active_rcu_lock ||
5426 	       env->cur_state->active_lock.ptr ||
5427 	       !in_sleepable(env);
5428 }
5429 
5430 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5431 BTF_SET_START(rcu_protected_types)
5432 BTF_ID(struct, prog_test_ref_kfunc)
5433 #ifdef CONFIG_CGROUPS
5434 BTF_ID(struct, cgroup)
5435 #endif
5436 #ifdef CONFIG_BPF_JIT
5437 BTF_ID(struct, bpf_cpumask)
5438 #endif
5439 BTF_ID(struct, task_struct)
5440 BTF_ID(struct, bpf_crypto_ctx)
5441 BTF_SET_END(rcu_protected_types)
5442 
5443 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5444 {
5445 	if (!btf_is_kernel(btf))
5446 		return true;
5447 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5448 }
5449 
5450 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5451 {
5452 	struct btf_struct_meta *meta;
5453 
5454 	if (btf_is_kernel(kptr_field->kptr.btf))
5455 		return NULL;
5456 
5457 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5458 				    kptr_field->kptr.btf_id);
5459 
5460 	return meta ? meta->record : NULL;
5461 }
5462 
5463 static bool rcu_safe_kptr(const struct btf_field *field)
5464 {
5465 	const struct btf_field_kptr *kptr = &field->kptr;
5466 
5467 	return field->type == BPF_KPTR_PERCPU ||
5468 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5469 }
5470 
5471 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5472 {
5473 	struct btf_record *rec;
5474 	u32 ret;
5475 
5476 	ret = PTR_MAYBE_NULL;
5477 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5478 		ret |= MEM_RCU;
5479 		if (kptr_field->type == BPF_KPTR_PERCPU)
5480 			ret |= MEM_PERCPU;
5481 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5482 			ret |= MEM_ALLOC;
5483 
5484 		rec = kptr_pointee_btf_record(kptr_field);
5485 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5486 			ret |= NON_OWN_REF;
5487 	} else {
5488 		ret |= PTR_UNTRUSTED;
5489 	}
5490 
5491 	return ret;
5492 }
5493 
5494 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5495 				 int value_regno, int insn_idx,
5496 				 struct btf_field *kptr_field)
5497 {
5498 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5499 	int class = BPF_CLASS(insn->code);
5500 	struct bpf_reg_state *val_reg;
5501 
5502 	/* Things we already checked for in check_map_access and caller:
5503 	 *  - Reject cases where variable offset may touch kptr
5504 	 *  - size of access (must be BPF_DW)
5505 	 *  - tnum_is_const(reg->var_off)
5506 	 *  - kptr_field->offset == off + reg->var_off.value
5507 	 */
5508 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5509 	if (BPF_MODE(insn->code) != BPF_MEM) {
5510 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5511 		return -EACCES;
5512 	}
5513 
5514 	/* We only allow loading referenced kptr, since it will be marked as
5515 	 * untrusted, similar to unreferenced kptr.
5516 	 */
5517 	if (class != BPF_LDX &&
5518 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5519 		verbose(env, "store to referenced kptr disallowed\n");
5520 		return -EACCES;
5521 	}
5522 
5523 	if (class == BPF_LDX) {
5524 		val_reg = reg_state(env, value_regno);
5525 		/* We can simply mark the value_regno receiving the pointer
5526 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5527 		 */
5528 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5529 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5530 	} else if (class == BPF_STX) {
5531 		val_reg = reg_state(env, value_regno);
5532 		if (!register_is_null(val_reg) &&
5533 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5534 			return -EACCES;
5535 	} else if (class == BPF_ST) {
5536 		if (insn->imm) {
5537 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5538 				kptr_field->offset);
5539 			return -EACCES;
5540 		}
5541 	} else {
5542 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5543 		return -EACCES;
5544 	}
5545 	return 0;
5546 }
5547 
5548 /* check read/write into a map element with possible variable offset */
5549 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5550 			    int off, int size, bool zero_size_allowed,
5551 			    enum bpf_access_src src)
5552 {
5553 	struct bpf_verifier_state *vstate = env->cur_state;
5554 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5555 	struct bpf_reg_state *reg = &state->regs[regno];
5556 	struct bpf_map *map = reg->map_ptr;
5557 	struct btf_record *rec;
5558 	int err, i;
5559 
5560 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5561 				      zero_size_allowed);
5562 	if (err)
5563 		return err;
5564 
5565 	if (IS_ERR_OR_NULL(map->record))
5566 		return 0;
5567 	rec = map->record;
5568 	for (i = 0; i < rec->cnt; i++) {
5569 		struct btf_field *field = &rec->fields[i];
5570 		u32 p = field->offset;
5571 
5572 		/* If any part of a field  can be touched by load/store, reject
5573 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5574 		 * it is sufficient to check x1 < y2 && y1 < x2.
5575 		 */
5576 		if (reg->smin_value + off < p + field->size &&
5577 		    p < reg->umax_value + off + size) {
5578 			switch (field->type) {
5579 			case BPF_KPTR_UNREF:
5580 			case BPF_KPTR_REF:
5581 			case BPF_KPTR_PERCPU:
5582 				if (src != ACCESS_DIRECT) {
5583 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5584 					return -EACCES;
5585 				}
5586 				if (!tnum_is_const(reg->var_off)) {
5587 					verbose(env, "kptr access cannot have variable offset\n");
5588 					return -EACCES;
5589 				}
5590 				if (p != off + reg->var_off.value) {
5591 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5592 						p, off + reg->var_off.value);
5593 					return -EACCES;
5594 				}
5595 				if (size != bpf_size_to_bytes(BPF_DW)) {
5596 					verbose(env, "kptr access size must be BPF_DW\n");
5597 					return -EACCES;
5598 				}
5599 				break;
5600 			default:
5601 				verbose(env, "%s cannot be accessed directly by load/store\n",
5602 					btf_field_type_name(field->type));
5603 				return -EACCES;
5604 			}
5605 		}
5606 	}
5607 	return 0;
5608 }
5609 
5610 #define MAX_PACKET_OFF 0xffff
5611 
5612 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5613 				       const struct bpf_call_arg_meta *meta,
5614 				       enum bpf_access_type t)
5615 {
5616 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5617 
5618 	switch (prog_type) {
5619 	/* Program types only with direct read access go here! */
5620 	case BPF_PROG_TYPE_LWT_IN:
5621 	case BPF_PROG_TYPE_LWT_OUT:
5622 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5623 	case BPF_PROG_TYPE_SK_REUSEPORT:
5624 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5625 	case BPF_PROG_TYPE_CGROUP_SKB:
5626 		if (t == BPF_WRITE)
5627 			return false;
5628 		fallthrough;
5629 
5630 	/* Program types with direct read + write access go here! */
5631 	case BPF_PROG_TYPE_SCHED_CLS:
5632 	case BPF_PROG_TYPE_SCHED_ACT:
5633 	case BPF_PROG_TYPE_XDP:
5634 	case BPF_PROG_TYPE_LWT_XMIT:
5635 	case BPF_PROG_TYPE_SK_SKB:
5636 	case BPF_PROG_TYPE_SK_MSG:
5637 		if (meta)
5638 			return meta->pkt_access;
5639 
5640 		env->seen_direct_write = true;
5641 		return true;
5642 
5643 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5644 		if (t == BPF_WRITE)
5645 			env->seen_direct_write = true;
5646 
5647 		return true;
5648 
5649 	default:
5650 		return false;
5651 	}
5652 }
5653 
5654 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5655 			       int size, bool zero_size_allowed)
5656 {
5657 	struct bpf_reg_state *regs = cur_regs(env);
5658 	struct bpf_reg_state *reg = &regs[regno];
5659 	int err;
5660 
5661 	/* We may have added a variable offset to the packet pointer; but any
5662 	 * reg->range we have comes after that.  We are only checking the fixed
5663 	 * offset.
5664 	 */
5665 
5666 	/* We don't allow negative numbers, because we aren't tracking enough
5667 	 * detail to prove they're safe.
5668 	 */
5669 	if (reg->smin_value < 0) {
5670 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5671 			regno);
5672 		return -EACCES;
5673 	}
5674 
5675 	err = reg->range < 0 ? -EINVAL :
5676 	      __check_mem_access(env, regno, off, size, reg->range,
5677 				 zero_size_allowed);
5678 	if (err) {
5679 		verbose(env, "R%d offset is outside of the packet\n", regno);
5680 		return err;
5681 	}
5682 
5683 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5684 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5685 	 * otherwise find_good_pkt_pointers would have refused to set range info
5686 	 * that __check_mem_access would have rejected this pkt access.
5687 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5688 	 */
5689 	env->prog->aux->max_pkt_offset =
5690 		max_t(u32, env->prog->aux->max_pkt_offset,
5691 		      off + reg->umax_value + size - 1);
5692 
5693 	return err;
5694 }
5695 
5696 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5697 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5698 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5699 			    struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx)
5700 {
5701 	struct bpf_insn_access_aux info = {
5702 		.reg_type = *reg_type,
5703 		.log = &env->log,
5704 		.is_retval = false,
5705 		.is_ldsx = is_ldsx,
5706 	};
5707 
5708 	if (env->ops->is_valid_access &&
5709 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5710 		/* A non zero info.ctx_field_size indicates that this field is a
5711 		 * candidate for later verifier transformation to load the whole
5712 		 * field and then apply a mask when accessed with a narrower
5713 		 * access than actual ctx access size. A zero info.ctx_field_size
5714 		 * will only allow for whole field access and rejects any other
5715 		 * type of narrower access.
5716 		 */
5717 		*reg_type = info.reg_type;
5718 		*is_retval = info.is_retval;
5719 
5720 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5721 			*btf = info.btf;
5722 			*btf_id = info.btf_id;
5723 		} else {
5724 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5725 		}
5726 		/* remember the offset of last byte accessed in ctx */
5727 		if (env->prog->aux->max_ctx_offset < off + size)
5728 			env->prog->aux->max_ctx_offset = off + size;
5729 		return 0;
5730 	}
5731 
5732 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5733 	return -EACCES;
5734 }
5735 
5736 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5737 				  int size)
5738 {
5739 	if (size < 0 || off < 0 ||
5740 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5741 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5742 			off, size);
5743 		return -EACCES;
5744 	}
5745 	return 0;
5746 }
5747 
5748 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5749 			     u32 regno, int off, int size,
5750 			     enum bpf_access_type t)
5751 {
5752 	struct bpf_reg_state *regs = cur_regs(env);
5753 	struct bpf_reg_state *reg = &regs[regno];
5754 	struct bpf_insn_access_aux info = {};
5755 	bool valid;
5756 
5757 	if (reg->smin_value < 0) {
5758 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5759 			regno);
5760 		return -EACCES;
5761 	}
5762 
5763 	switch (reg->type) {
5764 	case PTR_TO_SOCK_COMMON:
5765 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5766 		break;
5767 	case PTR_TO_SOCKET:
5768 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5769 		break;
5770 	case PTR_TO_TCP_SOCK:
5771 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5772 		break;
5773 	case PTR_TO_XDP_SOCK:
5774 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5775 		break;
5776 	default:
5777 		valid = false;
5778 	}
5779 
5780 
5781 	if (valid) {
5782 		env->insn_aux_data[insn_idx].ctx_field_size =
5783 			info.ctx_field_size;
5784 		return 0;
5785 	}
5786 
5787 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5788 		regno, reg_type_str(env, reg->type), off, size);
5789 
5790 	return -EACCES;
5791 }
5792 
5793 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5794 {
5795 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5796 }
5797 
5798 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5799 {
5800 	const struct bpf_reg_state *reg = reg_state(env, regno);
5801 
5802 	return reg->type == PTR_TO_CTX;
5803 }
5804 
5805 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5806 {
5807 	const struct bpf_reg_state *reg = reg_state(env, regno);
5808 
5809 	return type_is_sk_pointer(reg->type);
5810 }
5811 
5812 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5813 {
5814 	const struct bpf_reg_state *reg = reg_state(env, regno);
5815 
5816 	return type_is_pkt_pointer(reg->type);
5817 }
5818 
5819 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5820 {
5821 	const struct bpf_reg_state *reg = reg_state(env, regno);
5822 
5823 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5824 	return reg->type == PTR_TO_FLOW_KEYS;
5825 }
5826 
5827 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5828 {
5829 	const struct bpf_reg_state *reg = reg_state(env, regno);
5830 
5831 	return reg->type == PTR_TO_ARENA;
5832 }
5833 
5834 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5835 #ifdef CONFIG_NET
5836 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5837 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5838 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5839 #endif
5840 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5841 };
5842 
5843 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5844 {
5845 	/* A referenced register is always trusted. */
5846 	if (reg->ref_obj_id)
5847 		return true;
5848 
5849 	/* Types listed in the reg2btf_ids are always trusted */
5850 	if (reg2btf_ids[base_type(reg->type)] &&
5851 	    !bpf_type_has_unsafe_modifiers(reg->type))
5852 		return true;
5853 
5854 	/* If a register is not referenced, it is trusted if it has the
5855 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5856 	 * other type modifiers may be safe, but we elect to take an opt-in
5857 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5858 	 * not.
5859 	 *
5860 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5861 	 * for whether a register is trusted.
5862 	 */
5863 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5864 	       !bpf_type_has_unsafe_modifiers(reg->type);
5865 }
5866 
5867 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5868 {
5869 	return reg->type & MEM_RCU;
5870 }
5871 
5872 static void clear_trusted_flags(enum bpf_type_flag *flag)
5873 {
5874 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5875 }
5876 
5877 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5878 				   const struct bpf_reg_state *reg,
5879 				   int off, int size, bool strict)
5880 {
5881 	struct tnum reg_off;
5882 	int ip_align;
5883 
5884 	/* Byte size accesses are always allowed. */
5885 	if (!strict || size == 1)
5886 		return 0;
5887 
5888 	/* For platforms that do not have a Kconfig enabling
5889 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5890 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5891 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5892 	 * to this code only in strict mode where we want to emulate
5893 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5894 	 * unconditional IP align value of '2'.
5895 	 */
5896 	ip_align = 2;
5897 
5898 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5899 	if (!tnum_is_aligned(reg_off, size)) {
5900 		char tn_buf[48];
5901 
5902 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5903 		verbose(env,
5904 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5905 			ip_align, tn_buf, reg->off, off, size);
5906 		return -EACCES;
5907 	}
5908 
5909 	return 0;
5910 }
5911 
5912 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5913 				       const struct bpf_reg_state *reg,
5914 				       const char *pointer_desc,
5915 				       int off, int size, bool strict)
5916 {
5917 	struct tnum reg_off;
5918 
5919 	/* Byte size accesses are always allowed. */
5920 	if (!strict || size == 1)
5921 		return 0;
5922 
5923 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5924 	if (!tnum_is_aligned(reg_off, size)) {
5925 		char tn_buf[48];
5926 
5927 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5928 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5929 			pointer_desc, tn_buf, reg->off, off, size);
5930 		return -EACCES;
5931 	}
5932 
5933 	return 0;
5934 }
5935 
5936 static int check_ptr_alignment(struct bpf_verifier_env *env,
5937 			       const struct bpf_reg_state *reg, int off,
5938 			       int size, bool strict_alignment_once)
5939 {
5940 	bool strict = env->strict_alignment || strict_alignment_once;
5941 	const char *pointer_desc = "";
5942 
5943 	switch (reg->type) {
5944 	case PTR_TO_PACKET:
5945 	case PTR_TO_PACKET_META:
5946 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5947 		 * right in front, treat it the very same way.
5948 		 */
5949 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5950 	case PTR_TO_FLOW_KEYS:
5951 		pointer_desc = "flow keys ";
5952 		break;
5953 	case PTR_TO_MAP_KEY:
5954 		pointer_desc = "key ";
5955 		break;
5956 	case PTR_TO_MAP_VALUE:
5957 		pointer_desc = "value ";
5958 		break;
5959 	case PTR_TO_CTX:
5960 		pointer_desc = "context ";
5961 		break;
5962 	case PTR_TO_STACK:
5963 		pointer_desc = "stack ";
5964 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5965 		 * and check_stack_read_fixed_off() relies on stack accesses being
5966 		 * aligned.
5967 		 */
5968 		strict = true;
5969 		break;
5970 	case PTR_TO_SOCKET:
5971 		pointer_desc = "sock ";
5972 		break;
5973 	case PTR_TO_SOCK_COMMON:
5974 		pointer_desc = "sock_common ";
5975 		break;
5976 	case PTR_TO_TCP_SOCK:
5977 		pointer_desc = "tcp_sock ";
5978 		break;
5979 	case PTR_TO_XDP_SOCK:
5980 		pointer_desc = "xdp_sock ";
5981 		break;
5982 	case PTR_TO_ARENA:
5983 		return 0;
5984 	default:
5985 		break;
5986 	}
5987 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5988 					   strict);
5989 }
5990 
5991 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5992 {
5993 	if (env->prog->jit_requested)
5994 		return round_up(stack_depth, 16);
5995 
5996 	/* round up to 32-bytes, since this is granularity
5997 	 * of interpreter stack size
5998 	 */
5999 	return round_up(max_t(u32, stack_depth, 1), 32);
6000 }
6001 
6002 /* starting from main bpf function walk all instructions of the function
6003  * and recursively walk all callees that given function can call.
6004  * Ignore jump and exit insns.
6005  * Since recursion is prevented by check_cfg() this algorithm
6006  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6007  */
6008 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
6009 {
6010 	struct bpf_subprog_info *subprog = env->subprog_info;
6011 	struct bpf_insn *insn = env->prog->insnsi;
6012 	int depth = 0, frame = 0, i, subprog_end;
6013 	bool tail_call_reachable = false;
6014 	int ret_insn[MAX_CALL_FRAMES];
6015 	int ret_prog[MAX_CALL_FRAMES];
6016 	int j;
6017 
6018 	i = subprog[idx].start;
6019 process_func:
6020 	/* protect against potential stack overflow that might happen when
6021 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6022 	 * depth for such case down to 256 so that the worst case scenario
6023 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6024 	 * 8k).
6025 	 *
6026 	 * To get the idea what might happen, see an example:
6027 	 * func1 -> sub rsp, 128
6028 	 *  subfunc1 -> sub rsp, 256
6029 	 *  tailcall1 -> add rsp, 256
6030 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6031 	 *   subfunc2 -> sub rsp, 64
6032 	 *   subfunc22 -> sub rsp, 128
6033 	 *   tailcall2 -> add rsp, 128
6034 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6035 	 *
6036 	 * tailcall will unwind the current stack frame but it will not get rid
6037 	 * of caller's stack as shown on the example above.
6038 	 */
6039 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6040 		verbose(env,
6041 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6042 			depth);
6043 		return -EACCES;
6044 	}
6045 	depth += round_up_stack_depth(env, subprog[idx].stack_depth);
6046 	if (depth > MAX_BPF_STACK) {
6047 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
6048 			frame + 1, depth);
6049 		return -EACCES;
6050 	}
6051 continue_func:
6052 	subprog_end = subprog[idx + 1].start;
6053 	for (; i < subprog_end; i++) {
6054 		int next_insn, sidx;
6055 
6056 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6057 			bool err = false;
6058 
6059 			if (!is_bpf_throw_kfunc(insn + i))
6060 				continue;
6061 			if (subprog[idx].is_cb)
6062 				err = true;
6063 			for (int c = 0; c < frame && !err; c++) {
6064 				if (subprog[ret_prog[c]].is_cb) {
6065 					err = true;
6066 					break;
6067 				}
6068 			}
6069 			if (!err)
6070 				continue;
6071 			verbose(env,
6072 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6073 				i, idx);
6074 			return -EINVAL;
6075 		}
6076 
6077 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6078 			continue;
6079 		/* remember insn and function to return to */
6080 		ret_insn[frame] = i + 1;
6081 		ret_prog[frame] = idx;
6082 
6083 		/* find the callee */
6084 		next_insn = i + insn[i].imm + 1;
6085 		sidx = find_subprog(env, next_insn);
6086 		if (sidx < 0) {
6087 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6088 				  next_insn);
6089 			return -EFAULT;
6090 		}
6091 		if (subprog[sidx].is_async_cb) {
6092 			if (subprog[sidx].has_tail_call) {
6093 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6094 				return -EFAULT;
6095 			}
6096 			/* async callbacks don't increase bpf prog stack size unless called directly */
6097 			if (!bpf_pseudo_call(insn + i))
6098 				continue;
6099 			if (subprog[sidx].is_exception_cb) {
6100 				verbose(env, "insn %d cannot call exception cb directly\n", i);
6101 				return -EINVAL;
6102 			}
6103 		}
6104 		i = next_insn;
6105 		idx = sidx;
6106 
6107 		if (subprog[idx].has_tail_call)
6108 			tail_call_reachable = true;
6109 
6110 		frame++;
6111 		if (frame >= MAX_CALL_FRAMES) {
6112 			verbose(env, "the call stack of %d frames is too deep !\n",
6113 				frame);
6114 			return -E2BIG;
6115 		}
6116 		goto process_func;
6117 	}
6118 	/* if tail call got detected across bpf2bpf calls then mark each of the
6119 	 * currently present subprog frames as tail call reachable subprogs;
6120 	 * this info will be utilized by JIT so that we will be preserving the
6121 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6122 	 */
6123 	if (tail_call_reachable)
6124 		for (j = 0; j < frame; j++) {
6125 			if (subprog[ret_prog[j]].is_exception_cb) {
6126 				verbose(env, "cannot tail call within exception cb\n");
6127 				return -EINVAL;
6128 			}
6129 			subprog[ret_prog[j]].tail_call_reachable = true;
6130 		}
6131 	if (subprog[0].tail_call_reachable)
6132 		env->prog->aux->tail_call_reachable = true;
6133 
6134 	/* end of for() loop means the last insn of the 'subprog'
6135 	 * was reached. Doesn't matter whether it was JA or EXIT
6136 	 */
6137 	if (frame == 0)
6138 		return 0;
6139 	depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6140 	frame--;
6141 	i = ret_insn[frame];
6142 	idx = ret_prog[frame];
6143 	goto continue_func;
6144 }
6145 
6146 static int check_max_stack_depth(struct bpf_verifier_env *env)
6147 {
6148 	struct bpf_subprog_info *si = env->subprog_info;
6149 	int ret;
6150 
6151 	for (int i = 0; i < env->subprog_cnt; i++) {
6152 		if (!i || si[i].is_async_cb) {
6153 			ret = check_max_stack_depth_subprog(env, i);
6154 			if (ret < 0)
6155 				return ret;
6156 		}
6157 		continue;
6158 	}
6159 	return 0;
6160 }
6161 
6162 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6163 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6164 				  const struct bpf_insn *insn, int idx)
6165 {
6166 	int start = idx + insn->imm + 1, subprog;
6167 
6168 	subprog = find_subprog(env, start);
6169 	if (subprog < 0) {
6170 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6171 			  start);
6172 		return -EFAULT;
6173 	}
6174 	return env->subprog_info[subprog].stack_depth;
6175 }
6176 #endif
6177 
6178 static int __check_buffer_access(struct bpf_verifier_env *env,
6179 				 const char *buf_info,
6180 				 const struct bpf_reg_state *reg,
6181 				 int regno, int off, int size)
6182 {
6183 	if (off < 0) {
6184 		verbose(env,
6185 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6186 			regno, buf_info, off, size);
6187 		return -EACCES;
6188 	}
6189 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6190 		char tn_buf[48];
6191 
6192 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6193 		verbose(env,
6194 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6195 			regno, off, tn_buf);
6196 		return -EACCES;
6197 	}
6198 
6199 	return 0;
6200 }
6201 
6202 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6203 				  const struct bpf_reg_state *reg,
6204 				  int regno, int off, int size)
6205 {
6206 	int err;
6207 
6208 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6209 	if (err)
6210 		return err;
6211 
6212 	if (off + size > env->prog->aux->max_tp_access)
6213 		env->prog->aux->max_tp_access = off + size;
6214 
6215 	return 0;
6216 }
6217 
6218 static int check_buffer_access(struct bpf_verifier_env *env,
6219 			       const struct bpf_reg_state *reg,
6220 			       int regno, int off, int size,
6221 			       bool zero_size_allowed,
6222 			       u32 *max_access)
6223 {
6224 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6225 	int err;
6226 
6227 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6228 	if (err)
6229 		return err;
6230 
6231 	if (off + size > *max_access)
6232 		*max_access = off + size;
6233 
6234 	return 0;
6235 }
6236 
6237 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6238 static void zext_32_to_64(struct bpf_reg_state *reg)
6239 {
6240 	reg->var_off = tnum_subreg(reg->var_off);
6241 	__reg_assign_32_into_64(reg);
6242 }
6243 
6244 /* truncate register to smaller size (in bytes)
6245  * must be called with size < BPF_REG_SIZE
6246  */
6247 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6248 {
6249 	u64 mask;
6250 
6251 	/* clear high bits in bit representation */
6252 	reg->var_off = tnum_cast(reg->var_off, size);
6253 
6254 	/* fix arithmetic bounds */
6255 	mask = ((u64)1 << (size * 8)) - 1;
6256 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6257 		reg->umin_value &= mask;
6258 		reg->umax_value &= mask;
6259 	} else {
6260 		reg->umin_value = 0;
6261 		reg->umax_value = mask;
6262 	}
6263 	reg->smin_value = reg->umin_value;
6264 	reg->smax_value = reg->umax_value;
6265 
6266 	/* If size is smaller than 32bit register the 32bit register
6267 	 * values are also truncated so we push 64-bit bounds into
6268 	 * 32-bit bounds. Above were truncated < 32-bits already.
6269 	 */
6270 	if (size < 4)
6271 		__mark_reg32_unbounded(reg);
6272 
6273 	reg_bounds_sync(reg);
6274 }
6275 
6276 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6277 {
6278 	if (size == 1) {
6279 		reg->smin_value = reg->s32_min_value = S8_MIN;
6280 		reg->smax_value = reg->s32_max_value = S8_MAX;
6281 	} else if (size == 2) {
6282 		reg->smin_value = reg->s32_min_value = S16_MIN;
6283 		reg->smax_value = reg->s32_max_value = S16_MAX;
6284 	} else {
6285 		/* size == 4 */
6286 		reg->smin_value = reg->s32_min_value = S32_MIN;
6287 		reg->smax_value = reg->s32_max_value = S32_MAX;
6288 	}
6289 	reg->umin_value = reg->u32_min_value = 0;
6290 	reg->umax_value = U64_MAX;
6291 	reg->u32_max_value = U32_MAX;
6292 	reg->var_off = tnum_unknown;
6293 }
6294 
6295 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6296 {
6297 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6298 	u64 top_smax_value, top_smin_value;
6299 	u64 num_bits = size * 8;
6300 
6301 	if (tnum_is_const(reg->var_off)) {
6302 		u64_cval = reg->var_off.value;
6303 		if (size == 1)
6304 			reg->var_off = tnum_const((s8)u64_cval);
6305 		else if (size == 2)
6306 			reg->var_off = tnum_const((s16)u64_cval);
6307 		else
6308 			/* size == 4 */
6309 			reg->var_off = tnum_const((s32)u64_cval);
6310 
6311 		u64_cval = reg->var_off.value;
6312 		reg->smax_value = reg->smin_value = u64_cval;
6313 		reg->umax_value = reg->umin_value = u64_cval;
6314 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6315 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6316 		return;
6317 	}
6318 
6319 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6320 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6321 
6322 	if (top_smax_value != top_smin_value)
6323 		goto out;
6324 
6325 	/* find the s64_min and s64_min after sign extension */
6326 	if (size == 1) {
6327 		init_s64_max = (s8)reg->smax_value;
6328 		init_s64_min = (s8)reg->smin_value;
6329 	} else if (size == 2) {
6330 		init_s64_max = (s16)reg->smax_value;
6331 		init_s64_min = (s16)reg->smin_value;
6332 	} else {
6333 		init_s64_max = (s32)reg->smax_value;
6334 		init_s64_min = (s32)reg->smin_value;
6335 	}
6336 
6337 	s64_max = max(init_s64_max, init_s64_min);
6338 	s64_min = min(init_s64_max, init_s64_min);
6339 
6340 	/* both of s64_max/s64_min positive or negative */
6341 	if ((s64_max >= 0) == (s64_min >= 0)) {
6342 		reg->s32_min_value = reg->smin_value = s64_min;
6343 		reg->s32_max_value = reg->smax_value = s64_max;
6344 		reg->u32_min_value = reg->umin_value = s64_min;
6345 		reg->u32_max_value = reg->umax_value = s64_max;
6346 		reg->var_off = tnum_range(s64_min, s64_max);
6347 		return;
6348 	}
6349 
6350 out:
6351 	set_sext64_default_val(reg, size);
6352 }
6353 
6354 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6355 {
6356 	if (size == 1) {
6357 		reg->s32_min_value = S8_MIN;
6358 		reg->s32_max_value = S8_MAX;
6359 	} else {
6360 		/* size == 2 */
6361 		reg->s32_min_value = S16_MIN;
6362 		reg->s32_max_value = S16_MAX;
6363 	}
6364 	reg->u32_min_value = 0;
6365 	reg->u32_max_value = U32_MAX;
6366 	reg->var_off = tnum_subreg(tnum_unknown);
6367 }
6368 
6369 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6370 {
6371 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6372 	u32 top_smax_value, top_smin_value;
6373 	u32 num_bits = size * 8;
6374 
6375 	if (tnum_is_const(reg->var_off)) {
6376 		u32_val = reg->var_off.value;
6377 		if (size == 1)
6378 			reg->var_off = tnum_const((s8)u32_val);
6379 		else
6380 			reg->var_off = tnum_const((s16)u32_val);
6381 
6382 		u32_val = reg->var_off.value;
6383 		reg->s32_min_value = reg->s32_max_value = u32_val;
6384 		reg->u32_min_value = reg->u32_max_value = u32_val;
6385 		return;
6386 	}
6387 
6388 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6389 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6390 
6391 	if (top_smax_value != top_smin_value)
6392 		goto out;
6393 
6394 	/* find the s32_min and s32_min after sign extension */
6395 	if (size == 1) {
6396 		init_s32_max = (s8)reg->s32_max_value;
6397 		init_s32_min = (s8)reg->s32_min_value;
6398 	} else {
6399 		/* size == 2 */
6400 		init_s32_max = (s16)reg->s32_max_value;
6401 		init_s32_min = (s16)reg->s32_min_value;
6402 	}
6403 	s32_max = max(init_s32_max, init_s32_min);
6404 	s32_min = min(init_s32_max, init_s32_min);
6405 
6406 	if ((s32_min >= 0) == (s32_max >= 0)) {
6407 		reg->s32_min_value = s32_min;
6408 		reg->s32_max_value = s32_max;
6409 		reg->u32_min_value = (u32)s32_min;
6410 		reg->u32_max_value = (u32)s32_max;
6411 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6412 		return;
6413 	}
6414 
6415 out:
6416 	set_sext32_default_val(reg, size);
6417 }
6418 
6419 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6420 {
6421 	/* A map is considered read-only if the following condition are true:
6422 	 *
6423 	 * 1) BPF program side cannot change any of the map content. The
6424 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6425 	 *    and was set at map creation time.
6426 	 * 2) The map value(s) have been initialized from user space by a
6427 	 *    loader and then "frozen", such that no new map update/delete
6428 	 *    operations from syscall side are possible for the rest of
6429 	 *    the map's lifetime from that point onwards.
6430 	 * 3) Any parallel/pending map update/delete operations from syscall
6431 	 *    side have been completed. Only after that point, it's safe to
6432 	 *    assume that map value(s) are immutable.
6433 	 */
6434 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6435 	       READ_ONCE(map->frozen) &&
6436 	       !bpf_map_write_active(map);
6437 }
6438 
6439 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6440 			       bool is_ldsx)
6441 {
6442 	void *ptr;
6443 	u64 addr;
6444 	int err;
6445 
6446 	err = map->ops->map_direct_value_addr(map, &addr, off);
6447 	if (err)
6448 		return err;
6449 	ptr = (void *)(long)addr + off;
6450 
6451 	switch (size) {
6452 	case sizeof(u8):
6453 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6454 		break;
6455 	case sizeof(u16):
6456 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6457 		break;
6458 	case sizeof(u32):
6459 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6460 		break;
6461 	case sizeof(u64):
6462 		*val = *(u64 *)ptr;
6463 		break;
6464 	default:
6465 		return -EINVAL;
6466 	}
6467 	return 0;
6468 }
6469 
6470 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6471 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6472 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6473 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6474 
6475 /*
6476  * Allow list few fields as RCU trusted or full trusted.
6477  * This logic doesn't allow mix tagging and will be removed once GCC supports
6478  * btf_type_tag.
6479  */
6480 
6481 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6482 BTF_TYPE_SAFE_RCU(struct task_struct) {
6483 	const cpumask_t *cpus_ptr;
6484 	struct css_set __rcu *cgroups;
6485 	struct task_struct __rcu *real_parent;
6486 	struct task_struct *group_leader;
6487 };
6488 
6489 BTF_TYPE_SAFE_RCU(struct cgroup) {
6490 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6491 	struct kernfs_node *kn;
6492 };
6493 
6494 BTF_TYPE_SAFE_RCU(struct css_set) {
6495 	struct cgroup *dfl_cgrp;
6496 };
6497 
6498 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6499 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6500 	struct file __rcu *exe_file;
6501 };
6502 
6503 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6504  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6505  */
6506 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6507 	struct sock *sk;
6508 };
6509 
6510 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6511 	struct sock *sk;
6512 };
6513 
6514 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6515 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6516 	struct seq_file *seq;
6517 };
6518 
6519 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6520 	struct bpf_iter_meta *meta;
6521 	struct task_struct *task;
6522 };
6523 
6524 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6525 	struct file *file;
6526 };
6527 
6528 BTF_TYPE_SAFE_TRUSTED(struct file) {
6529 	struct inode *f_inode;
6530 };
6531 
6532 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6533 	/* no negative dentry-s in places where bpf can see it */
6534 	struct inode *d_inode;
6535 };
6536 
6537 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6538 	struct sock *sk;
6539 };
6540 
6541 static bool type_is_rcu(struct bpf_verifier_env *env,
6542 			struct bpf_reg_state *reg,
6543 			const char *field_name, u32 btf_id)
6544 {
6545 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6546 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6547 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6548 
6549 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6550 }
6551 
6552 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6553 				struct bpf_reg_state *reg,
6554 				const char *field_name, u32 btf_id)
6555 {
6556 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6557 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6558 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6559 
6560 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6561 }
6562 
6563 static bool type_is_trusted(struct bpf_verifier_env *env,
6564 			    struct bpf_reg_state *reg,
6565 			    const char *field_name, u32 btf_id)
6566 {
6567 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6568 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6569 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6570 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6571 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6572 
6573 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6574 }
6575 
6576 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6577 				    struct bpf_reg_state *reg,
6578 				    const char *field_name, u32 btf_id)
6579 {
6580 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6581 
6582 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6583 					  "__safe_trusted_or_null");
6584 }
6585 
6586 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6587 				   struct bpf_reg_state *regs,
6588 				   int regno, int off, int size,
6589 				   enum bpf_access_type atype,
6590 				   int value_regno)
6591 {
6592 	struct bpf_reg_state *reg = regs + regno;
6593 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6594 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6595 	const char *field_name = NULL;
6596 	enum bpf_type_flag flag = 0;
6597 	u32 btf_id = 0;
6598 	int ret;
6599 
6600 	if (!env->allow_ptr_leaks) {
6601 		verbose(env,
6602 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6603 			tname);
6604 		return -EPERM;
6605 	}
6606 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6607 		verbose(env,
6608 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6609 			tname);
6610 		return -EINVAL;
6611 	}
6612 	if (off < 0) {
6613 		verbose(env,
6614 			"R%d is ptr_%s invalid negative access: off=%d\n",
6615 			regno, tname, off);
6616 		return -EACCES;
6617 	}
6618 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6619 		char tn_buf[48];
6620 
6621 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6622 		verbose(env,
6623 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6624 			regno, tname, off, tn_buf);
6625 		return -EACCES;
6626 	}
6627 
6628 	if (reg->type & MEM_USER) {
6629 		verbose(env,
6630 			"R%d is ptr_%s access user memory: off=%d\n",
6631 			regno, tname, off);
6632 		return -EACCES;
6633 	}
6634 
6635 	if (reg->type & MEM_PERCPU) {
6636 		verbose(env,
6637 			"R%d is ptr_%s access percpu memory: off=%d\n",
6638 			regno, tname, off);
6639 		return -EACCES;
6640 	}
6641 
6642 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6643 		if (!btf_is_kernel(reg->btf)) {
6644 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6645 			return -EFAULT;
6646 		}
6647 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6648 	} else {
6649 		/* Writes are permitted with default btf_struct_access for
6650 		 * program allocated objects (which always have ref_obj_id > 0),
6651 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6652 		 */
6653 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6654 			verbose(env, "only read is supported\n");
6655 			return -EACCES;
6656 		}
6657 
6658 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6659 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6660 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6661 			return -EFAULT;
6662 		}
6663 
6664 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6665 	}
6666 
6667 	if (ret < 0)
6668 		return ret;
6669 
6670 	if (ret != PTR_TO_BTF_ID) {
6671 		/* just mark; */
6672 
6673 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6674 		/* If this is an untrusted pointer, all pointers formed by walking it
6675 		 * also inherit the untrusted flag.
6676 		 */
6677 		flag = PTR_UNTRUSTED;
6678 
6679 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6680 		/* By default any pointer obtained from walking a trusted pointer is no
6681 		 * longer trusted, unless the field being accessed has explicitly been
6682 		 * marked as inheriting its parent's state of trust (either full or RCU).
6683 		 * For example:
6684 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6685 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6686 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6687 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6688 		 *
6689 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6690 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6691 		 */
6692 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6693 			flag |= PTR_TRUSTED;
6694 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6695 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6696 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6697 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6698 				/* ignore __rcu tag and mark it MEM_RCU */
6699 				flag |= MEM_RCU;
6700 			} else if (flag & MEM_RCU ||
6701 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6702 				/* __rcu tagged pointers can be NULL */
6703 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6704 
6705 				/* We always trust them */
6706 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6707 				    flag & PTR_UNTRUSTED)
6708 					flag &= ~PTR_UNTRUSTED;
6709 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6710 				/* keep as-is */
6711 			} else {
6712 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6713 				clear_trusted_flags(&flag);
6714 			}
6715 		} else {
6716 			/*
6717 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6718 			 * aggressively mark as untrusted otherwise such
6719 			 * pointers will be plain PTR_TO_BTF_ID without flags
6720 			 * and will be allowed to be passed into helpers for
6721 			 * compat reasons.
6722 			 */
6723 			flag = PTR_UNTRUSTED;
6724 		}
6725 	} else {
6726 		/* Old compat. Deprecated */
6727 		clear_trusted_flags(&flag);
6728 	}
6729 
6730 	if (atype == BPF_READ && value_regno >= 0)
6731 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6732 
6733 	return 0;
6734 }
6735 
6736 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6737 				   struct bpf_reg_state *regs,
6738 				   int regno, int off, int size,
6739 				   enum bpf_access_type atype,
6740 				   int value_regno)
6741 {
6742 	struct bpf_reg_state *reg = regs + regno;
6743 	struct bpf_map *map = reg->map_ptr;
6744 	struct bpf_reg_state map_reg;
6745 	enum bpf_type_flag flag = 0;
6746 	const struct btf_type *t;
6747 	const char *tname;
6748 	u32 btf_id;
6749 	int ret;
6750 
6751 	if (!btf_vmlinux) {
6752 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6753 		return -ENOTSUPP;
6754 	}
6755 
6756 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6757 		verbose(env, "map_ptr access not supported for map type %d\n",
6758 			map->map_type);
6759 		return -ENOTSUPP;
6760 	}
6761 
6762 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6763 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6764 
6765 	if (!env->allow_ptr_leaks) {
6766 		verbose(env,
6767 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6768 			tname);
6769 		return -EPERM;
6770 	}
6771 
6772 	if (off < 0) {
6773 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6774 			regno, tname, off);
6775 		return -EACCES;
6776 	}
6777 
6778 	if (atype != BPF_READ) {
6779 		verbose(env, "only read from %s is supported\n", tname);
6780 		return -EACCES;
6781 	}
6782 
6783 	/* Simulate access to a PTR_TO_BTF_ID */
6784 	memset(&map_reg, 0, sizeof(map_reg));
6785 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6786 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6787 	if (ret < 0)
6788 		return ret;
6789 
6790 	if (value_regno >= 0)
6791 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6792 
6793 	return 0;
6794 }
6795 
6796 /* Check that the stack access at the given offset is within bounds. The
6797  * maximum valid offset is -1.
6798  *
6799  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6800  * -state->allocated_stack for reads.
6801  */
6802 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6803                                           s64 off,
6804                                           struct bpf_func_state *state,
6805                                           enum bpf_access_type t)
6806 {
6807 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx];
6808 	int min_valid_off, max_bpf_stack;
6809 
6810 	/* If accessing instruction is a spill/fill from bpf_fastcall pattern,
6811 	 * add room for all caller saved registers below MAX_BPF_STACK.
6812 	 * In case if bpf_fastcall rewrite won't happen maximal stack depth
6813 	 * would be checked by check_max_stack_depth_subprog().
6814 	 */
6815 	max_bpf_stack = MAX_BPF_STACK;
6816 	if (aux->fastcall_pattern)
6817 		max_bpf_stack += CALLER_SAVED_REGS * BPF_REG_SIZE;
6818 
6819 	if (t == BPF_WRITE || env->allow_uninit_stack)
6820 		min_valid_off = -max_bpf_stack;
6821 	else
6822 		min_valid_off = -state->allocated_stack;
6823 
6824 	if (off < min_valid_off || off > -1)
6825 		return -EACCES;
6826 	return 0;
6827 }
6828 
6829 /* Check that the stack access at 'regno + off' falls within the maximum stack
6830  * bounds.
6831  *
6832  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6833  */
6834 static int check_stack_access_within_bounds(
6835 		struct bpf_verifier_env *env,
6836 		int regno, int off, int access_size,
6837 		enum bpf_access_src src, enum bpf_access_type type)
6838 {
6839 	struct bpf_reg_state *regs = cur_regs(env);
6840 	struct bpf_reg_state *reg = regs + regno;
6841 	struct bpf_func_state *state = func(env, reg);
6842 	s64 min_off, max_off;
6843 	int err;
6844 	char *err_extra;
6845 
6846 	if (src == ACCESS_HELPER)
6847 		/* We don't know if helpers are reading or writing (or both). */
6848 		err_extra = " indirect access to";
6849 	else if (type == BPF_READ)
6850 		err_extra = " read from";
6851 	else
6852 		err_extra = " write to";
6853 
6854 	if (tnum_is_const(reg->var_off)) {
6855 		min_off = (s64)reg->var_off.value + off;
6856 		max_off = min_off + access_size;
6857 	} else {
6858 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6859 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6860 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6861 				err_extra, regno);
6862 			return -EACCES;
6863 		}
6864 		min_off = reg->smin_value + off;
6865 		max_off = reg->smax_value + off + access_size;
6866 	}
6867 
6868 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6869 	if (!err && max_off > 0)
6870 		err = -EINVAL; /* out of stack access into non-negative offsets */
6871 	if (!err && access_size < 0)
6872 		/* access_size should not be negative (or overflow an int); others checks
6873 		 * along the way should have prevented such an access.
6874 		 */
6875 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6876 
6877 	if (err) {
6878 		if (tnum_is_const(reg->var_off)) {
6879 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6880 				err_extra, regno, off, access_size);
6881 		} else {
6882 			char tn_buf[48];
6883 
6884 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6885 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6886 				err_extra, regno, tn_buf, off, access_size);
6887 		}
6888 		return err;
6889 	}
6890 
6891 	/* Note that there is no stack access with offset zero, so the needed stack
6892 	 * size is -min_off, not -min_off+1.
6893 	 */
6894 	return grow_stack_state(env, state, -min_off /* size */);
6895 }
6896 
6897 static bool get_func_retval_range(struct bpf_prog *prog,
6898 				  struct bpf_retval_range *range)
6899 {
6900 	if (prog->type == BPF_PROG_TYPE_LSM &&
6901 		prog->expected_attach_type == BPF_LSM_MAC &&
6902 		!bpf_lsm_get_retval_range(prog, range)) {
6903 		return true;
6904 	}
6905 	return false;
6906 }
6907 
6908 /* check whether memory at (regno + off) is accessible for t = (read | write)
6909  * if t==write, value_regno is a register which value is stored into memory
6910  * if t==read, value_regno is a register which will receive the value from memory
6911  * if t==write && value_regno==-1, some unknown value is stored into memory
6912  * if t==read && value_regno==-1, don't care what we read from memory
6913  */
6914 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6915 			    int off, int bpf_size, enum bpf_access_type t,
6916 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6917 {
6918 	struct bpf_reg_state *regs = cur_regs(env);
6919 	struct bpf_reg_state *reg = regs + regno;
6920 	int size, err = 0;
6921 
6922 	size = bpf_size_to_bytes(bpf_size);
6923 	if (size < 0)
6924 		return size;
6925 
6926 	/* alignment checks will add in reg->off themselves */
6927 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6928 	if (err)
6929 		return err;
6930 
6931 	/* for access checks, reg->off is just part of off */
6932 	off += reg->off;
6933 
6934 	if (reg->type == PTR_TO_MAP_KEY) {
6935 		if (t == BPF_WRITE) {
6936 			verbose(env, "write to change key R%d not allowed\n", regno);
6937 			return -EACCES;
6938 		}
6939 
6940 		err = check_mem_region_access(env, regno, off, size,
6941 					      reg->map_ptr->key_size, false);
6942 		if (err)
6943 			return err;
6944 		if (value_regno >= 0)
6945 			mark_reg_unknown(env, regs, value_regno);
6946 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6947 		struct btf_field *kptr_field = NULL;
6948 
6949 		if (t == BPF_WRITE && value_regno >= 0 &&
6950 		    is_pointer_value(env, value_regno)) {
6951 			verbose(env, "R%d leaks addr into map\n", value_regno);
6952 			return -EACCES;
6953 		}
6954 		err = check_map_access_type(env, regno, off, size, t);
6955 		if (err)
6956 			return err;
6957 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6958 		if (err)
6959 			return err;
6960 		if (tnum_is_const(reg->var_off))
6961 			kptr_field = btf_record_find(reg->map_ptr->record,
6962 						     off + reg->var_off.value, BPF_KPTR);
6963 		if (kptr_field) {
6964 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6965 		} else if (t == BPF_READ && value_regno >= 0) {
6966 			struct bpf_map *map = reg->map_ptr;
6967 
6968 			/* if map is read-only, track its contents as scalars */
6969 			if (tnum_is_const(reg->var_off) &&
6970 			    bpf_map_is_rdonly(map) &&
6971 			    map->ops->map_direct_value_addr) {
6972 				int map_off = off + reg->var_off.value;
6973 				u64 val = 0;
6974 
6975 				err = bpf_map_direct_read(map, map_off, size,
6976 							  &val, is_ldsx);
6977 				if (err)
6978 					return err;
6979 
6980 				regs[value_regno].type = SCALAR_VALUE;
6981 				__mark_reg_known(&regs[value_regno], val);
6982 			} else {
6983 				mark_reg_unknown(env, regs, value_regno);
6984 			}
6985 		}
6986 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6987 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6988 
6989 		if (type_may_be_null(reg->type)) {
6990 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6991 				reg_type_str(env, reg->type));
6992 			return -EACCES;
6993 		}
6994 
6995 		if (t == BPF_WRITE && rdonly_mem) {
6996 			verbose(env, "R%d cannot write into %s\n",
6997 				regno, reg_type_str(env, reg->type));
6998 			return -EACCES;
6999 		}
7000 
7001 		if (t == BPF_WRITE && value_regno >= 0 &&
7002 		    is_pointer_value(env, value_regno)) {
7003 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7004 			return -EACCES;
7005 		}
7006 
7007 		err = check_mem_region_access(env, regno, off, size,
7008 					      reg->mem_size, false);
7009 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7010 			mark_reg_unknown(env, regs, value_regno);
7011 	} else if (reg->type == PTR_TO_CTX) {
7012 		bool is_retval = false;
7013 		struct bpf_retval_range range;
7014 		enum bpf_reg_type reg_type = SCALAR_VALUE;
7015 		struct btf *btf = NULL;
7016 		u32 btf_id = 0;
7017 
7018 		if (t == BPF_WRITE && value_regno >= 0 &&
7019 		    is_pointer_value(env, value_regno)) {
7020 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7021 			return -EACCES;
7022 		}
7023 
7024 		err = check_ptr_off_reg(env, reg, regno);
7025 		if (err < 0)
7026 			return err;
7027 
7028 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
7029 				       &btf_id, &is_retval, is_ldsx);
7030 		if (err)
7031 			verbose_linfo(env, insn_idx, "; ");
7032 		if (!err && t == BPF_READ && value_regno >= 0) {
7033 			/* ctx access returns either a scalar, or a
7034 			 * PTR_TO_PACKET[_META,_END]. In the latter
7035 			 * case, we know the offset is zero.
7036 			 */
7037 			if (reg_type == SCALAR_VALUE) {
7038 				if (is_retval && get_func_retval_range(env->prog, &range)) {
7039 					err = __mark_reg_s32_range(env, regs, value_regno,
7040 								   range.minval, range.maxval);
7041 					if (err)
7042 						return err;
7043 				} else {
7044 					mark_reg_unknown(env, regs, value_regno);
7045 				}
7046 			} else {
7047 				mark_reg_known_zero(env, regs,
7048 						    value_regno);
7049 				if (type_may_be_null(reg_type))
7050 					regs[value_regno].id = ++env->id_gen;
7051 				/* A load of ctx field could have different
7052 				 * actual load size with the one encoded in the
7053 				 * insn. When the dst is PTR, it is for sure not
7054 				 * a sub-register.
7055 				 */
7056 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7057 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
7058 					regs[value_regno].btf = btf;
7059 					regs[value_regno].btf_id = btf_id;
7060 				}
7061 			}
7062 			regs[value_regno].type = reg_type;
7063 		}
7064 
7065 	} else if (reg->type == PTR_TO_STACK) {
7066 		/* Basic bounds checks. */
7067 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
7068 		if (err)
7069 			return err;
7070 
7071 		if (t == BPF_READ)
7072 			err = check_stack_read(env, regno, off, size,
7073 					       value_regno);
7074 		else
7075 			err = check_stack_write(env, regno, off, size,
7076 						value_regno, insn_idx);
7077 	} else if (reg_is_pkt_pointer(reg)) {
7078 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7079 			verbose(env, "cannot write into packet\n");
7080 			return -EACCES;
7081 		}
7082 		if (t == BPF_WRITE && value_regno >= 0 &&
7083 		    is_pointer_value(env, value_regno)) {
7084 			verbose(env, "R%d leaks addr into packet\n",
7085 				value_regno);
7086 			return -EACCES;
7087 		}
7088 		err = check_packet_access(env, regno, off, size, false);
7089 		if (!err && t == BPF_READ && value_regno >= 0)
7090 			mark_reg_unknown(env, regs, value_regno);
7091 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7092 		if (t == BPF_WRITE && value_regno >= 0 &&
7093 		    is_pointer_value(env, value_regno)) {
7094 			verbose(env, "R%d leaks addr into flow keys\n",
7095 				value_regno);
7096 			return -EACCES;
7097 		}
7098 
7099 		err = check_flow_keys_access(env, off, size);
7100 		if (!err && t == BPF_READ && value_regno >= 0)
7101 			mark_reg_unknown(env, regs, value_regno);
7102 	} else if (type_is_sk_pointer(reg->type)) {
7103 		if (t == BPF_WRITE) {
7104 			verbose(env, "R%d cannot write into %s\n",
7105 				regno, reg_type_str(env, reg->type));
7106 			return -EACCES;
7107 		}
7108 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7109 		if (!err && value_regno >= 0)
7110 			mark_reg_unknown(env, regs, value_regno);
7111 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7112 		err = check_tp_buffer_access(env, reg, regno, off, size);
7113 		if (!err && t == BPF_READ && value_regno >= 0)
7114 			mark_reg_unknown(env, regs, value_regno);
7115 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7116 		   !type_may_be_null(reg->type)) {
7117 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7118 					      value_regno);
7119 	} else if (reg->type == CONST_PTR_TO_MAP) {
7120 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7121 					      value_regno);
7122 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7123 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7124 		u32 *max_access;
7125 
7126 		if (rdonly_mem) {
7127 			if (t == BPF_WRITE) {
7128 				verbose(env, "R%d cannot write into %s\n",
7129 					regno, reg_type_str(env, reg->type));
7130 				return -EACCES;
7131 			}
7132 			max_access = &env->prog->aux->max_rdonly_access;
7133 		} else {
7134 			max_access = &env->prog->aux->max_rdwr_access;
7135 		}
7136 
7137 		err = check_buffer_access(env, reg, regno, off, size, false,
7138 					  max_access);
7139 
7140 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7141 			mark_reg_unknown(env, regs, value_regno);
7142 	} else if (reg->type == PTR_TO_ARENA) {
7143 		if (t == BPF_READ && value_regno >= 0)
7144 			mark_reg_unknown(env, regs, value_regno);
7145 	} else {
7146 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7147 			reg_type_str(env, reg->type));
7148 		return -EACCES;
7149 	}
7150 
7151 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7152 	    regs[value_regno].type == SCALAR_VALUE) {
7153 		if (!is_ldsx)
7154 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7155 			coerce_reg_to_size(&regs[value_regno], size);
7156 		else
7157 			coerce_reg_to_size_sx(&regs[value_regno], size);
7158 	}
7159 	return err;
7160 }
7161 
7162 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7163 			     bool allow_trust_mismatch);
7164 
7165 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7166 {
7167 	int load_reg;
7168 	int err;
7169 
7170 	switch (insn->imm) {
7171 	case BPF_ADD:
7172 	case BPF_ADD | BPF_FETCH:
7173 	case BPF_AND:
7174 	case BPF_AND | BPF_FETCH:
7175 	case BPF_OR:
7176 	case BPF_OR | BPF_FETCH:
7177 	case BPF_XOR:
7178 	case BPF_XOR | BPF_FETCH:
7179 	case BPF_XCHG:
7180 	case BPF_CMPXCHG:
7181 		break;
7182 	default:
7183 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7184 		return -EINVAL;
7185 	}
7186 
7187 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7188 		verbose(env, "invalid atomic operand size\n");
7189 		return -EINVAL;
7190 	}
7191 
7192 	/* check src1 operand */
7193 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7194 	if (err)
7195 		return err;
7196 
7197 	/* check src2 operand */
7198 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7199 	if (err)
7200 		return err;
7201 
7202 	if (insn->imm == BPF_CMPXCHG) {
7203 		/* Check comparison of R0 with memory location */
7204 		const u32 aux_reg = BPF_REG_0;
7205 
7206 		err = check_reg_arg(env, aux_reg, SRC_OP);
7207 		if (err)
7208 			return err;
7209 
7210 		if (is_pointer_value(env, aux_reg)) {
7211 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7212 			return -EACCES;
7213 		}
7214 	}
7215 
7216 	if (is_pointer_value(env, insn->src_reg)) {
7217 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7218 		return -EACCES;
7219 	}
7220 
7221 	if (is_ctx_reg(env, insn->dst_reg) ||
7222 	    is_pkt_reg(env, insn->dst_reg) ||
7223 	    is_flow_key_reg(env, insn->dst_reg) ||
7224 	    is_sk_reg(env, insn->dst_reg) ||
7225 	    (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7226 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7227 			insn->dst_reg,
7228 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7229 		return -EACCES;
7230 	}
7231 
7232 	if (insn->imm & BPF_FETCH) {
7233 		if (insn->imm == BPF_CMPXCHG)
7234 			load_reg = BPF_REG_0;
7235 		else
7236 			load_reg = insn->src_reg;
7237 
7238 		/* check and record load of old value */
7239 		err = check_reg_arg(env, load_reg, DST_OP);
7240 		if (err)
7241 			return err;
7242 	} else {
7243 		/* This instruction accesses a memory location but doesn't
7244 		 * actually load it into a register.
7245 		 */
7246 		load_reg = -1;
7247 	}
7248 
7249 	/* Check whether we can read the memory, with second call for fetch
7250 	 * case to simulate the register fill.
7251 	 */
7252 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7253 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7254 	if (!err && load_reg >= 0)
7255 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7256 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7257 				       true, false);
7258 	if (err)
7259 		return err;
7260 
7261 	if (is_arena_reg(env, insn->dst_reg)) {
7262 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7263 		if (err)
7264 			return err;
7265 	}
7266 	/* Check whether we can write into the same memory. */
7267 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7268 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7269 	if (err)
7270 		return err;
7271 	return 0;
7272 }
7273 
7274 /* When register 'regno' is used to read the stack (either directly or through
7275  * a helper function) make sure that it's within stack boundary and, depending
7276  * on the access type and privileges, that all elements of the stack are
7277  * initialized.
7278  *
7279  * 'off' includes 'regno->off', but not its dynamic part (if any).
7280  *
7281  * All registers that have been spilled on the stack in the slots within the
7282  * read offsets are marked as read.
7283  */
7284 static int check_stack_range_initialized(
7285 		struct bpf_verifier_env *env, int regno, int off,
7286 		int access_size, bool zero_size_allowed,
7287 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7288 {
7289 	struct bpf_reg_state *reg = reg_state(env, regno);
7290 	struct bpf_func_state *state = func(env, reg);
7291 	int err, min_off, max_off, i, j, slot, spi;
7292 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7293 	enum bpf_access_type bounds_check_type;
7294 	/* Some accesses can write anything into the stack, others are
7295 	 * read-only.
7296 	 */
7297 	bool clobber = false;
7298 
7299 	if (access_size == 0 && !zero_size_allowed) {
7300 		verbose(env, "invalid zero-sized read\n");
7301 		return -EACCES;
7302 	}
7303 
7304 	if (type == ACCESS_HELPER) {
7305 		/* The bounds checks for writes are more permissive than for
7306 		 * reads. However, if raw_mode is not set, we'll do extra
7307 		 * checks below.
7308 		 */
7309 		bounds_check_type = BPF_WRITE;
7310 		clobber = true;
7311 	} else {
7312 		bounds_check_type = BPF_READ;
7313 	}
7314 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7315 					       type, bounds_check_type);
7316 	if (err)
7317 		return err;
7318 
7319 
7320 	if (tnum_is_const(reg->var_off)) {
7321 		min_off = max_off = reg->var_off.value + off;
7322 	} else {
7323 		/* Variable offset is prohibited for unprivileged mode for
7324 		 * simplicity since it requires corresponding support in
7325 		 * Spectre masking for stack ALU.
7326 		 * See also retrieve_ptr_limit().
7327 		 */
7328 		if (!env->bypass_spec_v1) {
7329 			char tn_buf[48];
7330 
7331 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7332 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7333 				regno, err_extra, tn_buf);
7334 			return -EACCES;
7335 		}
7336 		/* Only initialized buffer on stack is allowed to be accessed
7337 		 * with variable offset. With uninitialized buffer it's hard to
7338 		 * guarantee that whole memory is marked as initialized on
7339 		 * helper return since specific bounds are unknown what may
7340 		 * cause uninitialized stack leaking.
7341 		 */
7342 		if (meta && meta->raw_mode)
7343 			meta = NULL;
7344 
7345 		min_off = reg->smin_value + off;
7346 		max_off = reg->smax_value + off;
7347 	}
7348 
7349 	if (meta && meta->raw_mode) {
7350 		/* Ensure we won't be overwriting dynptrs when simulating byte
7351 		 * by byte access in check_helper_call using meta.access_size.
7352 		 * This would be a problem if we have a helper in the future
7353 		 * which takes:
7354 		 *
7355 		 *	helper(uninit_mem, len, dynptr)
7356 		 *
7357 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7358 		 * may end up writing to dynptr itself when touching memory from
7359 		 * arg 1. This can be relaxed on a case by case basis for known
7360 		 * safe cases, but reject due to the possibilitiy of aliasing by
7361 		 * default.
7362 		 */
7363 		for (i = min_off; i < max_off + access_size; i++) {
7364 			int stack_off = -i - 1;
7365 
7366 			spi = __get_spi(i);
7367 			/* raw_mode may write past allocated_stack */
7368 			if (state->allocated_stack <= stack_off)
7369 				continue;
7370 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7371 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7372 				return -EACCES;
7373 			}
7374 		}
7375 		meta->access_size = access_size;
7376 		meta->regno = regno;
7377 		return 0;
7378 	}
7379 
7380 	for (i = min_off; i < max_off + access_size; i++) {
7381 		u8 *stype;
7382 
7383 		slot = -i - 1;
7384 		spi = slot / BPF_REG_SIZE;
7385 		if (state->allocated_stack <= slot) {
7386 			verbose(env, "verifier bug: allocated_stack too small");
7387 			return -EFAULT;
7388 		}
7389 
7390 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7391 		if (*stype == STACK_MISC)
7392 			goto mark;
7393 		if ((*stype == STACK_ZERO) ||
7394 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7395 			if (clobber) {
7396 				/* helper can write anything into the stack */
7397 				*stype = STACK_MISC;
7398 			}
7399 			goto mark;
7400 		}
7401 
7402 		if (is_spilled_reg(&state->stack[spi]) &&
7403 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7404 		     env->allow_ptr_leaks)) {
7405 			if (clobber) {
7406 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7407 				for (j = 0; j < BPF_REG_SIZE; j++)
7408 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7409 			}
7410 			goto mark;
7411 		}
7412 
7413 		if (tnum_is_const(reg->var_off)) {
7414 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7415 				err_extra, regno, min_off, i - min_off, access_size);
7416 		} else {
7417 			char tn_buf[48];
7418 
7419 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7420 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7421 				err_extra, regno, tn_buf, i - min_off, access_size);
7422 		}
7423 		return -EACCES;
7424 mark:
7425 		/* reading any byte out of 8-byte 'spill_slot' will cause
7426 		 * the whole slot to be marked as 'read'
7427 		 */
7428 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7429 			      state->stack[spi].spilled_ptr.parent,
7430 			      REG_LIVE_READ64);
7431 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7432 		 * be sure that whether stack slot is written to or not. Hence,
7433 		 * we must still conservatively propagate reads upwards even if
7434 		 * helper may write to the entire memory range.
7435 		 */
7436 	}
7437 	return 0;
7438 }
7439 
7440 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7441 				   int access_size, bool zero_size_allowed,
7442 				   struct bpf_call_arg_meta *meta)
7443 {
7444 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7445 	u32 *max_access;
7446 
7447 	switch (base_type(reg->type)) {
7448 	case PTR_TO_PACKET:
7449 	case PTR_TO_PACKET_META:
7450 		return check_packet_access(env, regno, reg->off, access_size,
7451 					   zero_size_allowed);
7452 	case PTR_TO_MAP_KEY:
7453 		if (meta && meta->raw_mode) {
7454 			verbose(env, "R%d cannot write into %s\n", regno,
7455 				reg_type_str(env, reg->type));
7456 			return -EACCES;
7457 		}
7458 		return check_mem_region_access(env, regno, reg->off, access_size,
7459 					       reg->map_ptr->key_size, false);
7460 	case PTR_TO_MAP_VALUE:
7461 		if (check_map_access_type(env, regno, reg->off, access_size,
7462 					  meta && meta->raw_mode ? BPF_WRITE :
7463 					  BPF_READ))
7464 			return -EACCES;
7465 		return check_map_access(env, regno, reg->off, access_size,
7466 					zero_size_allowed, ACCESS_HELPER);
7467 	case PTR_TO_MEM:
7468 		if (type_is_rdonly_mem(reg->type)) {
7469 			if (meta && meta->raw_mode) {
7470 				verbose(env, "R%d cannot write into %s\n", regno,
7471 					reg_type_str(env, reg->type));
7472 				return -EACCES;
7473 			}
7474 		}
7475 		return check_mem_region_access(env, regno, reg->off,
7476 					       access_size, reg->mem_size,
7477 					       zero_size_allowed);
7478 	case PTR_TO_BUF:
7479 		if (type_is_rdonly_mem(reg->type)) {
7480 			if (meta && meta->raw_mode) {
7481 				verbose(env, "R%d cannot write into %s\n", regno,
7482 					reg_type_str(env, reg->type));
7483 				return -EACCES;
7484 			}
7485 
7486 			max_access = &env->prog->aux->max_rdonly_access;
7487 		} else {
7488 			max_access = &env->prog->aux->max_rdwr_access;
7489 		}
7490 		return check_buffer_access(env, reg, regno, reg->off,
7491 					   access_size, zero_size_allowed,
7492 					   max_access);
7493 	case PTR_TO_STACK:
7494 		return check_stack_range_initialized(
7495 				env,
7496 				regno, reg->off, access_size,
7497 				zero_size_allowed, ACCESS_HELPER, meta);
7498 	case PTR_TO_BTF_ID:
7499 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7500 					       access_size, BPF_READ, -1);
7501 	case PTR_TO_CTX:
7502 		/* in case the function doesn't know how to access the context,
7503 		 * (because we are in a program of type SYSCALL for example), we
7504 		 * can not statically check its size.
7505 		 * Dynamically check it now.
7506 		 */
7507 		if (!env->ops->convert_ctx_access) {
7508 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7509 			int offset = access_size - 1;
7510 
7511 			/* Allow zero-byte read from PTR_TO_CTX */
7512 			if (access_size == 0)
7513 				return zero_size_allowed ? 0 : -EACCES;
7514 
7515 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7516 						atype, -1, false, false);
7517 		}
7518 
7519 		fallthrough;
7520 	default: /* scalar_value or invalid ptr */
7521 		/* Allow zero-byte read from NULL, regardless of pointer type */
7522 		if (zero_size_allowed && access_size == 0 &&
7523 		    register_is_null(reg))
7524 			return 0;
7525 
7526 		verbose(env, "R%d type=%s ", regno,
7527 			reg_type_str(env, reg->type));
7528 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7529 		return -EACCES;
7530 	}
7531 }
7532 
7533 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7534  * size.
7535  *
7536  * @regno is the register containing the access size. regno-1 is the register
7537  * containing the pointer.
7538  */
7539 static int check_mem_size_reg(struct bpf_verifier_env *env,
7540 			      struct bpf_reg_state *reg, u32 regno,
7541 			      bool zero_size_allowed,
7542 			      struct bpf_call_arg_meta *meta)
7543 {
7544 	int err;
7545 
7546 	/* This is used to refine r0 return value bounds for helpers
7547 	 * that enforce this value as an upper bound on return values.
7548 	 * See do_refine_retval_range() for helpers that can refine
7549 	 * the return value. C type of helper is u32 so we pull register
7550 	 * bound from umax_value however, if negative verifier errors
7551 	 * out. Only upper bounds can be learned because retval is an
7552 	 * int type and negative retvals are allowed.
7553 	 */
7554 	meta->msize_max_value = reg->umax_value;
7555 
7556 	/* The register is SCALAR_VALUE; the access check
7557 	 * happens using its boundaries.
7558 	 */
7559 	if (!tnum_is_const(reg->var_off))
7560 		/* For unprivileged variable accesses, disable raw
7561 		 * mode so that the program is required to
7562 		 * initialize all the memory that the helper could
7563 		 * just partially fill up.
7564 		 */
7565 		meta = NULL;
7566 
7567 	if (reg->smin_value < 0) {
7568 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7569 			regno);
7570 		return -EACCES;
7571 	}
7572 
7573 	if (reg->umin_value == 0 && !zero_size_allowed) {
7574 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7575 			regno, reg->umin_value, reg->umax_value);
7576 		return -EACCES;
7577 	}
7578 
7579 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7580 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7581 			regno);
7582 		return -EACCES;
7583 	}
7584 	err = check_helper_mem_access(env, regno - 1,
7585 				      reg->umax_value,
7586 				      zero_size_allowed, meta);
7587 	if (!err)
7588 		err = mark_chain_precision(env, regno);
7589 	return err;
7590 }
7591 
7592 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7593 			 u32 regno, u32 mem_size)
7594 {
7595 	bool may_be_null = type_may_be_null(reg->type);
7596 	struct bpf_reg_state saved_reg;
7597 	struct bpf_call_arg_meta meta;
7598 	int err;
7599 
7600 	if (register_is_null(reg))
7601 		return 0;
7602 
7603 	memset(&meta, 0, sizeof(meta));
7604 	/* Assuming that the register contains a value check if the memory
7605 	 * access is safe. Temporarily save and restore the register's state as
7606 	 * the conversion shouldn't be visible to a caller.
7607 	 */
7608 	if (may_be_null) {
7609 		saved_reg = *reg;
7610 		mark_ptr_not_null_reg(reg);
7611 	}
7612 
7613 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7614 	/* Check access for BPF_WRITE */
7615 	meta.raw_mode = true;
7616 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7617 
7618 	if (may_be_null)
7619 		*reg = saved_reg;
7620 
7621 	return err;
7622 }
7623 
7624 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7625 				    u32 regno)
7626 {
7627 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7628 	bool may_be_null = type_may_be_null(mem_reg->type);
7629 	struct bpf_reg_state saved_reg;
7630 	struct bpf_call_arg_meta meta;
7631 	int err;
7632 
7633 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7634 
7635 	memset(&meta, 0, sizeof(meta));
7636 
7637 	if (may_be_null) {
7638 		saved_reg = *mem_reg;
7639 		mark_ptr_not_null_reg(mem_reg);
7640 	}
7641 
7642 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7643 	/* Check access for BPF_WRITE */
7644 	meta.raw_mode = true;
7645 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7646 
7647 	if (may_be_null)
7648 		*mem_reg = saved_reg;
7649 	return err;
7650 }
7651 
7652 /* Implementation details:
7653  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7654  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7655  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7656  * Two separate bpf_obj_new will also have different reg->id.
7657  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7658  * clears reg->id after value_or_null->value transition, since the verifier only
7659  * cares about the range of access to valid map value pointer and doesn't care
7660  * about actual address of the map element.
7661  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7662  * reg->id > 0 after value_or_null->value transition. By doing so
7663  * two bpf_map_lookups will be considered two different pointers that
7664  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7665  * returned from bpf_obj_new.
7666  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7667  * dead-locks.
7668  * Since only one bpf_spin_lock is allowed the checks are simpler than
7669  * reg_is_refcounted() logic. The verifier needs to remember only
7670  * one spin_lock instead of array of acquired_refs.
7671  * cur_state->active_lock remembers which map value element or allocated
7672  * object got locked and clears it after bpf_spin_unlock.
7673  */
7674 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7675 			     bool is_lock)
7676 {
7677 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7678 	struct bpf_verifier_state *cur = env->cur_state;
7679 	bool is_const = tnum_is_const(reg->var_off);
7680 	u64 val = reg->var_off.value;
7681 	struct bpf_map *map = NULL;
7682 	struct btf *btf = NULL;
7683 	struct btf_record *rec;
7684 
7685 	if (!is_const) {
7686 		verbose(env,
7687 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7688 			regno);
7689 		return -EINVAL;
7690 	}
7691 	if (reg->type == PTR_TO_MAP_VALUE) {
7692 		map = reg->map_ptr;
7693 		if (!map->btf) {
7694 			verbose(env,
7695 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7696 				map->name);
7697 			return -EINVAL;
7698 		}
7699 	} else {
7700 		btf = reg->btf;
7701 	}
7702 
7703 	rec = reg_btf_record(reg);
7704 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7705 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7706 			map ? map->name : "kptr");
7707 		return -EINVAL;
7708 	}
7709 	if (rec->spin_lock_off != val + reg->off) {
7710 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7711 			val + reg->off, rec->spin_lock_off);
7712 		return -EINVAL;
7713 	}
7714 	if (is_lock) {
7715 		if (cur->active_lock.ptr) {
7716 			verbose(env,
7717 				"Locking two bpf_spin_locks are not allowed\n");
7718 			return -EINVAL;
7719 		}
7720 		if (map)
7721 			cur->active_lock.ptr = map;
7722 		else
7723 			cur->active_lock.ptr = btf;
7724 		cur->active_lock.id = reg->id;
7725 	} else {
7726 		void *ptr;
7727 
7728 		if (map)
7729 			ptr = map;
7730 		else
7731 			ptr = btf;
7732 
7733 		if (!cur->active_lock.ptr) {
7734 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7735 			return -EINVAL;
7736 		}
7737 		if (cur->active_lock.ptr != ptr ||
7738 		    cur->active_lock.id != reg->id) {
7739 			verbose(env, "bpf_spin_unlock of different lock\n");
7740 			return -EINVAL;
7741 		}
7742 
7743 		invalidate_non_owning_refs(env);
7744 
7745 		cur->active_lock.ptr = NULL;
7746 		cur->active_lock.id = 0;
7747 	}
7748 	return 0;
7749 }
7750 
7751 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7752 			      struct bpf_call_arg_meta *meta)
7753 {
7754 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7755 	bool is_const = tnum_is_const(reg->var_off);
7756 	struct bpf_map *map = reg->map_ptr;
7757 	u64 val = reg->var_off.value;
7758 
7759 	if (!is_const) {
7760 		verbose(env,
7761 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7762 			regno);
7763 		return -EINVAL;
7764 	}
7765 	if (!map->btf) {
7766 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7767 			map->name);
7768 		return -EINVAL;
7769 	}
7770 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7771 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7772 		return -EINVAL;
7773 	}
7774 	if (map->record->timer_off != val + reg->off) {
7775 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7776 			val + reg->off, map->record->timer_off);
7777 		return -EINVAL;
7778 	}
7779 	if (meta->map_ptr) {
7780 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7781 		return -EFAULT;
7782 	}
7783 	meta->map_uid = reg->map_uid;
7784 	meta->map_ptr = map;
7785 	return 0;
7786 }
7787 
7788 static int process_wq_func(struct bpf_verifier_env *env, int regno,
7789 			   struct bpf_kfunc_call_arg_meta *meta)
7790 {
7791 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7792 	struct bpf_map *map = reg->map_ptr;
7793 	u64 val = reg->var_off.value;
7794 
7795 	if (map->record->wq_off != val + reg->off) {
7796 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
7797 			val + reg->off, map->record->wq_off);
7798 		return -EINVAL;
7799 	}
7800 	meta->map.uid = reg->map_uid;
7801 	meta->map.ptr = map;
7802 	return 0;
7803 }
7804 
7805 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7806 			     struct bpf_call_arg_meta *meta)
7807 {
7808 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7809 	struct btf_field *kptr_field;
7810 	struct bpf_map *map_ptr;
7811 	struct btf_record *rec;
7812 	u32 kptr_off;
7813 
7814 	if (type_is_ptr_alloc_obj(reg->type)) {
7815 		rec = reg_btf_record(reg);
7816 	} else { /* PTR_TO_MAP_VALUE */
7817 		map_ptr = reg->map_ptr;
7818 		if (!map_ptr->btf) {
7819 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7820 				map_ptr->name);
7821 			return -EINVAL;
7822 		}
7823 		rec = map_ptr->record;
7824 		meta->map_ptr = map_ptr;
7825 	}
7826 
7827 	if (!tnum_is_const(reg->var_off)) {
7828 		verbose(env,
7829 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7830 			regno);
7831 		return -EINVAL;
7832 	}
7833 
7834 	if (!btf_record_has_field(rec, BPF_KPTR)) {
7835 		verbose(env, "R%d has no valid kptr\n", regno);
7836 		return -EINVAL;
7837 	}
7838 
7839 	kptr_off = reg->off + reg->var_off.value;
7840 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
7841 	if (!kptr_field) {
7842 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7843 		return -EACCES;
7844 	}
7845 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7846 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7847 		return -EACCES;
7848 	}
7849 	meta->kptr_field = kptr_field;
7850 	return 0;
7851 }
7852 
7853 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7854  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7855  *
7856  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7857  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7858  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7859  *
7860  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7861  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7862  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7863  * mutate the view of the dynptr and also possibly destroy it. In the latter
7864  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7865  * memory that dynptr points to.
7866  *
7867  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7868  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7869  * readonly dynptr view yet, hence only the first case is tracked and checked.
7870  *
7871  * This is consistent with how C applies the const modifier to a struct object,
7872  * where the pointer itself inside bpf_dynptr becomes const but not what it
7873  * points to.
7874  *
7875  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7876  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7877  */
7878 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7879 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7880 {
7881 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7882 	int err;
7883 
7884 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
7885 		verbose(env,
7886 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
7887 			regno);
7888 		return -EINVAL;
7889 	}
7890 
7891 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7892 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7893 	 */
7894 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7895 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7896 		return -EFAULT;
7897 	}
7898 
7899 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7900 	 *		 constructing a mutable bpf_dynptr object.
7901 	 *
7902 	 *		 Currently, this is only possible with PTR_TO_STACK
7903 	 *		 pointing to a region of at least 16 bytes which doesn't
7904 	 *		 contain an existing bpf_dynptr.
7905 	 *
7906 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7907 	 *		 mutated or destroyed. However, the memory it points to
7908 	 *		 may be mutated.
7909 	 *
7910 	 *  None       - Points to a initialized dynptr that can be mutated and
7911 	 *		 destroyed, including mutation of the memory it points
7912 	 *		 to.
7913 	 */
7914 	if (arg_type & MEM_UNINIT) {
7915 		int i;
7916 
7917 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7918 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7919 			return -EINVAL;
7920 		}
7921 
7922 		/* we write BPF_DW bits (8 bytes) at a time */
7923 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7924 			err = check_mem_access(env, insn_idx, regno,
7925 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7926 			if (err)
7927 				return err;
7928 		}
7929 
7930 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7931 	} else /* MEM_RDONLY and None case from above */ {
7932 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7933 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7934 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7935 			return -EINVAL;
7936 		}
7937 
7938 		if (!is_dynptr_reg_valid_init(env, reg)) {
7939 			verbose(env,
7940 				"Expected an initialized dynptr as arg #%d\n",
7941 				regno);
7942 			return -EINVAL;
7943 		}
7944 
7945 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7946 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7947 			verbose(env,
7948 				"Expected a dynptr of type %s as arg #%d\n",
7949 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7950 			return -EINVAL;
7951 		}
7952 
7953 		err = mark_dynptr_read(env, reg);
7954 	}
7955 	return err;
7956 }
7957 
7958 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7959 {
7960 	struct bpf_func_state *state = func(env, reg);
7961 
7962 	return state->stack[spi].spilled_ptr.ref_obj_id;
7963 }
7964 
7965 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7966 {
7967 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7968 }
7969 
7970 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7971 {
7972 	return meta->kfunc_flags & KF_ITER_NEW;
7973 }
7974 
7975 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7976 {
7977 	return meta->kfunc_flags & KF_ITER_NEXT;
7978 }
7979 
7980 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7981 {
7982 	return meta->kfunc_flags & KF_ITER_DESTROY;
7983 }
7984 
7985 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
7986 			      const struct btf_param *arg)
7987 {
7988 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7989 	 * kfunc is iter state pointer
7990 	 */
7991 	if (is_iter_kfunc(meta))
7992 		return arg_idx == 0;
7993 
7994 	/* iter passed as an argument to a generic kfunc */
7995 	return btf_param_match_suffix(meta->btf, arg, "__iter");
7996 }
7997 
7998 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7999 			    struct bpf_kfunc_call_arg_meta *meta)
8000 {
8001 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8002 	const struct btf_type *t;
8003 	int spi, err, i, nr_slots, btf_id;
8004 
8005 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8006 	 * ensures struct convention, so we wouldn't need to do any BTF
8007 	 * validation here. But given iter state can be passed as a parameter
8008 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8009 	 * conservative here.
8010 	 */
8011 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8012 	if (btf_id < 0) {
8013 		verbose(env, "expected valid iter pointer as arg #%d\n", regno);
8014 		return -EINVAL;
8015 	}
8016 	t = btf_type_by_id(meta->btf, btf_id);
8017 	nr_slots = t->size / BPF_REG_SIZE;
8018 
8019 	if (is_iter_new_kfunc(meta)) {
8020 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8021 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8022 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8023 				iter_type_str(meta->btf, btf_id), regno);
8024 			return -EINVAL;
8025 		}
8026 
8027 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8028 			err = check_mem_access(env, insn_idx, regno,
8029 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8030 			if (err)
8031 				return err;
8032 		}
8033 
8034 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8035 		if (err)
8036 			return err;
8037 	} else {
8038 		/* iter_next() or iter_destroy(), as well as any kfunc
8039 		 * accepting iter argument, expect initialized iter state
8040 		 */
8041 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8042 		switch (err) {
8043 		case 0:
8044 			break;
8045 		case -EINVAL:
8046 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8047 				iter_type_str(meta->btf, btf_id), regno);
8048 			return err;
8049 		case -EPROTO:
8050 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8051 			return err;
8052 		default:
8053 			return err;
8054 		}
8055 
8056 		spi = iter_get_spi(env, reg, nr_slots);
8057 		if (spi < 0)
8058 			return spi;
8059 
8060 		err = mark_iter_read(env, reg, spi, nr_slots);
8061 		if (err)
8062 			return err;
8063 
8064 		/* remember meta->iter info for process_iter_next_call() */
8065 		meta->iter.spi = spi;
8066 		meta->iter.frameno = reg->frameno;
8067 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8068 
8069 		if (is_iter_destroy_kfunc(meta)) {
8070 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8071 			if (err)
8072 				return err;
8073 		}
8074 	}
8075 
8076 	return 0;
8077 }
8078 
8079 /* Look for a previous loop entry at insn_idx: nearest parent state
8080  * stopped at insn_idx with callsites matching those in cur->frame.
8081  */
8082 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8083 						  struct bpf_verifier_state *cur,
8084 						  int insn_idx)
8085 {
8086 	struct bpf_verifier_state_list *sl;
8087 	struct bpf_verifier_state *st;
8088 
8089 	/* Explored states are pushed in stack order, most recent states come first */
8090 	sl = *explored_state(env, insn_idx);
8091 	for (; sl; sl = sl->next) {
8092 		/* If st->branches != 0 state is a part of current DFS verification path,
8093 		 * hence cur & st for a loop.
8094 		 */
8095 		st = &sl->state;
8096 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8097 		    st->dfs_depth < cur->dfs_depth)
8098 			return st;
8099 	}
8100 
8101 	return NULL;
8102 }
8103 
8104 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8105 static bool regs_exact(const struct bpf_reg_state *rold,
8106 		       const struct bpf_reg_state *rcur,
8107 		       struct bpf_idmap *idmap);
8108 
8109 static void maybe_widen_reg(struct bpf_verifier_env *env,
8110 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8111 			    struct bpf_idmap *idmap)
8112 {
8113 	if (rold->type != SCALAR_VALUE)
8114 		return;
8115 	if (rold->type != rcur->type)
8116 		return;
8117 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8118 		return;
8119 	__mark_reg_unknown(env, rcur);
8120 }
8121 
8122 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8123 				   struct bpf_verifier_state *old,
8124 				   struct bpf_verifier_state *cur)
8125 {
8126 	struct bpf_func_state *fold, *fcur;
8127 	int i, fr;
8128 
8129 	reset_idmap_scratch(env);
8130 	for (fr = old->curframe; fr >= 0; fr--) {
8131 		fold = old->frame[fr];
8132 		fcur = cur->frame[fr];
8133 
8134 		for (i = 0; i < MAX_BPF_REG; i++)
8135 			maybe_widen_reg(env,
8136 					&fold->regs[i],
8137 					&fcur->regs[i],
8138 					&env->idmap_scratch);
8139 
8140 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8141 			if (!is_spilled_reg(&fold->stack[i]) ||
8142 			    !is_spilled_reg(&fcur->stack[i]))
8143 				continue;
8144 
8145 			maybe_widen_reg(env,
8146 					&fold->stack[i].spilled_ptr,
8147 					&fcur->stack[i].spilled_ptr,
8148 					&env->idmap_scratch);
8149 		}
8150 	}
8151 	return 0;
8152 }
8153 
8154 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8155 						 struct bpf_kfunc_call_arg_meta *meta)
8156 {
8157 	int iter_frameno = meta->iter.frameno;
8158 	int iter_spi = meta->iter.spi;
8159 
8160 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8161 }
8162 
8163 /* process_iter_next_call() is called when verifier gets to iterator's next
8164  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8165  * to it as just "iter_next()" in comments below.
8166  *
8167  * BPF verifier relies on a crucial contract for any iter_next()
8168  * implementation: it should *eventually* return NULL, and once that happens
8169  * it should keep returning NULL. That is, once iterator exhausts elements to
8170  * iterate, it should never reset or spuriously return new elements.
8171  *
8172  * With the assumption of such contract, process_iter_next_call() simulates
8173  * a fork in the verifier state to validate loop logic correctness and safety
8174  * without having to simulate infinite amount of iterations.
8175  *
8176  * In current state, we first assume that iter_next() returned NULL and
8177  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8178  * conditions we should not form an infinite loop and should eventually reach
8179  * exit.
8180  *
8181  * Besides that, we also fork current state and enqueue it for later
8182  * verification. In a forked state we keep iterator state as ACTIVE
8183  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8184  * also bump iteration depth to prevent erroneous infinite loop detection
8185  * later on (see iter_active_depths_differ() comment for details). In this
8186  * state we assume that we'll eventually loop back to another iter_next()
8187  * calls (it could be in exactly same location or in some other instruction,
8188  * it doesn't matter, we don't make any unnecessary assumptions about this,
8189  * everything revolves around iterator state in a stack slot, not which
8190  * instruction is calling iter_next()). When that happens, we either will come
8191  * to iter_next() with equivalent state and can conclude that next iteration
8192  * will proceed in exactly the same way as we just verified, so it's safe to
8193  * assume that loop converges. If not, we'll go on another iteration
8194  * simulation with a different input state, until all possible starting states
8195  * are validated or we reach maximum number of instructions limit.
8196  *
8197  * This way, we will either exhaustively discover all possible input states
8198  * that iterator loop can start with and eventually will converge, or we'll
8199  * effectively regress into bounded loop simulation logic and either reach
8200  * maximum number of instructions if loop is not provably convergent, or there
8201  * is some statically known limit on number of iterations (e.g., if there is
8202  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8203  *
8204  * Iteration convergence logic in is_state_visited() relies on exact
8205  * states comparison, which ignores read and precision marks.
8206  * This is necessary because read and precision marks are not finalized
8207  * while in the loop. Exact comparison might preclude convergence for
8208  * simple programs like below:
8209  *
8210  *     i = 0;
8211  *     while(iter_next(&it))
8212  *       i++;
8213  *
8214  * At each iteration step i++ would produce a new distinct state and
8215  * eventually instruction processing limit would be reached.
8216  *
8217  * To avoid such behavior speculatively forget (widen) range for
8218  * imprecise scalar registers, if those registers were not precise at the
8219  * end of the previous iteration and do not match exactly.
8220  *
8221  * This is a conservative heuristic that allows to verify wide range of programs,
8222  * however it precludes verification of programs that conjure an
8223  * imprecise value on the first loop iteration and use it as precise on a second.
8224  * For example, the following safe program would fail to verify:
8225  *
8226  *     struct bpf_num_iter it;
8227  *     int arr[10];
8228  *     int i = 0, a = 0;
8229  *     bpf_iter_num_new(&it, 0, 10);
8230  *     while (bpf_iter_num_next(&it)) {
8231  *       if (a == 0) {
8232  *         a = 1;
8233  *         i = 7; // Because i changed verifier would forget
8234  *                // it's range on second loop entry.
8235  *       } else {
8236  *         arr[i] = 42; // This would fail to verify.
8237  *       }
8238  *     }
8239  *     bpf_iter_num_destroy(&it);
8240  */
8241 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8242 				  struct bpf_kfunc_call_arg_meta *meta)
8243 {
8244 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8245 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8246 	struct bpf_reg_state *cur_iter, *queued_iter;
8247 
8248 	BTF_TYPE_EMIT(struct bpf_iter);
8249 
8250 	cur_iter = get_iter_from_state(cur_st, meta);
8251 
8252 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8253 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8254 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8255 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8256 		return -EFAULT;
8257 	}
8258 
8259 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8260 		/* Because iter_next() call is a checkpoint is_state_visitied()
8261 		 * should guarantee parent state with same call sites and insn_idx.
8262 		 */
8263 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8264 		    !same_callsites(cur_st->parent, cur_st)) {
8265 			verbose(env, "bug: bad parent state for iter next call");
8266 			return -EFAULT;
8267 		}
8268 		/* Note cur_st->parent in the call below, it is necessary to skip
8269 		 * checkpoint created for cur_st by is_state_visited()
8270 		 * right at this instruction.
8271 		 */
8272 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8273 		/* branch out active iter state */
8274 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8275 		if (!queued_st)
8276 			return -ENOMEM;
8277 
8278 		queued_iter = get_iter_from_state(queued_st, meta);
8279 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8280 		queued_iter->iter.depth++;
8281 		if (prev_st)
8282 			widen_imprecise_scalars(env, prev_st, queued_st);
8283 
8284 		queued_fr = queued_st->frame[queued_st->curframe];
8285 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8286 	}
8287 
8288 	/* switch to DRAINED state, but keep the depth unchanged */
8289 	/* mark current iter state as drained and assume returned NULL */
8290 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8291 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8292 
8293 	return 0;
8294 }
8295 
8296 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8297 {
8298 	return type == ARG_CONST_SIZE ||
8299 	       type == ARG_CONST_SIZE_OR_ZERO;
8300 }
8301 
8302 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8303 {
8304 	return base_type(type) == ARG_PTR_TO_MEM &&
8305 	       type & MEM_UNINIT;
8306 }
8307 
8308 static bool arg_type_is_release(enum bpf_arg_type type)
8309 {
8310 	return type & OBJ_RELEASE;
8311 }
8312 
8313 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8314 {
8315 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8316 }
8317 
8318 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8319 				 const struct bpf_call_arg_meta *meta,
8320 				 enum bpf_arg_type *arg_type)
8321 {
8322 	if (!meta->map_ptr) {
8323 		/* kernel subsystem misconfigured verifier */
8324 		verbose(env, "invalid map_ptr to access map->type\n");
8325 		return -EACCES;
8326 	}
8327 
8328 	switch (meta->map_ptr->map_type) {
8329 	case BPF_MAP_TYPE_SOCKMAP:
8330 	case BPF_MAP_TYPE_SOCKHASH:
8331 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8332 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8333 		} else {
8334 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8335 			return -EINVAL;
8336 		}
8337 		break;
8338 	case BPF_MAP_TYPE_BLOOM_FILTER:
8339 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8340 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8341 		break;
8342 	default:
8343 		break;
8344 	}
8345 	return 0;
8346 }
8347 
8348 struct bpf_reg_types {
8349 	const enum bpf_reg_type types[10];
8350 	u32 *btf_id;
8351 };
8352 
8353 static const struct bpf_reg_types sock_types = {
8354 	.types = {
8355 		PTR_TO_SOCK_COMMON,
8356 		PTR_TO_SOCKET,
8357 		PTR_TO_TCP_SOCK,
8358 		PTR_TO_XDP_SOCK,
8359 	},
8360 };
8361 
8362 #ifdef CONFIG_NET
8363 static const struct bpf_reg_types btf_id_sock_common_types = {
8364 	.types = {
8365 		PTR_TO_SOCK_COMMON,
8366 		PTR_TO_SOCKET,
8367 		PTR_TO_TCP_SOCK,
8368 		PTR_TO_XDP_SOCK,
8369 		PTR_TO_BTF_ID,
8370 		PTR_TO_BTF_ID | PTR_TRUSTED,
8371 	},
8372 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8373 };
8374 #endif
8375 
8376 static const struct bpf_reg_types mem_types = {
8377 	.types = {
8378 		PTR_TO_STACK,
8379 		PTR_TO_PACKET,
8380 		PTR_TO_PACKET_META,
8381 		PTR_TO_MAP_KEY,
8382 		PTR_TO_MAP_VALUE,
8383 		PTR_TO_MEM,
8384 		PTR_TO_MEM | MEM_RINGBUF,
8385 		PTR_TO_BUF,
8386 		PTR_TO_BTF_ID | PTR_TRUSTED,
8387 	},
8388 };
8389 
8390 static const struct bpf_reg_types spin_lock_types = {
8391 	.types = {
8392 		PTR_TO_MAP_VALUE,
8393 		PTR_TO_BTF_ID | MEM_ALLOC,
8394 	}
8395 };
8396 
8397 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8398 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8399 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8400 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8401 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8402 static const struct bpf_reg_types btf_ptr_types = {
8403 	.types = {
8404 		PTR_TO_BTF_ID,
8405 		PTR_TO_BTF_ID | PTR_TRUSTED,
8406 		PTR_TO_BTF_ID | MEM_RCU,
8407 	},
8408 };
8409 static const struct bpf_reg_types percpu_btf_ptr_types = {
8410 	.types = {
8411 		PTR_TO_BTF_ID | MEM_PERCPU,
8412 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8413 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8414 	}
8415 };
8416 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8417 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8418 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8419 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8420 static const struct bpf_reg_types kptr_xchg_dest_types = {
8421 	.types = {
8422 		PTR_TO_MAP_VALUE,
8423 		PTR_TO_BTF_ID | MEM_ALLOC
8424 	}
8425 };
8426 static const struct bpf_reg_types dynptr_types = {
8427 	.types = {
8428 		PTR_TO_STACK,
8429 		CONST_PTR_TO_DYNPTR,
8430 	}
8431 };
8432 
8433 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8434 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8435 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8436 	[ARG_CONST_SIZE]		= &scalar_types,
8437 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8438 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8439 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8440 	[ARG_PTR_TO_CTX]		= &context_types,
8441 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8442 #ifdef CONFIG_NET
8443 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8444 #endif
8445 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8446 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8447 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8448 	[ARG_PTR_TO_MEM]		= &mem_types,
8449 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8450 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8451 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8452 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8453 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8454 	[ARG_PTR_TO_TIMER]		= &timer_types,
8455 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
8456 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8457 };
8458 
8459 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8460 			  enum bpf_arg_type arg_type,
8461 			  const u32 *arg_btf_id,
8462 			  struct bpf_call_arg_meta *meta)
8463 {
8464 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8465 	enum bpf_reg_type expected, type = reg->type;
8466 	const struct bpf_reg_types *compatible;
8467 	int i, j;
8468 
8469 	compatible = compatible_reg_types[base_type(arg_type)];
8470 	if (!compatible) {
8471 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8472 		return -EFAULT;
8473 	}
8474 
8475 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8476 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8477 	 *
8478 	 * Same for MAYBE_NULL:
8479 	 *
8480 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8481 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8482 	 *
8483 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8484 	 *
8485 	 * Therefore we fold these flags depending on the arg_type before comparison.
8486 	 */
8487 	if (arg_type & MEM_RDONLY)
8488 		type &= ~MEM_RDONLY;
8489 	if (arg_type & PTR_MAYBE_NULL)
8490 		type &= ~PTR_MAYBE_NULL;
8491 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8492 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8493 
8494 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
8495 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
8496 		type &= ~MEM_ALLOC;
8497 		type &= ~MEM_PERCPU;
8498 	}
8499 
8500 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8501 		expected = compatible->types[i];
8502 		if (expected == NOT_INIT)
8503 			break;
8504 
8505 		if (type == expected)
8506 			goto found;
8507 	}
8508 
8509 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8510 	for (j = 0; j + 1 < i; j++)
8511 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8512 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8513 	return -EACCES;
8514 
8515 found:
8516 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8517 		return 0;
8518 
8519 	if (compatible == &mem_types) {
8520 		if (!(arg_type & MEM_RDONLY)) {
8521 			verbose(env,
8522 				"%s() may write into memory pointed by R%d type=%s\n",
8523 				func_id_name(meta->func_id),
8524 				regno, reg_type_str(env, reg->type));
8525 			return -EACCES;
8526 		}
8527 		return 0;
8528 	}
8529 
8530 	switch ((int)reg->type) {
8531 	case PTR_TO_BTF_ID:
8532 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8533 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8534 	case PTR_TO_BTF_ID | MEM_RCU:
8535 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8536 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8537 	{
8538 		/* For bpf_sk_release, it needs to match against first member
8539 		 * 'struct sock_common', hence make an exception for it. This
8540 		 * allows bpf_sk_release to work for multiple socket types.
8541 		 */
8542 		bool strict_type_match = arg_type_is_release(arg_type) &&
8543 					 meta->func_id != BPF_FUNC_sk_release;
8544 
8545 		if (type_may_be_null(reg->type) &&
8546 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8547 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8548 			return -EACCES;
8549 		}
8550 
8551 		if (!arg_btf_id) {
8552 			if (!compatible->btf_id) {
8553 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8554 				return -EFAULT;
8555 			}
8556 			arg_btf_id = compatible->btf_id;
8557 		}
8558 
8559 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8560 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8561 				return -EACCES;
8562 		} else {
8563 			if (arg_btf_id == BPF_PTR_POISON) {
8564 				verbose(env, "verifier internal error:");
8565 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8566 					regno);
8567 				return -EACCES;
8568 			}
8569 
8570 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8571 						  btf_vmlinux, *arg_btf_id,
8572 						  strict_type_match)) {
8573 				verbose(env, "R%d is of type %s but %s is expected\n",
8574 					regno, btf_type_name(reg->btf, reg->btf_id),
8575 					btf_type_name(btf_vmlinux, *arg_btf_id));
8576 				return -EACCES;
8577 			}
8578 		}
8579 		break;
8580 	}
8581 	case PTR_TO_BTF_ID | MEM_ALLOC:
8582 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8583 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8584 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8585 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8586 			return -EFAULT;
8587 		}
8588 		/* Check if local kptr in src arg matches kptr in dst arg */
8589 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
8590 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8591 				return -EACCES;
8592 		}
8593 		break;
8594 	case PTR_TO_BTF_ID | MEM_PERCPU:
8595 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8596 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8597 		/* Handled by helper specific checks */
8598 		break;
8599 	default:
8600 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8601 		return -EFAULT;
8602 	}
8603 	return 0;
8604 }
8605 
8606 static struct btf_field *
8607 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8608 {
8609 	struct btf_field *field;
8610 	struct btf_record *rec;
8611 
8612 	rec = reg_btf_record(reg);
8613 	if (!rec)
8614 		return NULL;
8615 
8616 	field = btf_record_find(rec, off, fields);
8617 	if (!field)
8618 		return NULL;
8619 
8620 	return field;
8621 }
8622 
8623 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8624 				  const struct bpf_reg_state *reg, int regno,
8625 				  enum bpf_arg_type arg_type)
8626 {
8627 	u32 type = reg->type;
8628 
8629 	/* When referenced register is passed to release function, its fixed
8630 	 * offset must be 0.
8631 	 *
8632 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8633 	 * meta->release_regno.
8634 	 */
8635 	if (arg_type_is_release(arg_type)) {
8636 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8637 		 * may not directly point to the object being released, but to
8638 		 * dynptr pointing to such object, which might be at some offset
8639 		 * on the stack. In that case, we simply to fallback to the
8640 		 * default handling.
8641 		 */
8642 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8643 			return 0;
8644 
8645 		/* Doing check_ptr_off_reg check for the offset will catch this
8646 		 * because fixed_off_ok is false, but checking here allows us
8647 		 * to give the user a better error message.
8648 		 */
8649 		if (reg->off) {
8650 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8651 				regno);
8652 			return -EINVAL;
8653 		}
8654 		return __check_ptr_off_reg(env, reg, regno, false);
8655 	}
8656 
8657 	switch (type) {
8658 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8659 	case PTR_TO_STACK:
8660 	case PTR_TO_PACKET:
8661 	case PTR_TO_PACKET_META:
8662 	case PTR_TO_MAP_KEY:
8663 	case PTR_TO_MAP_VALUE:
8664 	case PTR_TO_MEM:
8665 	case PTR_TO_MEM | MEM_RDONLY:
8666 	case PTR_TO_MEM | MEM_RINGBUF:
8667 	case PTR_TO_BUF:
8668 	case PTR_TO_BUF | MEM_RDONLY:
8669 	case PTR_TO_ARENA:
8670 	case SCALAR_VALUE:
8671 		return 0;
8672 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8673 	 * fixed offset.
8674 	 */
8675 	case PTR_TO_BTF_ID:
8676 	case PTR_TO_BTF_ID | MEM_ALLOC:
8677 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8678 	case PTR_TO_BTF_ID | MEM_RCU:
8679 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8680 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8681 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8682 		 * its fixed offset must be 0. In the other cases, fixed offset
8683 		 * can be non-zero. This was already checked above. So pass
8684 		 * fixed_off_ok as true to allow fixed offset for all other
8685 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8686 		 * still need to do checks instead of returning.
8687 		 */
8688 		return __check_ptr_off_reg(env, reg, regno, true);
8689 	default:
8690 		return __check_ptr_off_reg(env, reg, regno, false);
8691 	}
8692 }
8693 
8694 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8695 						const struct bpf_func_proto *fn,
8696 						struct bpf_reg_state *regs)
8697 {
8698 	struct bpf_reg_state *state = NULL;
8699 	int i;
8700 
8701 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8702 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8703 			if (state) {
8704 				verbose(env, "verifier internal error: multiple dynptr args\n");
8705 				return NULL;
8706 			}
8707 			state = &regs[BPF_REG_1 + i];
8708 		}
8709 
8710 	if (!state)
8711 		verbose(env, "verifier internal error: no dynptr arg found\n");
8712 
8713 	return state;
8714 }
8715 
8716 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8717 {
8718 	struct bpf_func_state *state = func(env, reg);
8719 	int spi;
8720 
8721 	if (reg->type == CONST_PTR_TO_DYNPTR)
8722 		return reg->id;
8723 	spi = dynptr_get_spi(env, reg);
8724 	if (spi < 0)
8725 		return spi;
8726 	return state->stack[spi].spilled_ptr.id;
8727 }
8728 
8729 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8730 {
8731 	struct bpf_func_state *state = func(env, reg);
8732 	int spi;
8733 
8734 	if (reg->type == CONST_PTR_TO_DYNPTR)
8735 		return reg->ref_obj_id;
8736 	spi = dynptr_get_spi(env, reg);
8737 	if (spi < 0)
8738 		return spi;
8739 	return state->stack[spi].spilled_ptr.ref_obj_id;
8740 }
8741 
8742 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8743 					    struct bpf_reg_state *reg)
8744 {
8745 	struct bpf_func_state *state = func(env, reg);
8746 	int spi;
8747 
8748 	if (reg->type == CONST_PTR_TO_DYNPTR)
8749 		return reg->dynptr.type;
8750 
8751 	spi = __get_spi(reg->off);
8752 	if (spi < 0) {
8753 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8754 		return BPF_DYNPTR_TYPE_INVALID;
8755 	}
8756 
8757 	return state->stack[spi].spilled_ptr.dynptr.type;
8758 }
8759 
8760 static int check_reg_const_str(struct bpf_verifier_env *env,
8761 			       struct bpf_reg_state *reg, u32 regno)
8762 {
8763 	struct bpf_map *map = reg->map_ptr;
8764 	int err;
8765 	int map_off;
8766 	u64 map_addr;
8767 	char *str_ptr;
8768 
8769 	if (reg->type != PTR_TO_MAP_VALUE)
8770 		return -EINVAL;
8771 
8772 	if (!bpf_map_is_rdonly(map)) {
8773 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8774 		return -EACCES;
8775 	}
8776 
8777 	if (!tnum_is_const(reg->var_off)) {
8778 		verbose(env, "R%d is not a constant address'\n", regno);
8779 		return -EACCES;
8780 	}
8781 
8782 	if (!map->ops->map_direct_value_addr) {
8783 		verbose(env, "no direct value access support for this map type\n");
8784 		return -EACCES;
8785 	}
8786 
8787 	err = check_map_access(env, regno, reg->off,
8788 			       map->value_size - reg->off, false,
8789 			       ACCESS_HELPER);
8790 	if (err)
8791 		return err;
8792 
8793 	map_off = reg->off + reg->var_off.value;
8794 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8795 	if (err) {
8796 		verbose(env, "direct value access on string failed\n");
8797 		return err;
8798 	}
8799 
8800 	str_ptr = (char *)(long)(map_addr);
8801 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8802 		verbose(env, "string is not zero-terminated\n");
8803 		return -EINVAL;
8804 	}
8805 	return 0;
8806 }
8807 
8808 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8809 			  struct bpf_call_arg_meta *meta,
8810 			  const struct bpf_func_proto *fn,
8811 			  int insn_idx)
8812 {
8813 	u32 regno = BPF_REG_1 + arg;
8814 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8815 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8816 	enum bpf_reg_type type = reg->type;
8817 	u32 *arg_btf_id = NULL;
8818 	int err = 0;
8819 
8820 	if (arg_type == ARG_DONTCARE)
8821 		return 0;
8822 
8823 	err = check_reg_arg(env, regno, SRC_OP);
8824 	if (err)
8825 		return err;
8826 
8827 	if (arg_type == ARG_ANYTHING) {
8828 		if (is_pointer_value(env, regno)) {
8829 			verbose(env, "R%d leaks addr into helper function\n",
8830 				regno);
8831 			return -EACCES;
8832 		}
8833 		return 0;
8834 	}
8835 
8836 	if (type_is_pkt_pointer(type) &&
8837 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8838 		verbose(env, "helper access to the packet is not allowed\n");
8839 		return -EACCES;
8840 	}
8841 
8842 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8843 		err = resolve_map_arg_type(env, meta, &arg_type);
8844 		if (err)
8845 			return err;
8846 	}
8847 
8848 	if (register_is_null(reg) && type_may_be_null(arg_type))
8849 		/* A NULL register has a SCALAR_VALUE type, so skip
8850 		 * type checking.
8851 		 */
8852 		goto skip_type_check;
8853 
8854 	/* arg_btf_id and arg_size are in a union. */
8855 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8856 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8857 		arg_btf_id = fn->arg_btf_id[arg];
8858 
8859 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8860 	if (err)
8861 		return err;
8862 
8863 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8864 	if (err)
8865 		return err;
8866 
8867 skip_type_check:
8868 	if (arg_type_is_release(arg_type)) {
8869 		if (arg_type_is_dynptr(arg_type)) {
8870 			struct bpf_func_state *state = func(env, reg);
8871 			int spi;
8872 
8873 			/* Only dynptr created on stack can be released, thus
8874 			 * the get_spi and stack state checks for spilled_ptr
8875 			 * should only be done before process_dynptr_func for
8876 			 * PTR_TO_STACK.
8877 			 */
8878 			if (reg->type == PTR_TO_STACK) {
8879 				spi = dynptr_get_spi(env, reg);
8880 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8881 					verbose(env, "arg %d is an unacquired reference\n", regno);
8882 					return -EINVAL;
8883 				}
8884 			} else {
8885 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8886 				return -EINVAL;
8887 			}
8888 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8889 			verbose(env, "R%d must be referenced when passed to release function\n",
8890 				regno);
8891 			return -EINVAL;
8892 		}
8893 		if (meta->release_regno) {
8894 			verbose(env, "verifier internal error: more than one release argument\n");
8895 			return -EFAULT;
8896 		}
8897 		meta->release_regno = regno;
8898 	}
8899 
8900 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
8901 		if (meta->ref_obj_id) {
8902 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8903 				regno, reg->ref_obj_id,
8904 				meta->ref_obj_id);
8905 			return -EFAULT;
8906 		}
8907 		meta->ref_obj_id = reg->ref_obj_id;
8908 	}
8909 
8910 	switch (base_type(arg_type)) {
8911 	case ARG_CONST_MAP_PTR:
8912 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8913 		if (meta->map_ptr) {
8914 			/* Use map_uid (which is unique id of inner map) to reject:
8915 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8916 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8917 			 * if (inner_map1 && inner_map2) {
8918 			 *     timer = bpf_map_lookup_elem(inner_map1);
8919 			 *     if (timer)
8920 			 *         // mismatch would have been allowed
8921 			 *         bpf_timer_init(timer, inner_map2);
8922 			 * }
8923 			 *
8924 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8925 			 */
8926 			if (meta->map_ptr != reg->map_ptr ||
8927 			    meta->map_uid != reg->map_uid) {
8928 				verbose(env,
8929 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8930 					meta->map_uid, reg->map_uid);
8931 				return -EINVAL;
8932 			}
8933 		}
8934 		meta->map_ptr = reg->map_ptr;
8935 		meta->map_uid = reg->map_uid;
8936 		break;
8937 	case ARG_PTR_TO_MAP_KEY:
8938 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8939 		 * check that [key, key + map->key_size) are within
8940 		 * stack limits and initialized
8941 		 */
8942 		if (!meta->map_ptr) {
8943 			/* in function declaration map_ptr must come before
8944 			 * map_key, so that it's verified and known before
8945 			 * we have to check map_key here. Otherwise it means
8946 			 * that kernel subsystem misconfigured verifier
8947 			 */
8948 			verbose(env, "invalid map_ptr to access map->key\n");
8949 			return -EACCES;
8950 		}
8951 		err = check_helper_mem_access(env, regno,
8952 					      meta->map_ptr->key_size, false,
8953 					      NULL);
8954 		break;
8955 	case ARG_PTR_TO_MAP_VALUE:
8956 		if (type_may_be_null(arg_type) && register_is_null(reg))
8957 			return 0;
8958 
8959 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8960 		 * check [value, value + map->value_size) validity
8961 		 */
8962 		if (!meta->map_ptr) {
8963 			/* kernel subsystem misconfigured verifier */
8964 			verbose(env, "invalid map_ptr to access map->value\n");
8965 			return -EACCES;
8966 		}
8967 		meta->raw_mode = arg_type & MEM_UNINIT;
8968 		err = check_helper_mem_access(env, regno,
8969 					      meta->map_ptr->value_size, false,
8970 					      meta);
8971 		break;
8972 	case ARG_PTR_TO_PERCPU_BTF_ID:
8973 		if (!reg->btf_id) {
8974 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8975 			return -EACCES;
8976 		}
8977 		meta->ret_btf = reg->btf;
8978 		meta->ret_btf_id = reg->btf_id;
8979 		break;
8980 	case ARG_PTR_TO_SPIN_LOCK:
8981 		if (in_rbtree_lock_required_cb(env)) {
8982 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8983 			return -EACCES;
8984 		}
8985 		if (meta->func_id == BPF_FUNC_spin_lock) {
8986 			err = process_spin_lock(env, regno, true);
8987 			if (err)
8988 				return err;
8989 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8990 			err = process_spin_lock(env, regno, false);
8991 			if (err)
8992 				return err;
8993 		} else {
8994 			verbose(env, "verifier internal error\n");
8995 			return -EFAULT;
8996 		}
8997 		break;
8998 	case ARG_PTR_TO_TIMER:
8999 		err = process_timer_func(env, regno, meta);
9000 		if (err)
9001 			return err;
9002 		break;
9003 	case ARG_PTR_TO_FUNC:
9004 		meta->subprogno = reg->subprogno;
9005 		break;
9006 	case ARG_PTR_TO_MEM:
9007 		/* The access to this pointer is only checked when we hit the
9008 		 * next is_mem_size argument below.
9009 		 */
9010 		meta->raw_mode = arg_type & MEM_UNINIT;
9011 		if (arg_type & MEM_FIXED_SIZE) {
9012 			err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta);
9013 			if (err)
9014 				return err;
9015 			if (arg_type & MEM_ALIGNED)
9016 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9017 		}
9018 		break;
9019 	case ARG_CONST_SIZE:
9020 		err = check_mem_size_reg(env, reg, regno, false, meta);
9021 		break;
9022 	case ARG_CONST_SIZE_OR_ZERO:
9023 		err = check_mem_size_reg(env, reg, regno, true, meta);
9024 		break;
9025 	case ARG_PTR_TO_DYNPTR:
9026 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9027 		if (err)
9028 			return err;
9029 		break;
9030 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9031 		if (!tnum_is_const(reg->var_off)) {
9032 			verbose(env, "R%d is not a known constant'\n",
9033 				regno);
9034 			return -EACCES;
9035 		}
9036 		meta->mem_size = reg->var_off.value;
9037 		err = mark_chain_precision(env, regno);
9038 		if (err)
9039 			return err;
9040 		break;
9041 	case ARG_PTR_TO_CONST_STR:
9042 	{
9043 		err = check_reg_const_str(env, reg, regno);
9044 		if (err)
9045 			return err;
9046 		break;
9047 	}
9048 	case ARG_KPTR_XCHG_DEST:
9049 		err = process_kptr_func(env, regno, meta);
9050 		if (err)
9051 			return err;
9052 		break;
9053 	}
9054 
9055 	return err;
9056 }
9057 
9058 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9059 {
9060 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9061 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9062 
9063 	if (func_id != BPF_FUNC_map_update_elem &&
9064 	    func_id != BPF_FUNC_map_delete_elem)
9065 		return false;
9066 
9067 	/* It's not possible to get access to a locked struct sock in these
9068 	 * contexts, so updating is safe.
9069 	 */
9070 	switch (type) {
9071 	case BPF_PROG_TYPE_TRACING:
9072 		if (eatype == BPF_TRACE_ITER)
9073 			return true;
9074 		break;
9075 	case BPF_PROG_TYPE_SOCK_OPS:
9076 		/* map_update allowed only via dedicated helpers with event type checks */
9077 		if (func_id == BPF_FUNC_map_delete_elem)
9078 			return true;
9079 		break;
9080 	case BPF_PROG_TYPE_SOCKET_FILTER:
9081 	case BPF_PROG_TYPE_SCHED_CLS:
9082 	case BPF_PROG_TYPE_SCHED_ACT:
9083 	case BPF_PROG_TYPE_XDP:
9084 	case BPF_PROG_TYPE_SK_REUSEPORT:
9085 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9086 	case BPF_PROG_TYPE_SK_LOOKUP:
9087 		return true;
9088 	default:
9089 		break;
9090 	}
9091 
9092 	verbose(env, "cannot update sockmap in this context\n");
9093 	return false;
9094 }
9095 
9096 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9097 {
9098 	return env->prog->jit_requested &&
9099 	       bpf_jit_supports_subprog_tailcalls();
9100 }
9101 
9102 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9103 					struct bpf_map *map, int func_id)
9104 {
9105 	if (!map)
9106 		return 0;
9107 
9108 	/* We need a two way check, first is from map perspective ... */
9109 	switch (map->map_type) {
9110 	case BPF_MAP_TYPE_PROG_ARRAY:
9111 		if (func_id != BPF_FUNC_tail_call)
9112 			goto error;
9113 		break;
9114 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9115 		if (func_id != BPF_FUNC_perf_event_read &&
9116 		    func_id != BPF_FUNC_perf_event_output &&
9117 		    func_id != BPF_FUNC_skb_output &&
9118 		    func_id != BPF_FUNC_perf_event_read_value &&
9119 		    func_id != BPF_FUNC_xdp_output)
9120 			goto error;
9121 		break;
9122 	case BPF_MAP_TYPE_RINGBUF:
9123 		if (func_id != BPF_FUNC_ringbuf_output &&
9124 		    func_id != BPF_FUNC_ringbuf_reserve &&
9125 		    func_id != BPF_FUNC_ringbuf_query &&
9126 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9127 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9128 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9129 			goto error;
9130 		break;
9131 	case BPF_MAP_TYPE_USER_RINGBUF:
9132 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9133 			goto error;
9134 		break;
9135 	case BPF_MAP_TYPE_STACK_TRACE:
9136 		if (func_id != BPF_FUNC_get_stackid)
9137 			goto error;
9138 		break;
9139 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9140 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9141 		    func_id != BPF_FUNC_current_task_under_cgroup)
9142 			goto error;
9143 		break;
9144 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9145 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9146 		if (func_id != BPF_FUNC_get_local_storage)
9147 			goto error;
9148 		break;
9149 	case BPF_MAP_TYPE_DEVMAP:
9150 	case BPF_MAP_TYPE_DEVMAP_HASH:
9151 		if (func_id != BPF_FUNC_redirect_map &&
9152 		    func_id != BPF_FUNC_map_lookup_elem)
9153 			goto error;
9154 		break;
9155 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9156 	 * appear.
9157 	 */
9158 	case BPF_MAP_TYPE_CPUMAP:
9159 		if (func_id != BPF_FUNC_redirect_map)
9160 			goto error;
9161 		break;
9162 	case BPF_MAP_TYPE_XSKMAP:
9163 		if (func_id != BPF_FUNC_redirect_map &&
9164 		    func_id != BPF_FUNC_map_lookup_elem)
9165 			goto error;
9166 		break;
9167 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9168 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9169 		if (func_id != BPF_FUNC_map_lookup_elem)
9170 			goto error;
9171 		break;
9172 	case BPF_MAP_TYPE_SOCKMAP:
9173 		if (func_id != BPF_FUNC_sk_redirect_map &&
9174 		    func_id != BPF_FUNC_sock_map_update &&
9175 		    func_id != BPF_FUNC_msg_redirect_map &&
9176 		    func_id != BPF_FUNC_sk_select_reuseport &&
9177 		    func_id != BPF_FUNC_map_lookup_elem &&
9178 		    !may_update_sockmap(env, func_id))
9179 			goto error;
9180 		break;
9181 	case BPF_MAP_TYPE_SOCKHASH:
9182 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9183 		    func_id != BPF_FUNC_sock_hash_update &&
9184 		    func_id != BPF_FUNC_msg_redirect_hash &&
9185 		    func_id != BPF_FUNC_sk_select_reuseport &&
9186 		    func_id != BPF_FUNC_map_lookup_elem &&
9187 		    !may_update_sockmap(env, func_id))
9188 			goto error;
9189 		break;
9190 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9191 		if (func_id != BPF_FUNC_sk_select_reuseport)
9192 			goto error;
9193 		break;
9194 	case BPF_MAP_TYPE_QUEUE:
9195 	case BPF_MAP_TYPE_STACK:
9196 		if (func_id != BPF_FUNC_map_peek_elem &&
9197 		    func_id != BPF_FUNC_map_pop_elem &&
9198 		    func_id != BPF_FUNC_map_push_elem)
9199 			goto error;
9200 		break;
9201 	case BPF_MAP_TYPE_SK_STORAGE:
9202 		if (func_id != BPF_FUNC_sk_storage_get &&
9203 		    func_id != BPF_FUNC_sk_storage_delete &&
9204 		    func_id != BPF_FUNC_kptr_xchg)
9205 			goto error;
9206 		break;
9207 	case BPF_MAP_TYPE_INODE_STORAGE:
9208 		if (func_id != BPF_FUNC_inode_storage_get &&
9209 		    func_id != BPF_FUNC_inode_storage_delete &&
9210 		    func_id != BPF_FUNC_kptr_xchg)
9211 			goto error;
9212 		break;
9213 	case BPF_MAP_TYPE_TASK_STORAGE:
9214 		if (func_id != BPF_FUNC_task_storage_get &&
9215 		    func_id != BPF_FUNC_task_storage_delete &&
9216 		    func_id != BPF_FUNC_kptr_xchg)
9217 			goto error;
9218 		break;
9219 	case BPF_MAP_TYPE_CGRP_STORAGE:
9220 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9221 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9222 		    func_id != BPF_FUNC_kptr_xchg)
9223 			goto error;
9224 		break;
9225 	case BPF_MAP_TYPE_BLOOM_FILTER:
9226 		if (func_id != BPF_FUNC_map_peek_elem &&
9227 		    func_id != BPF_FUNC_map_push_elem)
9228 			goto error;
9229 		break;
9230 	default:
9231 		break;
9232 	}
9233 
9234 	/* ... and second from the function itself. */
9235 	switch (func_id) {
9236 	case BPF_FUNC_tail_call:
9237 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9238 			goto error;
9239 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9240 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9241 			return -EINVAL;
9242 		}
9243 		break;
9244 	case BPF_FUNC_perf_event_read:
9245 	case BPF_FUNC_perf_event_output:
9246 	case BPF_FUNC_perf_event_read_value:
9247 	case BPF_FUNC_skb_output:
9248 	case BPF_FUNC_xdp_output:
9249 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9250 			goto error;
9251 		break;
9252 	case BPF_FUNC_ringbuf_output:
9253 	case BPF_FUNC_ringbuf_reserve:
9254 	case BPF_FUNC_ringbuf_query:
9255 	case BPF_FUNC_ringbuf_reserve_dynptr:
9256 	case BPF_FUNC_ringbuf_submit_dynptr:
9257 	case BPF_FUNC_ringbuf_discard_dynptr:
9258 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9259 			goto error;
9260 		break;
9261 	case BPF_FUNC_user_ringbuf_drain:
9262 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9263 			goto error;
9264 		break;
9265 	case BPF_FUNC_get_stackid:
9266 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9267 			goto error;
9268 		break;
9269 	case BPF_FUNC_current_task_under_cgroup:
9270 	case BPF_FUNC_skb_under_cgroup:
9271 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9272 			goto error;
9273 		break;
9274 	case BPF_FUNC_redirect_map:
9275 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9276 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9277 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9278 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9279 			goto error;
9280 		break;
9281 	case BPF_FUNC_sk_redirect_map:
9282 	case BPF_FUNC_msg_redirect_map:
9283 	case BPF_FUNC_sock_map_update:
9284 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9285 			goto error;
9286 		break;
9287 	case BPF_FUNC_sk_redirect_hash:
9288 	case BPF_FUNC_msg_redirect_hash:
9289 	case BPF_FUNC_sock_hash_update:
9290 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9291 			goto error;
9292 		break;
9293 	case BPF_FUNC_get_local_storage:
9294 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9295 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9296 			goto error;
9297 		break;
9298 	case BPF_FUNC_sk_select_reuseport:
9299 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9300 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9301 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9302 			goto error;
9303 		break;
9304 	case BPF_FUNC_map_pop_elem:
9305 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9306 		    map->map_type != BPF_MAP_TYPE_STACK)
9307 			goto error;
9308 		break;
9309 	case BPF_FUNC_map_peek_elem:
9310 	case BPF_FUNC_map_push_elem:
9311 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9312 		    map->map_type != BPF_MAP_TYPE_STACK &&
9313 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9314 			goto error;
9315 		break;
9316 	case BPF_FUNC_map_lookup_percpu_elem:
9317 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9318 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9319 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9320 			goto error;
9321 		break;
9322 	case BPF_FUNC_sk_storage_get:
9323 	case BPF_FUNC_sk_storage_delete:
9324 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9325 			goto error;
9326 		break;
9327 	case BPF_FUNC_inode_storage_get:
9328 	case BPF_FUNC_inode_storage_delete:
9329 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9330 			goto error;
9331 		break;
9332 	case BPF_FUNC_task_storage_get:
9333 	case BPF_FUNC_task_storage_delete:
9334 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9335 			goto error;
9336 		break;
9337 	case BPF_FUNC_cgrp_storage_get:
9338 	case BPF_FUNC_cgrp_storage_delete:
9339 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9340 			goto error;
9341 		break;
9342 	default:
9343 		break;
9344 	}
9345 
9346 	return 0;
9347 error:
9348 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9349 		map->map_type, func_id_name(func_id), func_id);
9350 	return -EINVAL;
9351 }
9352 
9353 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9354 {
9355 	int count = 0;
9356 
9357 	if (arg_type_is_raw_mem(fn->arg1_type))
9358 		count++;
9359 	if (arg_type_is_raw_mem(fn->arg2_type))
9360 		count++;
9361 	if (arg_type_is_raw_mem(fn->arg3_type))
9362 		count++;
9363 	if (arg_type_is_raw_mem(fn->arg4_type))
9364 		count++;
9365 	if (arg_type_is_raw_mem(fn->arg5_type))
9366 		count++;
9367 
9368 	/* We only support one arg being in raw mode at the moment,
9369 	 * which is sufficient for the helper functions we have
9370 	 * right now.
9371 	 */
9372 	return count <= 1;
9373 }
9374 
9375 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9376 {
9377 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9378 	bool has_size = fn->arg_size[arg] != 0;
9379 	bool is_next_size = false;
9380 
9381 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9382 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9383 
9384 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9385 		return is_next_size;
9386 
9387 	return has_size == is_next_size || is_next_size == is_fixed;
9388 }
9389 
9390 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9391 {
9392 	/* bpf_xxx(..., buf, len) call will access 'len'
9393 	 * bytes from memory 'buf'. Both arg types need
9394 	 * to be paired, so make sure there's no buggy
9395 	 * helper function specification.
9396 	 */
9397 	if (arg_type_is_mem_size(fn->arg1_type) ||
9398 	    check_args_pair_invalid(fn, 0) ||
9399 	    check_args_pair_invalid(fn, 1) ||
9400 	    check_args_pair_invalid(fn, 2) ||
9401 	    check_args_pair_invalid(fn, 3) ||
9402 	    check_args_pair_invalid(fn, 4))
9403 		return false;
9404 
9405 	return true;
9406 }
9407 
9408 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9409 {
9410 	int i;
9411 
9412 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9413 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9414 			return !!fn->arg_btf_id[i];
9415 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9416 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9417 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9418 		    /* arg_btf_id and arg_size are in a union. */
9419 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9420 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9421 			return false;
9422 	}
9423 
9424 	return true;
9425 }
9426 
9427 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9428 {
9429 	return check_raw_mode_ok(fn) &&
9430 	       check_arg_pair_ok(fn) &&
9431 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9432 }
9433 
9434 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9435  * are now invalid, so turn them into unknown SCALAR_VALUE.
9436  *
9437  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9438  * since these slices point to packet data.
9439  */
9440 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9441 {
9442 	struct bpf_func_state *state;
9443 	struct bpf_reg_state *reg;
9444 
9445 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9446 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9447 			mark_reg_invalid(env, reg);
9448 	}));
9449 }
9450 
9451 enum {
9452 	AT_PKT_END = -1,
9453 	BEYOND_PKT_END = -2,
9454 };
9455 
9456 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9457 {
9458 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9459 	struct bpf_reg_state *reg = &state->regs[regn];
9460 
9461 	if (reg->type != PTR_TO_PACKET)
9462 		/* PTR_TO_PACKET_META is not supported yet */
9463 		return;
9464 
9465 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9466 	 * How far beyond pkt_end it goes is unknown.
9467 	 * if (!range_open) it's the case of pkt >= pkt_end
9468 	 * if (range_open) it's the case of pkt > pkt_end
9469 	 * hence this pointer is at least 1 byte bigger than pkt_end
9470 	 */
9471 	if (range_open)
9472 		reg->range = BEYOND_PKT_END;
9473 	else
9474 		reg->range = AT_PKT_END;
9475 }
9476 
9477 /* The pointer with the specified id has released its reference to kernel
9478  * resources. Identify all copies of the same pointer and clear the reference.
9479  */
9480 static int release_reference(struct bpf_verifier_env *env,
9481 			     int ref_obj_id)
9482 {
9483 	struct bpf_func_state *state;
9484 	struct bpf_reg_state *reg;
9485 	int err;
9486 
9487 	err = release_reference_state(cur_func(env), ref_obj_id);
9488 	if (err)
9489 		return err;
9490 
9491 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9492 		if (reg->ref_obj_id == ref_obj_id)
9493 			mark_reg_invalid(env, reg);
9494 	}));
9495 
9496 	return 0;
9497 }
9498 
9499 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9500 {
9501 	struct bpf_func_state *unused;
9502 	struct bpf_reg_state *reg;
9503 
9504 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9505 		if (type_is_non_owning_ref(reg->type))
9506 			mark_reg_invalid(env, reg);
9507 	}));
9508 }
9509 
9510 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9511 				    struct bpf_reg_state *regs)
9512 {
9513 	int i;
9514 
9515 	/* after the call registers r0 - r5 were scratched */
9516 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9517 		mark_reg_not_init(env, regs, caller_saved[i]);
9518 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9519 	}
9520 }
9521 
9522 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9523 				   struct bpf_func_state *caller,
9524 				   struct bpf_func_state *callee,
9525 				   int insn_idx);
9526 
9527 static int set_callee_state(struct bpf_verifier_env *env,
9528 			    struct bpf_func_state *caller,
9529 			    struct bpf_func_state *callee, int insn_idx);
9530 
9531 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9532 			    set_callee_state_fn set_callee_state_cb,
9533 			    struct bpf_verifier_state *state)
9534 {
9535 	struct bpf_func_state *caller, *callee;
9536 	int err;
9537 
9538 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9539 		verbose(env, "the call stack of %d frames is too deep\n",
9540 			state->curframe + 2);
9541 		return -E2BIG;
9542 	}
9543 
9544 	if (state->frame[state->curframe + 1]) {
9545 		verbose(env, "verifier bug. Frame %d already allocated\n",
9546 			state->curframe + 1);
9547 		return -EFAULT;
9548 	}
9549 
9550 	caller = state->frame[state->curframe];
9551 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9552 	if (!callee)
9553 		return -ENOMEM;
9554 	state->frame[state->curframe + 1] = callee;
9555 
9556 	/* callee cannot access r0, r6 - r9 for reading and has to write
9557 	 * into its own stack before reading from it.
9558 	 * callee can read/write into caller's stack
9559 	 */
9560 	init_func_state(env, callee,
9561 			/* remember the callsite, it will be used by bpf_exit */
9562 			callsite,
9563 			state->curframe + 1 /* frameno within this callchain */,
9564 			subprog /* subprog number within this prog */);
9565 	/* Transfer references to the callee */
9566 	err = copy_reference_state(callee, caller);
9567 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9568 	if (err)
9569 		goto err_out;
9570 
9571 	/* only increment it after check_reg_arg() finished */
9572 	state->curframe++;
9573 
9574 	return 0;
9575 
9576 err_out:
9577 	free_func_state(callee);
9578 	state->frame[state->curframe + 1] = NULL;
9579 	return err;
9580 }
9581 
9582 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9583 				    const struct btf *btf,
9584 				    struct bpf_reg_state *regs)
9585 {
9586 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9587 	struct bpf_verifier_log *log = &env->log;
9588 	u32 i;
9589 	int ret;
9590 
9591 	ret = btf_prepare_func_args(env, subprog);
9592 	if (ret)
9593 		return ret;
9594 
9595 	/* check that BTF function arguments match actual types that the
9596 	 * verifier sees.
9597 	 */
9598 	for (i = 0; i < sub->arg_cnt; i++) {
9599 		u32 regno = i + 1;
9600 		struct bpf_reg_state *reg = &regs[regno];
9601 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9602 
9603 		if (arg->arg_type == ARG_ANYTHING) {
9604 			if (reg->type != SCALAR_VALUE) {
9605 				bpf_log(log, "R%d is not a scalar\n", regno);
9606 				return -EINVAL;
9607 			}
9608 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9609 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9610 			if (ret < 0)
9611 				return ret;
9612 			/* If function expects ctx type in BTF check that caller
9613 			 * is passing PTR_TO_CTX.
9614 			 */
9615 			if (reg->type != PTR_TO_CTX) {
9616 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9617 				return -EINVAL;
9618 			}
9619 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9620 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9621 			if (ret < 0)
9622 				return ret;
9623 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9624 				return -EINVAL;
9625 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9626 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9627 				return -EINVAL;
9628 			}
9629 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9630 			/*
9631 			 * Can pass any value and the kernel won't crash, but
9632 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9633 			 * else is a bug in the bpf program. Point it out to
9634 			 * the user at the verification time instead of
9635 			 * run-time debug nightmare.
9636 			 */
9637 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9638 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9639 				return -EINVAL;
9640 			}
9641 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9642 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
9643 			if (ret)
9644 				return ret;
9645 
9646 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9647 			if (ret)
9648 				return ret;
9649 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9650 			struct bpf_call_arg_meta meta;
9651 			int err;
9652 
9653 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9654 				continue;
9655 
9656 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9657 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9658 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9659 			if (err)
9660 				return err;
9661 		} else {
9662 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9663 				i, arg->arg_type);
9664 			return -EFAULT;
9665 		}
9666 	}
9667 
9668 	return 0;
9669 }
9670 
9671 /* Compare BTF of a function call with given bpf_reg_state.
9672  * Returns:
9673  * EFAULT - there is a verifier bug. Abort verification.
9674  * EINVAL - there is a type mismatch or BTF is not available.
9675  * 0 - BTF matches with what bpf_reg_state expects.
9676  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9677  */
9678 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9679 				  struct bpf_reg_state *regs)
9680 {
9681 	struct bpf_prog *prog = env->prog;
9682 	struct btf *btf = prog->aux->btf;
9683 	u32 btf_id;
9684 	int err;
9685 
9686 	if (!prog->aux->func_info)
9687 		return -EINVAL;
9688 
9689 	btf_id = prog->aux->func_info[subprog].type_id;
9690 	if (!btf_id)
9691 		return -EFAULT;
9692 
9693 	if (prog->aux->func_info_aux[subprog].unreliable)
9694 		return -EINVAL;
9695 
9696 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9697 	/* Compiler optimizations can remove arguments from static functions
9698 	 * or mismatched type can be passed into a global function.
9699 	 * In such cases mark the function as unreliable from BTF point of view.
9700 	 */
9701 	if (err)
9702 		prog->aux->func_info_aux[subprog].unreliable = true;
9703 	return err;
9704 }
9705 
9706 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9707 			      int insn_idx, int subprog,
9708 			      set_callee_state_fn set_callee_state_cb)
9709 {
9710 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9711 	struct bpf_func_state *caller, *callee;
9712 	int err;
9713 
9714 	caller = state->frame[state->curframe];
9715 	err = btf_check_subprog_call(env, subprog, caller->regs);
9716 	if (err == -EFAULT)
9717 		return err;
9718 
9719 	/* set_callee_state is used for direct subprog calls, but we are
9720 	 * interested in validating only BPF helpers that can call subprogs as
9721 	 * callbacks
9722 	 */
9723 	env->subprog_info[subprog].is_cb = true;
9724 	if (bpf_pseudo_kfunc_call(insn) &&
9725 	    !is_callback_calling_kfunc(insn->imm)) {
9726 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9727 			func_id_name(insn->imm), insn->imm);
9728 		return -EFAULT;
9729 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9730 		   !is_callback_calling_function(insn->imm)) { /* helper */
9731 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9732 			func_id_name(insn->imm), insn->imm);
9733 		return -EFAULT;
9734 	}
9735 
9736 	if (is_async_callback_calling_insn(insn)) {
9737 		struct bpf_verifier_state *async_cb;
9738 
9739 		/* there is no real recursion here. timer and workqueue callbacks are async */
9740 		env->subprog_info[subprog].is_async_cb = true;
9741 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9742 					 insn_idx, subprog,
9743 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
9744 		if (!async_cb)
9745 			return -EFAULT;
9746 		callee = async_cb->frame[0];
9747 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9748 
9749 		/* Convert bpf_timer_set_callback() args into timer callback args */
9750 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9751 		if (err)
9752 			return err;
9753 
9754 		return 0;
9755 	}
9756 
9757 	/* for callback functions enqueue entry to callback and
9758 	 * proceed with next instruction within current frame.
9759 	 */
9760 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9761 	if (!callback_state)
9762 		return -ENOMEM;
9763 
9764 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9765 			       callback_state);
9766 	if (err)
9767 		return err;
9768 
9769 	callback_state->callback_unroll_depth++;
9770 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9771 	caller->callback_depth = 0;
9772 	return 0;
9773 }
9774 
9775 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9776 			   int *insn_idx)
9777 {
9778 	struct bpf_verifier_state *state = env->cur_state;
9779 	struct bpf_func_state *caller;
9780 	int err, subprog, target_insn;
9781 
9782 	target_insn = *insn_idx + insn->imm + 1;
9783 	subprog = find_subprog(env, target_insn);
9784 	if (subprog < 0) {
9785 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9786 		return -EFAULT;
9787 	}
9788 
9789 	caller = state->frame[state->curframe];
9790 	err = btf_check_subprog_call(env, subprog, caller->regs);
9791 	if (err == -EFAULT)
9792 		return err;
9793 	if (subprog_is_global(env, subprog)) {
9794 		const char *sub_name = subprog_name(env, subprog);
9795 
9796 		/* Only global subprogs cannot be called with a lock held. */
9797 		if (env->cur_state->active_lock.ptr) {
9798 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9799 				     "use static function instead\n");
9800 			return -EINVAL;
9801 		}
9802 
9803 		/* Only global subprogs cannot be called with preemption disabled. */
9804 		if (env->cur_state->active_preempt_lock) {
9805 			verbose(env, "global function calls are not allowed with preemption disabled,\n"
9806 				     "use static function instead\n");
9807 			return -EINVAL;
9808 		}
9809 
9810 		if (err) {
9811 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9812 				subprog, sub_name);
9813 			return err;
9814 		}
9815 
9816 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9817 			subprog, sub_name);
9818 		/* mark global subprog for verifying after main prog */
9819 		subprog_aux(env, subprog)->called = true;
9820 		clear_caller_saved_regs(env, caller->regs);
9821 
9822 		/* All global functions return a 64-bit SCALAR_VALUE */
9823 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9824 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9825 
9826 		/* continue with next insn after call */
9827 		return 0;
9828 	}
9829 
9830 	/* for regular function entry setup new frame and continue
9831 	 * from that frame.
9832 	 */
9833 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9834 	if (err)
9835 		return err;
9836 
9837 	clear_caller_saved_regs(env, caller->regs);
9838 
9839 	/* and go analyze first insn of the callee */
9840 	*insn_idx = env->subprog_info[subprog].start - 1;
9841 
9842 	if (env->log.level & BPF_LOG_LEVEL) {
9843 		verbose(env, "caller:\n");
9844 		print_verifier_state(env, caller, true);
9845 		verbose(env, "callee:\n");
9846 		print_verifier_state(env, state->frame[state->curframe], true);
9847 	}
9848 
9849 	return 0;
9850 }
9851 
9852 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9853 				   struct bpf_func_state *caller,
9854 				   struct bpf_func_state *callee)
9855 {
9856 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9857 	 *      void *callback_ctx, u64 flags);
9858 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9859 	 *      void *callback_ctx);
9860 	 */
9861 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9862 
9863 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9864 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9865 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9866 
9867 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9868 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9869 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9870 
9871 	/* pointer to stack or null */
9872 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9873 
9874 	/* unused */
9875 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9876 	return 0;
9877 }
9878 
9879 static int set_callee_state(struct bpf_verifier_env *env,
9880 			    struct bpf_func_state *caller,
9881 			    struct bpf_func_state *callee, int insn_idx)
9882 {
9883 	int i;
9884 
9885 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9886 	 * pointers, which connects us up to the liveness chain
9887 	 */
9888 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9889 		callee->regs[i] = caller->regs[i];
9890 	return 0;
9891 }
9892 
9893 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9894 				       struct bpf_func_state *caller,
9895 				       struct bpf_func_state *callee,
9896 				       int insn_idx)
9897 {
9898 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9899 	struct bpf_map *map;
9900 	int err;
9901 
9902 	/* valid map_ptr and poison value does not matter */
9903 	map = insn_aux->map_ptr_state.map_ptr;
9904 	if (!map->ops->map_set_for_each_callback_args ||
9905 	    !map->ops->map_for_each_callback) {
9906 		verbose(env, "callback function not allowed for map\n");
9907 		return -ENOTSUPP;
9908 	}
9909 
9910 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9911 	if (err)
9912 		return err;
9913 
9914 	callee->in_callback_fn = true;
9915 	callee->callback_ret_range = retval_range(0, 1);
9916 	return 0;
9917 }
9918 
9919 static int set_loop_callback_state(struct bpf_verifier_env *env,
9920 				   struct bpf_func_state *caller,
9921 				   struct bpf_func_state *callee,
9922 				   int insn_idx)
9923 {
9924 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9925 	 *	    u64 flags);
9926 	 * callback_fn(u32 index, void *callback_ctx);
9927 	 */
9928 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9929 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9930 
9931 	/* unused */
9932 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9933 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9934 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9935 
9936 	callee->in_callback_fn = true;
9937 	callee->callback_ret_range = retval_range(0, 1);
9938 	return 0;
9939 }
9940 
9941 static int set_timer_callback_state(struct bpf_verifier_env *env,
9942 				    struct bpf_func_state *caller,
9943 				    struct bpf_func_state *callee,
9944 				    int insn_idx)
9945 {
9946 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9947 
9948 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9949 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9950 	 */
9951 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9952 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9953 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9954 
9955 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9956 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9957 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9958 
9959 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9960 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9961 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9962 
9963 	/* unused */
9964 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9965 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9966 	callee->in_async_callback_fn = true;
9967 	callee->callback_ret_range = retval_range(0, 1);
9968 	return 0;
9969 }
9970 
9971 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9972 				       struct bpf_func_state *caller,
9973 				       struct bpf_func_state *callee,
9974 				       int insn_idx)
9975 {
9976 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9977 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9978 	 * (callback_fn)(struct task_struct *task,
9979 	 *               struct vm_area_struct *vma, void *callback_ctx);
9980 	 */
9981 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9982 
9983 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9984 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9985 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9986 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9987 
9988 	/* pointer to stack or null */
9989 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9990 
9991 	/* unused */
9992 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9993 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9994 	callee->in_callback_fn = true;
9995 	callee->callback_ret_range = retval_range(0, 1);
9996 	return 0;
9997 }
9998 
9999 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10000 					   struct bpf_func_state *caller,
10001 					   struct bpf_func_state *callee,
10002 					   int insn_idx)
10003 {
10004 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10005 	 *			  callback_ctx, u64 flags);
10006 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10007 	 */
10008 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10009 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10010 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10011 
10012 	/* unused */
10013 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10014 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10015 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10016 
10017 	callee->in_callback_fn = true;
10018 	callee->callback_ret_range = retval_range(0, 1);
10019 	return 0;
10020 }
10021 
10022 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10023 					 struct bpf_func_state *caller,
10024 					 struct bpf_func_state *callee,
10025 					 int insn_idx)
10026 {
10027 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10028 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10029 	 *
10030 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10031 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10032 	 * by this point, so look at 'root'
10033 	 */
10034 	struct btf_field *field;
10035 
10036 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10037 				      BPF_RB_ROOT);
10038 	if (!field || !field->graph_root.value_btf_id)
10039 		return -EFAULT;
10040 
10041 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10042 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10043 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10044 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10045 
10046 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10047 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10048 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10049 	callee->in_callback_fn = true;
10050 	callee->callback_ret_range = retval_range(0, 1);
10051 	return 0;
10052 }
10053 
10054 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10055 
10056 /* Are we currently verifying the callback for a rbtree helper that must
10057  * be called with lock held? If so, no need to complain about unreleased
10058  * lock
10059  */
10060 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10061 {
10062 	struct bpf_verifier_state *state = env->cur_state;
10063 	struct bpf_insn *insn = env->prog->insnsi;
10064 	struct bpf_func_state *callee;
10065 	int kfunc_btf_id;
10066 
10067 	if (!state->curframe)
10068 		return false;
10069 
10070 	callee = state->frame[state->curframe];
10071 
10072 	if (!callee->in_callback_fn)
10073 		return false;
10074 
10075 	kfunc_btf_id = insn[callee->callsite].imm;
10076 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10077 }
10078 
10079 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10080 				bool return_32bit)
10081 {
10082 	if (return_32bit)
10083 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10084 	else
10085 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10086 }
10087 
10088 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10089 {
10090 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10091 	struct bpf_func_state *caller, *callee;
10092 	struct bpf_reg_state *r0;
10093 	bool in_callback_fn;
10094 	int err;
10095 
10096 	callee = state->frame[state->curframe];
10097 	r0 = &callee->regs[BPF_REG_0];
10098 	if (r0->type == PTR_TO_STACK) {
10099 		/* technically it's ok to return caller's stack pointer
10100 		 * (or caller's caller's pointer) back to the caller,
10101 		 * since these pointers are valid. Only current stack
10102 		 * pointer will be invalid as soon as function exits,
10103 		 * but let's be conservative
10104 		 */
10105 		verbose(env, "cannot return stack pointer to the caller\n");
10106 		return -EINVAL;
10107 	}
10108 
10109 	caller = state->frame[state->curframe - 1];
10110 	if (callee->in_callback_fn) {
10111 		if (r0->type != SCALAR_VALUE) {
10112 			verbose(env, "R0 not a scalar value\n");
10113 			return -EACCES;
10114 		}
10115 
10116 		/* we are going to rely on register's precise value */
10117 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
10118 		err = err ?: mark_chain_precision(env, BPF_REG_0);
10119 		if (err)
10120 			return err;
10121 
10122 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
10123 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
10124 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
10125 					       "At callback return", "R0");
10126 			return -EINVAL;
10127 		}
10128 		if (!calls_callback(env, callee->callsite)) {
10129 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
10130 				*insn_idx, callee->callsite);
10131 			return -EFAULT;
10132 		}
10133 	} else {
10134 		/* return to the caller whatever r0 had in the callee */
10135 		caller->regs[BPF_REG_0] = *r0;
10136 	}
10137 
10138 	/* callback_fn frame should have released its own additions to parent's
10139 	 * reference state at this point, or check_reference_leak would
10140 	 * complain, hence it must be the same as the caller. There is no need
10141 	 * to copy it back.
10142 	 */
10143 	if (!callee->in_callback_fn) {
10144 		/* Transfer references to the caller */
10145 		err = copy_reference_state(caller, callee);
10146 		if (err)
10147 			return err;
10148 	}
10149 
10150 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
10151 	 * there function call logic would reschedule callback visit. If iteration
10152 	 * converges is_state_visited() would prune that visit eventually.
10153 	 */
10154 	in_callback_fn = callee->in_callback_fn;
10155 	if (in_callback_fn)
10156 		*insn_idx = callee->callsite;
10157 	else
10158 		*insn_idx = callee->callsite + 1;
10159 
10160 	if (env->log.level & BPF_LOG_LEVEL) {
10161 		verbose(env, "returning from callee:\n");
10162 		print_verifier_state(env, callee, true);
10163 		verbose(env, "to caller at %d:\n", *insn_idx);
10164 		print_verifier_state(env, caller, true);
10165 	}
10166 	/* clear everything in the callee. In case of exceptional exits using
10167 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10168 	free_func_state(callee);
10169 	state->frame[state->curframe--] = NULL;
10170 
10171 	/* for callbacks widen imprecise scalars to make programs like below verify:
10172 	 *
10173 	 *   struct ctx { int i; }
10174 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10175 	 *   ...
10176 	 *   struct ctx = { .i = 0; }
10177 	 *   bpf_loop(100, cb, &ctx, 0);
10178 	 *
10179 	 * This is similar to what is done in process_iter_next_call() for open
10180 	 * coded iterators.
10181 	 */
10182 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10183 	if (prev_st) {
10184 		err = widen_imprecise_scalars(env, prev_st, state);
10185 		if (err)
10186 			return err;
10187 	}
10188 	return 0;
10189 }
10190 
10191 static int do_refine_retval_range(struct bpf_verifier_env *env,
10192 				  struct bpf_reg_state *regs, int ret_type,
10193 				  int func_id,
10194 				  struct bpf_call_arg_meta *meta)
10195 {
10196 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10197 
10198 	if (ret_type != RET_INTEGER)
10199 		return 0;
10200 
10201 	switch (func_id) {
10202 	case BPF_FUNC_get_stack:
10203 	case BPF_FUNC_get_task_stack:
10204 	case BPF_FUNC_probe_read_str:
10205 	case BPF_FUNC_probe_read_kernel_str:
10206 	case BPF_FUNC_probe_read_user_str:
10207 		ret_reg->smax_value = meta->msize_max_value;
10208 		ret_reg->s32_max_value = meta->msize_max_value;
10209 		ret_reg->smin_value = -MAX_ERRNO;
10210 		ret_reg->s32_min_value = -MAX_ERRNO;
10211 		reg_bounds_sync(ret_reg);
10212 		break;
10213 	case BPF_FUNC_get_smp_processor_id:
10214 		ret_reg->umax_value = nr_cpu_ids - 1;
10215 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10216 		ret_reg->smax_value = nr_cpu_ids - 1;
10217 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10218 		ret_reg->umin_value = 0;
10219 		ret_reg->u32_min_value = 0;
10220 		ret_reg->smin_value = 0;
10221 		ret_reg->s32_min_value = 0;
10222 		reg_bounds_sync(ret_reg);
10223 		break;
10224 	}
10225 
10226 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10227 }
10228 
10229 static int
10230 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10231 		int func_id, int insn_idx)
10232 {
10233 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10234 	struct bpf_map *map = meta->map_ptr;
10235 
10236 	if (func_id != BPF_FUNC_tail_call &&
10237 	    func_id != BPF_FUNC_map_lookup_elem &&
10238 	    func_id != BPF_FUNC_map_update_elem &&
10239 	    func_id != BPF_FUNC_map_delete_elem &&
10240 	    func_id != BPF_FUNC_map_push_elem &&
10241 	    func_id != BPF_FUNC_map_pop_elem &&
10242 	    func_id != BPF_FUNC_map_peek_elem &&
10243 	    func_id != BPF_FUNC_for_each_map_elem &&
10244 	    func_id != BPF_FUNC_redirect_map &&
10245 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10246 		return 0;
10247 
10248 	if (map == NULL) {
10249 		verbose(env, "kernel subsystem misconfigured verifier\n");
10250 		return -EINVAL;
10251 	}
10252 
10253 	/* In case of read-only, some additional restrictions
10254 	 * need to be applied in order to prevent altering the
10255 	 * state of the map from program side.
10256 	 */
10257 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10258 	    (func_id == BPF_FUNC_map_delete_elem ||
10259 	     func_id == BPF_FUNC_map_update_elem ||
10260 	     func_id == BPF_FUNC_map_push_elem ||
10261 	     func_id == BPF_FUNC_map_pop_elem)) {
10262 		verbose(env, "write into map forbidden\n");
10263 		return -EACCES;
10264 	}
10265 
10266 	if (!aux->map_ptr_state.map_ptr)
10267 		bpf_map_ptr_store(aux, meta->map_ptr,
10268 				  !meta->map_ptr->bypass_spec_v1, false);
10269 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10270 		bpf_map_ptr_store(aux, meta->map_ptr,
10271 				  !meta->map_ptr->bypass_spec_v1, true);
10272 	return 0;
10273 }
10274 
10275 static int
10276 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10277 		int func_id, int insn_idx)
10278 {
10279 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10280 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10281 	struct bpf_map *map = meta->map_ptr;
10282 	u64 val, max;
10283 	int err;
10284 
10285 	if (func_id != BPF_FUNC_tail_call)
10286 		return 0;
10287 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10288 		verbose(env, "kernel subsystem misconfigured verifier\n");
10289 		return -EINVAL;
10290 	}
10291 
10292 	reg = &regs[BPF_REG_3];
10293 	val = reg->var_off.value;
10294 	max = map->max_entries;
10295 
10296 	if (!(is_reg_const(reg, false) && val < max)) {
10297 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10298 		return 0;
10299 	}
10300 
10301 	err = mark_chain_precision(env, BPF_REG_3);
10302 	if (err)
10303 		return err;
10304 	if (bpf_map_key_unseen(aux))
10305 		bpf_map_key_store(aux, val);
10306 	else if (!bpf_map_key_poisoned(aux) &&
10307 		  bpf_map_key_immediate(aux) != val)
10308 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10309 	return 0;
10310 }
10311 
10312 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10313 {
10314 	struct bpf_func_state *state = cur_func(env);
10315 	bool refs_lingering = false;
10316 	int i;
10317 
10318 	if (!exception_exit && state->frameno && !state->in_callback_fn)
10319 		return 0;
10320 
10321 	for (i = 0; i < state->acquired_refs; i++) {
10322 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10323 			continue;
10324 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10325 			state->refs[i].id, state->refs[i].insn_idx);
10326 		refs_lingering = true;
10327 	}
10328 	return refs_lingering ? -EINVAL : 0;
10329 }
10330 
10331 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10332 				   struct bpf_reg_state *regs)
10333 {
10334 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10335 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10336 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10337 	struct bpf_bprintf_data data = {};
10338 	int err, fmt_map_off, num_args;
10339 	u64 fmt_addr;
10340 	char *fmt;
10341 
10342 	/* data must be an array of u64 */
10343 	if (data_len_reg->var_off.value % 8)
10344 		return -EINVAL;
10345 	num_args = data_len_reg->var_off.value / 8;
10346 
10347 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10348 	 * and map_direct_value_addr is set.
10349 	 */
10350 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10351 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10352 						  fmt_map_off);
10353 	if (err) {
10354 		verbose(env, "verifier bug\n");
10355 		return -EFAULT;
10356 	}
10357 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10358 
10359 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10360 	 * can focus on validating the format specifiers.
10361 	 */
10362 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10363 	if (err < 0)
10364 		verbose(env, "Invalid format string\n");
10365 
10366 	return err;
10367 }
10368 
10369 static int check_get_func_ip(struct bpf_verifier_env *env)
10370 {
10371 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10372 	int func_id = BPF_FUNC_get_func_ip;
10373 
10374 	if (type == BPF_PROG_TYPE_TRACING) {
10375 		if (!bpf_prog_has_trampoline(env->prog)) {
10376 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10377 				func_id_name(func_id), func_id);
10378 			return -ENOTSUPP;
10379 		}
10380 		return 0;
10381 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10382 		return 0;
10383 	}
10384 
10385 	verbose(env, "func %s#%d not supported for program type %d\n",
10386 		func_id_name(func_id), func_id, type);
10387 	return -ENOTSUPP;
10388 }
10389 
10390 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10391 {
10392 	return &env->insn_aux_data[env->insn_idx];
10393 }
10394 
10395 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10396 {
10397 	struct bpf_reg_state *regs = cur_regs(env);
10398 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10399 	bool reg_is_null = register_is_null(reg);
10400 
10401 	if (reg_is_null)
10402 		mark_chain_precision(env, BPF_REG_4);
10403 
10404 	return reg_is_null;
10405 }
10406 
10407 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10408 {
10409 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10410 
10411 	if (!state->initialized) {
10412 		state->initialized = 1;
10413 		state->fit_for_inline = loop_flag_is_zero(env);
10414 		state->callback_subprogno = subprogno;
10415 		return;
10416 	}
10417 
10418 	if (!state->fit_for_inline)
10419 		return;
10420 
10421 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10422 				 state->callback_subprogno == subprogno);
10423 }
10424 
10425 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
10426 			    const struct bpf_func_proto **ptr)
10427 {
10428 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10429 		return -ERANGE;
10430 
10431 	if (!env->ops->get_func_proto)
10432 		return -EINVAL;
10433 
10434 	*ptr = env->ops->get_func_proto(func_id, env->prog);
10435 	return *ptr ? 0 : -EINVAL;
10436 }
10437 
10438 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10439 			     int *insn_idx_p)
10440 {
10441 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10442 	bool returns_cpu_specific_alloc_ptr = false;
10443 	const struct bpf_func_proto *fn = NULL;
10444 	enum bpf_return_type ret_type;
10445 	enum bpf_type_flag ret_flag;
10446 	struct bpf_reg_state *regs;
10447 	struct bpf_call_arg_meta meta;
10448 	int insn_idx = *insn_idx_p;
10449 	bool changes_data;
10450 	int i, err, func_id;
10451 
10452 	/* find function prototype */
10453 	func_id = insn->imm;
10454 	err = get_helper_proto(env, insn->imm, &fn);
10455 	if (err == -ERANGE) {
10456 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10457 		return -EINVAL;
10458 	}
10459 
10460 	if (err) {
10461 		verbose(env, "program of this type cannot use helper %s#%d\n",
10462 			func_id_name(func_id), func_id);
10463 		return err;
10464 	}
10465 
10466 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10467 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10468 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10469 		return -EINVAL;
10470 	}
10471 
10472 	if (fn->allowed && !fn->allowed(env->prog)) {
10473 		verbose(env, "helper call is not allowed in probe\n");
10474 		return -EINVAL;
10475 	}
10476 
10477 	if (!in_sleepable(env) && fn->might_sleep) {
10478 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10479 		return -EINVAL;
10480 	}
10481 
10482 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10483 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10484 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10485 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10486 			func_id_name(func_id), func_id);
10487 		return -EINVAL;
10488 	}
10489 
10490 	memset(&meta, 0, sizeof(meta));
10491 	meta.pkt_access = fn->pkt_access;
10492 
10493 	err = check_func_proto(fn, func_id);
10494 	if (err) {
10495 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10496 			func_id_name(func_id), func_id);
10497 		return err;
10498 	}
10499 
10500 	if (env->cur_state->active_rcu_lock) {
10501 		if (fn->might_sleep) {
10502 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10503 				func_id_name(func_id), func_id);
10504 			return -EINVAL;
10505 		}
10506 
10507 		if (in_sleepable(env) && is_storage_get_function(func_id))
10508 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10509 	}
10510 
10511 	if (env->cur_state->active_preempt_lock) {
10512 		if (fn->might_sleep) {
10513 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10514 				func_id_name(func_id), func_id);
10515 			return -EINVAL;
10516 		}
10517 
10518 		if (in_sleepable(env) && is_storage_get_function(func_id))
10519 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10520 	}
10521 
10522 	meta.func_id = func_id;
10523 	/* check args */
10524 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10525 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10526 		if (err)
10527 			return err;
10528 	}
10529 
10530 	err = record_func_map(env, &meta, func_id, insn_idx);
10531 	if (err)
10532 		return err;
10533 
10534 	err = record_func_key(env, &meta, func_id, insn_idx);
10535 	if (err)
10536 		return err;
10537 
10538 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10539 	 * is inferred from register state.
10540 	 */
10541 	for (i = 0; i < meta.access_size; i++) {
10542 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10543 				       BPF_WRITE, -1, false, false);
10544 		if (err)
10545 			return err;
10546 	}
10547 
10548 	regs = cur_regs(env);
10549 
10550 	if (meta.release_regno) {
10551 		err = -EINVAL;
10552 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10553 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10554 		 * is safe to do directly.
10555 		 */
10556 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10557 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10558 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10559 				return -EFAULT;
10560 			}
10561 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10562 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10563 			u32 ref_obj_id = meta.ref_obj_id;
10564 			bool in_rcu = in_rcu_cs(env);
10565 			struct bpf_func_state *state;
10566 			struct bpf_reg_state *reg;
10567 
10568 			err = release_reference_state(cur_func(env), ref_obj_id);
10569 			if (!err) {
10570 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10571 					if (reg->ref_obj_id == ref_obj_id) {
10572 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10573 							reg->ref_obj_id = 0;
10574 							reg->type &= ~MEM_ALLOC;
10575 							reg->type |= MEM_RCU;
10576 						} else {
10577 							mark_reg_invalid(env, reg);
10578 						}
10579 					}
10580 				}));
10581 			}
10582 		} else if (meta.ref_obj_id) {
10583 			err = release_reference(env, meta.ref_obj_id);
10584 		} else if (register_is_null(&regs[meta.release_regno])) {
10585 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10586 			 * released is NULL, which must be > R0.
10587 			 */
10588 			err = 0;
10589 		}
10590 		if (err) {
10591 			verbose(env, "func %s#%d reference has not been acquired before\n",
10592 				func_id_name(func_id), func_id);
10593 			return err;
10594 		}
10595 	}
10596 
10597 	switch (func_id) {
10598 	case BPF_FUNC_tail_call:
10599 		err = check_reference_leak(env, false);
10600 		if (err) {
10601 			verbose(env, "tail_call would lead to reference leak\n");
10602 			return err;
10603 		}
10604 		break;
10605 	case BPF_FUNC_get_local_storage:
10606 		/* check that flags argument in get_local_storage(map, flags) is 0,
10607 		 * this is required because get_local_storage() can't return an error.
10608 		 */
10609 		if (!register_is_null(&regs[BPF_REG_2])) {
10610 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10611 			return -EINVAL;
10612 		}
10613 		break;
10614 	case BPF_FUNC_for_each_map_elem:
10615 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10616 					 set_map_elem_callback_state);
10617 		break;
10618 	case BPF_FUNC_timer_set_callback:
10619 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10620 					 set_timer_callback_state);
10621 		break;
10622 	case BPF_FUNC_find_vma:
10623 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10624 					 set_find_vma_callback_state);
10625 		break;
10626 	case BPF_FUNC_snprintf:
10627 		err = check_bpf_snprintf_call(env, regs);
10628 		break;
10629 	case BPF_FUNC_loop:
10630 		update_loop_inline_state(env, meta.subprogno);
10631 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10632 		 * is finished, thus mark it precise.
10633 		 */
10634 		err = mark_chain_precision(env, BPF_REG_1);
10635 		if (err)
10636 			return err;
10637 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10638 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10639 						 set_loop_callback_state);
10640 		} else {
10641 			cur_func(env)->callback_depth = 0;
10642 			if (env->log.level & BPF_LOG_LEVEL2)
10643 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10644 					env->cur_state->curframe);
10645 		}
10646 		break;
10647 	case BPF_FUNC_dynptr_from_mem:
10648 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10649 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10650 				reg_type_str(env, regs[BPF_REG_1].type));
10651 			return -EACCES;
10652 		}
10653 		break;
10654 	case BPF_FUNC_set_retval:
10655 		if (prog_type == BPF_PROG_TYPE_LSM &&
10656 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10657 			if (!env->prog->aux->attach_func_proto->type) {
10658 				/* Make sure programs that attach to void
10659 				 * hooks don't try to modify return value.
10660 				 */
10661 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10662 				return -EINVAL;
10663 			}
10664 		}
10665 		break;
10666 	case BPF_FUNC_dynptr_data:
10667 	{
10668 		struct bpf_reg_state *reg;
10669 		int id, ref_obj_id;
10670 
10671 		reg = get_dynptr_arg_reg(env, fn, regs);
10672 		if (!reg)
10673 			return -EFAULT;
10674 
10675 
10676 		if (meta.dynptr_id) {
10677 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10678 			return -EFAULT;
10679 		}
10680 		if (meta.ref_obj_id) {
10681 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10682 			return -EFAULT;
10683 		}
10684 
10685 		id = dynptr_id(env, reg);
10686 		if (id < 0) {
10687 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10688 			return id;
10689 		}
10690 
10691 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10692 		if (ref_obj_id < 0) {
10693 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10694 			return ref_obj_id;
10695 		}
10696 
10697 		meta.dynptr_id = id;
10698 		meta.ref_obj_id = ref_obj_id;
10699 
10700 		break;
10701 	}
10702 	case BPF_FUNC_dynptr_write:
10703 	{
10704 		enum bpf_dynptr_type dynptr_type;
10705 		struct bpf_reg_state *reg;
10706 
10707 		reg = get_dynptr_arg_reg(env, fn, regs);
10708 		if (!reg)
10709 			return -EFAULT;
10710 
10711 		dynptr_type = dynptr_get_type(env, reg);
10712 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10713 			return -EFAULT;
10714 
10715 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10716 			/* this will trigger clear_all_pkt_pointers(), which will
10717 			 * invalidate all dynptr slices associated with the skb
10718 			 */
10719 			changes_data = true;
10720 
10721 		break;
10722 	}
10723 	case BPF_FUNC_per_cpu_ptr:
10724 	case BPF_FUNC_this_cpu_ptr:
10725 	{
10726 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10727 		const struct btf_type *type;
10728 
10729 		if (reg->type & MEM_RCU) {
10730 			type = btf_type_by_id(reg->btf, reg->btf_id);
10731 			if (!type || !btf_type_is_struct(type)) {
10732 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10733 				return -EFAULT;
10734 			}
10735 			returns_cpu_specific_alloc_ptr = true;
10736 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10737 		}
10738 		break;
10739 	}
10740 	case BPF_FUNC_user_ringbuf_drain:
10741 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10742 					 set_user_ringbuf_callback_state);
10743 		break;
10744 	}
10745 
10746 	if (err)
10747 		return err;
10748 
10749 	/* reset caller saved regs */
10750 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10751 		mark_reg_not_init(env, regs, caller_saved[i]);
10752 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10753 	}
10754 
10755 	/* helper call returns 64-bit value. */
10756 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10757 
10758 	/* update return register (already marked as written above) */
10759 	ret_type = fn->ret_type;
10760 	ret_flag = type_flag(ret_type);
10761 
10762 	switch (base_type(ret_type)) {
10763 	case RET_INTEGER:
10764 		/* sets type to SCALAR_VALUE */
10765 		mark_reg_unknown(env, regs, BPF_REG_0);
10766 		break;
10767 	case RET_VOID:
10768 		regs[BPF_REG_0].type = NOT_INIT;
10769 		break;
10770 	case RET_PTR_TO_MAP_VALUE:
10771 		/* There is no offset yet applied, variable or fixed */
10772 		mark_reg_known_zero(env, regs, BPF_REG_0);
10773 		/* remember map_ptr, so that check_map_access()
10774 		 * can check 'value_size' boundary of memory access
10775 		 * to map element returned from bpf_map_lookup_elem()
10776 		 */
10777 		if (meta.map_ptr == NULL) {
10778 			verbose(env,
10779 				"kernel subsystem misconfigured verifier\n");
10780 			return -EINVAL;
10781 		}
10782 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10783 		regs[BPF_REG_0].map_uid = meta.map_uid;
10784 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10785 		if (!type_may_be_null(ret_type) &&
10786 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10787 			regs[BPF_REG_0].id = ++env->id_gen;
10788 		}
10789 		break;
10790 	case RET_PTR_TO_SOCKET:
10791 		mark_reg_known_zero(env, regs, BPF_REG_0);
10792 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10793 		break;
10794 	case RET_PTR_TO_SOCK_COMMON:
10795 		mark_reg_known_zero(env, regs, BPF_REG_0);
10796 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10797 		break;
10798 	case RET_PTR_TO_TCP_SOCK:
10799 		mark_reg_known_zero(env, regs, BPF_REG_0);
10800 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10801 		break;
10802 	case RET_PTR_TO_MEM:
10803 		mark_reg_known_zero(env, regs, BPF_REG_0);
10804 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10805 		regs[BPF_REG_0].mem_size = meta.mem_size;
10806 		break;
10807 	case RET_PTR_TO_MEM_OR_BTF_ID:
10808 	{
10809 		const struct btf_type *t;
10810 
10811 		mark_reg_known_zero(env, regs, BPF_REG_0);
10812 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10813 		if (!btf_type_is_struct(t)) {
10814 			u32 tsize;
10815 			const struct btf_type *ret;
10816 			const char *tname;
10817 
10818 			/* resolve the type size of ksym. */
10819 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10820 			if (IS_ERR(ret)) {
10821 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10822 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10823 					tname, PTR_ERR(ret));
10824 				return -EINVAL;
10825 			}
10826 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10827 			regs[BPF_REG_0].mem_size = tsize;
10828 		} else {
10829 			if (returns_cpu_specific_alloc_ptr) {
10830 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10831 			} else {
10832 				/* MEM_RDONLY may be carried from ret_flag, but it
10833 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10834 				 * it will confuse the check of PTR_TO_BTF_ID in
10835 				 * check_mem_access().
10836 				 */
10837 				ret_flag &= ~MEM_RDONLY;
10838 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10839 			}
10840 
10841 			regs[BPF_REG_0].btf = meta.ret_btf;
10842 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10843 		}
10844 		break;
10845 	}
10846 	case RET_PTR_TO_BTF_ID:
10847 	{
10848 		struct btf *ret_btf;
10849 		int ret_btf_id;
10850 
10851 		mark_reg_known_zero(env, regs, BPF_REG_0);
10852 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10853 		if (func_id == BPF_FUNC_kptr_xchg) {
10854 			ret_btf = meta.kptr_field->kptr.btf;
10855 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10856 			if (!btf_is_kernel(ret_btf)) {
10857 				regs[BPF_REG_0].type |= MEM_ALLOC;
10858 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10859 					regs[BPF_REG_0].type |= MEM_PERCPU;
10860 			}
10861 		} else {
10862 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10863 				verbose(env, "verifier internal error:");
10864 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10865 					func_id_name(func_id));
10866 				return -EINVAL;
10867 			}
10868 			ret_btf = btf_vmlinux;
10869 			ret_btf_id = *fn->ret_btf_id;
10870 		}
10871 		if (ret_btf_id == 0) {
10872 			verbose(env, "invalid return type %u of func %s#%d\n",
10873 				base_type(ret_type), func_id_name(func_id),
10874 				func_id);
10875 			return -EINVAL;
10876 		}
10877 		regs[BPF_REG_0].btf = ret_btf;
10878 		regs[BPF_REG_0].btf_id = ret_btf_id;
10879 		break;
10880 	}
10881 	default:
10882 		verbose(env, "unknown return type %u of func %s#%d\n",
10883 			base_type(ret_type), func_id_name(func_id), func_id);
10884 		return -EINVAL;
10885 	}
10886 
10887 	if (type_may_be_null(regs[BPF_REG_0].type))
10888 		regs[BPF_REG_0].id = ++env->id_gen;
10889 
10890 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10891 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10892 			func_id_name(func_id), func_id);
10893 		return -EFAULT;
10894 	}
10895 
10896 	if (is_dynptr_ref_function(func_id))
10897 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10898 
10899 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10900 		/* For release_reference() */
10901 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10902 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10903 		int id = acquire_reference_state(env, insn_idx);
10904 
10905 		if (id < 0)
10906 			return id;
10907 		/* For mark_ptr_or_null_reg() */
10908 		regs[BPF_REG_0].id = id;
10909 		/* For release_reference() */
10910 		regs[BPF_REG_0].ref_obj_id = id;
10911 	}
10912 
10913 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10914 	if (err)
10915 		return err;
10916 
10917 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10918 	if (err)
10919 		return err;
10920 
10921 	if ((func_id == BPF_FUNC_get_stack ||
10922 	     func_id == BPF_FUNC_get_task_stack) &&
10923 	    !env->prog->has_callchain_buf) {
10924 		const char *err_str;
10925 
10926 #ifdef CONFIG_PERF_EVENTS
10927 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10928 		err_str = "cannot get callchain buffer for func %s#%d\n";
10929 #else
10930 		err = -ENOTSUPP;
10931 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10932 #endif
10933 		if (err) {
10934 			verbose(env, err_str, func_id_name(func_id), func_id);
10935 			return err;
10936 		}
10937 
10938 		env->prog->has_callchain_buf = true;
10939 	}
10940 
10941 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10942 		env->prog->call_get_stack = true;
10943 
10944 	if (func_id == BPF_FUNC_get_func_ip) {
10945 		if (check_get_func_ip(env))
10946 			return -ENOTSUPP;
10947 		env->prog->call_get_func_ip = true;
10948 	}
10949 
10950 	if (changes_data)
10951 		clear_all_pkt_pointers(env);
10952 	return 0;
10953 }
10954 
10955 /* mark_btf_func_reg_size() is used when the reg size is determined by
10956  * the BTF func_proto's return value size and argument.
10957  */
10958 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10959 				   size_t reg_size)
10960 {
10961 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10962 
10963 	if (regno == BPF_REG_0) {
10964 		/* Function return value */
10965 		reg->live |= REG_LIVE_WRITTEN;
10966 		reg->subreg_def = reg_size == sizeof(u64) ?
10967 			DEF_NOT_SUBREG : env->insn_idx + 1;
10968 	} else {
10969 		/* Function argument */
10970 		if (reg_size == sizeof(u64)) {
10971 			mark_insn_zext(env, reg);
10972 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10973 		} else {
10974 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10975 		}
10976 	}
10977 }
10978 
10979 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10980 {
10981 	return meta->kfunc_flags & KF_ACQUIRE;
10982 }
10983 
10984 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10985 {
10986 	return meta->kfunc_flags & KF_RELEASE;
10987 }
10988 
10989 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10990 {
10991 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10992 }
10993 
10994 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10995 {
10996 	return meta->kfunc_flags & KF_SLEEPABLE;
10997 }
10998 
10999 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11000 {
11001 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11002 }
11003 
11004 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11005 {
11006 	return meta->kfunc_flags & KF_RCU;
11007 }
11008 
11009 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11010 {
11011 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11012 }
11013 
11014 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11015 				  const struct btf_param *arg,
11016 				  const struct bpf_reg_state *reg)
11017 {
11018 	const struct btf_type *t;
11019 
11020 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11021 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11022 		return false;
11023 
11024 	return btf_param_match_suffix(btf, arg, "__sz");
11025 }
11026 
11027 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11028 					const struct btf_param *arg,
11029 					const struct bpf_reg_state *reg)
11030 {
11031 	const struct btf_type *t;
11032 
11033 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11034 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11035 		return false;
11036 
11037 	return btf_param_match_suffix(btf, arg, "__szk");
11038 }
11039 
11040 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11041 {
11042 	return btf_param_match_suffix(btf, arg, "__opt");
11043 }
11044 
11045 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11046 {
11047 	return btf_param_match_suffix(btf, arg, "__k");
11048 }
11049 
11050 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11051 {
11052 	return btf_param_match_suffix(btf, arg, "__ign");
11053 }
11054 
11055 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11056 {
11057 	return btf_param_match_suffix(btf, arg, "__map");
11058 }
11059 
11060 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11061 {
11062 	return btf_param_match_suffix(btf, arg, "__alloc");
11063 }
11064 
11065 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
11066 {
11067 	return btf_param_match_suffix(btf, arg, "__uninit");
11068 }
11069 
11070 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
11071 {
11072 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
11073 }
11074 
11075 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
11076 {
11077 	return btf_param_match_suffix(btf, arg, "__nullable");
11078 }
11079 
11080 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
11081 {
11082 	return btf_param_match_suffix(btf, arg, "__str");
11083 }
11084 
11085 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
11086 					  const struct btf_param *arg,
11087 					  const char *name)
11088 {
11089 	int len, target_len = strlen(name);
11090 	const char *param_name;
11091 
11092 	param_name = btf_name_by_offset(btf, arg->name_off);
11093 	if (str_is_empty(param_name))
11094 		return false;
11095 	len = strlen(param_name);
11096 	if (len != target_len)
11097 		return false;
11098 	if (strcmp(param_name, name))
11099 		return false;
11100 
11101 	return true;
11102 }
11103 
11104 enum {
11105 	KF_ARG_DYNPTR_ID,
11106 	KF_ARG_LIST_HEAD_ID,
11107 	KF_ARG_LIST_NODE_ID,
11108 	KF_ARG_RB_ROOT_ID,
11109 	KF_ARG_RB_NODE_ID,
11110 	KF_ARG_WORKQUEUE_ID,
11111 };
11112 
11113 BTF_ID_LIST(kf_arg_btf_ids)
11114 BTF_ID(struct, bpf_dynptr)
11115 BTF_ID(struct, bpf_list_head)
11116 BTF_ID(struct, bpf_list_node)
11117 BTF_ID(struct, bpf_rb_root)
11118 BTF_ID(struct, bpf_rb_node)
11119 BTF_ID(struct, bpf_wq)
11120 
11121 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
11122 				    const struct btf_param *arg, int type)
11123 {
11124 	const struct btf_type *t;
11125 	u32 res_id;
11126 
11127 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11128 	if (!t)
11129 		return false;
11130 	if (!btf_type_is_ptr(t))
11131 		return false;
11132 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
11133 	if (!t)
11134 		return false;
11135 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
11136 }
11137 
11138 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
11139 {
11140 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
11141 }
11142 
11143 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
11144 {
11145 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
11146 }
11147 
11148 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
11149 {
11150 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
11151 }
11152 
11153 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
11154 {
11155 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
11156 }
11157 
11158 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
11159 {
11160 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
11161 }
11162 
11163 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
11164 {
11165 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
11166 }
11167 
11168 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11169 				  const struct btf_param *arg)
11170 {
11171 	const struct btf_type *t;
11172 
11173 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
11174 	if (!t)
11175 		return false;
11176 
11177 	return true;
11178 }
11179 
11180 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
11181 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
11182 					const struct btf *btf,
11183 					const struct btf_type *t, int rec)
11184 {
11185 	const struct btf_type *member_type;
11186 	const struct btf_member *member;
11187 	u32 i;
11188 
11189 	if (!btf_type_is_struct(t))
11190 		return false;
11191 
11192 	for_each_member(i, t, member) {
11193 		const struct btf_array *array;
11194 
11195 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11196 		if (btf_type_is_struct(member_type)) {
11197 			if (rec >= 3) {
11198 				verbose(env, "max struct nesting depth exceeded\n");
11199 				return false;
11200 			}
11201 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11202 				return false;
11203 			continue;
11204 		}
11205 		if (btf_type_is_array(member_type)) {
11206 			array = btf_array(member_type);
11207 			if (!array->nelems)
11208 				return false;
11209 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11210 			if (!btf_type_is_scalar(member_type))
11211 				return false;
11212 			continue;
11213 		}
11214 		if (!btf_type_is_scalar(member_type))
11215 			return false;
11216 	}
11217 	return true;
11218 }
11219 
11220 enum kfunc_ptr_arg_type {
11221 	KF_ARG_PTR_TO_CTX,
11222 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11223 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11224 	KF_ARG_PTR_TO_DYNPTR,
11225 	KF_ARG_PTR_TO_ITER,
11226 	KF_ARG_PTR_TO_LIST_HEAD,
11227 	KF_ARG_PTR_TO_LIST_NODE,
11228 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11229 	KF_ARG_PTR_TO_MEM,
11230 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
11231 	KF_ARG_PTR_TO_CALLBACK,
11232 	KF_ARG_PTR_TO_RB_ROOT,
11233 	KF_ARG_PTR_TO_RB_NODE,
11234 	KF_ARG_PTR_TO_NULL,
11235 	KF_ARG_PTR_TO_CONST_STR,
11236 	KF_ARG_PTR_TO_MAP,
11237 	KF_ARG_PTR_TO_WORKQUEUE,
11238 };
11239 
11240 enum special_kfunc_type {
11241 	KF_bpf_obj_new_impl,
11242 	KF_bpf_obj_drop_impl,
11243 	KF_bpf_refcount_acquire_impl,
11244 	KF_bpf_list_push_front_impl,
11245 	KF_bpf_list_push_back_impl,
11246 	KF_bpf_list_pop_front,
11247 	KF_bpf_list_pop_back,
11248 	KF_bpf_cast_to_kern_ctx,
11249 	KF_bpf_rdonly_cast,
11250 	KF_bpf_rcu_read_lock,
11251 	KF_bpf_rcu_read_unlock,
11252 	KF_bpf_rbtree_remove,
11253 	KF_bpf_rbtree_add_impl,
11254 	KF_bpf_rbtree_first,
11255 	KF_bpf_dynptr_from_skb,
11256 	KF_bpf_dynptr_from_xdp,
11257 	KF_bpf_dynptr_slice,
11258 	KF_bpf_dynptr_slice_rdwr,
11259 	KF_bpf_dynptr_clone,
11260 	KF_bpf_percpu_obj_new_impl,
11261 	KF_bpf_percpu_obj_drop_impl,
11262 	KF_bpf_throw,
11263 	KF_bpf_wq_set_callback_impl,
11264 	KF_bpf_preempt_disable,
11265 	KF_bpf_preempt_enable,
11266 	KF_bpf_iter_css_task_new,
11267 	KF_bpf_session_cookie,
11268 };
11269 
11270 BTF_SET_START(special_kfunc_set)
11271 BTF_ID(func, bpf_obj_new_impl)
11272 BTF_ID(func, bpf_obj_drop_impl)
11273 BTF_ID(func, bpf_refcount_acquire_impl)
11274 BTF_ID(func, bpf_list_push_front_impl)
11275 BTF_ID(func, bpf_list_push_back_impl)
11276 BTF_ID(func, bpf_list_pop_front)
11277 BTF_ID(func, bpf_list_pop_back)
11278 BTF_ID(func, bpf_cast_to_kern_ctx)
11279 BTF_ID(func, bpf_rdonly_cast)
11280 BTF_ID(func, bpf_rbtree_remove)
11281 BTF_ID(func, bpf_rbtree_add_impl)
11282 BTF_ID(func, bpf_rbtree_first)
11283 BTF_ID(func, bpf_dynptr_from_skb)
11284 BTF_ID(func, bpf_dynptr_from_xdp)
11285 BTF_ID(func, bpf_dynptr_slice)
11286 BTF_ID(func, bpf_dynptr_slice_rdwr)
11287 BTF_ID(func, bpf_dynptr_clone)
11288 BTF_ID(func, bpf_percpu_obj_new_impl)
11289 BTF_ID(func, bpf_percpu_obj_drop_impl)
11290 BTF_ID(func, bpf_throw)
11291 BTF_ID(func, bpf_wq_set_callback_impl)
11292 #ifdef CONFIG_CGROUPS
11293 BTF_ID(func, bpf_iter_css_task_new)
11294 #endif
11295 BTF_SET_END(special_kfunc_set)
11296 
11297 BTF_ID_LIST(special_kfunc_list)
11298 BTF_ID(func, bpf_obj_new_impl)
11299 BTF_ID(func, bpf_obj_drop_impl)
11300 BTF_ID(func, bpf_refcount_acquire_impl)
11301 BTF_ID(func, bpf_list_push_front_impl)
11302 BTF_ID(func, bpf_list_push_back_impl)
11303 BTF_ID(func, bpf_list_pop_front)
11304 BTF_ID(func, bpf_list_pop_back)
11305 BTF_ID(func, bpf_cast_to_kern_ctx)
11306 BTF_ID(func, bpf_rdonly_cast)
11307 BTF_ID(func, bpf_rcu_read_lock)
11308 BTF_ID(func, bpf_rcu_read_unlock)
11309 BTF_ID(func, bpf_rbtree_remove)
11310 BTF_ID(func, bpf_rbtree_add_impl)
11311 BTF_ID(func, bpf_rbtree_first)
11312 BTF_ID(func, bpf_dynptr_from_skb)
11313 BTF_ID(func, bpf_dynptr_from_xdp)
11314 BTF_ID(func, bpf_dynptr_slice)
11315 BTF_ID(func, bpf_dynptr_slice_rdwr)
11316 BTF_ID(func, bpf_dynptr_clone)
11317 BTF_ID(func, bpf_percpu_obj_new_impl)
11318 BTF_ID(func, bpf_percpu_obj_drop_impl)
11319 BTF_ID(func, bpf_throw)
11320 BTF_ID(func, bpf_wq_set_callback_impl)
11321 BTF_ID(func, bpf_preempt_disable)
11322 BTF_ID(func, bpf_preempt_enable)
11323 #ifdef CONFIG_CGROUPS
11324 BTF_ID(func, bpf_iter_css_task_new)
11325 #else
11326 BTF_ID_UNUSED
11327 #endif
11328 #ifdef CONFIG_BPF_EVENTS
11329 BTF_ID(func, bpf_session_cookie)
11330 #else
11331 BTF_ID_UNUSED
11332 #endif
11333 
11334 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11335 {
11336 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11337 	    meta->arg_owning_ref) {
11338 		return false;
11339 	}
11340 
11341 	return meta->kfunc_flags & KF_RET_NULL;
11342 }
11343 
11344 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11345 {
11346 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11347 }
11348 
11349 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11350 {
11351 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11352 }
11353 
11354 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11355 {
11356 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11357 }
11358 
11359 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11360 {
11361 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11362 }
11363 
11364 static enum kfunc_ptr_arg_type
11365 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11366 		       struct bpf_kfunc_call_arg_meta *meta,
11367 		       const struct btf_type *t, const struct btf_type *ref_t,
11368 		       const char *ref_tname, const struct btf_param *args,
11369 		       int argno, int nargs)
11370 {
11371 	u32 regno = argno + 1;
11372 	struct bpf_reg_state *regs = cur_regs(env);
11373 	struct bpf_reg_state *reg = &regs[regno];
11374 	bool arg_mem_size = false;
11375 
11376 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11377 		return KF_ARG_PTR_TO_CTX;
11378 
11379 	/* In this function, we verify the kfunc's BTF as per the argument type,
11380 	 * leaving the rest of the verification with respect to the register
11381 	 * type to our caller. When a set of conditions hold in the BTF type of
11382 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11383 	 */
11384 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11385 		return KF_ARG_PTR_TO_CTX;
11386 
11387 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11388 		return KF_ARG_PTR_TO_NULL;
11389 
11390 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11391 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11392 
11393 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11394 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11395 
11396 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11397 		return KF_ARG_PTR_TO_DYNPTR;
11398 
11399 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
11400 		return KF_ARG_PTR_TO_ITER;
11401 
11402 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11403 		return KF_ARG_PTR_TO_LIST_HEAD;
11404 
11405 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11406 		return KF_ARG_PTR_TO_LIST_NODE;
11407 
11408 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11409 		return KF_ARG_PTR_TO_RB_ROOT;
11410 
11411 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11412 		return KF_ARG_PTR_TO_RB_NODE;
11413 
11414 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11415 		return KF_ARG_PTR_TO_CONST_STR;
11416 
11417 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11418 		return KF_ARG_PTR_TO_MAP;
11419 
11420 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11421 		return KF_ARG_PTR_TO_WORKQUEUE;
11422 
11423 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11424 		if (!btf_type_is_struct(ref_t)) {
11425 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11426 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11427 			return -EINVAL;
11428 		}
11429 		return KF_ARG_PTR_TO_BTF_ID;
11430 	}
11431 
11432 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11433 		return KF_ARG_PTR_TO_CALLBACK;
11434 
11435 	if (argno + 1 < nargs &&
11436 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11437 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11438 		arg_mem_size = true;
11439 
11440 	/* This is the catch all argument type of register types supported by
11441 	 * check_helper_mem_access. However, we only allow when argument type is
11442 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11443 	 * arg_mem_size is true, the pointer can be void *.
11444 	 */
11445 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11446 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11447 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11448 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11449 		return -EINVAL;
11450 	}
11451 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11452 }
11453 
11454 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11455 					struct bpf_reg_state *reg,
11456 					const struct btf_type *ref_t,
11457 					const char *ref_tname, u32 ref_id,
11458 					struct bpf_kfunc_call_arg_meta *meta,
11459 					int argno)
11460 {
11461 	const struct btf_type *reg_ref_t;
11462 	bool strict_type_match = false;
11463 	const struct btf *reg_btf;
11464 	const char *reg_ref_tname;
11465 	bool taking_projection;
11466 	bool struct_same;
11467 	u32 reg_ref_id;
11468 
11469 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11470 		reg_btf = reg->btf;
11471 		reg_ref_id = reg->btf_id;
11472 	} else {
11473 		reg_btf = btf_vmlinux;
11474 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11475 	}
11476 
11477 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11478 	 * or releasing a reference, or are no-cast aliases. We do _not_
11479 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11480 	 * as we want to enable BPF programs to pass types that are bitwise
11481 	 * equivalent without forcing them to explicitly cast with something
11482 	 * like bpf_cast_to_kern_ctx().
11483 	 *
11484 	 * For example, say we had a type like the following:
11485 	 *
11486 	 * struct bpf_cpumask {
11487 	 *	cpumask_t cpumask;
11488 	 *	refcount_t usage;
11489 	 * };
11490 	 *
11491 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11492 	 * to a struct cpumask, so it would be safe to pass a struct
11493 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11494 	 *
11495 	 * The philosophy here is similar to how we allow scalars of different
11496 	 * types to be passed to kfuncs as long as the size is the same. The
11497 	 * only difference here is that we're simply allowing
11498 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11499 	 * resolve types.
11500 	 */
11501 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
11502 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11503 		strict_type_match = true;
11504 
11505 	WARN_ON_ONCE(is_kfunc_release(meta) &&
11506 		     (reg->off || !tnum_is_const(reg->var_off) ||
11507 		      reg->var_off.value));
11508 
11509 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11510 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11511 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
11512 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
11513 	 * actually use it -- it must cast to the underlying type. So we allow
11514 	 * caller to pass in the underlying type.
11515 	 */
11516 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
11517 	if (!taking_projection && !struct_same) {
11518 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11519 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11520 			btf_type_str(reg_ref_t), reg_ref_tname);
11521 		return -EINVAL;
11522 	}
11523 	return 0;
11524 }
11525 
11526 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11527 {
11528 	struct bpf_verifier_state *state = env->cur_state;
11529 	struct btf_record *rec = reg_btf_record(reg);
11530 
11531 	if (!state->active_lock.ptr) {
11532 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11533 		return -EFAULT;
11534 	}
11535 
11536 	if (type_flag(reg->type) & NON_OWN_REF) {
11537 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11538 		return -EFAULT;
11539 	}
11540 
11541 	reg->type |= NON_OWN_REF;
11542 	if (rec->refcount_off >= 0)
11543 		reg->type |= MEM_RCU;
11544 
11545 	return 0;
11546 }
11547 
11548 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11549 {
11550 	struct bpf_func_state *state, *unused;
11551 	struct bpf_reg_state *reg;
11552 	int i;
11553 
11554 	state = cur_func(env);
11555 
11556 	if (!ref_obj_id) {
11557 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11558 			     "owning -> non-owning conversion\n");
11559 		return -EFAULT;
11560 	}
11561 
11562 	for (i = 0; i < state->acquired_refs; i++) {
11563 		if (state->refs[i].id != ref_obj_id)
11564 			continue;
11565 
11566 		/* Clear ref_obj_id here so release_reference doesn't clobber
11567 		 * the whole reg
11568 		 */
11569 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11570 			if (reg->ref_obj_id == ref_obj_id) {
11571 				reg->ref_obj_id = 0;
11572 				ref_set_non_owning(env, reg);
11573 			}
11574 		}));
11575 		return 0;
11576 	}
11577 
11578 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11579 	return -EFAULT;
11580 }
11581 
11582 /* Implementation details:
11583  *
11584  * Each register points to some region of memory, which we define as an
11585  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11586  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11587  * allocation. The lock and the data it protects are colocated in the same
11588  * memory region.
11589  *
11590  * Hence, everytime a register holds a pointer value pointing to such
11591  * allocation, the verifier preserves a unique reg->id for it.
11592  *
11593  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11594  * bpf_spin_lock is called.
11595  *
11596  * To enable this, lock state in the verifier captures two values:
11597  *	active_lock.ptr = Register's type specific pointer
11598  *	active_lock.id  = A unique ID for each register pointer value
11599  *
11600  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11601  * supported register types.
11602  *
11603  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11604  * allocated objects is the reg->btf pointer.
11605  *
11606  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11607  * can establish the provenance of the map value statically for each distinct
11608  * lookup into such maps. They always contain a single map value hence unique
11609  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11610  *
11611  * So, in case of global variables, they use array maps with max_entries = 1,
11612  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11613  * into the same map value as max_entries is 1, as described above).
11614  *
11615  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11616  * outer map pointer (in verifier context), but each lookup into an inner map
11617  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11618  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11619  * will get different reg->id assigned to each lookup, hence different
11620  * active_lock.id.
11621  *
11622  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11623  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11624  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11625  */
11626 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11627 {
11628 	void *ptr;
11629 	u32 id;
11630 
11631 	switch ((int)reg->type) {
11632 	case PTR_TO_MAP_VALUE:
11633 		ptr = reg->map_ptr;
11634 		break;
11635 	case PTR_TO_BTF_ID | MEM_ALLOC:
11636 		ptr = reg->btf;
11637 		break;
11638 	default:
11639 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11640 		return -EFAULT;
11641 	}
11642 	id = reg->id;
11643 
11644 	if (!env->cur_state->active_lock.ptr)
11645 		return -EINVAL;
11646 	if (env->cur_state->active_lock.ptr != ptr ||
11647 	    env->cur_state->active_lock.id != id) {
11648 		verbose(env, "held lock and object are not in the same allocation\n");
11649 		return -EINVAL;
11650 	}
11651 	return 0;
11652 }
11653 
11654 static bool is_bpf_list_api_kfunc(u32 btf_id)
11655 {
11656 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11657 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11658 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11659 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11660 }
11661 
11662 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11663 {
11664 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11665 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11666 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11667 }
11668 
11669 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11670 {
11671 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11672 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11673 }
11674 
11675 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11676 {
11677 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11678 }
11679 
11680 static bool is_async_callback_calling_kfunc(u32 btf_id)
11681 {
11682 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11683 }
11684 
11685 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11686 {
11687 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11688 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11689 }
11690 
11691 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
11692 {
11693 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11694 }
11695 
11696 static bool is_callback_calling_kfunc(u32 btf_id)
11697 {
11698 	return is_sync_callback_calling_kfunc(btf_id) ||
11699 	       is_async_callback_calling_kfunc(btf_id);
11700 }
11701 
11702 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11703 {
11704 	return is_bpf_rbtree_api_kfunc(btf_id);
11705 }
11706 
11707 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11708 					  enum btf_field_type head_field_type,
11709 					  u32 kfunc_btf_id)
11710 {
11711 	bool ret;
11712 
11713 	switch (head_field_type) {
11714 	case BPF_LIST_HEAD:
11715 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11716 		break;
11717 	case BPF_RB_ROOT:
11718 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11719 		break;
11720 	default:
11721 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11722 			btf_field_type_name(head_field_type));
11723 		return false;
11724 	}
11725 
11726 	if (!ret)
11727 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11728 			btf_field_type_name(head_field_type));
11729 	return ret;
11730 }
11731 
11732 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11733 					  enum btf_field_type node_field_type,
11734 					  u32 kfunc_btf_id)
11735 {
11736 	bool ret;
11737 
11738 	switch (node_field_type) {
11739 	case BPF_LIST_NODE:
11740 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11741 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11742 		break;
11743 	case BPF_RB_NODE:
11744 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11745 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11746 		break;
11747 	default:
11748 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11749 			btf_field_type_name(node_field_type));
11750 		return false;
11751 	}
11752 
11753 	if (!ret)
11754 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11755 			btf_field_type_name(node_field_type));
11756 	return ret;
11757 }
11758 
11759 static int
11760 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11761 				   struct bpf_reg_state *reg, u32 regno,
11762 				   struct bpf_kfunc_call_arg_meta *meta,
11763 				   enum btf_field_type head_field_type,
11764 				   struct btf_field **head_field)
11765 {
11766 	const char *head_type_name;
11767 	struct btf_field *field;
11768 	struct btf_record *rec;
11769 	u32 head_off;
11770 
11771 	if (meta->btf != btf_vmlinux) {
11772 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11773 		return -EFAULT;
11774 	}
11775 
11776 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11777 		return -EFAULT;
11778 
11779 	head_type_name = btf_field_type_name(head_field_type);
11780 	if (!tnum_is_const(reg->var_off)) {
11781 		verbose(env,
11782 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11783 			regno, head_type_name);
11784 		return -EINVAL;
11785 	}
11786 
11787 	rec = reg_btf_record(reg);
11788 	head_off = reg->off + reg->var_off.value;
11789 	field = btf_record_find(rec, head_off, head_field_type);
11790 	if (!field) {
11791 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11792 		return -EINVAL;
11793 	}
11794 
11795 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11796 	if (check_reg_allocation_locked(env, reg)) {
11797 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11798 			rec->spin_lock_off, head_type_name);
11799 		return -EINVAL;
11800 	}
11801 
11802 	if (*head_field) {
11803 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11804 		return -EFAULT;
11805 	}
11806 	*head_field = field;
11807 	return 0;
11808 }
11809 
11810 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11811 					   struct bpf_reg_state *reg, u32 regno,
11812 					   struct bpf_kfunc_call_arg_meta *meta)
11813 {
11814 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11815 							  &meta->arg_list_head.field);
11816 }
11817 
11818 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11819 					     struct bpf_reg_state *reg, u32 regno,
11820 					     struct bpf_kfunc_call_arg_meta *meta)
11821 {
11822 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11823 							  &meta->arg_rbtree_root.field);
11824 }
11825 
11826 static int
11827 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11828 				   struct bpf_reg_state *reg, u32 regno,
11829 				   struct bpf_kfunc_call_arg_meta *meta,
11830 				   enum btf_field_type head_field_type,
11831 				   enum btf_field_type node_field_type,
11832 				   struct btf_field **node_field)
11833 {
11834 	const char *node_type_name;
11835 	const struct btf_type *et, *t;
11836 	struct btf_field *field;
11837 	u32 node_off;
11838 
11839 	if (meta->btf != btf_vmlinux) {
11840 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11841 		return -EFAULT;
11842 	}
11843 
11844 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11845 		return -EFAULT;
11846 
11847 	node_type_name = btf_field_type_name(node_field_type);
11848 	if (!tnum_is_const(reg->var_off)) {
11849 		verbose(env,
11850 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11851 			regno, node_type_name);
11852 		return -EINVAL;
11853 	}
11854 
11855 	node_off = reg->off + reg->var_off.value;
11856 	field = reg_find_field_offset(reg, node_off, node_field_type);
11857 	if (!field) {
11858 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11859 		return -EINVAL;
11860 	}
11861 
11862 	field = *node_field;
11863 
11864 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11865 	t = btf_type_by_id(reg->btf, reg->btf_id);
11866 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11867 				  field->graph_root.value_btf_id, true)) {
11868 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11869 			"in struct %s, but arg is at offset=%d in struct %s\n",
11870 			btf_field_type_name(head_field_type),
11871 			btf_field_type_name(node_field_type),
11872 			field->graph_root.node_offset,
11873 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11874 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11875 		return -EINVAL;
11876 	}
11877 	meta->arg_btf = reg->btf;
11878 	meta->arg_btf_id = reg->btf_id;
11879 
11880 	if (node_off != field->graph_root.node_offset) {
11881 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11882 			node_off, btf_field_type_name(node_field_type),
11883 			field->graph_root.node_offset,
11884 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11885 		return -EINVAL;
11886 	}
11887 
11888 	return 0;
11889 }
11890 
11891 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11892 					   struct bpf_reg_state *reg, u32 regno,
11893 					   struct bpf_kfunc_call_arg_meta *meta)
11894 {
11895 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11896 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11897 						  &meta->arg_list_head.field);
11898 }
11899 
11900 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11901 					     struct bpf_reg_state *reg, u32 regno,
11902 					     struct bpf_kfunc_call_arg_meta *meta)
11903 {
11904 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11905 						  BPF_RB_ROOT, BPF_RB_NODE,
11906 						  &meta->arg_rbtree_root.field);
11907 }
11908 
11909 /*
11910  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11911  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11912  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11913  * them can only be attached to some specific hook points.
11914  */
11915 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11916 {
11917 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11918 
11919 	switch (prog_type) {
11920 	case BPF_PROG_TYPE_LSM:
11921 		return true;
11922 	case BPF_PROG_TYPE_TRACING:
11923 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11924 			return true;
11925 		fallthrough;
11926 	default:
11927 		return in_sleepable(env);
11928 	}
11929 }
11930 
11931 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11932 			    int insn_idx)
11933 {
11934 	const char *func_name = meta->func_name, *ref_tname;
11935 	const struct btf *btf = meta->btf;
11936 	const struct btf_param *args;
11937 	struct btf_record *rec;
11938 	u32 i, nargs;
11939 	int ret;
11940 
11941 	args = (const struct btf_param *)(meta->func_proto + 1);
11942 	nargs = btf_type_vlen(meta->func_proto);
11943 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11944 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11945 			MAX_BPF_FUNC_REG_ARGS);
11946 		return -EINVAL;
11947 	}
11948 
11949 	/* Check that BTF function arguments match actual types that the
11950 	 * verifier sees.
11951 	 */
11952 	for (i = 0; i < nargs; i++) {
11953 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11954 		const struct btf_type *t, *ref_t, *resolve_ret;
11955 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11956 		u32 regno = i + 1, ref_id, type_size;
11957 		bool is_ret_buf_sz = false;
11958 		int kf_arg_type;
11959 
11960 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11961 
11962 		if (is_kfunc_arg_ignore(btf, &args[i]))
11963 			continue;
11964 
11965 		if (btf_type_is_scalar(t)) {
11966 			if (reg->type != SCALAR_VALUE) {
11967 				verbose(env, "R%d is not a scalar\n", regno);
11968 				return -EINVAL;
11969 			}
11970 
11971 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11972 				if (meta->arg_constant.found) {
11973 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11974 					return -EFAULT;
11975 				}
11976 				if (!tnum_is_const(reg->var_off)) {
11977 					verbose(env, "R%d must be a known constant\n", regno);
11978 					return -EINVAL;
11979 				}
11980 				ret = mark_chain_precision(env, regno);
11981 				if (ret < 0)
11982 					return ret;
11983 				meta->arg_constant.found = true;
11984 				meta->arg_constant.value = reg->var_off.value;
11985 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11986 				meta->r0_rdonly = true;
11987 				is_ret_buf_sz = true;
11988 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11989 				is_ret_buf_sz = true;
11990 			}
11991 
11992 			if (is_ret_buf_sz) {
11993 				if (meta->r0_size) {
11994 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11995 					return -EINVAL;
11996 				}
11997 
11998 				if (!tnum_is_const(reg->var_off)) {
11999 					verbose(env, "R%d is not a const\n", regno);
12000 					return -EINVAL;
12001 				}
12002 
12003 				meta->r0_size = reg->var_off.value;
12004 				ret = mark_chain_precision(env, regno);
12005 				if (ret)
12006 					return ret;
12007 			}
12008 			continue;
12009 		}
12010 
12011 		if (!btf_type_is_ptr(t)) {
12012 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
12013 			return -EINVAL;
12014 		}
12015 
12016 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
12017 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
12018 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
12019 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
12020 			return -EACCES;
12021 		}
12022 
12023 		if (reg->ref_obj_id) {
12024 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
12025 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
12026 					regno, reg->ref_obj_id,
12027 					meta->ref_obj_id);
12028 				return -EFAULT;
12029 			}
12030 			meta->ref_obj_id = reg->ref_obj_id;
12031 			if (is_kfunc_release(meta))
12032 				meta->release_regno = regno;
12033 		}
12034 
12035 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12036 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12037 
12038 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
12039 		if (kf_arg_type < 0)
12040 			return kf_arg_type;
12041 
12042 		switch (kf_arg_type) {
12043 		case KF_ARG_PTR_TO_NULL:
12044 			continue;
12045 		case KF_ARG_PTR_TO_MAP:
12046 			if (!reg->map_ptr) {
12047 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
12048 				return -EINVAL;
12049 			}
12050 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
12051 				/* Use map_uid (which is unique id of inner map) to reject:
12052 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12053 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
12054 				 * if (inner_map1 && inner_map2) {
12055 				 *     wq = bpf_map_lookup_elem(inner_map1);
12056 				 *     if (wq)
12057 				 *         // mismatch would have been allowed
12058 				 *         bpf_wq_init(wq, inner_map2);
12059 				 * }
12060 				 *
12061 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
12062 				 */
12063 				if (meta->map.ptr != reg->map_ptr ||
12064 				    meta->map.uid != reg->map_uid) {
12065 					verbose(env,
12066 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
12067 						meta->map.uid, reg->map_uid);
12068 					return -EINVAL;
12069 				}
12070 			}
12071 			meta->map.ptr = reg->map_ptr;
12072 			meta->map.uid = reg->map_uid;
12073 			fallthrough;
12074 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12075 		case KF_ARG_PTR_TO_BTF_ID:
12076 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
12077 				break;
12078 
12079 			if (!is_trusted_reg(reg)) {
12080 				if (!is_kfunc_rcu(meta)) {
12081 					verbose(env, "R%d must be referenced or trusted\n", regno);
12082 					return -EINVAL;
12083 				}
12084 				if (!is_rcu_reg(reg)) {
12085 					verbose(env, "R%d must be a rcu pointer\n", regno);
12086 					return -EINVAL;
12087 				}
12088 			}
12089 			fallthrough;
12090 		case KF_ARG_PTR_TO_CTX:
12091 		case KF_ARG_PTR_TO_DYNPTR:
12092 		case KF_ARG_PTR_TO_ITER:
12093 		case KF_ARG_PTR_TO_LIST_HEAD:
12094 		case KF_ARG_PTR_TO_LIST_NODE:
12095 		case KF_ARG_PTR_TO_RB_ROOT:
12096 		case KF_ARG_PTR_TO_RB_NODE:
12097 		case KF_ARG_PTR_TO_MEM:
12098 		case KF_ARG_PTR_TO_MEM_SIZE:
12099 		case KF_ARG_PTR_TO_CALLBACK:
12100 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12101 		case KF_ARG_PTR_TO_CONST_STR:
12102 		case KF_ARG_PTR_TO_WORKQUEUE:
12103 			break;
12104 		default:
12105 			WARN_ON_ONCE(1);
12106 			return -EFAULT;
12107 		}
12108 
12109 		if (is_kfunc_release(meta) && reg->ref_obj_id)
12110 			arg_type |= OBJ_RELEASE;
12111 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
12112 		if (ret < 0)
12113 			return ret;
12114 
12115 		switch (kf_arg_type) {
12116 		case KF_ARG_PTR_TO_CTX:
12117 			if (reg->type != PTR_TO_CTX) {
12118 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
12119 					i, reg_type_str(env, reg->type));
12120 				return -EINVAL;
12121 			}
12122 
12123 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12124 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12125 				if (ret < 0)
12126 					return -EINVAL;
12127 				meta->ret_btf_id  = ret;
12128 			}
12129 			break;
12130 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12131 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12132 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
12133 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
12134 					return -EINVAL;
12135 				}
12136 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12137 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12138 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
12139 					return -EINVAL;
12140 				}
12141 			} else {
12142 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12143 				return -EINVAL;
12144 			}
12145 			if (!reg->ref_obj_id) {
12146 				verbose(env, "allocated object must be referenced\n");
12147 				return -EINVAL;
12148 			}
12149 			if (meta->btf == btf_vmlinux) {
12150 				meta->arg_btf = reg->btf;
12151 				meta->arg_btf_id = reg->btf_id;
12152 			}
12153 			break;
12154 		case KF_ARG_PTR_TO_DYNPTR:
12155 		{
12156 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12157 			int clone_ref_obj_id = 0;
12158 
12159 			if (reg->type == CONST_PTR_TO_DYNPTR)
12160 				dynptr_arg_type |= MEM_RDONLY;
12161 
12162 			if (is_kfunc_arg_uninit(btf, &args[i]))
12163 				dynptr_arg_type |= MEM_UNINIT;
12164 
12165 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12166 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
12167 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12168 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12169 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12170 				   (dynptr_arg_type & MEM_UNINIT)) {
12171 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
12172 
12173 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12174 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
12175 					return -EFAULT;
12176 				}
12177 
12178 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12179 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
12180 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
12181 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
12182 					return -EFAULT;
12183 				}
12184 			}
12185 
12186 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
12187 			if (ret < 0)
12188 				return ret;
12189 
12190 			if (!(dynptr_arg_type & MEM_UNINIT)) {
12191 				int id = dynptr_id(env, reg);
12192 
12193 				if (id < 0) {
12194 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
12195 					return id;
12196 				}
12197 				meta->initialized_dynptr.id = id;
12198 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
12199 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
12200 			}
12201 
12202 			break;
12203 		}
12204 		case KF_ARG_PTR_TO_ITER:
12205 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12206 				if (!check_css_task_iter_allowlist(env)) {
12207 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12208 					return -EINVAL;
12209 				}
12210 			}
12211 			ret = process_iter_arg(env, regno, insn_idx, meta);
12212 			if (ret < 0)
12213 				return ret;
12214 			break;
12215 		case KF_ARG_PTR_TO_LIST_HEAD:
12216 			if (reg->type != PTR_TO_MAP_VALUE &&
12217 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12218 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12219 				return -EINVAL;
12220 			}
12221 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12222 				verbose(env, "allocated object must be referenced\n");
12223 				return -EINVAL;
12224 			}
12225 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12226 			if (ret < 0)
12227 				return ret;
12228 			break;
12229 		case KF_ARG_PTR_TO_RB_ROOT:
12230 			if (reg->type != PTR_TO_MAP_VALUE &&
12231 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12232 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12233 				return -EINVAL;
12234 			}
12235 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12236 				verbose(env, "allocated object must be referenced\n");
12237 				return -EINVAL;
12238 			}
12239 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12240 			if (ret < 0)
12241 				return ret;
12242 			break;
12243 		case KF_ARG_PTR_TO_LIST_NODE:
12244 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12245 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12246 				return -EINVAL;
12247 			}
12248 			if (!reg->ref_obj_id) {
12249 				verbose(env, "allocated object must be referenced\n");
12250 				return -EINVAL;
12251 			}
12252 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12253 			if (ret < 0)
12254 				return ret;
12255 			break;
12256 		case KF_ARG_PTR_TO_RB_NODE:
12257 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12258 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12259 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
12260 					return -EINVAL;
12261 				}
12262 				if (in_rbtree_lock_required_cb(env)) {
12263 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12264 					return -EINVAL;
12265 				}
12266 			} else {
12267 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12268 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
12269 					return -EINVAL;
12270 				}
12271 				if (!reg->ref_obj_id) {
12272 					verbose(env, "allocated object must be referenced\n");
12273 					return -EINVAL;
12274 				}
12275 			}
12276 
12277 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12278 			if (ret < 0)
12279 				return ret;
12280 			break;
12281 		case KF_ARG_PTR_TO_MAP:
12282 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12283 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12284 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12285 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12286 			fallthrough;
12287 		case KF_ARG_PTR_TO_BTF_ID:
12288 			/* Only base_type is checked, further checks are done here */
12289 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12290 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12291 			    !reg2btf_ids[base_type(reg->type)]) {
12292 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12293 				verbose(env, "expected %s or socket\n",
12294 					reg_type_str(env, base_type(reg->type) |
12295 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12296 				return -EINVAL;
12297 			}
12298 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12299 			if (ret < 0)
12300 				return ret;
12301 			break;
12302 		case KF_ARG_PTR_TO_MEM:
12303 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12304 			if (IS_ERR(resolve_ret)) {
12305 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12306 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12307 				return -EINVAL;
12308 			}
12309 			ret = check_mem_reg(env, reg, regno, type_size);
12310 			if (ret < 0)
12311 				return ret;
12312 			break;
12313 		case KF_ARG_PTR_TO_MEM_SIZE:
12314 		{
12315 			struct bpf_reg_state *buff_reg = &regs[regno];
12316 			const struct btf_param *buff_arg = &args[i];
12317 			struct bpf_reg_state *size_reg = &regs[regno + 1];
12318 			const struct btf_param *size_arg = &args[i + 1];
12319 
12320 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12321 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12322 				if (ret < 0) {
12323 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12324 					return ret;
12325 				}
12326 			}
12327 
12328 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12329 				if (meta->arg_constant.found) {
12330 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12331 					return -EFAULT;
12332 				}
12333 				if (!tnum_is_const(size_reg->var_off)) {
12334 					verbose(env, "R%d must be a known constant\n", regno + 1);
12335 					return -EINVAL;
12336 				}
12337 				meta->arg_constant.found = true;
12338 				meta->arg_constant.value = size_reg->var_off.value;
12339 			}
12340 
12341 			/* Skip next '__sz' or '__szk' argument */
12342 			i++;
12343 			break;
12344 		}
12345 		case KF_ARG_PTR_TO_CALLBACK:
12346 			if (reg->type != PTR_TO_FUNC) {
12347 				verbose(env, "arg%d expected pointer to func\n", i);
12348 				return -EINVAL;
12349 			}
12350 			meta->subprogno = reg->subprogno;
12351 			break;
12352 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12353 			if (!type_is_ptr_alloc_obj(reg->type)) {
12354 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12355 				return -EINVAL;
12356 			}
12357 			if (!type_is_non_owning_ref(reg->type))
12358 				meta->arg_owning_ref = true;
12359 
12360 			rec = reg_btf_record(reg);
12361 			if (!rec) {
12362 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12363 				return -EFAULT;
12364 			}
12365 
12366 			if (rec->refcount_off < 0) {
12367 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12368 				return -EINVAL;
12369 			}
12370 
12371 			meta->arg_btf = reg->btf;
12372 			meta->arg_btf_id = reg->btf_id;
12373 			break;
12374 		case KF_ARG_PTR_TO_CONST_STR:
12375 			if (reg->type != PTR_TO_MAP_VALUE) {
12376 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12377 				return -EINVAL;
12378 			}
12379 			ret = check_reg_const_str(env, reg, regno);
12380 			if (ret)
12381 				return ret;
12382 			break;
12383 		case KF_ARG_PTR_TO_WORKQUEUE:
12384 			if (reg->type != PTR_TO_MAP_VALUE) {
12385 				verbose(env, "arg#%d doesn't point to a map value\n", i);
12386 				return -EINVAL;
12387 			}
12388 			ret = process_wq_func(env, regno, meta);
12389 			if (ret < 0)
12390 				return ret;
12391 			break;
12392 		}
12393 	}
12394 
12395 	if (is_kfunc_release(meta) && !meta->release_regno) {
12396 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12397 			func_name);
12398 		return -EINVAL;
12399 	}
12400 
12401 	return 0;
12402 }
12403 
12404 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12405 			    struct bpf_insn *insn,
12406 			    struct bpf_kfunc_call_arg_meta *meta,
12407 			    const char **kfunc_name)
12408 {
12409 	const struct btf_type *func, *func_proto;
12410 	u32 func_id, *kfunc_flags;
12411 	const char *func_name;
12412 	struct btf *desc_btf;
12413 
12414 	if (kfunc_name)
12415 		*kfunc_name = NULL;
12416 
12417 	if (!insn->imm)
12418 		return -EINVAL;
12419 
12420 	desc_btf = find_kfunc_desc_btf(env, insn->off);
12421 	if (IS_ERR(desc_btf))
12422 		return PTR_ERR(desc_btf);
12423 
12424 	func_id = insn->imm;
12425 	func = btf_type_by_id(desc_btf, func_id);
12426 	func_name = btf_name_by_offset(desc_btf, func->name_off);
12427 	if (kfunc_name)
12428 		*kfunc_name = func_name;
12429 	func_proto = btf_type_by_id(desc_btf, func->type);
12430 
12431 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12432 	if (!kfunc_flags) {
12433 		return -EACCES;
12434 	}
12435 
12436 	memset(meta, 0, sizeof(*meta));
12437 	meta->btf = desc_btf;
12438 	meta->func_id = func_id;
12439 	meta->kfunc_flags = *kfunc_flags;
12440 	meta->func_proto = func_proto;
12441 	meta->func_name = func_name;
12442 
12443 	return 0;
12444 }
12445 
12446 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12447 
12448 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12449 			    int *insn_idx_p)
12450 {
12451 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12452 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12453 	struct bpf_reg_state *regs = cur_regs(env);
12454 	const char *func_name, *ptr_type_name;
12455 	const struct btf_type *t, *ptr_type;
12456 	struct bpf_kfunc_call_arg_meta meta;
12457 	struct bpf_insn_aux_data *insn_aux;
12458 	int err, insn_idx = *insn_idx_p;
12459 	const struct btf_param *args;
12460 	const struct btf_type *ret_t;
12461 	struct btf *desc_btf;
12462 
12463 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12464 	if (!insn->imm)
12465 		return 0;
12466 
12467 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12468 	if (err == -EACCES && func_name)
12469 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12470 	if (err)
12471 		return err;
12472 	desc_btf = meta.btf;
12473 	insn_aux = &env->insn_aux_data[insn_idx];
12474 
12475 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12476 
12477 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12478 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12479 		return -EACCES;
12480 	}
12481 
12482 	sleepable = is_kfunc_sleepable(&meta);
12483 	if (sleepable && !in_sleepable(env)) {
12484 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12485 		return -EACCES;
12486 	}
12487 
12488 	/* Check the arguments */
12489 	err = check_kfunc_args(env, &meta, insn_idx);
12490 	if (err < 0)
12491 		return err;
12492 
12493 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12494 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12495 					 set_rbtree_add_callback_state);
12496 		if (err) {
12497 			verbose(env, "kfunc %s#%d failed callback verification\n",
12498 				func_name, meta.func_id);
12499 			return err;
12500 		}
12501 	}
12502 
12503 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
12504 		meta.r0_size = sizeof(u64);
12505 		meta.r0_rdonly = false;
12506 	}
12507 
12508 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
12509 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12510 					 set_timer_callback_state);
12511 		if (err) {
12512 			verbose(env, "kfunc %s#%d failed callback verification\n",
12513 				func_name, meta.func_id);
12514 			return err;
12515 		}
12516 	}
12517 
12518 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12519 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12520 
12521 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
12522 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
12523 
12524 	if (env->cur_state->active_rcu_lock) {
12525 		struct bpf_func_state *state;
12526 		struct bpf_reg_state *reg;
12527 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12528 
12529 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12530 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12531 			return -EACCES;
12532 		}
12533 
12534 		if (rcu_lock) {
12535 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12536 			return -EINVAL;
12537 		} else if (rcu_unlock) {
12538 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12539 				if (reg->type & MEM_RCU) {
12540 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12541 					reg->type |= PTR_UNTRUSTED;
12542 				}
12543 			}));
12544 			env->cur_state->active_rcu_lock = false;
12545 		} else if (sleepable) {
12546 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12547 			return -EACCES;
12548 		}
12549 	} else if (rcu_lock) {
12550 		env->cur_state->active_rcu_lock = true;
12551 	} else if (rcu_unlock) {
12552 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12553 		return -EINVAL;
12554 	}
12555 
12556 	if (env->cur_state->active_preempt_lock) {
12557 		if (preempt_disable) {
12558 			env->cur_state->active_preempt_lock++;
12559 		} else if (preempt_enable) {
12560 			env->cur_state->active_preempt_lock--;
12561 		} else if (sleepable) {
12562 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
12563 			return -EACCES;
12564 		}
12565 	} else if (preempt_disable) {
12566 		env->cur_state->active_preempt_lock++;
12567 	} else if (preempt_enable) {
12568 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
12569 		return -EINVAL;
12570 	}
12571 
12572 	/* In case of release function, we get register number of refcounted
12573 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12574 	 */
12575 	if (meta.release_regno) {
12576 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12577 		if (err) {
12578 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12579 				func_name, meta.func_id);
12580 			return err;
12581 		}
12582 	}
12583 
12584 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12585 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12586 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12587 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12588 		insn_aux->insert_off = regs[BPF_REG_2].off;
12589 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12590 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12591 		if (err) {
12592 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12593 				func_name, meta.func_id);
12594 			return err;
12595 		}
12596 
12597 		err = release_reference(env, release_ref_obj_id);
12598 		if (err) {
12599 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12600 				func_name, meta.func_id);
12601 			return err;
12602 		}
12603 	}
12604 
12605 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12606 		if (!bpf_jit_supports_exceptions()) {
12607 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12608 				func_name, meta.func_id);
12609 			return -ENOTSUPP;
12610 		}
12611 		env->seen_exception = true;
12612 
12613 		/* In the case of the default callback, the cookie value passed
12614 		 * to bpf_throw becomes the return value of the program.
12615 		 */
12616 		if (!env->exception_callback_subprog) {
12617 			err = check_return_code(env, BPF_REG_1, "R1");
12618 			if (err < 0)
12619 				return err;
12620 		}
12621 	}
12622 
12623 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12624 		mark_reg_not_init(env, regs, caller_saved[i]);
12625 
12626 	/* Check return type */
12627 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12628 
12629 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12630 		/* Only exception is bpf_obj_new_impl */
12631 		if (meta.btf != btf_vmlinux ||
12632 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12633 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12634 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12635 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12636 			return -EINVAL;
12637 		}
12638 	}
12639 
12640 	if (btf_type_is_scalar(t)) {
12641 		mark_reg_unknown(env, regs, BPF_REG_0);
12642 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12643 	} else if (btf_type_is_ptr(t)) {
12644 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12645 
12646 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12647 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12648 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12649 				struct btf_struct_meta *struct_meta;
12650 				struct btf *ret_btf;
12651 				u32 ret_btf_id;
12652 
12653 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12654 					return -ENOMEM;
12655 
12656 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12657 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12658 					return -EINVAL;
12659 				}
12660 
12661 				ret_btf = env->prog->aux->btf;
12662 				ret_btf_id = meta.arg_constant.value;
12663 
12664 				/* This may be NULL due to user not supplying a BTF */
12665 				if (!ret_btf) {
12666 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12667 					return -EINVAL;
12668 				}
12669 
12670 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12671 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12672 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12673 					return -EINVAL;
12674 				}
12675 
12676 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12677 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12678 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12679 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12680 						return -EINVAL;
12681 					}
12682 
12683 					if (!bpf_global_percpu_ma_set) {
12684 						mutex_lock(&bpf_percpu_ma_lock);
12685 						if (!bpf_global_percpu_ma_set) {
12686 							/* Charge memory allocated with bpf_global_percpu_ma to
12687 							 * root memcg. The obj_cgroup for root memcg is NULL.
12688 							 */
12689 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12690 							if (!err)
12691 								bpf_global_percpu_ma_set = true;
12692 						}
12693 						mutex_unlock(&bpf_percpu_ma_lock);
12694 						if (err)
12695 							return err;
12696 					}
12697 
12698 					mutex_lock(&bpf_percpu_ma_lock);
12699 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12700 					mutex_unlock(&bpf_percpu_ma_lock);
12701 					if (err)
12702 						return err;
12703 				}
12704 
12705 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12706 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12707 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12708 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12709 						return -EINVAL;
12710 					}
12711 
12712 					if (struct_meta) {
12713 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12714 						return -EINVAL;
12715 					}
12716 				}
12717 
12718 				mark_reg_known_zero(env, regs, BPF_REG_0);
12719 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12720 				regs[BPF_REG_0].btf = ret_btf;
12721 				regs[BPF_REG_0].btf_id = ret_btf_id;
12722 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12723 					regs[BPF_REG_0].type |= MEM_PERCPU;
12724 
12725 				insn_aux->obj_new_size = ret_t->size;
12726 				insn_aux->kptr_struct_meta = struct_meta;
12727 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12728 				mark_reg_known_zero(env, regs, BPF_REG_0);
12729 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12730 				regs[BPF_REG_0].btf = meta.arg_btf;
12731 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12732 
12733 				insn_aux->kptr_struct_meta =
12734 					btf_find_struct_meta(meta.arg_btf,
12735 							     meta.arg_btf_id);
12736 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12737 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12738 				struct btf_field *field = meta.arg_list_head.field;
12739 
12740 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12741 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12742 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12743 				struct btf_field *field = meta.arg_rbtree_root.field;
12744 
12745 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12746 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12747 				mark_reg_known_zero(env, regs, BPF_REG_0);
12748 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12749 				regs[BPF_REG_0].btf = desc_btf;
12750 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12751 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12752 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12753 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12754 					verbose(env,
12755 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12756 					return -EINVAL;
12757 				}
12758 
12759 				mark_reg_known_zero(env, regs, BPF_REG_0);
12760 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12761 				regs[BPF_REG_0].btf = desc_btf;
12762 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12763 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12764 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12765 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12766 
12767 				mark_reg_known_zero(env, regs, BPF_REG_0);
12768 
12769 				if (!meta.arg_constant.found) {
12770 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12771 					return -EFAULT;
12772 				}
12773 
12774 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12775 
12776 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12777 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12778 
12779 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12780 					regs[BPF_REG_0].type |= MEM_RDONLY;
12781 				} else {
12782 					/* this will set env->seen_direct_write to true */
12783 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12784 						verbose(env, "the prog does not allow writes to packet data\n");
12785 						return -EINVAL;
12786 					}
12787 				}
12788 
12789 				if (!meta.initialized_dynptr.id) {
12790 					verbose(env, "verifier internal error: no dynptr id\n");
12791 					return -EFAULT;
12792 				}
12793 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12794 
12795 				/* we don't need to set BPF_REG_0's ref obj id
12796 				 * because packet slices are not refcounted (see
12797 				 * dynptr_type_refcounted)
12798 				 */
12799 			} else {
12800 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12801 					meta.func_name);
12802 				return -EFAULT;
12803 			}
12804 		} else if (btf_type_is_void(ptr_type)) {
12805 			/* kfunc returning 'void *' is equivalent to returning scalar */
12806 			mark_reg_unknown(env, regs, BPF_REG_0);
12807 		} else if (!__btf_type_is_struct(ptr_type)) {
12808 			if (!meta.r0_size) {
12809 				__u32 sz;
12810 
12811 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12812 					meta.r0_size = sz;
12813 					meta.r0_rdonly = true;
12814 				}
12815 			}
12816 			if (!meta.r0_size) {
12817 				ptr_type_name = btf_name_by_offset(desc_btf,
12818 								   ptr_type->name_off);
12819 				verbose(env,
12820 					"kernel function %s returns pointer type %s %s is not supported\n",
12821 					func_name,
12822 					btf_type_str(ptr_type),
12823 					ptr_type_name);
12824 				return -EINVAL;
12825 			}
12826 
12827 			mark_reg_known_zero(env, regs, BPF_REG_0);
12828 			regs[BPF_REG_0].type = PTR_TO_MEM;
12829 			regs[BPF_REG_0].mem_size = meta.r0_size;
12830 
12831 			if (meta.r0_rdonly)
12832 				regs[BPF_REG_0].type |= MEM_RDONLY;
12833 
12834 			/* Ensures we don't access the memory after a release_reference() */
12835 			if (meta.ref_obj_id)
12836 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12837 		} else {
12838 			mark_reg_known_zero(env, regs, BPF_REG_0);
12839 			regs[BPF_REG_0].btf = desc_btf;
12840 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12841 			regs[BPF_REG_0].btf_id = ptr_type_id;
12842 
12843 			if (is_iter_next_kfunc(&meta)) {
12844 				struct bpf_reg_state *cur_iter;
12845 
12846 				cur_iter = get_iter_from_state(env->cur_state, &meta);
12847 
12848 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12849 					regs[BPF_REG_0].type |= MEM_RCU;
12850 				else
12851 					regs[BPF_REG_0].type |= PTR_TRUSTED;
12852 			}
12853 		}
12854 
12855 		if (is_kfunc_ret_null(&meta)) {
12856 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12857 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12858 			regs[BPF_REG_0].id = ++env->id_gen;
12859 		}
12860 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12861 		if (is_kfunc_acquire(&meta)) {
12862 			int id = acquire_reference_state(env, insn_idx);
12863 
12864 			if (id < 0)
12865 				return id;
12866 			if (is_kfunc_ret_null(&meta))
12867 				regs[BPF_REG_0].id = id;
12868 			regs[BPF_REG_0].ref_obj_id = id;
12869 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12870 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12871 		}
12872 
12873 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12874 			regs[BPF_REG_0].id = ++env->id_gen;
12875 	} else if (btf_type_is_void(t)) {
12876 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12877 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12878 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12879 				insn_aux->kptr_struct_meta =
12880 					btf_find_struct_meta(meta.arg_btf,
12881 							     meta.arg_btf_id);
12882 			}
12883 		}
12884 	}
12885 
12886 	nargs = btf_type_vlen(meta.func_proto);
12887 	args = (const struct btf_param *)(meta.func_proto + 1);
12888 	for (i = 0; i < nargs; i++) {
12889 		u32 regno = i + 1;
12890 
12891 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12892 		if (btf_type_is_ptr(t))
12893 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12894 		else
12895 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12896 			mark_btf_func_reg_size(env, regno, t->size);
12897 	}
12898 
12899 	if (is_iter_next_kfunc(&meta)) {
12900 		err = process_iter_next_call(env, insn_idx, &meta);
12901 		if (err)
12902 			return err;
12903 	}
12904 
12905 	return 0;
12906 }
12907 
12908 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12909 				  const struct bpf_reg_state *reg,
12910 				  enum bpf_reg_type type)
12911 {
12912 	bool known = tnum_is_const(reg->var_off);
12913 	s64 val = reg->var_off.value;
12914 	s64 smin = reg->smin_value;
12915 
12916 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12917 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12918 			reg_type_str(env, type), val);
12919 		return false;
12920 	}
12921 
12922 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12923 		verbose(env, "%s pointer offset %d is not allowed\n",
12924 			reg_type_str(env, type), reg->off);
12925 		return false;
12926 	}
12927 
12928 	if (smin == S64_MIN) {
12929 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12930 			reg_type_str(env, type));
12931 		return false;
12932 	}
12933 
12934 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12935 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12936 			smin, reg_type_str(env, type));
12937 		return false;
12938 	}
12939 
12940 	return true;
12941 }
12942 
12943 enum {
12944 	REASON_BOUNDS	= -1,
12945 	REASON_TYPE	= -2,
12946 	REASON_PATHS	= -3,
12947 	REASON_LIMIT	= -4,
12948 	REASON_STACK	= -5,
12949 };
12950 
12951 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12952 			      u32 *alu_limit, bool mask_to_left)
12953 {
12954 	u32 max = 0, ptr_limit = 0;
12955 
12956 	switch (ptr_reg->type) {
12957 	case PTR_TO_STACK:
12958 		/* Offset 0 is out-of-bounds, but acceptable start for the
12959 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12960 		 * offset where we would need to deal with min/max bounds is
12961 		 * currently prohibited for unprivileged.
12962 		 */
12963 		max = MAX_BPF_STACK + mask_to_left;
12964 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12965 		break;
12966 	case PTR_TO_MAP_VALUE:
12967 		max = ptr_reg->map_ptr->value_size;
12968 		ptr_limit = (mask_to_left ?
12969 			     ptr_reg->smin_value :
12970 			     ptr_reg->umax_value) + ptr_reg->off;
12971 		break;
12972 	default:
12973 		return REASON_TYPE;
12974 	}
12975 
12976 	if (ptr_limit >= max)
12977 		return REASON_LIMIT;
12978 	*alu_limit = ptr_limit;
12979 	return 0;
12980 }
12981 
12982 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12983 				    const struct bpf_insn *insn)
12984 {
12985 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12986 }
12987 
12988 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12989 				       u32 alu_state, u32 alu_limit)
12990 {
12991 	/* If we arrived here from different branches with different
12992 	 * state or limits to sanitize, then this won't work.
12993 	 */
12994 	if (aux->alu_state &&
12995 	    (aux->alu_state != alu_state ||
12996 	     aux->alu_limit != alu_limit))
12997 		return REASON_PATHS;
12998 
12999 	/* Corresponding fixup done in do_misc_fixups(). */
13000 	aux->alu_state = alu_state;
13001 	aux->alu_limit = alu_limit;
13002 	return 0;
13003 }
13004 
13005 static int sanitize_val_alu(struct bpf_verifier_env *env,
13006 			    struct bpf_insn *insn)
13007 {
13008 	struct bpf_insn_aux_data *aux = cur_aux(env);
13009 
13010 	if (can_skip_alu_sanitation(env, insn))
13011 		return 0;
13012 
13013 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
13014 }
13015 
13016 static bool sanitize_needed(u8 opcode)
13017 {
13018 	return opcode == BPF_ADD || opcode == BPF_SUB;
13019 }
13020 
13021 struct bpf_sanitize_info {
13022 	struct bpf_insn_aux_data aux;
13023 	bool mask_to_left;
13024 };
13025 
13026 static struct bpf_verifier_state *
13027 sanitize_speculative_path(struct bpf_verifier_env *env,
13028 			  const struct bpf_insn *insn,
13029 			  u32 next_idx, u32 curr_idx)
13030 {
13031 	struct bpf_verifier_state *branch;
13032 	struct bpf_reg_state *regs;
13033 
13034 	branch = push_stack(env, next_idx, curr_idx, true);
13035 	if (branch && insn) {
13036 		regs = branch->frame[branch->curframe]->regs;
13037 		if (BPF_SRC(insn->code) == BPF_K) {
13038 			mark_reg_unknown(env, regs, insn->dst_reg);
13039 		} else if (BPF_SRC(insn->code) == BPF_X) {
13040 			mark_reg_unknown(env, regs, insn->dst_reg);
13041 			mark_reg_unknown(env, regs, insn->src_reg);
13042 		}
13043 	}
13044 	return branch;
13045 }
13046 
13047 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
13048 			    struct bpf_insn *insn,
13049 			    const struct bpf_reg_state *ptr_reg,
13050 			    const struct bpf_reg_state *off_reg,
13051 			    struct bpf_reg_state *dst_reg,
13052 			    struct bpf_sanitize_info *info,
13053 			    const bool commit_window)
13054 {
13055 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
13056 	struct bpf_verifier_state *vstate = env->cur_state;
13057 	bool off_is_imm = tnum_is_const(off_reg->var_off);
13058 	bool off_is_neg = off_reg->smin_value < 0;
13059 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
13060 	u8 opcode = BPF_OP(insn->code);
13061 	u32 alu_state, alu_limit;
13062 	struct bpf_reg_state tmp;
13063 	bool ret;
13064 	int err;
13065 
13066 	if (can_skip_alu_sanitation(env, insn))
13067 		return 0;
13068 
13069 	/* We already marked aux for masking from non-speculative
13070 	 * paths, thus we got here in the first place. We only care
13071 	 * to explore bad access from here.
13072 	 */
13073 	if (vstate->speculative)
13074 		goto do_sim;
13075 
13076 	if (!commit_window) {
13077 		if (!tnum_is_const(off_reg->var_off) &&
13078 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
13079 			return REASON_BOUNDS;
13080 
13081 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
13082 				     (opcode == BPF_SUB && !off_is_neg);
13083 	}
13084 
13085 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
13086 	if (err < 0)
13087 		return err;
13088 
13089 	if (commit_window) {
13090 		/* In commit phase we narrow the masking window based on
13091 		 * the observed pointer move after the simulated operation.
13092 		 */
13093 		alu_state = info->aux.alu_state;
13094 		alu_limit = abs(info->aux.alu_limit - alu_limit);
13095 	} else {
13096 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
13097 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
13098 		alu_state |= ptr_is_dst_reg ?
13099 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
13100 
13101 		/* Limit pruning on unknown scalars to enable deep search for
13102 		 * potential masking differences from other program paths.
13103 		 */
13104 		if (!off_is_imm)
13105 			env->explore_alu_limits = true;
13106 	}
13107 
13108 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
13109 	if (err < 0)
13110 		return err;
13111 do_sim:
13112 	/* If we're in commit phase, we're done here given we already
13113 	 * pushed the truncated dst_reg into the speculative verification
13114 	 * stack.
13115 	 *
13116 	 * Also, when register is a known constant, we rewrite register-based
13117 	 * operation to immediate-based, and thus do not need masking (and as
13118 	 * a consequence, do not need to simulate the zero-truncation either).
13119 	 */
13120 	if (commit_window || off_is_imm)
13121 		return 0;
13122 
13123 	/* Simulate and find potential out-of-bounds access under
13124 	 * speculative execution from truncation as a result of
13125 	 * masking when off was not within expected range. If off
13126 	 * sits in dst, then we temporarily need to move ptr there
13127 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
13128 	 * for cases where we use K-based arithmetic in one direction
13129 	 * and truncated reg-based in the other in order to explore
13130 	 * bad access.
13131 	 */
13132 	if (!ptr_is_dst_reg) {
13133 		tmp = *dst_reg;
13134 		copy_register_state(dst_reg, ptr_reg);
13135 	}
13136 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
13137 					env->insn_idx);
13138 	if (!ptr_is_dst_reg && ret)
13139 		*dst_reg = tmp;
13140 	return !ret ? REASON_STACK : 0;
13141 }
13142 
13143 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
13144 {
13145 	struct bpf_verifier_state *vstate = env->cur_state;
13146 
13147 	/* If we simulate paths under speculation, we don't update the
13148 	 * insn as 'seen' such that when we verify unreachable paths in
13149 	 * the non-speculative domain, sanitize_dead_code() can still
13150 	 * rewrite/sanitize them.
13151 	 */
13152 	if (!vstate->speculative)
13153 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
13154 }
13155 
13156 static int sanitize_err(struct bpf_verifier_env *env,
13157 			const struct bpf_insn *insn, int reason,
13158 			const struct bpf_reg_state *off_reg,
13159 			const struct bpf_reg_state *dst_reg)
13160 {
13161 	static const char *err = "pointer arithmetic with it prohibited for !root";
13162 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
13163 	u32 dst = insn->dst_reg, src = insn->src_reg;
13164 
13165 	switch (reason) {
13166 	case REASON_BOUNDS:
13167 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13168 			off_reg == dst_reg ? dst : src, err);
13169 		break;
13170 	case REASON_TYPE:
13171 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13172 			off_reg == dst_reg ? src : dst, err);
13173 		break;
13174 	case REASON_PATHS:
13175 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13176 			dst, op, err);
13177 		break;
13178 	case REASON_LIMIT:
13179 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13180 			dst, op, err);
13181 		break;
13182 	case REASON_STACK:
13183 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13184 			dst, err);
13185 		break;
13186 	default:
13187 		verbose(env, "verifier internal error: unknown reason (%d)\n",
13188 			reason);
13189 		break;
13190 	}
13191 
13192 	return -EACCES;
13193 }
13194 
13195 /* check that stack access falls within stack limits and that 'reg' doesn't
13196  * have a variable offset.
13197  *
13198  * Variable offset is prohibited for unprivileged mode for simplicity since it
13199  * requires corresponding support in Spectre masking for stack ALU.  See also
13200  * retrieve_ptr_limit().
13201  *
13202  *
13203  * 'off' includes 'reg->off'.
13204  */
13205 static int check_stack_access_for_ptr_arithmetic(
13206 				struct bpf_verifier_env *env,
13207 				int regno,
13208 				const struct bpf_reg_state *reg,
13209 				int off)
13210 {
13211 	if (!tnum_is_const(reg->var_off)) {
13212 		char tn_buf[48];
13213 
13214 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13215 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13216 			regno, tn_buf, off);
13217 		return -EACCES;
13218 	}
13219 
13220 	if (off >= 0 || off < -MAX_BPF_STACK) {
13221 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13222 			"prohibited for !root; off=%d\n", regno, off);
13223 		return -EACCES;
13224 	}
13225 
13226 	return 0;
13227 }
13228 
13229 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13230 				 const struct bpf_insn *insn,
13231 				 const struct bpf_reg_state *dst_reg)
13232 {
13233 	u32 dst = insn->dst_reg;
13234 
13235 	/* For unprivileged we require that resulting offset must be in bounds
13236 	 * in order to be able to sanitize access later on.
13237 	 */
13238 	if (env->bypass_spec_v1)
13239 		return 0;
13240 
13241 	switch (dst_reg->type) {
13242 	case PTR_TO_STACK:
13243 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13244 					dst_reg->off + dst_reg->var_off.value))
13245 			return -EACCES;
13246 		break;
13247 	case PTR_TO_MAP_VALUE:
13248 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13249 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13250 				"prohibited for !root\n", dst);
13251 			return -EACCES;
13252 		}
13253 		break;
13254 	default:
13255 		break;
13256 	}
13257 
13258 	return 0;
13259 }
13260 
13261 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13262  * Caller should also handle BPF_MOV case separately.
13263  * If we return -EACCES, caller may want to try again treating pointer as a
13264  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13265  */
13266 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13267 				   struct bpf_insn *insn,
13268 				   const struct bpf_reg_state *ptr_reg,
13269 				   const struct bpf_reg_state *off_reg)
13270 {
13271 	struct bpf_verifier_state *vstate = env->cur_state;
13272 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13273 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13274 	bool known = tnum_is_const(off_reg->var_off);
13275 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13276 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13277 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13278 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13279 	struct bpf_sanitize_info info = {};
13280 	u8 opcode = BPF_OP(insn->code);
13281 	u32 dst = insn->dst_reg;
13282 	int ret;
13283 
13284 	dst_reg = &regs[dst];
13285 
13286 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13287 	    smin_val > smax_val || umin_val > umax_val) {
13288 		/* Taint dst register if offset had invalid bounds derived from
13289 		 * e.g. dead branches.
13290 		 */
13291 		__mark_reg_unknown(env, dst_reg);
13292 		return 0;
13293 	}
13294 
13295 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13296 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13297 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13298 			__mark_reg_unknown(env, dst_reg);
13299 			return 0;
13300 		}
13301 
13302 		verbose(env,
13303 			"R%d 32-bit pointer arithmetic prohibited\n",
13304 			dst);
13305 		return -EACCES;
13306 	}
13307 
13308 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13309 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13310 			dst, reg_type_str(env, ptr_reg->type));
13311 		return -EACCES;
13312 	}
13313 
13314 	switch (base_type(ptr_reg->type)) {
13315 	case PTR_TO_CTX:
13316 	case PTR_TO_MAP_VALUE:
13317 	case PTR_TO_MAP_KEY:
13318 	case PTR_TO_STACK:
13319 	case PTR_TO_PACKET_META:
13320 	case PTR_TO_PACKET:
13321 	case PTR_TO_TP_BUFFER:
13322 	case PTR_TO_BTF_ID:
13323 	case PTR_TO_MEM:
13324 	case PTR_TO_BUF:
13325 	case PTR_TO_FUNC:
13326 	case CONST_PTR_TO_DYNPTR:
13327 		break;
13328 	case PTR_TO_FLOW_KEYS:
13329 		if (known)
13330 			break;
13331 		fallthrough;
13332 	case CONST_PTR_TO_MAP:
13333 		/* smin_val represents the known value */
13334 		if (known && smin_val == 0 && opcode == BPF_ADD)
13335 			break;
13336 		fallthrough;
13337 	default:
13338 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13339 			dst, reg_type_str(env, ptr_reg->type));
13340 		return -EACCES;
13341 	}
13342 
13343 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13344 	 * The id may be overwritten later if we create a new variable offset.
13345 	 */
13346 	dst_reg->type = ptr_reg->type;
13347 	dst_reg->id = ptr_reg->id;
13348 
13349 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13350 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13351 		return -EINVAL;
13352 
13353 	/* pointer types do not carry 32-bit bounds at the moment. */
13354 	__mark_reg32_unbounded(dst_reg);
13355 
13356 	if (sanitize_needed(opcode)) {
13357 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13358 				       &info, false);
13359 		if (ret < 0)
13360 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13361 	}
13362 
13363 	switch (opcode) {
13364 	case BPF_ADD:
13365 		/* We can take a fixed offset as long as it doesn't overflow
13366 		 * the s32 'off' field
13367 		 */
13368 		if (known && (ptr_reg->off + smin_val ==
13369 			      (s64)(s32)(ptr_reg->off + smin_val))) {
13370 			/* pointer += K.  Accumulate it into fixed offset */
13371 			dst_reg->smin_value = smin_ptr;
13372 			dst_reg->smax_value = smax_ptr;
13373 			dst_reg->umin_value = umin_ptr;
13374 			dst_reg->umax_value = umax_ptr;
13375 			dst_reg->var_off = ptr_reg->var_off;
13376 			dst_reg->off = ptr_reg->off + smin_val;
13377 			dst_reg->raw = ptr_reg->raw;
13378 			break;
13379 		}
13380 		/* A new variable offset is created.  Note that off_reg->off
13381 		 * == 0, since it's a scalar.
13382 		 * dst_reg gets the pointer type and since some positive
13383 		 * integer value was added to the pointer, give it a new 'id'
13384 		 * if it's a PTR_TO_PACKET.
13385 		 * this creates a new 'base' pointer, off_reg (variable) gets
13386 		 * added into the variable offset, and we copy the fixed offset
13387 		 * from ptr_reg.
13388 		 */
13389 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
13390 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
13391 			dst_reg->smin_value = S64_MIN;
13392 			dst_reg->smax_value = S64_MAX;
13393 		}
13394 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
13395 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
13396 			dst_reg->umin_value = 0;
13397 			dst_reg->umax_value = U64_MAX;
13398 		}
13399 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13400 		dst_reg->off = ptr_reg->off;
13401 		dst_reg->raw = ptr_reg->raw;
13402 		if (reg_is_pkt_pointer(ptr_reg)) {
13403 			dst_reg->id = ++env->id_gen;
13404 			/* something was added to pkt_ptr, set range to zero */
13405 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13406 		}
13407 		break;
13408 	case BPF_SUB:
13409 		if (dst_reg == off_reg) {
13410 			/* scalar -= pointer.  Creates an unknown scalar */
13411 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13412 				dst);
13413 			return -EACCES;
13414 		}
13415 		/* We don't allow subtraction from FP, because (according to
13416 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13417 		 * be able to deal with it.
13418 		 */
13419 		if (ptr_reg->type == PTR_TO_STACK) {
13420 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13421 				dst);
13422 			return -EACCES;
13423 		}
13424 		if (known && (ptr_reg->off - smin_val ==
13425 			      (s64)(s32)(ptr_reg->off - smin_val))) {
13426 			/* pointer -= K.  Subtract it from fixed offset */
13427 			dst_reg->smin_value = smin_ptr;
13428 			dst_reg->smax_value = smax_ptr;
13429 			dst_reg->umin_value = umin_ptr;
13430 			dst_reg->umax_value = umax_ptr;
13431 			dst_reg->var_off = ptr_reg->var_off;
13432 			dst_reg->id = ptr_reg->id;
13433 			dst_reg->off = ptr_reg->off - smin_val;
13434 			dst_reg->raw = ptr_reg->raw;
13435 			break;
13436 		}
13437 		/* A new variable offset is created.  If the subtrahend is known
13438 		 * nonnegative, then any reg->range we had before is still good.
13439 		 */
13440 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
13441 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
13442 			/* Overflow possible, we know nothing */
13443 			dst_reg->smin_value = S64_MIN;
13444 			dst_reg->smax_value = S64_MAX;
13445 		}
13446 		if (umin_ptr < umax_val) {
13447 			/* Overflow possible, we know nothing */
13448 			dst_reg->umin_value = 0;
13449 			dst_reg->umax_value = U64_MAX;
13450 		} else {
13451 			/* Cannot overflow (as long as bounds are consistent) */
13452 			dst_reg->umin_value = umin_ptr - umax_val;
13453 			dst_reg->umax_value = umax_ptr - umin_val;
13454 		}
13455 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13456 		dst_reg->off = ptr_reg->off;
13457 		dst_reg->raw = ptr_reg->raw;
13458 		if (reg_is_pkt_pointer(ptr_reg)) {
13459 			dst_reg->id = ++env->id_gen;
13460 			/* something was added to pkt_ptr, set range to zero */
13461 			if (smin_val < 0)
13462 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13463 		}
13464 		break;
13465 	case BPF_AND:
13466 	case BPF_OR:
13467 	case BPF_XOR:
13468 		/* bitwise ops on pointers are troublesome, prohibit. */
13469 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13470 			dst, bpf_alu_string[opcode >> 4]);
13471 		return -EACCES;
13472 	default:
13473 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13474 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13475 			dst, bpf_alu_string[opcode >> 4]);
13476 		return -EACCES;
13477 	}
13478 
13479 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13480 		return -EINVAL;
13481 	reg_bounds_sync(dst_reg);
13482 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13483 		return -EACCES;
13484 	if (sanitize_needed(opcode)) {
13485 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13486 				       &info, true);
13487 		if (ret < 0)
13488 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13489 	}
13490 
13491 	return 0;
13492 }
13493 
13494 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13495 				 struct bpf_reg_state *src_reg)
13496 {
13497 	s32 *dst_smin = &dst_reg->s32_min_value;
13498 	s32 *dst_smax = &dst_reg->s32_max_value;
13499 	u32 *dst_umin = &dst_reg->u32_min_value;
13500 	u32 *dst_umax = &dst_reg->u32_max_value;
13501 
13502 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
13503 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
13504 		*dst_smin = S32_MIN;
13505 		*dst_smax = S32_MAX;
13506 	}
13507 	if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
13508 	    check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
13509 		*dst_umin = 0;
13510 		*dst_umax = U32_MAX;
13511 	}
13512 }
13513 
13514 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13515 			       struct bpf_reg_state *src_reg)
13516 {
13517 	s64 *dst_smin = &dst_reg->smin_value;
13518 	s64 *dst_smax = &dst_reg->smax_value;
13519 	u64 *dst_umin = &dst_reg->umin_value;
13520 	u64 *dst_umax = &dst_reg->umax_value;
13521 
13522 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
13523 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
13524 		*dst_smin = S64_MIN;
13525 		*dst_smax = S64_MAX;
13526 	}
13527 	if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
13528 	    check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
13529 		*dst_umin = 0;
13530 		*dst_umax = U64_MAX;
13531 	}
13532 }
13533 
13534 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13535 				 struct bpf_reg_state *src_reg)
13536 {
13537 	s32 *dst_smin = &dst_reg->s32_min_value;
13538 	s32 *dst_smax = &dst_reg->s32_max_value;
13539 	u32 umin_val = src_reg->u32_min_value;
13540 	u32 umax_val = src_reg->u32_max_value;
13541 
13542 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
13543 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
13544 		/* Overflow possible, we know nothing */
13545 		*dst_smin = S32_MIN;
13546 		*dst_smax = S32_MAX;
13547 	}
13548 	if (dst_reg->u32_min_value < umax_val) {
13549 		/* Overflow possible, we know nothing */
13550 		dst_reg->u32_min_value = 0;
13551 		dst_reg->u32_max_value = U32_MAX;
13552 	} else {
13553 		/* Cannot overflow (as long as bounds are consistent) */
13554 		dst_reg->u32_min_value -= umax_val;
13555 		dst_reg->u32_max_value -= umin_val;
13556 	}
13557 }
13558 
13559 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13560 			       struct bpf_reg_state *src_reg)
13561 {
13562 	s64 *dst_smin = &dst_reg->smin_value;
13563 	s64 *dst_smax = &dst_reg->smax_value;
13564 	u64 umin_val = src_reg->umin_value;
13565 	u64 umax_val = src_reg->umax_value;
13566 
13567 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
13568 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
13569 		/* Overflow possible, we know nothing */
13570 		*dst_smin = S64_MIN;
13571 		*dst_smax = S64_MAX;
13572 	}
13573 	if (dst_reg->umin_value < umax_val) {
13574 		/* Overflow possible, we know nothing */
13575 		dst_reg->umin_value = 0;
13576 		dst_reg->umax_value = U64_MAX;
13577 	} else {
13578 		/* Cannot overflow (as long as bounds are consistent) */
13579 		dst_reg->umin_value -= umax_val;
13580 		dst_reg->umax_value -= umin_val;
13581 	}
13582 }
13583 
13584 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13585 				 struct bpf_reg_state *src_reg)
13586 {
13587 	s32 smin_val = src_reg->s32_min_value;
13588 	u32 umin_val = src_reg->u32_min_value;
13589 	u32 umax_val = src_reg->u32_max_value;
13590 
13591 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13592 		/* Ain't nobody got time to multiply that sign */
13593 		__mark_reg32_unbounded(dst_reg);
13594 		return;
13595 	}
13596 	/* Both values are positive, so we can work with unsigned and
13597 	 * copy the result to signed (unless it exceeds S32_MAX).
13598 	 */
13599 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13600 		/* Potential overflow, we know nothing */
13601 		__mark_reg32_unbounded(dst_reg);
13602 		return;
13603 	}
13604 	dst_reg->u32_min_value *= umin_val;
13605 	dst_reg->u32_max_value *= umax_val;
13606 	if (dst_reg->u32_max_value > S32_MAX) {
13607 		/* Overflow possible, we know nothing */
13608 		dst_reg->s32_min_value = S32_MIN;
13609 		dst_reg->s32_max_value = S32_MAX;
13610 	} else {
13611 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13612 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13613 	}
13614 }
13615 
13616 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13617 			       struct bpf_reg_state *src_reg)
13618 {
13619 	s64 smin_val = src_reg->smin_value;
13620 	u64 umin_val = src_reg->umin_value;
13621 	u64 umax_val = src_reg->umax_value;
13622 
13623 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13624 		/* Ain't nobody got time to multiply that sign */
13625 		__mark_reg64_unbounded(dst_reg);
13626 		return;
13627 	}
13628 	/* Both values are positive, so we can work with unsigned and
13629 	 * copy the result to signed (unless it exceeds S64_MAX).
13630 	 */
13631 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13632 		/* Potential overflow, we know nothing */
13633 		__mark_reg64_unbounded(dst_reg);
13634 		return;
13635 	}
13636 	dst_reg->umin_value *= umin_val;
13637 	dst_reg->umax_value *= umax_val;
13638 	if (dst_reg->umax_value > S64_MAX) {
13639 		/* Overflow possible, we know nothing */
13640 		dst_reg->smin_value = S64_MIN;
13641 		dst_reg->smax_value = S64_MAX;
13642 	} else {
13643 		dst_reg->smin_value = dst_reg->umin_value;
13644 		dst_reg->smax_value = dst_reg->umax_value;
13645 	}
13646 }
13647 
13648 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13649 				 struct bpf_reg_state *src_reg)
13650 {
13651 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13652 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13653 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13654 	u32 umax_val = src_reg->u32_max_value;
13655 
13656 	if (src_known && dst_known) {
13657 		__mark_reg32_known(dst_reg, var32_off.value);
13658 		return;
13659 	}
13660 
13661 	/* We get our minimum from the var_off, since that's inherently
13662 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13663 	 */
13664 	dst_reg->u32_min_value = var32_off.value;
13665 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13666 
13667 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13668 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13669 	 */
13670 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13671 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13672 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13673 	} else {
13674 		dst_reg->s32_min_value = S32_MIN;
13675 		dst_reg->s32_max_value = S32_MAX;
13676 	}
13677 }
13678 
13679 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13680 			       struct bpf_reg_state *src_reg)
13681 {
13682 	bool src_known = tnum_is_const(src_reg->var_off);
13683 	bool dst_known = tnum_is_const(dst_reg->var_off);
13684 	u64 umax_val = src_reg->umax_value;
13685 
13686 	if (src_known && dst_known) {
13687 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13688 		return;
13689 	}
13690 
13691 	/* We get our minimum from the var_off, since that's inherently
13692 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13693 	 */
13694 	dst_reg->umin_value = dst_reg->var_off.value;
13695 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13696 
13697 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13698 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13699 	 */
13700 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13701 		dst_reg->smin_value = dst_reg->umin_value;
13702 		dst_reg->smax_value = dst_reg->umax_value;
13703 	} else {
13704 		dst_reg->smin_value = S64_MIN;
13705 		dst_reg->smax_value = S64_MAX;
13706 	}
13707 	/* We may learn something more from the var_off */
13708 	__update_reg_bounds(dst_reg);
13709 }
13710 
13711 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13712 				struct bpf_reg_state *src_reg)
13713 {
13714 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13715 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13716 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13717 	u32 umin_val = src_reg->u32_min_value;
13718 
13719 	if (src_known && dst_known) {
13720 		__mark_reg32_known(dst_reg, var32_off.value);
13721 		return;
13722 	}
13723 
13724 	/* We get our maximum from the var_off, and our minimum is the
13725 	 * maximum of the operands' minima
13726 	 */
13727 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13728 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13729 
13730 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13731 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13732 	 */
13733 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13734 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13735 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13736 	} else {
13737 		dst_reg->s32_min_value = S32_MIN;
13738 		dst_reg->s32_max_value = S32_MAX;
13739 	}
13740 }
13741 
13742 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13743 			      struct bpf_reg_state *src_reg)
13744 {
13745 	bool src_known = tnum_is_const(src_reg->var_off);
13746 	bool dst_known = tnum_is_const(dst_reg->var_off);
13747 	u64 umin_val = src_reg->umin_value;
13748 
13749 	if (src_known && dst_known) {
13750 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13751 		return;
13752 	}
13753 
13754 	/* We get our maximum from the var_off, and our minimum is the
13755 	 * maximum of the operands' minima
13756 	 */
13757 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13758 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13759 
13760 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13761 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13762 	 */
13763 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13764 		dst_reg->smin_value = dst_reg->umin_value;
13765 		dst_reg->smax_value = dst_reg->umax_value;
13766 	} else {
13767 		dst_reg->smin_value = S64_MIN;
13768 		dst_reg->smax_value = S64_MAX;
13769 	}
13770 	/* We may learn something more from the var_off */
13771 	__update_reg_bounds(dst_reg);
13772 }
13773 
13774 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13775 				 struct bpf_reg_state *src_reg)
13776 {
13777 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13778 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13779 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13780 
13781 	if (src_known && dst_known) {
13782 		__mark_reg32_known(dst_reg, var32_off.value);
13783 		return;
13784 	}
13785 
13786 	/* We get both minimum and maximum from the var32_off. */
13787 	dst_reg->u32_min_value = var32_off.value;
13788 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13789 
13790 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13791 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13792 	 */
13793 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13794 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13795 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13796 	} else {
13797 		dst_reg->s32_min_value = S32_MIN;
13798 		dst_reg->s32_max_value = S32_MAX;
13799 	}
13800 }
13801 
13802 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13803 			       struct bpf_reg_state *src_reg)
13804 {
13805 	bool src_known = tnum_is_const(src_reg->var_off);
13806 	bool dst_known = tnum_is_const(dst_reg->var_off);
13807 
13808 	if (src_known && dst_known) {
13809 		/* dst_reg->var_off.value has been updated earlier */
13810 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13811 		return;
13812 	}
13813 
13814 	/* We get both minimum and maximum from the var_off. */
13815 	dst_reg->umin_value = dst_reg->var_off.value;
13816 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13817 
13818 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13819 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13820 	 */
13821 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13822 		dst_reg->smin_value = dst_reg->umin_value;
13823 		dst_reg->smax_value = dst_reg->umax_value;
13824 	} else {
13825 		dst_reg->smin_value = S64_MIN;
13826 		dst_reg->smax_value = S64_MAX;
13827 	}
13828 
13829 	__update_reg_bounds(dst_reg);
13830 }
13831 
13832 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13833 				   u64 umin_val, u64 umax_val)
13834 {
13835 	/* We lose all sign bit information (except what we can pick
13836 	 * up from var_off)
13837 	 */
13838 	dst_reg->s32_min_value = S32_MIN;
13839 	dst_reg->s32_max_value = S32_MAX;
13840 	/* If we might shift our top bit out, then we know nothing */
13841 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13842 		dst_reg->u32_min_value = 0;
13843 		dst_reg->u32_max_value = U32_MAX;
13844 	} else {
13845 		dst_reg->u32_min_value <<= umin_val;
13846 		dst_reg->u32_max_value <<= umax_val;
13847 	}
13848 }
13849 
13850 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13851 				 struct bpf_reg_state *src_reg)
13852 {
13853 	u32 umax_val = src_reg->u32_max_value;
13854 	u32 umin_val = src_reg->u32_min_value;
13855 	/* u32 alu operation will zext upper bits */
13856 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13857 
13858 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13859 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13860 	/* Not required but being careful mark reg64 bounds as unknown so
13861 	 * that we are forced to pick them up from tnum and zext later and
13862 	 * if some path skips this step we are still safe.
13863 	 */
13864 	__mark_reg64_unbounded(dst_reg);
13865 	__update_reg32_bounds(dst_reg);
13866 }
13867 
13868 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13869 				   u64 umin_val, u64 umax_val)
13870 {
13871 	/* Special case <<32 because it is a common compiler pattern to sign
13872 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13873 	 * positive we know this shift will also be positive so we can track
13874 	 * bounds correctly. Otherwise we lose all sign bit information except
13875 	 * what we can pick up from var_off. Perhaps we can generalize this
13876 	 * later to shifts of any length.
13877 	 */
13878 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13879 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13880 	else
13881 		dst_reg->smax_value = S64_MAX;
13882 
13883 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13884 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13885 	else
13886 		dst_reg->smin_value = S64_MIN;
13887 
13888 	/* If we might shift our top bit out, then we know nothing */
13889 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13890 		dst_reg->umin_value = 0;
13891 		dst_reg->umax_value = U64_MAX;
13892 	} else {
13893 		dst_reg->umin_value <<= umin_val;
13894 		dst_reg->umax_value <<= umax_val;
13895 	}
13896 }
13897 
13898 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13899 			       struct bpf_reg_state *src_reg)
13900 {
13901 	u64 umax_val = src_reg->umax_value;
13902 	u64 umin_val = src_reg->umin_value;
13903 
13904 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13905 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13906 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13907 
13908 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13909 	/* We may learn something more from the var_off */
13910 	__update_reg_bounds(dst_reg);
13911 }
13912 
13913 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13914 				 struct bpf_reg_state *src_reg)
13915 {
13916 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13917 	u32 umax_val = src_reg->u32_max_value;
13918 	u32 umin_val = src_reg->u32_min_value;
13919 
13920 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13921 	 * be negative, then either:
13922 	 * 1) src_reg might be zero, so the sign bit of the result is
13923 	 *    unknown, so we lose our signed bounds
13924 	 * 2) it's known negative, thus the unsigned bounds capture the
13925 	 *    signed bounds
13926 	 * 3) the signed bounds cross zero, so they tell us nothing
13927 	 *    about the result
13928 	 * If the value in dst_reg is known nonnegative, then again the
13929 	 * unsigned bounds capture the signed bounds.
13930 	 * Thus, in all cases it suffices to blow away our signed bounds
13931 	 * and rely on inferring new ones from the unsigned bounds and
13932 	 * var_off of the result.
13933 	 */
13934 	dst_reg->s32_min_value = S32_MIN;
13935 	dst_reg->s32_max_value = S32_MAX;
13936 
13937 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13938 	dst_reg->u32_min_value >>= umax_val;
13939 	dst_reg->u32_max_value >>= umin_val;
13940 
13941 	__mark_reg64_unbounded(dst_reg);
13942 	__update_reg32_bounds(dst_reg);
13943 }
13944 
13945 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13946 			       struct bpf_reg_state *src_reg)
13947 {
13948 	u64 umax_val = src_reg->umax_value;
13949 	u64 umin_val = src_reg->umin_value;
13950 
13951 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13952 	 * be negative, then either:
13953 	 * 1) src_reg might be zero, so the sign bit of the result is
13954 	 *    unknown, so we lose our signed bounds
13955 	 * 2) it's known negative, thus the unsigned bounds capture the
13956 	 *    signed bounds
13957 	 * 3) the signed bounds cross zero, so they tell us nothing
13958 	 *    about the result
13959 	 * If the value in dst_reg is known nonnegative, then again the
13960 	 * unsigned bounds capture the signed bounds.
13961 	 * Thus, in all cases it suffices to blow away our signed bounds
13962 	 * and rely on inferring new ones from the unsigned bounds and
13963 	 * var_off of the result.
13964 	 */
13965 	dst_reg->smin_value = S64_MIN;
13966 	dst_reg->smax_value = S64_MAX;
13967 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13968 	dst_reg->umin_value >>= umax_val;
13969 	dst_reg->umax_value >>= umin_val;
13970 
13971 	/* Its not easy to operate on alu32 bounds here because it depends
13972 	 * on bits being shifted in. Take easy way out and mark unbounded
13973 	 * so we can recalculate later from tnum.
13974 	 */
13975 	__mark_reg32_unbounded(dst_reg);
13976 	__update_reg_bounds(dst_reg);
13977 }
13978 
13979 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13980 				  struct bpf_reg_state *src_reg)
13981 {
13982 	u64 umin_val = src_reg->u32_min_value;
13983 
13984 	/* Upon reaching here, src_known is true and
13985 	 * umax_val is equal to umin_val.
13986 	 */
13987 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13988 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13989 
13990 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13991 
13992 	/* blow away the dst_reg umin_value/umax_value and rely on
13993 	 * dst_reg var_off to refine the result.
13994 	 */
13995 	dst_reg->u32_min_value = 0;
13996 	dst_reg->u32_max_value = U32_MAX;
13997 
13998 	__mark_reg64_unbounded(dst_reg);
13999 	__update_reg32_bounds(dst_reg);
14000 }
14001 
14002 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
14003 				struct bpf_reg_state *src_reg)
14004 {
14005 	u64 umin_val = src_reg->umin_value;
14006 
14007 	/* Upon reaching here, src_known is true and umax_val is equal
14008 	 * to umin_val.
14009 	 */
14010 	dst_reg->smin_value >>= umin_val;
14011 	dst_reg->smax_value >>= umin_val;
14012 
14013 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
14014 
14015 	/* blow away the dst_reg umin_value/umax_value and rely on
14016 	 * dst_reg var_off to refine the result.
14017 	 */
14018 	dst_reg->umin_value = 0;
14019 	dst_reg->umax_value = U64_MAX;
14020 
14021 	/* Its not easy to operate on alu32 bounds here because it depends
14022 	 * on bits being shifted in from upper 32-bits. Take easy way out
14023 	 * and mark unbounded so we can recalculate later from tnum.
14024 	 */
14025 	__mark_reg32_unbounded(dst_reg);
14026 	__update_reg_bounds(dst_reg);
14027 }
14028 
14029 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
14030 					     const struct bpf_reg_state *src_reg)
14031 {
14032 	bool src_is_const = false;
14033 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
14034 
14035 	if (insn_bitness == 32) {
14036 		if (tnum_subreg_is_const(src_reg->var_off)
14037 		    && src_reg->s32_min_value == src_reg->s32_max_value
14038 		    && src_reg->u32_min_value == src_reg->u32_max_value)
14039 			src_is_const = true;
14040 	} else {
14041 		if (tnum_is_const(src_reg->var_off)
14042 		    && src_reg->smin_value == src_reg->smax_value
14043 		    && src_reg->umin_value == src_reg->umax_value)
14044 			src_is_const = true;
14045 	}
14046 
14047 	switch (BPF_OP(insn->code)) {
14048 	case BPF_ADD:
14049 	case BPF_SUB:
14050 	case BPF_AND:
14051 	case BPF_XOR:
14052 	case BPF_OR:
14053 	case BPF_MUL:
14054 		return true;
14055 
14056 	/* Shift operators range is only computable if shift dimension operand
14057 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
14058 	 * includes shifts by a negative number.
14059 	 */
14060 	case BPF_LSH:
14061 	case BPF_RSH:
14062 	case BPF_ARSH:
14063 		return (src_is_const && src_reg->umax_value < insn_bitness);
14064 	default:
14065 		return false;
14066 	}
14067 }
14068 
14069 /* WARNING: This function does calculations on 64-bit values, but the actual
14070  * execution may occur on 32-bit values. Therefore, things like bitshifts
14071  * need extra checks in the 32-bit case.
14072  */
14073 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
14074 				      struct bpf_insn *insn,
14075 				      struct bpf_reg_state *dst_reg,
14076 				      struct bpf_reg_state src_reg)
14077 {
14078 	u8 opcode = BPF_OP(insn->code);
14079 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14080 	int ret;
14081 
14082 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
14083 		__mark_reg_unknown(env, dst_reg);
14084 		return 0;
14085 	}
14086 
14087 	if (sanitize_needed(opcode)) {
14088 		ret = sanitize_val_alu(env, insn);
14089 		if (ret < 0)
14090 			return sanitize_err(env, insn, ret, NULL, NULL);
14091 	}
14092 
14093 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
14094 	 * There are two classes of instructions: The first class we track both
14095 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
14096 	 * greatest amount of precision when alu operations are mixed with jmp32
14097 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
14098 	 * and BPF_OR. This is possible because these ops have fairly easy to
14099 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
14100 	 * See alu32 verifier tests for examples. The second class of
14101 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
14102 	 * with regards to tracking sign/unsigned bounds because the bits may
14103 	 * cross subreg boundaries in the alu64 case. When this happens we mark
14104 	 * the reg unbounded in the subreg bound space and use the resulting
14105 	 * tnum to calculate an approximation of the sign/unsigned bounds.
14106 	 */
14107 	switch (opcode) {
14108 	case BPF_ADD:
14109 		scalar32_min_max_add(dst_reg, &src_reg);
14110 		scalar_min_max_add(dst_reg, &src_reg);
14111 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
14112 		break;
14113 	case BPF_SUB:
14114 		scalar32_min_max_sub(dst_reg, &src_reg);
14115 		scalar_min_max_sub(dst_reg, &src_reg);
14116 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
14117 		break;
14118 	case BPF_MUL:
14119 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
14120 		scalar32_min_max_mul(dst_reg, &src_reg);
14121 		scalar_min_max_mul(dst_reg, &src_reg);
14122 		break;
14123 	case BPF_AND:
14124 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
14125 		scalar32_min_max_and(dst_reg, &src_reg);
14126 		scalar_min_max_and(dst_reg, &src_reg);
14127 		break;
14128 	case BPF_OR:
14129 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
14130 		scalar32_min_max_or(dst_reg, &src_reg);
14131 		scalar_min_max_or(dst_reg, &src_reg);
14132 		break;
14133 	case BPF_XOR:
14134 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
14135 		scalar32_min_max_xor(dst_reg, &src_reg);
14136 		scalar_min_max_xor(dst_reg, &src_reg);
14137 		break;
14138 	case BPF_LSH:
14139 		if (alu32)
14140 			scalar32_min_max_lsh(dst_reg, &src_reg);
14141 		else
14142 			scalar_min_max_lsh(dst_reg, &src_reg);
14143 		break;
14144 	case BPF_RSH:
14145 		if (alu32)
14146 			scalar32_min_max_rsh(dst_reg, &src_reg);
14147 		else
14148 			scalar_min_max_rsh(dst_reg, &src_reg);
14149 		break;
14150 	case BPF_ARSH:
14151 		if (alu32)
14152 			scalar32_min_max_arsh(dst_reg, &src_reg);
14153 		else
14154 			scalar_min_max_arsh(dst_reg, &src_reg);
14155 		break;
14156 	default:
14157 		break;
14158 	}
14159 
14160 	/* ALU32 ops are zero extended into 64bit register */
14161 	if (alu32)
14162 		zext_32_to_64(dst_reg);
14163 	reg_bounds_sync(dst_reg);
14164 	return 0;
14165 }
14166 
14167 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14168  * and var_off.
14169  */
14170 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14171 				   struct bpf_insn *insn)
14172 {
14173 	struct bpf_verifier_state *vstate = env->cur_state;
14174 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14175 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14176 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14177 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14178 	u8 opcode = BPF_OP(insn->code);
14179 	int err;
14180 
14181 	dst_reg = &regs[insn->dst_reg];
14182 	src_reg = NULL;
14183 
14184 	if (dst_reg->type == PTR_TO_ARENA) {
14185 		struct bpf_insn_aux_data *aux = cur_aux(env);
14186 
14187 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14188 			/*
14189 			 * 32-bit operations zero upper bits automatically.
14190 			 * 64-bit operations need to be converted to 32.
14191 			 */
14192 			aux->needs_zext = true;
14193 
14194 		/* Any arithmetic operations are allowed on arena pointers */
14195 		return 0;
14196 	}
14197 
14198 	if (dst_reg->type != SCALAR_VALUE)
14199 		ptr_reg = dst_reg;
14200 
14201 	if (BPF_SRC(insn->code) == BPF_X) {
14202 		src_reg = &regs[insn->src_reg];
14203 		if (src_reg->type != SCALAR_VALUE) {
14204 			if (dst_reg->type != SCALAR_VALUE) {
14205 				/* Combining two pointers by any ALU op yields
14206 				 * an arbitrary scalar. Disallow all math except
14207 				 * pointer subtraction
14208 				 */
14209 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14210 					mark_reg_unknown(env, regs, insn->dst_reg);
14211 					return 0;
14212 				}
14213 				verbose(env, "R%d pointer %s pointer prohibited\n",
14214 					insn->dst_reg,
14215 					bpf_alu_string[opcode >> 4]);
14216 				return -EACCES;
14217 			} else {
14218 				/* scalar += pointer
14219 				 * This is legal, but we have to reverse our
14220 				 * src/dest handling in computing the range
14221 				 */
14222 				err = mark_chain_precision(env, insn->dst_reg);
14223 				if (err)
14224 					return err;
14225 				return adjust_ptr_min_max_vals(env, insn,
14226 							       src_reg, dst_reg);
14227 			}
14228 		} else if (ptr_reg) {
14229 			/* pointer += scalar */
14230 			err = mark_chain_precision(env, insn->src_reg);
14231 			if (err)
14232 				return err;
14233 			return adjust_ptr_min_max_vals(env, insn,
14234 						       dst_reg, src_reg);
14235 		} else if (dst_reg->precise) {
14236 			/* if dst_reg is precise, src_reg should be precise as well */
14237 			err = mark_chain_precision(env, insn->src_reg);
14238 			if (err)
14239 				return err;
14240 		}
14241 	} else {
14242 		/* Pretend the src is a reg with a known value, since we only
14243 		 * need to be able to read from this state.
14244 		 */
14245 		off_reg.type = SCALAR_VALUE;
14246 		__mark_reg_known(&off_reg, insn->imm);
14247 		src_reg = &off_reg;
14248 		if (ptr_reg) /* pointer += K */
14249 			return adjust_ptr_min_max_vals(env, insn,
14250 						       ptr_reg, src_reg);
14251 	}
14252 
14253 	/* Got here implies adding two SCALAR_VALUEs */
14254 	if (WARN_ON_ONCE(ptr_reg)) {
14255 		print_verifier_state(env, state, true);
14256 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14257 		return -EINVAL;
14258 	}
14259 	if (WARN_ON(!src_reg)) {
14260 		print_verifier_state(env, state, true);
14261 		verbose(env, "verifier internal error: no src_reg\n");
14262 		return -EINVAL;
14263 	}
14264 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14265 	if (err)
14266 		return err;
14267 	/*
14268 	 * Compilers can generate the code
14269 	 * r1 = r2
14270 	 * r1 += 0x1
14271 	 * if r2 < 1000 goto ...
14272 	 * use r1 in memory access
14273 	 * So for 64-bit alu remember constant delta between r2 and r1 and
14274 	 * update r1 after 'if' condition.
14275 	 */
14276 	if (env->bpf_capable &&
14277 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
14278 	    dst_reg->id && is_reg_const(src_reg, false)) {
14279 		u64 val = reg_const_value(src_reg, false);
14280 
14281 		if ((dst_reg->id & BPF_ADD_CONST) ||
14282 		    /* prevent overflow in sync_linked_regs() later */
14283 		    val > (u32)S32_MAX) {
14284 			/*
14285 			 * If the register already went through rX += val
14286 			 * we cannot accumulate another val into rx->off.
14287 			 */
14288 			dst_reg->off = 0;
14289 			dst_reg->id = 0;
14290 		} else {
14291 			dst_reg->id |= BPF_ADD_CONST;
14292 			dst_reg->off = val;
14293 		}
14294 	} else {
14295 		/*
14296 		 * Make sure ID is cleared otherwise dst_reg min/max could be
14297 		 * incorrectly propagated into other registers by sync_linked_regs()
14298 		 */
14299 		dst_reg->id = 0;
14300 	}
14301 	return 0;
14302 }
14303 
14304 /* check validity of 32-bit and 64-bit arithmetic operations */
14305 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14306 {
14307 	struct bpf_reg_state *regs = cur_regs(env);
14308 	u8 opcode = BPF_OP(insn->code);
14309 	int err;
14310 
14311 	if (opcode == BPF_END || opcode == BPF_NEG) {
14312 		if (opcode == BPF_NEG) {
14313 			if (BPF_SRC(insn->code) != BPF_K ||
14314 			    insn->src_reg != BPF_REG_0 ||
14315 			    insn->off != 0 || insn->imm != 0) {
14316 				verbose(env, "BPF_NEG uses reserved fields\n");
14317 				return -EINVAL;
14318 			}
14319 		} else {
14320 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14321 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14322 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
14323 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
14324 				verbose(env, "BPF_END uses reserved fields\n");
14325 				return -EINVAL;
14326 			}
14327 		}
14328 
14329 		/* check src operand */
14330 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14331 		if (err)
14332 			return err;
14333 
14334 		if (is_pointer_value(env, insn->dst_reg)) {
14335 			verbose(env, "R%d pointer arithmetic prohibited\n",
14336 				insn->dst_reg);
14337 			return -EACCES;
14338 		}
14339 
14340 		/* check dest operand */
14341 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14342 		if (err)
14343 			return err;
14344 
14345 	} else if (opcode == BPF_MOV) {
14346 
14347 		if (BPF_SRC(insn->code) == BPF_X) {
14348 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14349 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14350 				    insn->imm) {
14351 					verbose(env, "BPF_MOV uses reserved fields\n");
14352 					return -EINVAL;
14353 				}
14354 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14355 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14356 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14357 					return -EINVAL;
14358 				}
14359 				if (!env->prog->aux->arena) {
14360 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14361 					return -EINVAL;
14362 				}
14363 			} else {
14364 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14365 				     insn->off != 32) || insn->imm) {
14366 					verbose(env, "BPF_MOV uses reserved fields\n");
14367 					return -EINVAL;
14368 				}
14369 			}
14370 
14371 			/* check src operand */
14372 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14373 			if (err)
14374 				return err;
14375 		} else {
14376 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14377 				verbose(env, "BPF_MOV uses reserved fields\n");
14378 				return -EINVAL;
14379 			}
14380 		}
14381 
14382 		/* check dest operand, mark as required later */
14383 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14384 		if (err)
14385 			return err;
14386 
14387 		if (BPF_SRC(insn->code) == BPF_X) {
14388 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14389 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14390 
14391 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14392 				if (insn->imm) {
14393 					/* off == BPF_ADDR_SPACE_CAST */
14394 					mark_reg_unknown(env, regs, insn->dst_reg);
14395 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14396 						dst_reg->type = PTR_TO_ARENA;
14397 						/* PTR_TO_ARENA is 32-bit */
14398 						dst_reg->subreg_def = env->insn_idx + 1;
14399 					}
14400 				} else if (insn->off == 0) {
14401 					/* case: R1 = R2
14402 					 * copy register state to dest reg
14403 					 */
14404 					assign_scalar_id_before_mov(env, src_reg);
14405 					copy_register_state(dst_reg, src_reg);
14406 					dst_reg->live |= REG_LIVE_WRITTEN;
14407 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14408 				} else {
14409 					/* case: R1 = (s8, s16 s32)R2 */
14410 					if (is_pointer_value(env, insn->src_reg)) {
14411 						verbose(env,
14412 							"R%d sign-extension part of pointer\n",
14413 							insn->src_reg);
14414 						return -EACCES;
14415 					} else if (src_reg->type == SCALAR_VALUE) {
14416 						bool no_sext;
14417 
14418 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14419 						if (no_sext)
14420 							assign_scalar_id_before_mov(env, src_reg);
14421 						copy_register_state(dst_reg, src_reg);
14422 						if (!no_sext)
14423 							dst_reg->id = 0;
14424 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14425 						dst_reg->live |= REG_LIVE_WRITTEN;
14426 						dst_reg->subreg_def = DEF_NOT_SUBREG;
14427 					} else {
14428 						mark_reg_unknown(env, regs, insn->dst_reg);
14429 					}
14430 				}
14431 			} else {
14432 				/* R1 = (u32) R2 */
14433 				if (is_pointer_value(env, insn->src_reg)) {
14434 					verbose(env,
14435 						"R%d partial copy of pointer\n",
14436 						insn->src_reg);
14437 					return -EACCES;
14438 				} else if (src_reg->type == SCALAR_VALUE) {
14439 					if (insn->off == 0) {
14440 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14441 
14442 						if (is_src_reg_u32)
14443 							assign_scalar_id_before_mov(env, src_reg);
14444 						copy_register_state(dst_reg, src_reg);
14445 						/* Make sure ID is cleared if src_reg is not in u32
14446 						 * range otherwise dst_reg min/max could be incorrectly
14447 						 * propagated into src_reg by sync_linked_regs()
14448 						 */
14449 						if (!is_src_reg_u32)
14450 							dst_reg->id = 0;
14451 						dst_reg->live |= REG_LIVE_WRITTEN;
14452 						dst_reg->subreg_def = env->insn_idx + 1;
14453 					} else {
14454 						/* case: W1 = (s8, s16)W2 */
14455 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14456 
14457 						if (no_sext)
14458 							assign_scalar_id_before_mov(env, src_reg);
14459 						copy_register_state(dst_reg, src_reg);
14460 						if (!no_sext)
14461 							dst_reg->id = 0;
14462 						dst_reg->live |= REG_LIVE_WRITTEN;
14463 						dst_reg->subreg_def = env->insn_idx + 1;
14464 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14465 					}
14466 				} else {
14467 					mark_reg_unknown(env, regs,
14468 							 insn->dst_reg);
14469 				}
14470 				zext_32_to_64(dst_reg);
14471 				reg_bounds_sync(dst_reg);
14472 			}
14473 		} else {
14474 			/* case: R = imm
14475 			 * remember the value we stored into this reg
14476 			 */
14477 			/* clear any state __mark_reg_known doesn't set */
14478 			mark_reg_unknown(env, regs, insn->dst_reg);
14479 			regs[insn->dst_reg].type = SCALAR_VALUE;
14480 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14481 				__mark_reg_known(regs + insn->dst_reg,
14482 						 insn->imm);
14483 			} else {
14484 				__mark_reg_known(regs + insn->dst_reg,
14485 						 (u32)insn->imm);
14486 			}
14487 		}
14488 
14489 	} else if (opcode > BPF_END) {
14490 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14491 		return -EINVAL;
14492 
14493 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14494 
14495 		if (BPF_SRC(insn->code) == BPF_X) {
14496 			if (insn->imm != 0 || insn->off > 1 ||
14497 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14498 				verbose(env, "BPF_ALU uses reserved fields\n");
14499 				return -EINVAL;
14500 			}
14501 			/* check src1 operand */
14502 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14503 			if (err)
14504 				return err;
14505 		} else {
14506 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14507 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14508 				verbose(env, "BPF_ALU uses reserved fields\n");
14509 				return -EINVAL;
14510 			}
14511 		}
14512 
14513 		/* check src2 operand */
14514 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14515 		if (err)
14516 			return err;
14517 
14518 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14519 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14520 			verbose(env, "div by zero\n");
14521 			return -EINVAL;
14522 		}
14523 
14524 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14525 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14526 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14527 
14528 			if (insn->imm < 0 || insn->imm >= size) {
14529 				verbose(env, "invalid shift %d\n", insn->imm);
14530 				return -EINVAL;
14531 			}
14532 		}
14533 
14534 		/* check dest operand */
14535 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14536 		err = err ?: adjust_reg_min_max_vals(env, insn);
14537 		if (err)
14538 			return err;
14539 	}
14540 
14541 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14542 }
14543 
14544 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14545 				   struct bpf_reg_state *dst_reg,
14546 				   enum bpf_reg_type type,
14547 				   bool range_right_open)
14548 {
14549 	struct bpf_func_state *state;
14550 	struct bpf_reg_state *reg;
14551 	int new_range;
14552 
14553 	if (dst_reg->off < 0 ||
14554 	    (dst_reg->off == 0 && range_right_open))
14555 		/* This doesn't give us any range */
14556 		return;
14557 
14558 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14559 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14560 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14561 		 * than pkt_end, but that's because it's also less than pkt.
14562 		 */
14563 		return;
14564 
14565 	new_range = dst_reg->off;
14566 	if (range_right_open)
14567 		new_range++;
14568 
14569 	/* Examples for register markings:
14570 	 *
14571 	 * pkt_data in dst register:
14572 	 *
14573 	 *   r2 = r3;
14574 	 *   r2 += 8;
14575 	 *   if (r2 > pkt_end) goto <handle exception>
14576 	 *   <access okay>
14577 	 *
14578 	 *   r2 = r3;
14579 	 *   r2 += 8;
14580 	 *   if (r2 < pkt_end) goto <access okay>
14581 	 *   <handle exception>
14582 	 *
14583 	 *   Where:
14584 	 *     r2 == dst_reg, pkt_end == src_reg
14585 	 *     r2=pkt(id=n,off=8,r=0)
14586 	 *     r3=pkt(id=n,off=0,r=0)
14587 	 *
14588 	 * pkt_data in src register:
14589 	 *
14590 	 *   r2 = r3;
14591 	 *   r2 += 8;
14592 	 *   if (pkt_end >= r2) goto <access okay>
14593 	 *   <handle exception>
14594 	 *
14595 	 *   r2 = r3;
14596 	 *   r2 += 8;
14597 	 *   if (pkt_end <= r2) goto <handle exception>
14598 	 *   <access okay>
14599 	 *
14600 	 *   Where:
14601 	 *     pkt_end == dst_reg, r2 == src_reg
14602 	 *     r2=pkt(id=n,off=8,r=0)
14603 	 *     r3=pkt(id=n,off=0,r=0)
14604 	 *
14605 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14606 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14607 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14608 	 * the check.
14609 	 */
14610 
14611 	/* If our ids match, then we must have the same max_value.  And we
14612 	 * don't care about the other reg's fixed offset, since if it's too big
14613 	 * the range won't allow anything.
14614 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14615 	 */
14616 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14617 		if (reg->type == type && reg->id == dst_reg->id)
14618 			/* keep the maximum range already checked */
14619 			reg->range = max(reg->range, new_range);
14620 	}));
14621 }
14622 
14623 /*
14624  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14625  */
14626 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14627 				  u8 opcode, bool is_jmp32)
14628 {
14629 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14630 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14631 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14632 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14633 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14634 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14635 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14636 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14637 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14638 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14639 
14640 	switch (opcode) {
14641 	case BPF_JEQ:
14642 		/* constants, umin/umax and smin/smax checks would be
14643 		 * redundant in this case because they all should match
14644 		 */
14645 		if (tnum_is_const(t1) && tnum_is_const(t2))
14646 			return t1.value == t2.value;
14647 		/* non-overlapping ranges */
14648 		if (umin1 > umax2 || umax1 < umin2)
14649 			return 0;
14650 		if (smin1 > smax2 || smax1 < smin2)
14651 			return 0;
14652 		if (!is_jmp32) {
14653 			/* if 64-bit ranges are inconclusive, see if we can
14654 			 * utilize 32-bit subrange knowledge to eliminate
14655 			 * branches that can't be taken a priori
14656 			 */
14657 			if (reg1->u32_min_value > reg2->u32_max_value ||
14658 			    reg1->u32_max_value < reg2->u32_min_value)
14659 				return 0;
14660 			if (reg1->s32_min_value > reg2->s32_max_value ||
14661 			    reg1->s32_max_value < reg2->s32_min_value)
14662 				return 0;
14663 		}
14664 		break;
14665 	case BPF_JNE:
14666 		/* constants, umin/umax and smin/smax checks would be
14667 		 * redundant in this case because they all should match
14668 		 */
14669 		if (tnum_is_const(t1) && tnum_is_const(t2))
14670 			return t1.value != t2.value;
14671 		/* non-overlapping ranges */
14672 		if (umin1 > umax2 || umax1 < umin2)
14673 			return 1;
14674 		if (smin1 > smax2 || smax1 < smin2)
14675 			return 1;
14676 		if (!is_jmp32) {
14677 			/* if 64-bit ranges are inconclusive, see if we can
14678 			 * utilize 32-bit subrange knowledge to eliminate
14679 			 * branches that can't be taken a priori
14680 			 */
14681 			if (reg1->u32_min_value > reg2->u32_max_value ||
14682 			    reg1->u32_max_value < reg2->u32_min_value)
14683 				return 1;
14684 			if (reg1->s32_min_value > reg2->s32_max_value ||
14685 			    reg1->s32_max_value < reg2->s32_min_value)
14686 				return 1;
14687 		}
14688 		break;
14689 	case BPF_JSET:
14690 		if (!is_reg_const(reg2, is_jmp32)) {
14691 			swap(reg1, reg2);
14692 			swap(t1, t2);
14693 		}
14694 		if (!is_reg_const(reg2, is_jmp32))
14695 			return -1;
14696 		if ((~t1.mask & t1.value) & t2.value)
14697 			return 1;
14698 		if (!((t1.mask | t1.value) & t2.value))
14699 			return 0;
14700 		break;
14701 	case BPF_JGT:
14702 		if (umin1 > umax2)
14703 			return 1;
14704 		else if (umax1 <= umin2)
14705 			return 0;
14706 		break;
14707 	case BPF_JSGT:
14708 		if (smin1 > smax2)
14709 			return 1;
14710 		else if (smax1 <= smin2)
14711 			return 0;
14712 		break;
14713 	case BPF_JLT:
14714 		if (umax1 < umin2)
14715 			return 1;
14716 		else if (umin1 >= umax2)
14717 			return 0;
14718 		break;
14719 	case BPF_JSLT:
14720 		if (smax1 < smin2)
14721 			return 1;
14722 		else if (smin1 >= smax2)
14723 			return 0;
14724 		break;
14725 	case BPF_JGE:
14726 		if (umin1 >= umax2)
14727 			return 1;
14728 		else if (umax1 < umin2)
14729 			return 0;
14730 		break;
14731 	case BPF_JSGE:
14732 		if (smin1 >= smax2)
14733 			return 1;
14734 		else if (smax1 < smin2)
14735 			return 0;
14736 		break;
14737 	case BPF_JLE:
14738 		if (umax1 <= umin2)
14739 			return 1;
14740 		else if (umin1 > umax2)
14741 			return 0;
14742 		break;
14743 	case BPF_JSLE:
14744 		if (smax1 <= smin2)
14745 			return 1;
14746 		else if (smin1 > smax2)
14747 			return 0;
14748 		break;
14749 	}
14750 
14751 	return -1;
14752 }
14753 
14754 static int flip_opcode(u32 opcode)
14755 {
14756 	/* How can we transform "a <op> b" into "b <op> a"? */
14757 	static const u8 opcode_flip[16] = {
14758 		/* these stay the same */
14759 		[BPF_JEQ  >> 4] = BPF_JEQ,
14760 		[BPF_JNE  >> 4] = BPF_JNE,
14761 		[BPF_JSET >> 4] = BPF_JSET,
14762 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14763 		[BPF_JGE  >> 4] = BPF_JLE,
14764 		[BPF_JGT  >> 4] = BPF_JLT,
14765 		[BPF_JLE  >> 4] = BPF_JGE,
14766 		[BPF_JLT  >> 4] = BPF_JGT,
14767 		[BPF_JSGE >> 4] = BPF_JSLE,
14768 		[BPF_JSGT >> 4] = BPF_JSLT,
14769 		[BPF_JSLE >> 4] = BPF_JSGE,
14770 		[BPF_JSLT >> 4] = BPF_JSGT
14771 	};
14772 	return opcode_flip[opcode >> 4];
14773 }
14774 
14775 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14776 				   struct bpf_reg_state *src_reg,
14777 				   u8 opcode)
14778 {
14779 	struct bpf_reg_state *pkt;
14780 
14781 	if (src_reg->type == PTR_TO_PACKET_END) {
14782 		pkt = dst_reg;
14783 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14784 		pkt = src_reg;
14785 		opcode = flip_opcode(opcode);
14786 	} else {
14787 		return -1;
14788 	}
14789 
14790 	if (pkt->range >= 0)
14791 		return -1;
14792 
14793 	switch (opcode) {
14794 	case BPF_JLE:
14795 		/* pkt <= pkt_end */
14796 		fallthrough;
14797 	case BPF_JGT:
14798 		/* pkt > pkt_end */
14799 		if (pkt->range == BEYOND_PKT_END)
14800 			/* pkt has at last one extra byte beyond pkt_end */
14801 			return opcode == BPF_JGT;
14802 		break;
14803 	case BPF_JLT:
14804 		/* pkt < pkt_end */
14805 		fallthrough;
14806 	case BPF_JGE:
14807 		/* pkt >= pkt_end */
14808 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14809 			return opcode == BPF_JGE;
14810 		break;
14811 	}
14812 	return -1;
14813 }
14814 
14815 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14816  * and return:
14817  *  1 - branch will be taken and "goto target" will be executed
14818  *  0 - branch will not be taken and fall-through to next insn
14819  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14820  *      range [0,10]
14821  */
14822 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14823 			   u8 opcode, bool is_jmp32)
14824 {
14825 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14826 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14827 
14828 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14829 		u64 val;
14830 
14831 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14832 		if (!is_reg_const(reg2, is_jmp32)) {
14833 			opcode = flip_opcode(opcode);
14834 			swap(reg1, reg2);
14835 		}
14836 		/* and ensure that reg2 is a constant */
14837 		if (!is_reg_const(reg2, is_jmp32))
14838 			return -1;
14839 
14840 		if (!reg_not_null(reg1))
14841 			return -1;
14842 
14843 		/* If pointer is valid tests against zero will fail so we can
14844 		 * use this to direct branch taken.
14845 		 */
14846 		val = reg_const_value(reg2, is_jmp32);
14847 		if (val != 0)
14848 			return -1;
14849 
14850 		switch (opcode) {
14851 		case BPF_JEQ:
14852 			return 0;
14853 		case BPF_JNE:
14854 			return 1;
14855 		default:
14856 			return -1;
14857 		}
14858 	}
14859 
14860 	/* now deal with two scalars, but not necessarily constants */
14861 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14862 }
14863 
14864 /* Opcode that corresponds to a *false* branch condition.
14865  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14866  */
14867 static u8 rev_opcode(u8 opcode)
14868 {
14869 	switch (opcode) {
14870 	case BPF_JEQ:		return BPF_JNE;
14871 	case BPF_JNE:		return BPF_JEQ;
14872 	/* JSET doesn't have it's reverse opcode in BPF, so add
14873 	 * BPF_X flag to denote the reverse of that operation
14874 	 */
14875 	case BPF_JSET:		return BPF_JSET | BPF_X;
14876 	case BPF_JSET | BPF_X:	return BPF_JSET;
14877 	case BPF_JGE:		return BPF_JLT;
14878 	case BPF_JGT:		return BPF_JLE;
14879 	case BPF_JLE:		return BPF_JGT;
14880 	case BPF_JLT:		return BPF_JGE;
14881 	case BPF_JSGE:		return BPF_JSLT;
14882 	case BPF_JSGT:		return BPF_JSLE;
14883 	case BPF_JSLE:		return BPF_JSGT;
14884 	case BPF_JSLT:		return BPF_JSGE;
14885 	default:		return 0;
14886 	}
14887 }
14888 
14889 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14890 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14891 				u8 opcode, bool is_jmp32)
14892 {
14893 	struct tnum t;
14894 	u64 val;
14895 
14896 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
14897 	switch (opcode) {
14898 	case BPF_JGE:
14899 	case BPF_JGT:
14900 	case BPF_JSGE:
14901 	case BPF_JSGT:
14902 		opcode = flip_opcode(opcode);
14903 		swap(reg1, reg2);
14904 		break;
14905 	default:
14906 		break;
14907 	}
14908 
14909 	switch (opcode) {
14910 	case BPF_JEQ:
14911 		if (is_jmp32) {
14912 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14913 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14914 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14915 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14916 			reg2->u32_min_value = reg1->u32_min_value;
14917 			reg2->u32_max_value = reg1->u32_max_value;
14918 			reg2->s32_min_value = reg1->s32_min_value;
14919 			reg2->s32_max_value = reg1->s32_max_value;
14920 
14921 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14922 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14923 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14924 		} else {
14925 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14926 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14927 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14928 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14929 			reg2->umin_value = reg1->umin_value;
14930 			reg2->umax_value = reg1->umax_value;
14931 			reg2->smin_value = reg1->smin_value;
14932 			reg2->smax_value = reg1->smax_value;
14933 
14934 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14935 			reg2->var_off = reg1->var_off;
14936 		}
14937 		break;
14938 	case BPF_JNE:
14939 		if (!is_reg_const(reg2, is_jmp32))
14940 			swap(reg1, reg2);
14941 		if (!is_reg_const(reg2, is_jmp32))
14942 			break;
14943 
14944 		/* try to recompute the bound of reg1 if reg2 is a const and
14945 		 * is exactly the edge of reg1.
14946 		 */
14947 		val = reg_const_value(reg2, is_jmp32);
14948 		if (is_jmp32) {
14949 			/* u32_min_value is not equal to 0xffffffff at this point,
14950 			 * because otherwise u32_max_value is 0xffffffff as well,
14951 			 * in such a case both reg1 and reg2 would be constants,
14952 			 * jump would be predicted and reg_set_min_max() won't
14953 			 * be called.
14954 			 *
14955 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14956 			 * below.
14957 			 */
14958 			if (reg1->u32_min_value == (u32)val)
14959 				reg1->u32_min_value++;
14960 			if (reg1->u32_max_value == (u32)val)
14961 				reg1->u32_max_value--;
14962 			if (reg1->s32_min_value == (s32)val)
14963 				reg1->s32_min_value++;
14964 			if (reg1->s32_max_value == (s32)val)
14965 				reg1->s32_max_value--;
14966 		} else {
14967 			if (reg1->umin_value == (u64)val)
14968 				reg1->umin_value++;
14969 			if (reg1->umax_value == (u64)val)
14970 				reg1->umax_value--;
14971 			if (reg1->smin_value == (s64)val)
14972 				reg1->smin_value++;
14973 			if (reg1->smax_value == (s64)val)
14974 				reg1->smax_value--;
14975 		}
14976 		break;
14977 	case BPF_JSET:
14978 		if (!is_reg_const(reg2, is_jmp32))
14979 			swap(reg1, reg2);
14980 		if (!is_reg_const(reg2, is_jmp32))
14981 			break;
14982 		val = reg_const_value(reg2, is_jmp32);
14983 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14984 		 * requires single bit to learn something useful. E.g., if we
14985 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14986 		 * are actually set? We can learn something definite only if
14987 		 * it's a single-bit value to begin with.
14988 		 *
14989 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14990 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14991 		 * bit 1 is set, which we can readily use in adjustments.
14992 		 */
14993 		if (!is_power_of_2(val))
14994 			break;
14995 		if (is_jmp32) {
14996 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14997 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14998 		} else {
14999 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
15000 		}
15001 		break;
15002 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
15003 		if (!is_reg_const(reg2, is_jmp32))
15004 			swap(reg1, reg2);
15005 		if (!is_reg_const(reg2, is_jmp32))
15006 			break;
15007 		val = reg_const_value(reg2, is_jmp32);
15008 		if (is_jmp32) {
15009 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
15010 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15011 		} else {
15012 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
15013 		}
15014 		break;
15015 	case BPF_JLE:
15016 		if (is_jmp32) {
15017 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15018 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15019 		} else {
15020 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15021 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
15022 		}
15023 		break;
15024 	case BPF_JLT:
15025 		if (is_jmp32) {
15026 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
15027 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
15028 		} else {
15029 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
15030 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
15031 		}
15032 		break;
15033 	case BPF_JSLE:
15034 		if (is_jmp32) {
15035 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15036 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15037 		} else {
15038 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15039 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
15040 		}
15041 		break;
15042 	case BPF_JSLT:
15043 		if (is_jmp32) {
15044 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
15045 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
15046 		} else {
15047 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
15048 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
15049 		}
15050 		break;
15051 	default:
15052 		return;
15053 	}
15054 }
15055 
15056 /* Adjusts the register min/max values in the case that the dst_reg and
15057  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
15058  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
15059  * Technically we can do similar adjustments for pointers to the same object,
15060  * but we don't support that right now.
15061  */
15062 static int reg_set_min_max(struct bpf_verifier_env *env,
15063 			   struct bpf_reg_state *true_reg1,
15064 			   struct bpf_reg_state *true_reg2,
15065 			   struct bpf_reg_state *false_reg1,
15066 			   struct bpf_reg_state *false_reg2,
15067 			   u8 opcode, bool is_jmp32)
15068 {
15069 	int err;
15070 
15071 	/* If either register is a pointer, we can't learn anything about its
15072 	 * variable offset from the compare (unless they were a pointer into
15073 	 * the same object, but we don't bother with that).
15074 	 */
15075 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
15076 		return 0;
15077 
15078 	/* fallthrough (FALSE) branch */
15079 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
15080 	reg_bounds_sync(false_reg1);
15081 	reg_bounds_sync(false_reg2);
15082 
15083 	/* jump (TRUE) branch */
15084 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
15085 	reg_bounds_sync(true_reg1);
15086 	reg_bounds_sync(true_reg2);
15087 
15088 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
15089 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
15090 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
15091 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
15092 	return err;
15093 }
15094 
15095 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
15096 				 struct bpf_reg_state *reg, u32 id,
15097 				 bool is_null)
15098 {
15099 	if (type_may_be_null(reg->type) && reg->id == id &&
15100 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
15101 		/* Old offset (both fixed and variable parts) should have been
15102 		 * known-zero, because we don't allow pointer arithmetic on
15103 		 * pointers that might be NULL. If we see this happening, don't
15104 		 * convert the register.
15105 		 *
15106 		 * But in some cases, some helpers that return local kptrs
15107 		 * advance offset for the returned pointer. In those cases, it
15108 		 * is fine to expect to see reg->off.
15109 		 */
15110 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
15111 			return;
15112 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
15113 		    WARN_ON_ONCE(reg->off))
15114 			return;
15115 
15116 		if (is_null) {
15117 			reg->type = SCALAR_VALUE;
15118 			/* We don't need id and ref_obj_id from this point
15119 			 * onwards anymore, thus we should better reset it,
15120 			 * so that state pruning has chances to take effect.
15121 			 */
15122 			reg->id = 0;
15123 			reg->ref_obj_id = 0;
15124 
15125 			return;
15126 		}
15127 
15128 		mark_ptr_not_null_reg(reg);
15129 
15130 		if (!reg_may_point_to_spin_lock(reg)) {
15131 			/* For not-NULL ptr, reg->ref_obj_id will be reset
15132 			 * in release_reference().
15133 			 *
15134 			 * reg->id is still used by spin_lock ptr. Other
15135 			 * than spin_lock ptr type, reg->id can be reset.
15136 			 */
15137 			reg->id = 0;
15138 		}
15139 	}
15140 }
15141 
15142 /* The logic is similar to find_good_pkt_pointers(), both could eventually
15143  * be folded together at some point.
15144  */
15145 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
15146 				  bool is_null)
15147 {
15148 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15149 	struct bpf_reg_state *regs = state->regs, *reg;
15150 	u32 ref_obj_id = regs[regno].ref_obj_id;
15151 	u32 id = regs[regno].id;
15152 
15153 	if (ref_obj_id && ref_obj_id == id && is_null)
15154 		/* regs[regno] is in the " == NULL" branch.
15155 		 * No one could have freed the reference state before
15156 		 * doing the NULL check.
15157 		 */
15158 		WARN_ON_ONCE(release_reference_state(state, id));
15159 
15160 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15161 		mark_ptr_or_null_reg(state, reg, id, is_null);
15162 	}));
15163 }
15164 
15165 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
15166 				   struct bpf_reg_state *dst_reg,
15167 				   struct bpf_reg_state *src_reg,
15168 				   struct bpf_verifier_state *this_branch,
15169 				   struct bpf_verifier_state *other_branch)
15170 {
15171 	if (BPF_SRC(insn->code) != BPF_X)
15172 		return false;
15173 
15174 	/* Pointers are always 64-bit. */
15175 	if (BPF_CLASS(insn->code) == BPF_JMP32)
15176 		return false;
15177 
15178 	switch (BPF_OP(insn->code)) {
15179 	case BPF_JGT:
15180 		if ((dst_reg->type == PTR_TO_PACKET &&
15181 		     src_reg->type == PTR_TO_PACKET_END) ||
15182 		    (dst_reg->type == PTR_TO_PACKET_META &&
15183 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15184 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15185 			find_good_pkt_pointers(this_branch, dst_reg,
15186 					       dst_reg->type, false);
15187 			mark_pkt_end(other_branch, insn->dst_reg, true);
15188 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15189 			    src_reg->type == PTR_TO_PACKET) ||
15190 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15191 			    src_reg->type == PTR_TO_PACKET_META)) {
15192 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15193 			find_good_pkt_pointers(other_branch, src_reg,
15194 					       src_reg->type, true);
15195 			mark_pkt_end(this_branch, insn->src_reg, false);
15196 		} else {
15197 			return false;
15198 		}
15199 		break;
15200 	case BPF_JLT:
15201 		if ((dst_reg->type == PTR_TO_PACKET &&
15202 		     src_reg->type == PTR_TO_PACKET_END) ||
15203 		    (dst_reg->type == PTR_TO_PACKET_META &&
15204 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15205 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15206 			find_good_pkt_pointers(other_branch, dst_reg,
15207 					       dst_reg->type, true);
15208 			mark_pkt_end(this_branch, insn->dst_reg, false);
15209 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15210 			    src_reg->type == PTR_TO_PACKET) ||
15211 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15212 			    src_reg->type == PTR_TO_PACKET_META)) {
15213 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15214 			find_good_pkt_pointers(this_branch, src_reg,
15215 					       src_reg->type, false);
15216 			mark_pkt_end(other_branch, insn->src_reg, true);
15217 		} else {
15218 			return false;
15219 		}
15220 		break;
15221 	case BPF_JGE:
15222 		if ((dst_reg->type == PTR_TO_PACKET &&
15223 		     src_reg->type == PTR_TO_PACKET_END) ||
15224 		    (dst_reg->type == PTR_TO_PACKET_META &&
15225 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15226 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15227 			find_good_pkt_pointers(this_branch, dst_reg,
15228 					       dst_reg->type, true);
15229 			mark_pkt_end(other_branch, insn->dst_reg, false);
15230 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15231 			    src_reg->type == PTR_TO_PACKET) ||
15232 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15233 			    src_reg->type == PTR_TO_PACKET_META)) {
15234 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15235 			find_good_pkt_pointers(other_branch, src_reg,
15236 					       src_reg->type, false);
15237 			mark_pkt_end(this_branch, insn->src_reg, true);
15238 		} else {
15239 			return false;
15240 		}
15241 		break;
15242 	case BPF_JLE:
15243 		if ((dst_reg->type == PTR_TO_PACKET &&
15244 		     src_reg->type == PTR_TO_PACKET_END) ||
15245 		    (dst_reg->type == PTR_TO_PACKET_META &&
15246 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15247 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15248 			find_good_pkt_pointers(other_branch, dst_reg,
15249 					       dst_reg->type, false);
15250 			mark_pkt_end(this_branch, insn->dst_reg, true);
15251 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15252 			    src_reg->type == PTR_TO_PACKET) ||
15253 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15254 			    src_reg->type == PTR_TO_PACKET_META)) {
15255 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15256 			find_good_pkt_pointers(this_branch, src_reg,
15257 					       src_reg->type, true);
15258 			mark_pkt_end(other_branch, insn->src_reg, false);
15259 		} else {
15260 			return false;
15261 		}
15262 		break;
15263 	default:
15264 		return false;
15265 	}
15266 
15267 	return true;
15268 }
15269 
15270 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
15271 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
15272 {
15273 	struct linked_reg *e;
15274 
15275 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
15276 		return;
15277 
15278 	e = linked_regs_push(reg_set);
15279 	if (e) {
15280 		e->frameno = frameno;
15281 		e->is_reg = is_reg;
15282 		e->regno = spi_or_reg;
15283 	} else {
15284 		reg->id = 0;
15285 	}
15286 }
15287 
15288 /* For all R being scalar registers or spilled scalar registers
15289  * in verifier state, save R in linked_regs if R->id == id.
15290  * If there are too many Rs sharing same id, reset id for leftover Rs.
15291  */
15292 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
15293 				struct linked_regs *linked_regs)
15294 {
15295 	struct bpf_func_state *func;
15296 	struct bpf_reg_state *reg;
15297 	int i, j;
15298 
15299 	id = id & ~BPF_ADD_CONST;
15300 	for (i = vstate->curframe; i >= 0; i--) {
15301 		func = vstate->frame[i];
15302 		for (j = 0; j < BPF_REG_FP; j++) {
15303 			reg = &func->regs[j];
15304 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
15305 		}
15306 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
15307 			if (!is_spilled_reg(&func->stack[j]))
15308 				continue;
15309 			reg = &func->stack[j].spilled_ptr;
15310 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
15311 		}
15312 	}
15313 }
15314 
15315 /* For all R in linked_regs, copy known_reg range into R
15316  * if R->id == known_reg->id.
15317  */
15318 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
15319 			     struct linked_regs *linked_regs)
15320 {
15321 	struct bpf_reg_state fake_reg;
15322 	struct bpf_reg_state *reg;
15323 	struct linked_reg *e;
15324 	int i;
15325 
15326 	for (i = 0; i < linked_regs->cnt; ++i) {
15327 		e = &linked_regs->entries[i];
15328 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
15329 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
15330 		if (reg->type != SCALAR_VALUE || reg == known_reg)
15331 			continue;
15332 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15333 			continue;
15334 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15335 		    reg->off == known_reg->off) {
15336 			s32 saved_subreg_def = reg->subreg_def;
15337 
15338 			copy_register_state(reg, known_reg);
15339 			reg->subreg_def = saved_subreg_def;
15340 		} else {
15341 			s32 saved_subreg_def = reg->subreg_def;
15342 			s32 saved_off = reg->off;
15343 
15344 			fake_reg.type = SCALAR_VALUE;
15345 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
15346 
15347 			/* reg = known_reg; reg += delta */
15348 			copy_register_state(reg, known_reg);
15349 			/*
15350 			 * Must preserve off, id and add_const flag,
15351 			 * otherwise another sync_linked_regs() will be incorrect.
15352 			 */
15353 			reg->off = saved_off;
15354 			reg->subreg_def = saved_subreg_def;
15355 
15356 			scalar32_min_max_add(reg, &fake_reg);
15357 			scalar_min_max_add(reg, &fake_reg);
15358 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15359 		}
15360 	}
15361 }
15362 
15363 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15364 			     struct bpf_insn *insn, int *insn_idx)
15365 {
15366 	struct bpf_verifier_state *this_branch = env->cur_state;
15367 	struct bpf_verifier_state *other_branch;
15368 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15369 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15370 	struct bpf_reg_state *eq_branch_regs;
15371 	struct linked_regs linked_regs = {};
15372 	u8 opcode = BPF_OP(insn->code);
15373 	bool is_jmp32;
15374 	int pred = -1;
15375 	int err;
15376 
15377 	/* Only conditional jumps are expected to reach here. */
15378 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15379 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15380 		return -EINVAL;
15381 	}
15382 
15383 	if (opcode == BPF_JCOND) {
15384 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15385 		int idx = *insn_idx;
15386 
15387 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
15388 		    insn->src_reg != BPF_MAY_GOTO ||
15389 		    insn->dst_reg || insn->imm || insn->off == 0) {
15390 			verbose(env, "invalid may_goto off %d imm %d\n",
15391 				insn->off, insn->imm);
15392 			return -EINVAL;
15393 		}
15394 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15395 
15396 		/* branch out 'fallthrough' insn as a new state to explore */
15397 		queued_st = push_stack(env, idx + 1, idx, false);
15398 		if (!queued_st)
15399 			return -ENOMEM;
15400 
15401 		queued_st->may_goto_depth++;
15402 		if (prev_st)
15403 			widen_imprecise_scalars(env, prev_st, queued_st);
15404 		*insn_idx += insn->off;
15405 		return 0;
15406 	}
15407 
15408 	/* check src2 operand */
15409 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15410 	if (err)
15411 		return err;
15412 
15413 	dst_reg = &regs[insn->dst_reg];
15414 	if (BPF_SRC(insn->code) == BPF_X) {
15415 		if (insn->imm != 0) {
15416 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15417 			return -EINVAL;
15418 		}
15419 
15420 		/* check src1 operand */
15421 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15422 		if (err)
15423 			return err;
15424 
15425 		src_reg = &regs[insn->src_reg];
15426 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15427 		    is_pointer_value(env, insn->src_reg)) {
15428 			verbose(env, "R%d pointer comparison prohibited\n",
15429 				insn->src_reg);
15430 			return -EACCES;
15431 		}
15432 	} else {
15433 		if (insn->src_reg != BPF_REG_0) {
15434 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15435 			return -EINVAL;
15436 		}
15437 		src_reg = &env->fake_reg[0];
15438 		memset(src_reg, 0, sizeof(*src_reg));
15439 		src_reg->type = SCALAR_VALUE;
15440 		__mark_reg_known(src_reg, insn->imm);
15441 	}
15442 
15443 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15444 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15445 	if (pred >= 0) {
15446 		/* If we get here with a dst_reg pointer type it is because
15447 		 * above is_branch_taken() special cased the 0 comparison.
15448 		 */
15449 		if (!__is_pointer_value(false, dst_reg))
15450 			err = mark_chain_precision(env, insn->dst_reg);
15451 		if (BPF_SRC(insn->code) == BPF_X && !err &&
15452 		    !__is_pointer_value(false, src_reg))
15453 			err = mark_chain_precision(env, insn->src_reg);
15454 		if (err)
15455 			return err;
15456 	}
15457 
15458 	if (pred == 1) {
15459 		/* Only follow the goto, ignore fall-through. If needed, push
15460 		 * the fall-through branch for simulation under speculative
15461 		 * execution.
15462 		 */
15463 		if (!env->bypass_spec_v1 &&
15464 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
15465 					       *insn_idx))
15466 			return -EFAULT;
15467 		if (env->log.level & BPF_LOG_LEVEL)
15468 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15469 		*insn_idx += insn->off;
15470 		return 0;
15471 	} else if (pred == 0) {
15472 		/* Only follow the fall-through branch, since that's where the
15473 		 * program will go. If needed, push the goto branch for
15474 		 * simulation under speculative execution.
15475 		 */
15476 		if (!env->bypass_spec_v1 &&
15477 		    !sanitize_speculative_path(env, insn,
15478 					       *insn_idx + insn->off + 1,
15479 					       *insn_idx))
15480 			return -EFAULT;
15481 		if (env->log.level & BPF_LOG_LEVEL)
15482 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15483 		return 0;
15484 	}
15485 
15486 	/* Push scalar registers sharing same ID to jump history,
15487 	 * do this before creating 'other_branch', so that both
15488 	 * 'this_branch' and 'other_branch' share this history
15489 	 * if parent state is created.
15490 	 */
15491 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
15492 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
15493 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
15494 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
15495 	if (linked_regs.cnt > 1) {
15496 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
15497 		if (err)
15498 			return err;
15499 	}
15500 
15501 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15502 				  false);
15503 	if (!other_branch)
15504 		return -EFAULT;
15505 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15506 
15507 	if (BPF_SRC(insn->code) == BPF_X) {
15508 		err = reg_set_min_max(env,
15509 				      &other_branch_regs[insn->dst_reg],
15510 				      &other_branch_regs[insn->src_reg],
15511 				      dst_reg, src_reg, opcode, is_jmp32);
15512 	} else /* BPF_SRC(insn->code) == BPF_K */ {
15513 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
15514 		 * so that these are two different memory locations. The
15515 		 * src_reg is not used beyond here in context of K.
15516 		 */
15517 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
15518 		       sizeof(env->fake_reg[0]));
15519 		err = reg_set_min_max(env,
15520 				      &other_branch_regs[insn->dst_reg],
15521 				      &env->fake_reg[0],
15522 				      dst_reg, &env->fake_reg[1],
15523 				      opcode, is_jmp32);
15524 	}
15525 	if (err)
15526 		return err;
15527 
15528 	if (BPF_SRC(insn->code) == BPF_X &&
15529 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
15530 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15531 		sync_linked_regs(this_branch, src_reg, &linked_regs);
15532 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
15533 	}
15534 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15535 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15536 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
15537 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
15538 	}
15539 
15540 	/* if one pointer register is compared to another pointer
15541 	 * register check if PTR_MAYBE_NULL could be lifted.
15542 	 * E.g. register A - maybe null
15543 	 *      register B - not null
15544 	 * for JNE A, B, ... - A is not null in the false branch;
15545 	 * for JEQ A, B, ... - A is not null in the true branch.
15546 	 *
15547 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
15548 	 * not need to be null checked by the BPF program, i.e.,
15549 	 * could be null even without PTR_MAYBE_NULL marking, so
15550 	 * only propagate nullness when neither reg is that type.
15551 	 */
15552 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15553 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15554 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15555 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
15556 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15557 		eq_branch_regs = NULL;
15558 		switch (opcode) {
15559 		case BPF_JEQ:
15560 			eq_branch_regs = other_branch_regs;
15561 			break;
15562 		case BPF_JNE:
15563 			eq_branch_regs = regs;
15564 			break;
15565 		default:
15566 			/* do nothing */
15567 			break;
15568 		}
15569 		if (eq_branch_regs) {
15570 			if (type_may_be_null(src_reg->type))
15571 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15572 			else
15573 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15574 		}
15575 	}
15576 
15577 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15578 	 * NOTE: these optimizations below are related with pointer comparison
15579 	 *       which will never be JMP32.
15580 	 */
15581 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15582 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15583 	    type_may_be_null(dst_reg->type)) {
15584 		/* Mark all identical registers in each branch as either
15585 		 * safe or unknown depending R == 0 or R != 0 conditional.
15586 		 */
15587 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15588 				      opcode == BPF_JNE);
15589 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15590 				      opcode == BPF_JEQ);
15591 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15592 					   this_branch, other_branch) &&
15593 		   is_pointer_value(env, insn->dst_reg)) {
15594 		verbose(env, "R%d pointer comparison prohibited\n",
15595 			insn->dst_reg);
15596 		return -EACCES;
15597 	}
15598 	if (env->log.level & BPF_LOG_LEVEL)
15599 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
15600 	return 0;
15601 }
15602 
15603 /* verify BPF_LD_IMM64 instruction */
15604 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15605 {
15606 	struct bpf_insn_aux_data *aux = cur_aux(env);
15607 	struct bpf_reg_state *regs = cur_regs(env);
15608 	struct bpf_reg_state *dst_reg;
15609 	struct bpf_map *map;
15610 	int err;
15611 
15612 	if (BPF_SIZE(insn->code) != BPF_DW) {
15613 		verbose(env, "invalid BPF_LD_IMM insn\n");
15614 		return -EINVAL;
15615 	}
15616 	if (insn->off != 0) {
15617 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15618 		return -EINVAL;
15619 	}
15620 
15621 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15622 	if (err)
15623 		return err;
15624 
15625 	dst_reg = &regs[insn->dst_reg];
15626 	if (insn->src_reg == 0) {
15627 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15628 
15629 		dst_reg->type = SCALAR_VALUE;
15630 		__mark_reg_known(&regs[insn->dst_reg], imm);
15631 		return 0;
15632 	}
15633 
15634 	/* All special src_reg cases are listed below. From this point onwards
15635 	 * we either succeed and assign a corresponding dst_reg->type after
15636 	 * zeroing the offset, or fail and reject the program.
15637 	 */
15638 	mark_reg_known_zero(env, regs, insn->dst_reg);
15639 
15640 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15641 		dst_reg->type = aux->btf_var.reg_type;
15642 		switch (base_type(dst_reg->type)) {
15643 		case PTR_TO_MEM:
15644 			dst_reg->mem_size = aux->btf_var.mem_size;
15645 			break;
15646 		case PTR_TO_BTF_ID:
15647 			dst_reg->btf = aux->btf_var.btf;
15648 			dst_reg->btf_id = aux->btf_var.btf_id;
15649 			break;
15650 		default:
15651 			verbose(env, "bpf verifier is misconfigured\n");
15652 			return -EFAULT;
15653 		}
15654 		return 0;
15655 	}
15656 
15657 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15658 		struct bpf_prog_aux *aux = env->prog->aux;
15659 		u32 subprogno = find_subprog(env,
15660 					     env->insn_idx + insn->imm + 1);
15661 
15662 		if (!aux->func_info) {
15663 			verbose(env, "missing btf func_info\n");
15664 			return -EINVAL;
15665 		}
15666 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15667 			verbose(env, "callback function not static\n");
15668 			return -EINVAL;
15669 		}
15670 
15671 		dst_reg->type = PTR_TO_FUNC;
15672 		dst_reg->subprogno = subprogno;
15673 		return 0;
15674 	}
15675 
15676 	map = env->used_maps[aux->map_index];
15677 	dst_reg->map_ptr = map;
15678 
15679 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15680 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15681 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
15682 			__mark_reg_unknown(env, dst_reg);
15683 			return 0;
15684 		}
15685 		dst_reg->type = PTR_TO_MAP_VALUE;
15686 		dst_reg->off = aux->map_off;
15687 		WARN_ON_ONCE(map->max_entries != 1);
15688 		/* We want reg->id to be same (0) as map_value is not distinct */
15689 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15690 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15691 		dst_reg->type = CONST_PTR_TO_MAP;
15692 	} else {
15693 		verbose(env, "bpf verifier is misconfigured\n");
15694 		return -EINVAL;
15695 	}
15696 
15697 	return 0;
15698 }
15699 
15700 static bool may_access_skb(enum bpf_prog_type type)
15701 {
15702 	switch (type) {
15703 	case BPF_PROG_TYPE_SOCKET_FILTER:
15704 	case BPF_PROG_TYPE_SCHED_CLS:
15705 	case BPF_PROG_TYPE_SCHED_ACT:
15706 		return true;
15707 	default:
15708 		return false;
15709 	}
15710 }
15711 
15712 /* verify safety of LD_ABS|LD_IND instructions:
15713  * - they can only appear in the programs where ctx == skb
15714  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15715  *   preserve R6-R9, and store return value into R0
15716  *
15717  * Implicit input:
15718  *   ctx == skb == R6 == CTX
15719  *
15720  * Explicit input:
15721  *   SRC == any register
15722  *   IMM == 32-bit immediate
15723  *
15724  * Output:
15725  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15726  */
15727 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15728 {
15729 	struct bpf_reg_state *regs = cur_regs(env);
15730 	static const int ctx_reg = BPF_REG_6;
15731 	u8 mode = BPF_MODE(insn->code);
15732 	int i, err;
15733 
15734 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15735 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15736 		return -EINVAL;
15737 	}
15738 
15739 	if (!env->ops->gen_ld_abs) {
15740 		verbose(env, "bpf verifier is misconfigured\n");
15741 		return -EINVAL;
15742 	}
15743 
15744 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15745 	    BPF_SIZE(insn->code) == BPF_DW ||
15746 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15747 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15748 		return -EINVAL;
15749 	}
15750 
15751 	/* check whether implicit source operand (register R6) is readable */
15752 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15753 	if (err)
15754 		return err;
15755 
15756 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15757 	 * gen_ld_abs() may terminate the program at runtime, leading to
15758 	 * reference leak.
15759 	 */
15760 	err = check_reference_leak(env, false);
15761 	if (err) {
15762 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15763 		return err;
15764 	}
15765 
15766 	if (env->cur_state->active_lock.ptr) {
15767 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15768 		return -EINVAL;
15769 	}
15770 
15771 	if (env->cur_state->active_rcu_lock) {
15772 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15773 		return -EINVAL;
15774 	}
15775 
15776 	if (env->cur_state->active_preempt_lock) {
15777 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n");
15778 		return -EINVAL;
15779 	}
15780 
15781 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15782 		verbose(env,
15783 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15784 		return -EINVAL;
15785 	}
15786 
15787 	if (mode == BPF_IND) {
15788 		/* check explicit source operand */
15789 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15790 		if (err)
15791 			return err;
15792 	}
15793 
15794 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15795 	if (err < 0)
15796 		return err;
15797 
15798 	/* reset caller saved regs to unreadable */
15799 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15800 		mark_reg_not_init(env, regs, caller_saved[i]);
15801 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15802 	}
15803 
15804 	/* mark destination R0 register as readable, since it contains
15805 	 * the value fetched from the packet.
15806 	 * Already marked as written above.
15807 	 */
15808 	mark_reg_unknown(env, regs, BPF_REG_0);
15809 	/* ld_abs load up to 32-bit skb data. */
15810 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15811 	return 0;
15812 }
15813 
15814 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15815 {
15816 	const char *exit_ctx = "At program exit";
15817 	struct tnum enforce_attach_type_range = tnum_unknown;
15818 	const struct bpf_prog *prog = env->prog;
15819 	struct bpf_reg_state *reg;
15820 	struct bpf_retval_range range = retval_range(0, 1);
15821 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15822 	int err;
15823 	struct bpf_func_state *frame = env->cur_state->frame[0];
15824 	const bool is_subprog = frame->subprogno;
15825 	bool return_32bit = false;
15826 
15827 	/* LSM and struct_ops func-ptr's return type could be "void" */
15828 	if (!is_subprog || frame->in_exception_callback_fn) {
15829 		switch (prog_type) {
15830 		case BPF_PROG_TYPE_LSM:
15831 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15832 				/* See below, can be 0 or 0-1 depending on hook. */
15833 				break;
15834 			fallthrough;
15835 		case BPF_PROG_TYPE_STRUCT_OPS:
15836 			if (!prog->aux->attach_func_proto->type)
15837 				return 0;
15838 			break;
15839 		default:
15840 			break;
15841 		}
15842 	}
15843 
15844 	/* eBPF calling convention is such that R0 is used
15845 	 * to return the value from eBPF program.
15846 	 * Make sure that it's readable at this time
15847 	 * of bpf_exit, which means that program wrote
15848 	 * something into it earlier
15849 	 */
15850 	err = check_reg_arg(env, regno, SRC_OP);
15851 	if (err)
15852 		return err;
15853 
15854 	if (is_pointer_value(env, regno)) {
15855 		verbose(env, "R%d leaks addr as return value\n", regno);
15856 		return -EACCES;
15857 	}
15858 
15859 	reg = cur_regs(env) + regno;
15860 
15861 	if (frame->in_async_callback_fn) {
15862 		/* enforce return zero from async callbacks like timer */
15863 		exit_ctx = "At async callback return";
15864 		range = retval_range(0, 0);
15865 		goto enforce_retval;
15866 	}
15867 
15868 	if (is_subprog && !frame->in_exception_callback_fn) {
15869 		if (reg->type != SCALAR_VALUE) {
15870 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15871 				regno, reg_type_str(env, reg->type));
15872 			return -EINVAL;
15873 		}
15874 		return 0;
15875 	}
15876 
15877 	switch (prog_type) {
15878 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15879 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15880 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15881 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15882 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15883 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15884 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15885 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15886 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15887 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15888 			range = retval_range(1, 1);
15889 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15890 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15891 			range = retval_range(0, 3);
15892 		break;
15893 	case BPF_PROG_TYPE_CGROUP_SKB:
15894 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15895 			range = retval_range(0, 3);
15896 			enforce_attach_type_range = tnum_range(2, 3);
15897 		}
15898 		break;
15899 	case BPF_PROG_TYPE_CGROUP_SOCK:
15900 	case BPF_PROG_TYPE_SOCK_OPS:
15901 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15902 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15903 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15904 		break;
15905 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15906 		if (!env->prog->aux->attach_btf_id)
15907 			return 0;
15908 		range = retval_range(0, 0);
15909 		break;
15910 	case BPF_PROG_TYPE_TRACING:
15911 		switch (env->prog->expected_attach_type) {
15912 		case BPF_TRACE_FENTRY:
15913 		case BPF_TRACE_FEXIT:
15914 			range = retval_range(0, 0);
15915 			break;
15916 		case BPF_TRACE_RAW_TP:
15917 		case BPF_MODIFY_RETURN:
15918 			return 0;
15919 		case BPF_TRACE_ITER:
15920 			break;
15921 		default:
15922 			return -ENOTSUPP;
15923 		}
15924 		break;
15925 	case BPF_PROG_TYPE_SK_LOOKUP:
15926 		range = retval_range(SK_DROP, SK_PASS);
15927 		break;
15928 
15929 	case BPF_PROG_TYPE_LSM:
15930 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15931 			/* no range found, any return value is allowed */
15932 			if (!get_func_retval_range(env->prog, &range))
15933 				return 0;
15934 			/* no restricted range, any return value is allowed */
15935 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
15936 				return 0;
15937 			return_32bit = true;
15938 		} else if (!env->prog->aux->attach_func_proto->type) {
15939 			/* Make sure programs that attach to void
15940 			 * hooks don't try to modify return value.
15941 			 */
15942 			range = retval_range(1, 1);
15943 		}
15944 		break;
15945 
15946 	case BPF_PROG_TYPE_NETFILTER:
15947 		range = retval_range(NF_DROP, NF_ACCEPT);
15948 		break;
15949 	case BPF_PROG_TYPE_EXT:
15950 		/* freplace program can return anything as its return value
15951 		 * depends on the to-be-replaced kernel func or bpf program.
15952 		 */
15953 	default:
15954 		return 0;
15955 	}
15956 
15957 enforce_retval:
15958 	if (reg->type != SCALAR_VALUE) {
15959 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15960 			exit_ctx, regno, reg_type_str(env, reg->type));
15961 		return -EINVAL;
15962 	}
15963 
15964 	err = mark_chain_precision(env, regno);
15965 	if (err)
15966 		return err;
15967 
15968 	if (!retval_range_within(range, reg, return_32bit)) {
15969 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15970 		if (!is_subprog &&
15971 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15972 		    prog_type == BPF_PROG_TYPE_LSM &&
15973 		    !prog->aux->attach_func_proto->type)
15974 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15975 		return -EINVAL;
15976 	}
15977 
15978 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15979 	    tnum_in(enforce_attach_type_range, reg->var_off))
15980 		env->prog->enforce_expected_attach_type = 1;
15981 	return 0;
15982 }
15983 
15984 /* non-recursive DFS pseudo code
15985  * 1  procedure DFS-iterative(G,v):
15986  * 2      label v as discovered
15987  * 3      let S be a stack
15988  * 4      S.push(v)
15989  * 5      while S is not empty
15990  * 6            t <- S.peek()
15991  * 7            if t is what we're looking for:
15992  * 8                return t
15993  * 9            for all edges e in G.adjacentEdges(t) do
15994  * 10               if edge e is already labelled
15995  * 11                   continue with the next edge
15996  * 12               w <- G.adjacentVertex(t,e)
15997  * 13               if vertex w is not discovered and not explored
15998  * 14                   label e as tree-edge
15999  * 15                   label w as discovered
16000  * 16                   S.push(w)
16001  * 17                   continue at 5
16002  * 18               else if vertex w is discovered
16003  * 19                   label e as back-edge
16004  * 20               else
16005  * 21                   // vertex w is explored
16006  * 22                   label e as forward- or cross-edge
16007  * 23           label t as explored
16008  * 24           S.pop()
16009  *
16010  * convention:
16011  * 0x10 - discovered
16012  * 0x11 - discovered and fall-through edge labelled
16013  * 0x12 - discovered and fall-through and branch edges labelled
16014  * 0x20 - explored
16015  */
16016 
16017 enum {
16018 	DISCOVERED = 0x10,
16019 	EXPLORED = 0x20,
16020 	FALLTHROUGH = 1,
16021 	BRANCH = 2,
16022 };
16023 
16024 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
16025 {
16026 	env->insn_aux_data[idx].prune_point = true;
16027 }
16028 
16029 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
16030 {
16031 	return env->insn_aux_data[insn_idx].prune_point;
16032 }
16033 
16034 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
16035 {
16036 	env->insn_aux_data[idx].force_checkpoint = true;
16037 }
16038 
16039 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
16040 {
16041 	return env->insn_aux_data[insn_idx].force_checkpoint;
16042 }
16043 
16044 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
16045 {
16046 	env->insn_aux_data[idx].calls_callback = true;
16047 }
16048 
16049 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
16050 {
16051 	return env->insn_aux_data[insn_idx].calls_callback;
16052 }
16053 
16054 enum {
16055 	DONE_EXPLORING = 0,
16056 	KEEP_EXPLORING = 1,
16057 };
16058 
16059 /* t, w, e - match pseudo-code above:
16060  * t - index of current instruction
16061  * w - next instruction
16062  * e - edge
16063  */
16064 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
16065 {
16066 	int *insn_stack = env->cfg.insn_stack;
16067 	int *insn_state = env->cfg.insn_state;
16068 
16069 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
16070 		return DONE_EXPLORING;
16071 
16072 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
16073 		return DONE_EXPLORING;
16074 
16075 	if (w < 0 || w >= env->prog->len) {
16076 		verbose_linfo(env, t, "%d: ", t);
16077 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
16078 		return -EINVAL;
16079 	}
16080 
16081 	if (e == BRANCH) {
16082 		/* mark branch target for state pruning */
16083 		mark_prune_point(env, w);
16084 		mark_jmp_point(env, w);
16085 	}
16086 
16087 	if (insn_state[w] == 0) {
16088 		/* tree-edge */
16089 		insn_state[t] = DISCOVERED | e;
16090 		insn_state[w] = DISCOVERED;
16091 		if (env->cfg.cur_stack >= env->prog->len)
16092 			return -E2BIG;
16093 		insn_stack[env->cfg.cur_stack++] = w;
16094 		return KEEP_EXPLORING;
16095 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
16096 		if (env->bpf_capable)
16097 			return DONE_EXPLORING;
16098 		verbose_linfo(env, t, "%d: ", t);
16099 		verbose_linfo(env, w, "%d: ", w);
16100 		verbose(env, "back-edge from insn %d to %d\n", t, w);
16101 		return -EINVAL;
16102 	} else if (insn_state[w] == EXPLORED) {
16103 		/* forward- or cross-edge */
16104 		insn_state[t] = DISCOVERED | e;
16105 	} else {
16106 		verbose(env, "insn state internal bug\n");
16107 		return -EFAULT;
16108 	}
16109 	return DONE_EXPLORING;
16110 }
16111 
16112 static int visit_func_call_insn(int t, struct bpf_insn *insns,
16113 				struct bpf_verifier_env *env,
16114 				bool visit_callee)
16115 {
16116 	int ret, insn_sz;
16117 
16118 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
16119 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
16120 	if (ret)
16121 		return ret;
16122 
16123 	mark_prune_point(env, t + insn_sz);
16124 	/* when we exit from subprog, we need to record non-linear history */
16125 	mark_jmp_point(env, t + insn_sz);
16126 
16127 	if (visit_callee) {
16128 		mark_prune_point(env, t);
16129 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
16130 	}
16131 	return ret;
16132 }
16133 
16134 /* Bitmask with 1s for all caller saved registers */
16135 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
16136 
16137 /* Return a bitmask specifying which caller saved registers are
16138  * clobbered by a call to a helper *as if* this helper follows
16139  * bpf_fastcall contract:
16140  * - includes R0 if function is non-void;
16141  * - includes R1-R5 if corresponding parameter has is described
16142  *   in the function prototype.
16143  */
16144 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn)
16145 {
16146 	u32 mask;
16147 	int i;
16148 
16149 	mask = 0;
16150 	if (fn->ret_type != RET_VOID)
16151 		mask |= BIT(BPF_REG_0);
16152 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i)
16153 		if (fn->arg_type[i] != ARG_DONTCARE)
16154 			mask |= BIT(BPF_REG_1 + i);
16155 	return mask;
16156 }
16157 
16158 /* True if do_misc_fixups() replaces calls to helper number 'imm',
16159  * replacement patch is presumed to follow bpf_fastcall contract
16160  * (see mark_fastcall_pattern_for_call() below).
16161  */
16162 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
16163 {
16164 	switch (imm) {
16165 #ifdef CONFIG_X86_64
16166 	case BPF_FUNC_get_smp_processor_id:
16167 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
16168 #endif
16169 	default:
16170 		return false;
16171 	}
16172 }
16173 
16174 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */
16175 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta)
16176 {
16177 	u32 vlen, i, mask;
16178 
16179 	vlen = btf_type_vlen(meta->func_proto);
16180 	mask = 0;
16181 	if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type)))
16182 		mask |= BIT(BPF_REG_0);
16183 	for (i = 0; i < vlen; ++i)
16184 		mask |= BIT(BPF_REG_1 + i);
16185 	return mask;
16186 }
16187 
16188 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */
16189 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta)
16190 {
16191 	if (meta->btf == btf_vmlinux)
16192 		return meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
16193 		       meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast];
16194 	return false;
16195 }
16196 
16197 /* LLVM define a bpf_fastcall function attribute.
16198  * This attribute means that function scratches only some of
16199  * the caller saved registers defined by ABI.
16200  * For BPF the set of such registers could be defined as follows:
16201  * - R0 is scratched only if function is non-void;
16202  * - R1-R5 are scratched only if corresponding parameter type is defined
16203  *   in the function prototype.
16204  *
16205  * The contract between kernel and clang allows to simultaneously use
16206  * such functions and maintain backwards compatibility with old
16207  * kernels that don't understand bpf_fastcall calls:
16208  *
16209  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
16210  *   registers are not scratched by the call;
16211  *
16212  * - as a post-processing step, clang visits each bpf_fastcall call and adds
16213  *   spill/fill for every live r0-r5;
16214  *
16215  * - stack offsets used for the spill/fill are allocated as lowest
16216  *   stack offsets in whole function and are not used for any other
16217  *   purposes;
16218  *
16219  * - when kernel loads a program, it looks for such patterns
16220  *   (bpf_fastcall function surrounded by spills/fills) and checks if
16221  *   spill/fill stack offsets are used exclusively in fastcall patterns;
16222  *
16223  * - if so, and if verifier or current JIT inlines the call to the
16224  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
16225  *   spill/fill pairs;
16226  *
16227  * - when old kernel loads a program, presence of spill/fill pairs
16228  *   keeps BPF program valid, albeit slightly less efficient.
16229  *
16230  * For example:
16231  *
16232  *   r1 = 1;
16233  *   r2 = 2;
16234  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16235  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
16236  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16237  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
16238  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
16239  *   r0 = r1;                            exit;
16240  *   r0 += r2;
16241  *   exit;
16242  *
16243  * The purpose of mark_fastcall_pattern_for_call is to:
16244  * - look for such patterns;
16245  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
16246  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
16247  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
16248  *   at which bpf_fastcall spill/fill stack slots start;
16249  * - update env->subprog_info[*]->keep_fastcall_stack.
16250  *
16251  * The .fastcall_pattern and .fastcall_stack_off are used by
16252  * check_fastcall_stack_contract() to check if every stack access to
16253  * fastcall spill/fill stack slot originates from spill/fill
16254  * instructions, members of fastcall patterns.
16255  *
16256  * If such condition holds true for a subprogram, fastcall patterns could
16257  * be rewritten by remove_fastcall_spills_fills().
16258  * Otherwise bpf_fastcall patterns are not changed in the subprogram
16259  * (code, presumably, generated by an older clang version).
16260  *
16261  * For example, it is *not* safe to remove spill/fill below:
16262  *
16263  *   r1 = 1;
16264  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16265  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16266  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
16267  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
16268  *   r0 += r1;                           exit;
16269  *   exit;
16270  */
16271 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
16272 					   struct bpf_subprog_info *subprog,
16273 					   int insn_idx, s16 lowest_off)
16274 {
16275 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
16276 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
16277 	const struct bpf_func_proto *fn;
16278 	u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS;
16279 	u32 expected_regs_mask;
16280 	bool can_be_inlined = false;
16281 	s16 off;
16282 	int i;
16283 
16284 	if (bpf_helper_call(call)) {
16285 		if (get_helper_proto(env, call->imm, &fn) < 0)
16286 			/* error would be reported later */
16287 			return;
16288 		clobbered_regs_mask = helper_fastcall_clobber_mask(fn);
16289 		can_be_inlined = fn->allow_fastcall &&
16290 				 (verifier_inlines_helper_call(env, call->imm) ||
16291 				  bpf_jit_inlines_helper_call(call->imm));
16292 	}
16293 
16294 	if (bpf_pseudo_kfunc_call(call)) {
16295 		struct bpf_kfunc_call_arg_meta meta;
16296 		int err;
16297 
16298 		err = fetch_kfunc_meta(env, call, &meta, NULL);
16299 		if (err < 0)
16300 			/* error would be reported later */
16301 			return;
16302 
16303 		clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta);
16304 		can_be_inlined = is_fastcall_kfunc_call(&meta);
16305 	}
16306 
16307 	if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS)
16308 		return;
16309 
16310 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
16311 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
16312 
16313 	/* match pairs of form:
16314 	 *
16315 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
16316 	 * ...
16317 	 * call %[to_be_inlined]
16318 	 * ...
16319 	 * rX = *(u64 *)(r10 - Y)
16320 	 */
16321 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
16322 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
16323 			break;
16324 		stx = &insns[insn_idx - i];
16325 		ldx = &insns[insn_idx + i];
16326 		/* must be a stack spill/fill pair */
16327 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16328 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
16329 		    stx->dst_reg != BPF_REG_10 ||
16330 		    ldx->src_reg != BPF_REG_10)
16331 			break;
16332 		/* must be a spill/fill for the same reg */
16333 		if (stx->src_reg != ldx->dst_reg)
16334 			break;
16335 		/* must be one of the previously unseen registers */
16336 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
16337 			break;
16338 		/* must be a spill/fill for the same expected offset,
16339 		 * no need to check offset alignment, BPF_DW stack access
16340 		 * is always 8-byte aligned.
16341 		 */
16342 		if (stx->off != off || ldx->off != off)
16343 			break;
16344 		expected_regs_mask &= ~BIT(stx->src_reg);
16345 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
16346 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
16347 	}
16348 	if (i == 1)
16349 		return;
16350 
16351 	/* Conditionally set 'fastcall_spills_num' to allow forward
16352 	 * compatibility when more helper functions are marked as
16353 	 * bpf_fastcall at compile time than current kernel supports, e.g:
16354 	 *
16355 	 *   1: *(u64 *)(r10 - 8) = r1
16356 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
16357 	 *   3: r1 = *(u64 *)(r10 - 8)
16358 	 *   4: *(u64 *)(r10 - 8) = r1
16359 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
16360 	 *   6: r1 = *(u64 *)(r10 - 8)
16361 	 *
16362 	 * There is no need to block bpf_fastcall rewrite for such program.
16363 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
16364 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
16365 	 * does not remove spill/fill pair {4,6}.
16366 	 */
16367 	if (can_be_inlined)
16368 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
16369 	else
16370 		subprog->keep_fastcall_stack = 1;
16371 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
16372 }
16373 
16374 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
16375 {
16376 	struct bpf_subprog_info *subprog = env->subprog_info;
16377 	struct bpf_insn *insn;
16378 	s16 lowest_off;
16379 	int s, i;
16380 
16381 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
16382 		/* find lowest stack spill offset used in this subprog */
16383 		lowest_off = 0;
16384 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16385 			insn = env->prog->insnsi + i;
16386 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16387 			    insn->dst_reg != BPF_REG_10)
16388 				continue;
16389 			lowest_off = min(lowest_off, insn->off);
16390 		}
16391 		/* use this offset to find fastcall patterns */
16392 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16393 			insn = env->prog->insnsi + i;
16394 			if (insn->code != (BPF_JMP | BPF_CALL))
16395 				continue;
16396 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
16397 		}
16398 	}
16399 	return 0;
16400 }
16401 
16402 /* Visits the instruction at index t and returns one of the following:
16403  *  < 0 - an error occurred
16404  *  DONE_EXPLORING - the instruction was fully explored
16405  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
16406  */
16407 static int visit_insn(int t, struct bpf_verifier_env *env)
16408 {
16409 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
16410 	int ret, off, insn_sz;
16411 
16412 	if (bpf_pseudo_func(insn))
16413 		return visit_func_call_insn(t, insns, env, true);
16414 
16415 	/* All non-branch instructions have a single fall-through edge. */
16416 	if (BPF_CLASS(insn->code) != BPF_JMP &&
16417 	    BPF_CLASS(insn->code) != BPF_JMP32) {
16418 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
16419 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
16420 	}
16421 
16422 	switch (BPF_OP(insn->code)) {
16423 	case BPF_EXIT:
16424 		return DONE_EXPLORING;
16425 
16426 	case BPF_CALL:
16427 		if (is_async_callback_calling_insn(insn))
16428 			/* Mark this call insn as a prune point to trigger
16429 			 * is_state_visited() check before call itself is
16430 			 * processed by __check_func_call(). Otherwise new
16431 			 * async state will be pushed for further exploration.
16432 			 */
16433 			mark_prune_point(env, t);
16434 		/* For functions that invoke callbacks it is not known how many times
16435 		 * callback would be called. Verifier models callback calling functions
16436 		 * by repeatedly visiting callback bodies and returning to origin call
16437 		 * instruction.
16438 		 * In order to stop such iteration verifier needs to identify when a
16439 		 * state identical some state from a previous iteration is reached.
16440 		 * Check below forces creation of checkpoint before callback calling
16441 		 * instruction to allow search for such identical states.
16442 		 */
16443 		if (is_sync_callback_calling_insn(insn)) {
16444 			mark_calls_callback(env, t);
16445 			mark_force_checkpoint(env, t);
16446 			mark_prune_point(env, t);
16447 			mark_jmp_point(env, t);
16448 		}
16449 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16450 			struct bpf_kfunc_call_arg_meta meta;
16451 
16452 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
16453 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
16454 				mark_prune_point(env, t);
16455 				/* Checking and saving state checkpoints at iter_next() call
16456 				 * is crucial for fast convergence of open-coded iterator loop
16457 				 * logic, so we need to force it. If we don't do that,
16458 				 * is_state_visited() might skip saving a checkpoint, causing
16459 				 * unnecessarily long sequence of not checkpointed
16460 				 * instructions and jumps, leading to exhaustion of jump
16461 				 * history buffer, and potentially other undesired outcomes.
16462 				 * It is expected that with correct open-coded iterators
16463 				 * convergence will happen quickly, so we don't run a risk of
16464 				 * exhausting memory.
16465 				 */
16466 				mark_force_checkpoint(env, t);
16467 			}
16468 		}
16469 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
16470 
16471 	case BPF_JA:
16472 		if (BPF_SRC(insn->code) != BPF_K)
16473 			return -EINVAL;
16474 
16475 		if (BPF_CLASS(insn->code) == BPF_JMP)
16476 			off = insn->off;
16477 		else
16478 			off = insn->imm;
16479 
16480 		/* unconditional jump with single edge */
16481 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
16482 		if (ret)
16483 			return ret;
16484 
16485 		mark_prune_point(env, t + off + 1);
16486 		mark_jmp_point(env, t + off + 1);
16487 
16488 		return ret;
16489 
16490 	default:
16491 		/* conditional jump with two edges */
16492 		mark_prune_point(env, t);
16493 		if (is_may_goto_insn(insn))
16494 			mark_force_checkpoint(env, t);
16495 
16496 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
16497 		if (ret)
16498 			return ret;
16499 
16500 		return push_insn(t, t + insn->off + 1, BRANCH, env);
16501 	}
16502 }
16503 
16504 /* non-recursive depth-first-search to detect loops in BPF program
16505  * loop == back-edge in directed graph
16506  */
16507 static int check_cfg(struct bpf_verifier_env *env)
16508 {
16509 	int insn_cnt = env->prog->len;
16510 	int *insn_stack, *insn_state;
16511 	int ex_insn_beg, i, ret = 0;
16512 	bool ex_done = false;
16513 
16514 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
16515 	if (!insn_state)
16516 		return -ENOMEM;
16517 
16518 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
16519 	if (!insn_stack) {
16520 		kvfree(insn_state);
16521 		return -ENOMEM;
16522 	}
16523 
16524 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
16525 	insn_stack[0] = 0; /* 0 is the first instruction */
16526 	env->cfg.cur_stack = 1;
16527 
16528 walk_cfg:
16529 	while (env->cfg.cur_stack > 0) {
16530 		int t = insn_stack[env->cfg.cur_stack - 1];
16531 
16532 		ret = visit_insn(t, env);
16533 		switch (ret) {
16534 		case DONE_EXPLORING:
16535 			insn_state[t] = EXPLORED;
16536 			env->cfg.cur_stack--;
16537 			break;
16538 		case KEEP_EXPLORING:
16539 			break;
16540 		default:
16541 			if (ret > 0) {
16542 				verbose(env, "visit_insn internal bug\n");
16543 				ret = -EFAULT;
16544 			}
16545 			goto err_free;
16546 		}
16547 	}
16548 
16549 	if (env->cfg.cur_stack < 0) {
16550 		verbose(env, "pop stack internal bug\n");
16551 		ret = -EFAULT;
16552 		goto err_free;
16553 	}
16554 
16555 	if (env->exception_callback_subprog && !ex_done) {
16556 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
16557 
16558 		insn_state[ex_insn_beg] = DISCOVERED;
16559 		insn_stack[0] = ex_insn_beg;
16560 		env->cfg.cur_stack = 1;
16561 		ex_done = true;
16562 		goto walk_cfg;
16563 	}
16564 
16565 	for (i = 0; i < insn_cnt; i++) {
16566 		struct bpf_insn *insn = &env->prog->insnsi[i];
16567 
16568 		if (insn_state[i] != EXPLORED) {
16569 			verbose(env, "unreachable insn %d\n", i);
16570 			ret = -EINVAL;
16571 			goto err_free;
16572 		}
16573 		if (bpf_is_ldimm64(insn)) {
16574 			if (insn_state[i + 1] != 0) {
16575 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
16576 				ret = -EINVAL;
16577 				goto err_free;
16578 			}
16579 			i++; /* skip second half of ldimm64 */
16580 		}
16581 	}
16582 	ret = 0; /* cfg looks good */
16583 
16584 err_free:
16585 	kvfree(insn_state);
16586 	kvfree(insn_stack);
16587 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
16588 	return ret;
16589 }
16590 
16591 static int check_abnormal_return(struct bpf_verifier_env *env)
16592 {
16593 	int i;
16594 
16595 	for (i = 1; i < env->subprog_cnt; i++) {
16596 		if (env->subprog_info[i].has_ld_abs) {
16597 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
16598 			return -EINVAL;
16599 		}
16600 		if (env->subprog_info[i].has_tail_call) {
16601 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
16602 			return -EINVAL;
16603 		}
16604 	}
16605 	return 0;
16606 }
16607 
16608 /* The minimum supported BTF func info size */
16609 #define MIN_BPF_FUNCINFO_SIZE	8
16610 #define MAX_FUNCINFO_REC_SIZE	252
16611 
16612 static int check_btf_func_early(struct bpf_verifier_env *env,
16613 				const union bpf_attr *attr,
16614 				bpfptr_t uattr)
16615 {
16616 	u32 krec_size = sizeof(struct bpf_func_info);
16617 	const struct btf_type *type, *func_proto;
16618 	u32 i, nfuncs, urec_size, min_size;
16619 	struct bpf_func_info *krecord;
16620 	struct bpf_prog *prog;
16621 	const struct btf *btf;
16622 	u32 prev_offset = 0;
16623 	bpfptr_t urecord;
16624 	int ret = -ENOMEM;
16625 
16626 	nfuncs = attr->func_info_cnt;
16627 	if (!nfuncs) {
16628 		if (check_abnormal_return(env))
16629 			return -EINVAL;
16630 		return 0;
16631 	}
16632 
16633 	urec_size = attr->func_info_rec_size;
16634 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
16635 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
16636 	    urec_size % sizeof(u32)) {
16637 		verbose(env, "invalid func info rec size %u\n", urec_size);
16638 		return -EINVAL;
16639 	}
16640 
16641 	prog = env->prog;
16642 	btf = prog->aux->btf;
16643 
16644 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16645 	min_size = min_t(u32, krec_size, urec_size);
16646 
16647 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
16648 	if (!krecord)
16649 		return -ENOMEM;
16650 
16651 	for (i = 0; i < nfuncs; i++) {
16652 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
16653 		if (ret) {
16654 			if (ret == -E2BIG) {
16655 				verbose(env, "nonzero tailing record in func info");
16656 				/* set the size kernel expects so loader can zero
16657 				 * out the rest of the record.
16658 				 */
16659 				if (copy_to_bpfptr_offset(uattr,
16660 							  offsetof(union bpf_attr, func_info_rec_size),
16661 							  &min_size, sizeof(min_size)))
16662 					ret = -EFAULT;
16663 			}
16664 			goto err_free;
16665 		}
16666 
16667 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
16668 			ret = -EFAULT;
16669 			goto err_free;
16670 		}
16671 
16672 		/* check insn_off */
16673 		ret = -EINVAL;
16674 		if (i == 0) {
16675 			if (krecord[i].insn_off) {
16676 				verbose(env,
16677 					"nonzero insn_off %u for the first func info record",
16678 					krecord[i].insn_off);
16679 				goto err_free;
16680 			}
16681 		} else if (krecord[i].insn_off <= prev_offset) {
16682 			verbose(env,
16683 				"same or smaller insn offset (%u) than previous func info record (%u)",
16684 				krecord[i].insn_off, prev_offset);
16685 			goto err_free;
16686 		}
16687 
16688 		/* check type_id */
16689 		type = btf_type_by_id(btf, krecord[i].type_id);
16690 		if (!type || !btf_type_is_func(type)) {
16691 			verbose(env, "invalid type id %d in func info",
16692 				krecord[i].type_id);
16693 			goto err_free;
16694 		}
16695 
16696 		func_proto = btf_type_by_id(btf, type->type);
16697 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
16698 			/* btf_func_check() already verified it during BTF load */
16699 			goto err_free;
16700 
16701 		prev_offset = krecord[i].insn_off;
16702 		bpfptr_add(&urecord, urec_size);
16703 	}
16704 
16705 	prog->aux->func_info = krecord;
16706 	prog->aux->func_info_cnt = nfuncs;
16707 	return 0;
16708 
16709 err_free:
16710 	kvfree(krecord);
16711 	return ret;
16712 }
16713 
16714 static int check_btf_func(struct bpf_verifier_env *env,
16715 			  const union bpf_attr *attr,
16716 			  bpfptr_t uattr)
16717 {
16718 	const struct btf_type *type, *func_proto, *ret_type;
16719 	u32 i, nfuncs, urec_size;
16720 	struct bpf_func_info *krecord;
16721 	struct bpf_func_info_aux *info_aux = NULL;
16722 	struct bpf_prog *prog;
16723 	const struct btf *btf;
16724 	bpfptr_t urecord;
16725 	bool scalar_return;
16726 	int ret = -ENOMEM;
16727 
16728 	nfuncs = attr->func_info_cnt;
16729 	if (!nfuncs) {
16730 		if (check_abnormal_return(env))
16731 			return -EINVAL;
16732 		return 0;
16733 	}
16734 	if (nfuncs != env->subprog_cnt) {
16735 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16736 		return -EINVAL;
16737 	}
16738 
16739 	urec_size = attr->func_info_rec_size;
16740 
16741 	prog = env->prog;
16742 	btf = prog->aux->btf;
16743 
16744 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16745 
16746 	krecord = prog->aux->func_info;
16747 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16748 	if (!info_aux)
16749 		return -ENOMEM;
16750 
16751 	for (i = 0; i < nfuncs; i++) {
16752 		/* check insn_off */
16753 		ret = -EINVAL;
16754 
16755 		if (env->subprog_info[i].start != krecord[i].insn_off) {
16756 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16757 			goto err_free;
16758 		}
16759 
16760 		/* Already checked type_id */
16761 		type = btf_type_by_id(btf, krecord[i].type_id);
16762 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16763 		/* Already checked func_proto */
16764 		func_proto = btf_type_by_id(btf, type->type);
16765 
16766 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16767 		scalar_return =
16768 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16769 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16770 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16771 			goto err_free;
16772 		}
16773 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16774 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16775 			goto err_free;
16776 		}
16777 
16778 		bpfptr_add(&urecord, urec_size);
16779 	}
16780 
16781 	prog->aux->func_info_aux = info_aux;
16782 	return 0;
16783 
16784 err_free:
16785 	kfree(info_aux);
16786 	return ret;
16787 }
16788 
16789 static void adjust_btf_func(struct bpf_verifier_env *env)
16790 {
16791 	struct bpf_prog_aux *aux = env->prog->aux;
16792 	int i;
16793 
16794 	if (!aux->func_info)
16795 		return;
16796 
16797 	/* func_info is not available for hidden subprogs */
16798 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16799 		aux->func_info[i].insn_off = env->subprog_info[i].start;
16800 }
16801 
16802 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
16803 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
16804 
16805 static int check_btf_line(struct bpf_verifier_env *env,
16806 			  const union bpf_attr *attr,
16807 			  bpfptr_t uattr)
16808 {
16809 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16810 	struct bpf_subprog_info *sub;
16811 	struct bpf_line_info *linfo;
16812 	struct bpf_prog *prog;
16813 	const struct btf *btf;
16814 	bpfptr_t ulinfo;
16815 	int err;
16816 
16817 	nr_linfo = attr->line_info_cnt;
16818 	if (!nr_linfo)
16819 		return 0;
16820 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16821 		return -EINVAL;
16822 
16823 	rec_size = attr->line_info_rec_size;
16824 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16825 	    rec_size > MAX_LINEINFO_REC_SIZE ||
16826 	    rec_size & (sizeof(u32) - 1))
16827 		return -EINVAL;
16828 
16829 	/* Need to zero it in case the userspace may
16830 	 * pass in a smaller bpf_line_info object.
16831 	 */
16832 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16833 			 GFP_KERNEL | __GFP_NOWARN);
16834 	if (!linfo)
16835 		return -ENOMEM;
16836 
16837 	prog = env->prog;
16838 	btf = prog->aux->btf;
16839 
16840 	s = 0;
16841 	sub = env->subprog_info;
16842 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16843 	expected_size = sizeof(struct bpf_line_info);
16844 	ncopy = min_t(u32, expected_size, rec_size);
16845 	for (i = 0; i < nr_linfo; i++) {
16846 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16847 		if (err) {
16848 			if (err == -E2BIG) {
16849 				verbose(env, "nonzero tailing record in line_info");
16850 				if (copy_to_bpfptr_offset(uattr,
16851 							  offsetof(union bpf_attr, line_info_rec_size),
16852 							  &expected_size, sizeof(expected_size)))
16853 					err = -EFAULT;
16854 			}
16855 			goto err_free;
16856 		}
16857 
16858 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16859 			err = -EFAULT;
16860 			goto err_free;
16861 		}
16862 
16863 		/*
16864 		 * Check insn_off to ensure
16865 		 * 1) strictly increasing AND
16866 		 * 2) bounded by prog->len
16867 		 *
16868 		 * The linfo[0].insn_off == 0 check logically falls into
16869 		 * the later "missing bpf_line_info for func..." case
16870 		 * because the first linfo[0].insn_off must be the
16871 		 * first sub also and the first sub must have
16872 		 * subprog_info[0].start == 0.
16873 		 */
16874 		if ((i && linfo[i].insn_off <= prev_offset) ||
16875 		    linfo[i].insn_off >= prog->len) {
16876 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16877 				i, linfo[i].insn_off, prev_offset,
16878 				prog->len);
16879 			err = -EINVAL;
16880 			goto err_free;
16881 		}
16882 
16883 		if (!prog->insnsi[linfo[i].insn_off].code) {
16884 			verbose(env,
16885 				"Invalid insn code at line_info[%u].insn_off\n",
16886 				i);
16887 			err = -EINVAL;
16888 			goto err_free;
16889 		}
16890 
16891 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16892 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16893 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16894 			err = -EINVAL;
16895 			goto err_free;
16896 		}
16897 
16898 		if (s != env->subprog_cnt) {
16899 			if (linfo[i].insn_off == sub[s].start) {
16900 				sub[s].linfo_idx = i;
16901 				s++;
16902 			} else if (sub[s].start < linfo[i].insn_off) {
16903 				verbose(env, "missing bpf_line_info for func#%u\n", s);
16904 				err = -EINVAL;
16905 				goto err_free;
16906 			}
16907 		}
16908 
16909 		prev_offset = linfo[i].insn_off;
16910 		bpfptr_add(&ulinfo, rec_size);
16911 	}
16912 
16913 	if (s != env->subprog_cnt) {
16914 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16915 			env->subprog_cnt - s, s);
16916 		err = -EINVAL;
16917 		goto err_free;
16918 	}
16919 
16920 	prog->aux->linfo = linfo;
16921 	prog->aux->nr_linfo = nr_linfo;
16922 
16923 	return 0;
16924 
16925 err_free:
16926 	kvfree(linfo);
16927 	return err;
16928 }
16929 
16930 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16931 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16932 
16933 static int check_core_relo(struct bpf_verifier_env *env,
16934 			   const union bpf_attr *attr,
16935 			   bpfptr_t uattr)
16936 {
16937 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16938 	struct bpf_core_relo core_relo = {};
16939 	struct bpf_prog *prog = env->prog;
16940 	const struct btf *btf = prog->aux->btf;
16941 	struct bpf_core_ctx ctx = {
16942 		.log = &env->log,
16943 		.btf = btf,
16944 	};
16945 	bpfptr_t u_core_relo;
16946 	int err;
16947 
16948 	nr_core_relo = attr->core_relo_cnt;
16949 	if (!nr_core_relo)
16950 		return 0;
16951 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16952 		return -EINVAL;
16953 
16954 	rec_size = attr->core_relo_rec_size;
16955 	if (rec_size < MIN_CORE_RELO_SIZE ||
16956 	    rec_size > MAX_CORE_RELO_SIZE ||
16957 	    rec_size % sizeof(u32))
16958 		return -EINVAL;
16959 
16960 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16961 	expected_size = sizeof(struct bpf_core_relo);
16962 	ncopy = min_t(u32, expected_size, rec_size);
16963 
16964 	/* Unlike func_info and line_info, copy and apply each CO-RE
16965 	 * relocation record one at a time.
16966 	 */
16967 	for (i = 0; i < nr_core_relo; i++) {
16968 		/* future proofing when sizeof(bpf_core_relo) changes */
16969 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16970 		if (err) {
16971 			if (err == -E2BIG) {
16972 				verbose(env, "nonzero tailing record in core_relo");
16973 				if (copy_to_bpfptr_offset(uattr,
16974 							  offsetof(union bpf_attr, core_relo_rec_size),
16975 							  &expected_size, sizeof(expected_size)))
16976 					err = -EFAULT;
16977 			}
16978 			break;
16979 		}
16980 
16981 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16982 			err = -EFAULT;
16983 			break;
16984 		}
16985 
16986 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16987 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16988 				i, core_relo.insn_off, prog->len);
16989 			err = -EINVAL;
16990 			break;
16991 		}
16992 
16993 		err = bpf_core_apply(&ctx, &core_relo, i,
16994 				     &prog->insnsi[core_relo.insn_off / 8]);
16995 		if (err)
16996 			break;
16997 		bpfptr_add(&u_core_relo, rec_size);
16998 	}
16999 	return err;
17000 }
17001 
17002 static int check_btf_info_early(struct bpf_verifier_env *env,
17003 				const union bpf_attr *attr,
17004 				bpfptr_t uattr)
17005 {
17006 	struct btf *btf;
17007 	int err;
17008 
17009 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17010 		if (check_abnormal_return(env))
17011 			return -EINVAL;
17012 		return 0;
17013 	}
17014 
17015 	btf = btf_get_by_fd(attr->prog_btf_fd);
17016 	if (IS_ERR(btf))
17017 		return PTR_ERR(btf);
17018 	if (btf_is_kernel(btf)) {
17019 		btf_put(btf);
17020 		return -EACCES;
17021 	}
17022 	env->prog->aux->btf = btf;
17023 
17024 	err = check_btf_func_early(env, attr, uattr);
17025 	if (err)
17026 		return err;
17027 	return 0;
17028 }
17029 
17030 static int check_btf_info(struct bpf_verifier_env *env,
17031 			  const union bpf_attr *attr,
17032 			  bpfptr_t uattr)
17033 {
17034 	int err;
17035 
17036 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
17037 		if (check_abnormal_return(env))
17038 			return -EINVAL;
17039 		return 0;
17040 	}
17041 
17042 	err = check_btf_func(env, attr, uattr);
17043 	if (err)
17044 		return err;
17045 
17046 	err = check_btf_line(env, attr, uattr);
17047 	if (err)
17048 		return err;
17049 
17050 	err = check_core_relo(env, attr, uattr);
17051 	if (err)
17052 		return err;
17053 
17054 	return 0;
17055 }
17056 
17057 /* check %cur's range satisfies %old's */
17058 static bool range_within(const struct bpf_reg_state *old,
17059 			 const struct bpf_reg_state *cur)
17060 {
17061 	return old->umin_value <= cur->umin_value &&
17062 	       old->umax_value >= cur->umax_value &&
17063 	       old->smin_value <= cur->smin_value &&
17064 	       old->smax_value >= cur->smax_value &&
17065 	       old->u32_min_value <= cur->u32_min_value &&
17066 	       old->u32_max_value >= cur->u32_max_value &&
17067 	       old->s32_min_value <= cur->s32_min_value &&
17068 	       old->s32_max_value >= cur->s32_max_value;
17069 }
17070 
17071 /* If in the old state two registers had the same id, then they need to have
17072  * the same id in the new state as well.  But that id could be different from
17073  * the old state, so we need to track the mapping from old to new ids.
17074  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
17075  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
17076  * regs with a different old id could still have new id 9, we don't care about
17077  * that.
17078  * So we look through our idmap to see if this old id has been seen before.  If
17079  * so, we require the new id to match; otherwise, we add the id pair to the map.
17080  */
17081 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17082 {
17083 	struct bpf_id_pair *map = idmap->map;
17084 	unsigned int i;
17085 
17086 	/* either both IDs should be set or both should be zero */
17087 	if (!!old_id != !!cur_id)
17088 		return false;
17089 
17090 	if (old_id == 0) /* cur_id == 0 as well */
17091 		return true;
17092 
17093 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
17094 		if (!map[i].old) {
17095 			/* Reached an empty slot; haven't seen this id before */
17096 			map[i].old = old_id;
17097 			map[i].cur = cur_id;
17098 			return true;
17099 		}
17100 		if (map[i].old == old_id)
17101 			return map[i].cur == cur_id;
17102 		if (map[i].cur == cur_id)
17103 			return false;
17104 	}
17105 	/* We ran out of idmap slots, which should be impossible */
17106 	WARN_ON_ONCE(1);
17107 	return false;
17108 }
17109 
17110 /* Similar to check_ids(), but allocate a unique temporary ID
17111  * for 'old_id' or 'cur_id' of zero.
17112  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
17113  */
17114 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17115 {
17116 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
17117 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
17118 
17119 	return check_ids(old_id, cur_id, idmap);
17120 }
17121 
17122 static void clean_func_state(struct bpf_verifier_env *env,
17123 			     struct bpf_func_state *st)
17124 {
17125 	enum bpf_reg_liveness live;
17126 	int i, j;
17127 
17128 	for (i = 0; i < BPF_REG_FP; i++) {
17129 		live = st->regs[i].live;
17130 		/* liveness must not touch this register anymore */
17131 		st->regs[i].live |= REG_LIVE_DONE;
17132 		if (!(live & REG_LIVE_READ))
17133 			/* since the register is unused, clear its state
17134 			 * to make further comparison simpler
17135 			 */
17136 			__mark_reg_not_init(env, &st->regs[i]);
17137 	}
17138 
17139 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
17140 		live = st->stack[i].spilled_ptr.live;
17141 		/* liveness must not touch this stack slot anymore */
17142 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
17143 		if (!(live & REG_LIVE_READ)) {
17144 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
17145 			for (j = 0; j < BPF_REG_SIZE; j++)
17146 				st->stack[i].slot_type[j] = STACK_INVALID;
17147 		}
17148 	}
17149 }
17150 
17151 static void clean_verifier_state(struct bpf_verifier_env *env,
17152 				 struct bpf_verifier_state *st)
17153 {
17154 	int i;
17155 
17156 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
17157 		/* all regs in this state in all frames were already marked */
17158 		return;
17159 
17160 	for (i = 0; i <= st->curframe; i++)
17161 		clean_func_state(env, st->frame[i]);
17162 }
17163 
17164 /* the parentage chains form a tree.
17165  * the verifier states are added to state lists at given insn and
17166  * pushed into state stack for future exploration.
17167  * when the verifier reaches bpf_exit insn some of the verifer states
17168  * stored in the state lists have their final liveness state already,
17169  * but a lot of states will get revised from liveness point of view when
17170  * the verifier explores other branches.
17171  * Example:
17172  * 1: r0 = 1
17173  * 2: if r1 == 100 goto pc+1
17174  * 3: r0 = 2
17175  * 4: exit
17176  * when the verifier reaches exit insn the register r0 in the state list of
17177  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
17178  * of insn 2 and goes exploring further. At the insn 4 it will walk the
17179  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
17180  *
17181  * Since the verifier pushes the branch states as it sees them while exploring
17182  * the program the condition of walking the branch instruction for the second
17183  * time means that all states below this branch were already explored and
17184  * their final liveness marks are already propagated.
17185  * Hence when the verifier completes the search of state list in is_state_visited()
17186  * we can call this clean_live_states() function to mark all liveness states
17187  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
17188  * will not be used.
17189  * This function also clears the registers and stack for states that !READ
17190  * to simplify state merging.
17191  *
17192  * Important note here that walking the same branch instruction in the callee
17193  * doesn't meant that the states are DONE. The verifier has to compare
17194  * the callsites
17195  */
17196 static void clean_live_states(struct bpf_verifier_env *env, int insn,
17197 			      struct bpf_verifier_state *cur)
17198 {
17199 	struct bpf_verifier_state_list *sl;
17200 
17201 	sl = *explored_state(env, insn);
17202 	while (sl) {
17203 		if (sl->state.branches)
17204 			goto next;
17205 		if (sl->state.insn_idx != insn ||
17206 		    !same_callsites(&sl->state, cur))
17207 			goto next;
17208 		clean_verifier_state(env, &sl->state);
17209 next:
17210 		sl = sl->next;
17211 	}
17212 }
17213 
17214 static bool regs_exact(const struct bpf_reg_state *rold,
17215 		       const struct bpf_reg_state *rcur,
17216 		       struct bpf_idmap *idmap)
17217 {
17218 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17219 	       check_ids(rold->id, rcur->id, idmap) &&
17220 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17221 }
17222 
17223 enum exact_level {
17224 	NOT_EXACT,
17225 	EXACT,
17226 	RANGE_WITHIN
17227 };
17228 
17229 /* Returns true if (rold safe implies rcur safe) */
17230 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
17231 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
17232 		    enum exact_level exact)
17233 {
17234 	if (exact == EXACT)
17235 		return regs_exact(rold, rcur, idmap);
17236 
17237 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
17238 		/* explored state didn't use this */
17239 		return true;
17240 	if (rold->type == NOT_INIT) {
17241 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
17242 			/* explored state can't have used this */
17243 			return true;
17244 	}
17245 
17246 	/* Enforce that register types have to match exactly, including their
17247 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
17248 	 * rule.
17249 	 *
17250 	 * One can make a point that using a pointer register as unbounded
17251 	 * SCALAR would be technically acceptable, but this could lead to
17252 	 * pointer leaks because scalars are allowed to leak while pointers
17253 	 * are not. We could make this safe in special cases if root is
17254 	 * calling us, but it's probably not worth the hassle.
17255 	 *
17256 	 * Also, register types that are *not* MAYBE_NULL could technically be
17257 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
17258 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
17259 	 * to the same map).
17260 	 * However, if the old MAYBE_NULL register then got NULL checked,
17261 	 * doing so could have affected others with the same id, and we can't
17262 	 * check for that because we lost the id when we converted to
17263 	 * a non-MAYBE_NULL variant.
17264 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
17265 	 * non-MAYBE_NULL registers as well.
17266 	 */
17267 	if (rold->type != rcur->type)
17268 		return false;
17269 
17270 	switch (base_type(rold->type)) {
17271 	case SCALAR_VALUE:
17272 		if (env->explore_alu_limits) {
17273 			/* explore_alu_limits disables tnum_in() and range_within()
17274 			 * logic and requires everything to be strict
17275 			 */
17276 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17277 			       check_scalar_ids(rold->id, rcur->id, idmap);
17278 		}
17279 		if (!rold->precise && exact == NOT_EXACT)
17280 			return true;
17281 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
17282 			return false;
17283 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
17284 			return false;
17285 		/* Why check_ids() for scalar registers?
17286 		 *
17287 		 * Consider the following BPF code:
17288 		 *   1: r6 = ... unbound scalar, ID=a ...
17289 		 *   2: r7 = ... unbound scalar, ID=b ...
17290 		 *   3: if (r6 > r7) goto +1
17291 		 *   4: r6 = r7
17292 		 *   5: if (r6 > X) goto ...
17293 		 *   6: ... memory operation using r7 ...
17294 		 *
17295 		 * First verification path is [1-6]:
17296 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
17297 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
17298 		 *   r7 <= X, because r6 and r7 share same id.
17299 		 * Next verification path is [1-4, 6].
17300 		 *
17301 		 * Instruction (6) would be reached in two states:
17302 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
17303 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
17304 		 *
17305 		 * Use check_ids() to distinguish these states.
17306 		 * ---
17307 		 * Also verify that new value satisfies old value range knowledge.
17308 		 */
17309 		return range_within(rold, rcur) &&
17310 		       tnum_in(rold->var_off, rcur->var_off) &&
17311 		       check_scalar_ids(rold->id, rcur->id, idmap);
17312 	case PTR_TO_MAP_KEY:
17313 	case PTR_TO_MAP_VALUE:
17314 	case PTR_TO_MEM:
17315 	case PTR_TO_BUF:
17316 	case PTR_TO_TP_BUFFER:
17317 		/* If the new min/max/var_off satisfy the old ones and
17318 		 * everything else matches, we are OK.
17319 		 */
17320 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
17321 		       range_within(rold, rcur) &&
17322 		       tnum_in(rold->var_off, rcur->var_off) &&
17323 		       check_ids(rold->id, rcur->id, idmap) &&
17324 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17325 	case PTR_TO_PACKET_META:
17326 	case PTR_TO_PACKET:
17327 		/* We must have at least as much range as the old ptr
17328 		 * did, so that any accesses which were safe before are
17329 		 * still safe.  This is true even if old range < old off,
17330 		 * since someone could have accessed through (ptr - k), or
17331 		 * even done ptr -= k in a register, to get a safe access.
17332 		 */
17333 		if (rold->range > rcur->range)
17334 			return false;
17335 		/* If the offsets don't match, we can't trust our alignment;
17336 		 * nor can we be sure that we won't fall out of range.
17337 		 */
17338 		if (rold->off != rcur->off)
17339 			return false;
17340 		/* id relations must be preserved */
17341 		if (!check_ids(rold->id, rcur->id, idmap))
17342 			return false;
17343 		/* new val must satisfy old val knowledge */
17344 		return range_within(rold, rcur) &&
17345 		       tnum_in(rold->var_off, rcur->var_off);
17346 	case PTR_TO_STACK:
17347 		/* two stack pointers are equal only if they're pointing to
17348 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
17349 		 */
17350 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
17351 	case PTR_TO_ARENA:
17352 		return true;
17353 	default:
17354 		return regs_exact(rold, rcur, idmap);
17355 	}
17356 }
17357 
17358 static struct bpf_reg_state unbound_reg;
17359 
17360 static __init int unbound_reg_init(void)
17361 {
17362 	__mark_reg_unknown_imprecise(&unbound_reg);
17363 	unbound_reg.live |= REG_LIVE_READ;
17364 	return 0;
17365 }
17366 late_initcall(unbound_reg_init);
17367 
17368 static bool is_stack_all_misc(struct bpf_verifier_env *env,
17369 			      struct bpf_stack_state *stack)
17370 {
17371 	u32 i;
17372 
17373 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
17374 		if ((stack->slot_type[i] == STACK_MISC) ||
17375 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
17376 			continue;
17377 		return false;
17378 	}
17379 
17380 	return true;
17381 }
17382 
17383 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
17384 						  struct bpf_stack_state *stack)
17385 {
17386 	if (is_spilled_scalar_reg64(stack))
17387 		return &stack->spilled_ptr;
17388 
17389 	if (is_stack_all_misc(env, stack))
17390 		return &unbound_reg;
17391 
17392 	return NULL;
17393 }
17394 
17395 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
17396 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
17397 		      enum exact_level exact)
17398 {
17399 	int i, spi;
17400 
17401 	/* walk slots of the explored stack and ignore any additional
17402 	 * slots in the current stack, since explored(safe) state
17403 	 * didn't use them
17404 	 */
17405 	for (i = 0; i < old->allocated_stack; i++) {
17406 		struct bpf_reg_state *old_reg, *cur_reg;
17407 
17408 		spi = i / BPF_REG_SIZE;
17409 
17410 		if (exact != NOT_EXACT &&
17411 		    (i >= cur->allocated_stack ||
17412 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17413 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
17414 			return false;
17415 
17416 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
17417 		    && exact == NOT_EXACT) {
17418 			i += BPF_REG_SIZE - 1;
17419 			/* explored state didn't use this */
17420 			continue;
17421 		}
17422 
17423 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
17424 			continue;
17425 
17426 		if (env->allow_uninit_stack &&
17427 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
17428 			continue;
17429 
17430 		/* explored stack has more populated slots than current stack
17431 		 * and these slots were used
17432 		 */
17433 		if (i >= cur->allocated_stack)
17434 			return false;
17435 
17436 		/* 64-bit scalar spill vs all slots MISC and vice versa.
17437 		 * Load from all slots MISC produces unbound scalar.
17438 		 * Construct a fake register for such stack and call
17439 		 * regsafe() to ensure scalar ids are compared.
17440 		 */
17441 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
17442 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
17443 		if (old_reg && cur_reg) {
17444 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
17445 				return false;
17446 			i += BPF_REG_SIZE - 1;
17447 			continue;
17448 		}
17449 
17450 		/* if old state was safe with misc data in the stack
17451 		 * it will be safe with zero-initialized stack.
17452 		 * The opposite is not true
17453 		 */
17454 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
17455 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
17456 			continue;
17457 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17458 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
17459 			/* Ex: old explored (safe) state has STACK_SPILL in
17460 			 * this stack slot, but current has STACK_MISC ->
17461 			 * this verifier states are not equivalent,
17462 			 * return false to continue verification of this path
17463 			 */
17464 			return false;
17465 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
17466 			continue;
17467 		/* Both old and cur are having same slot_type */
17468 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
17469 		case STACK_SPILL:
17470 			/* when explored and current stack slot are both storing
17471 			 * spilled registers, check that stored pointers types
17472 			 * are the same as well.
17473 			 * Ex: explored safe path could have stored
17474 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
17475 			 * but current path has stored:
17476 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
17477 			 * such verifier states are not equivalent.
17478 			 * return false to continue verification of this path
17479 			 */
17480 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
17481 				     &cur->stack[spi].spilled_ptr, idmap, exact))
17482 				return false;
17483 			break;
17484 		case STACK_DYNPTR:
17485 			old_reg = &old->stack[spi].spilled_ptr;
17486 			cur_reg = &cur->stack[spi].spilled_ptr;
17487 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
17488 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
17489 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
17490 				return false;
17491 			break;
17492 		case STACK_ITER:
17493 			old_reg = &old->stack[spi].spilled_ptr;
17494 			cur_reg = &cur->stack[spi].spilled_ptr;
17495 			/* iter.depth is not compared between states as it
17496 			 * doesn't matter for correctness and would otherwise
17497 			 * prevent convergence; we maintain it only to prevent
17498 			 * infinite loop check triggering, see
17499 			 * iter_active_depths_differ()
17500 			 */
17501 			if (old_reg->iter.btf != cur_reg->iter.btf ||
17502 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
17503 			    old_reg->iter.state != cur_reg->iter.state ||
17504 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
17505 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
17506 				return false;
17507 			break;
17508 		case STACK_MISC:
17509 		case STACK_ZERO:
17510 		case STACK_INVALID:
17511 			continue;
17512 		/* Ensure that new unhandled slot types return false by default */
17513 		default:
17514 			return false;
17515 		}
17516 	}
17517 	return true;
17518 }
17519 
17520 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
17521 		    struct bpf_idmap *idmap)
17522 {
17523 	int i;
17524 
17525 	if (old->acquired_refs != cur->acquired_refs)
17526 		return false;
17527 
17528 	for (i = 0; i < old->acquired_refs; i++) {
17529 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
17530 			return false;
17531 	}
17532 
17533 	return true;
17534 }
17535 
17536 /* compare two verifier states
17537  *
17538  * all states stored in state_list are known to be valid, since
17539  * verifier reached 'bpf_exit' instruction through them
17540  *
17541  * this function is called when verifier exploring different branches of
17542  * execution popped from the state stack. If it sees an old state that has
17543  * more strict register state and more strict stack state then this execution
17544  * branch doesn't need to be explored further, since verifier already
17545  * concluded that more strict state leads to valid finish.
17546  *
17547  * Therefore two states are equivalent if register state is more conservative
17548  * and explored stack state is more conservative than the current one.
17549  * Example:
17550  *       explored                   current
17551  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
17552  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
17553  *
17554  * In other words if current stack state (one being explored) has more
17555  * valid slots than old one that already passed validation, it means
17556  * the verifier can stop exploring and conclude that current state is valid too
17557  *
17558  * Similarly with registers. If explored state has register type as invalid
17559  * whereas register type in current state is meaningful, it means that
17560  * the current state will reach 'bpf_exit' instruction safely
17561  */
17562 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
17563 			      struct bpf_func_state *cur, enum exact_level exact)
17564 {
17565 	int i;
17566 
17567 	if (old->callback_depth > cur->callback_depth)
17568 		return false;
17569 
17570 	for (i = 0; i < MAX_BPF_REG; i++)
17571 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
17572 			     &env->idmap_scratch, exact))
17573 			return false;
17574 
17575 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
17576 		return false;
17577 
17578 	if (!refsafe(old, cur, &env->idmap_scratch))
17579 		return false;
17580 
17581 	return true;
17582 }
17583 
17584 static void reset_idmap_scratch(struct bpf_verifier_env *env)
17585 {
17586 	env->idmap_scratch.tmp_id_gen = env->id_gen;
17587 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
17588 }
17589 
17590 static bool states_equal(struct bpf_verifier_env *env,
17591 			 struct bpf_verifier_state *old,
17592 			 struct bpf_verifier_state *cur,
17593 			 enum exact_level exact)
17594 {
17595 	int i;
17596 
17597 	if (old->curframe != cur->curframe)
17598 		return false;
17599 
17600 	reset_idmap_scratch(env);
17601 
17602 	/* Verification state from speculative execution simulation
17603 	 * must never prune a non-speculative execution one.
17604 	 */
17605 	if (old->speculative && !cur->speculative)
17606 		return false;
17607 
17608 	if (old->active_lock.ptr != cur->active_lock.ptr)
17609 		return false;
17610 
17611 	/* Old and cur active_lock's have to be either both present
17612 	 * or both absent.
17613 	 */
17614 	if (!!old->active_lock.id != !!cur->active_lock.id)
17615 		return false;
17616 
17617 	if (old->active_lock.id &&
17618 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
17619 		return false;
17620 
17621 	if (old->active_rcu_lock != cur->active_rcu_lock)
17622 		return false;
17623 
17624 	if (old->active_preempt_lock != cur->active_preempt_lock)
17625 		return false;
17626 
17627 	if (old->in_sleepable != cur->in_sleepable)
17628 		return false;
17629 
17630 	/* for states to be equal callsites have to be the same
17631 	 * and all frame states need to be equivalent
17632 	 */
17633 	for (i = 0; i <= old->curframe; i++) {
17634 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
17635 			return false;
17636 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
17637 			return false;
17638 	}
17639 	return true;
17640 }
17641 
17642 /* Return 0 if no propagation happened. Return negative error code if error
17643  * happened. Otherwise, return the propagated bit.
17644  */
17645 static int propagate_liveness_reg(struct bpf_verifier_env *env,
17646 				  struct bpf_reg_state *reg,
17647 				  struct bpf_reg_state *parent_reg)
17648 {
17649 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
17650 	u8 flag = reg->live & REG_LIVE_READ;
17651 	int err;
17652 
17653 	/* When comes here, read flags of PARENT_REG or REG could be any of
17654 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
17655 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
17656 	 */
17657 	if (parent_flag == REG_LIVE_READ64 ||
17658 	    /* Or if there is no read flag from REG. */
17659 	    !flag ||
17660 	    /* Or if the read flag from REG is the same as PARENT_REG. */
17661 	    parent_flag == flag)
17662 		return 0;
17663 
17664 	err = mark_reg_read(env, reg, parent_reg, flag);
17665 	if (err)
17666 		return err;
17667 
17668 	return flag;
17669 }
17670 
17671 /* A write screens off any subsequent reads; but write marks come from the
17672  * straight-line code between a state and its parent.  When we arrive at an
17673  * equivalent state (jump target or such) we didn't arrive by the straight-line
17674  * code, so read marks in the state must propagate to the parent regardless
17675  * of the state's write marks. That's what 'parent == state->parent' comparison
17676  * in mark_reg_read() is for.
17677  */
17678 static int propagate_liveness(struct bpf_verifier_env *env,
17679 			      const struct bpf_verifier_state *vstate,
17680 			      struct bpf_verifier_state *vparent)
17681 {
17682 	struct bpf_reg_state *state_reg, *parent_reg;
17683 	struct bpf_func_state *state, *parent;
17684 	int i, frame, err = 0;
17685 
17686 	if (vparent->curframe != vstate->curframe) {
17687 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
17688 		     vparent->curframe, vstate->curframe);
17689 		return -EFAULT;
17690 	}
17691 	/* Propagate read liveness of registers... */
17692 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
17693 	for (frame = 0; frame <= vstate->curframe; frame++) {
17694 		parent = vparent->frame[frame];
17695 		state = vstate->frame[frame];
17696 		parent_reg = parent->regs;
17697 		state_reg = state->regs;
17698 		/* We don't need to worry about FP liveness, it's read-only */
17699 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
17700 			err = propagate_liveness_reg(env, &state_reg[i],
17701 						     &parent_reg[i]);
17702 			if (err < 0)
17703 				return err;
17704 			if (err == REG_LIVE_READ64)
17705 				mark_insn_zext(env, &parent_reg[i]);
17706 		}
17707 
17708 		/* Propagate stack slots. */
17709 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
17710 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
17711 			parent_reg = &parent->stack[i].spilled_ptr;
17712 			state_reg = &state->stack[i].spilled_ptr;
17713 			err = propagate_liveness_reg(env, state_reg,
17714 						     parent_reg);
17715 			if (err < 0)
17716 				return err;
17717 		}
17718 	}
17719 	return 0;
17720 }
17721 
17722 /* find precise scalars in the previous equivalent state and
17723  * propagate them into the current state
17724  */
17725 static int propagate_precision(struct bpf_verifier_env *env,
17726 			       const struct bpf_verifier_state *old)
17727 {
17728 	struct bpf_reg_state *state_reg;
17729 	struct bpf_func_state *state;
17730 	int i, err = 0, fr;
17731 	bool first;
17732 
17733 	for (fr = old->curframe; fr >= 0; fr--) {
17734 		state = old->frame[fr];
17735 		state_reg = state->regs;
17736 		first = true;
17737 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
17738 			if (state_reg->type != SCALAR_VALUE ||
17739 			    !state_reg->precise ||
17740 			    !(state_reg->live & REG_LIVE_READ))
17741 				continue;
17742 			if (env->log.level & BPF_LOG_LEVEL2) {
17743 				if (first)
17744 					verbose(env, "frame %d: propagating r%d", fr, i);
17745 				else
17746 					verbose(env, ",r%d", i);
17747 			}
17748 			bt_set_frame_reg(&env->bt, fr, i);
17749 			first = false;
17750 		}
17751 
17752 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17753 			if (!is_spilled_reg(&state->stack[i]))
17754 				continue;
17755 			state_reg = &state->stack[i].spilled_ptr;
17756 			if (state_reg->type != SCALAR_VALUE ||
17757 			    !state_reg->precise ||
17758 			    !(state_reg->live & REG_LIVE_READ))
17759 				continue;
17760 			if (env->log.level & BPF_LOG_LEVEL2) {
17761 				if (first)
17762 					verbose(env, "frame %d: propagating fp%d",
17763 						fr, (-i - 1) * BPF_REG_SIZE);
17764 				else
17765 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17766 			}
17767 			bt_set_frame_slot(&env->bt, fr, i);
17768 			first = false;
17769 		}
17770 		if (!first)
17771 			verbose(env, "\n");
17772 	}
17773 
17774 	err = mark_chain_precision_batch(env);
17775 	if (err < 0)
17776 		return err;
17777 
17778 	return 0;
17779 }
17780 
17781 static bool states_maybe_looping(struct bpf_verifier_state *old,
17782 				 struct bpf_verifier_state *cur)
17783 {
17784 	struct bpf_func_state *fold, *fcur;
17785 	int i, fr = cur->curframe;
17786 
17787 	if (old->curframe != fr)
17788 		return false;
17789 
17790 	fold = old->frame[fr];
17791 	fcur = cur->frame[fr];
17792 	for (i = 0; i < MAX_BPF_REG; i++)
17793 		if (memcmp(&fold->regs[i], &fcur->regs[i],
17794 			   offsetof(struct bpf_reg_state, parent)))
17795 			return false;
17796 	return true;
17797 }
17798 
17799 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17800 {
17801 	return env->insn_aux_data[insn_idx].is_iter_next;
17802 }
17803 
17804 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17805  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17806  * states to match, which otherwise would look like an infinite loop. So while
17807  * iter_next() calls are taken care of, we still need to be careful and
17808  * prevent erroneous and too eager declaration of "ininite loop", when
17809  * iterators are involved.
17810  *
17811  * Here's a situation in pseudo-BPF assembly form:
17812  *
17813  *   0: again:                          ; set up iter_next() call args
17814  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
17815  *   2:   call bpf_iter_num_next        ; this is iter_next() call
17816  *   3:   if r0 == 0 goto done
17817  *   4:   ... something useful here ...
17818  *   5:   goto again                    ; another iteration
17819  *   6: done:
17820  *   7:   r1 = &it
17821  *   8:   call bpf_iter_num_destroy     ; clean up iter state
17822  *   9:   exit
17823  *
17824  * This is a typical loop. Let's assume that we have a prune point at 1:,
17825  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17826  * again`, assuming other heuristics don't get in a way).
17827  *
17828  * When we first time come to 1:, let's say we have some state X. We proceed
17829  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17830  * Now we come back to validate that forked ACTIVE state. We proceed through
17831  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17832  * are converging. But the problem is that we don't know that yet, as this
17833  * convergence has to happen at iter_next() call site only. So if nothing is
17834  * done, at 1: verifier will use bounded loop logic and declare infinite
17835  * looping (and would be *technically* correct, if not for iterator's
17836  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17837  * don't want that. So what we do in process_iter_next_call() when we go on
17838  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17839  * a different iteration. So when we suspect an infinite loop, we additionally
17840  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17841  * pretend we are not looping and wait for next iter_next() call.
17842  *
17843  * This only applies to ACTIVE state. In DRAINED state we don't expect to
17844  * loop, because that would actually mean infinite loop, as DRAINED state is
17845  * "sticky", and so we'll keep returning into the same instruction with the
17846  * same state (at least in one of possible code paths).
17847  *
17848  * This approach allows to keep infinite loop heuristic even in the face of
17849  * active iterator. E.g., C snippet below is and will be detected as
17850  * inifintely looping:
17851  *
17852  *   struct bpf_iter_num it;
17853  *   int *p, x;
17854  *
17855  *   bpf_iter_num_new(&it, 0, 10);
17856  *   while ((p = bpf_iter_num_next(&t))) {
17857  *       x = p;
17858  *       while (x--) {} // <<-- infinite loop here
17859  *   }
17860  *
17861  */
17862 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17863 {
17864 	struct bpf_reg_state *slot, *cur_slot;
17865 	struct bpf_func_state *state;
17866 	int i, fr;
17867 
17868 	for (fr = old->curframe; fr >= 0; fr--) {
17869 		state = old->frame[fr];
17870 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17871 			if (state->stack[i].slot_type[0] != STACK_ITER)
17872 				continue;
17873 
17874 			slot = &state->stack[i].spilled_ptr;
17875 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17876 				continue;
17877 
17878 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17879 			if (cur_slot->iter.depth != slot->iter.depth)
17880 				return true;
17881 		}
17882 	}
17883 	return false;
17884 }
17885 
17886 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17887 {
17888 	struct bpf_verifier_state_list *new_sl;
17889 	struct bpf_verifier_state_list *sl, **pprev;
17890 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17891 	int i, j, n, err, states_cnt = 0;
17892 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17893 	bool add_new_state = force_new_state;
17894 	bool force_exact;
17895 
17896 	/* bpf progs typically have pruning point every 4 instructions
17897 	 * http://vger.kernel.org/bpfconf2019.html#session-1
17898 	 * Do not add new state for future pruning if the verifier hasn't seen
17899 	 * at least 2 jumps and at least 8 instructions.
17900 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17901 	 * In tests that amounts to up to 50% reduction into total verifier
17902 	 * memory consumption and 20% verifier time speedup.
17903 	 */
17904 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17905 	    env->insn_processed - env->prev_insn_processed >= 8)
17906 		add_new_state = true;
17907 
17908 	pprev = explored_state(env, insn_idx);
17909 	sl = *pprev;
17910 
17911 	clean_live_states(env, insn_idx, cur);
17912 
17913 	while (sl) {
17914 		states_cnt++;
17915 		if (sl->state.insn_idx != insn_idx)
17916 			goto next;
17917 
17918 		if (sl->state.branches) {
17919 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17920 
17921 			if (frame->in_async_callback_fn &&
17922 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17923 				/* Different async_entry_cnt means that the verifier is
17924 				 * processing another entry into async callback.
17925 				 * Seeing the same state is not an indication of infinite
17926 				 * loop or infinite recursion.
17927 				 * But finding the same state doesn't mean that it's safe
17928 				 * to stop processing the current state. The previous state
17929 				 * hasn't yet reached bpf_exit, since state.branches > 0.
17930 				 * Checking in_async_callback_fn alone is not enough either.
17931 				 * Since the verifier still needs to catch infinite loops
17932 				 * inside async callbacks.
17933 				 */
17934 				goto skip_inf_loop_check;
17935 			}
17936 			/* BPF open-coded iterators loop detection is special.
17937 			 * states_maybe_looping() logic is too simplistic in detecting
17938 			 * states that *might* be equivalent, because it doesn't know
17939 			 * about ID remapping, so don't even perform it.
17940 			 * See process_iter_next_call() and iter_active_depths_differ()
17941 			 * for overview of the logic. When current and one of parent
17942 			 * states are detected as equivalent, it's a good thing: we prove
17943 			 * convergence and can stop simulating further iterations.
17944 			 * It's safe to assume that iterator loop will finish, taking into
17945 			 * account iter_next() contract of eventually returning
17946 			 * sticky NULL result.
17947 			 *
17948 			 * Note, that states have to be compared exactly in this case because
17949 			 * read and precision marks might not be finalized inside the loop.
17950 			 * E.g. as in the program below:
17951 			 *
17952 			 *     1. r7 = -16
17953 			 *     2. r6 = bpf_get_prandom_u32()
17954 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
17955 			 *     4.   if (r6 != 42) {
17956 			 *     5.     r7 = -32
17957 			 *     6.     r6 = bpf_get_prandom_u32()
17958 			 *     7.     continue
17959 			 *     8.   }
17960 			 *     9.   r0 = r10
17961 			 *    10.   r0 += r7
17962 			 *    11.   r8 = *(u64 *)(r0 + 0)
17963 			 *    12.   r6 = bpf_get_prandom_u32()
17964 			 *    13. }
17965 			 *
17966 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
17967 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17968 			 * not have read or precision mark for r7 yet, thus inexact states
17969 			 * comparison would discard current state with r7=-32
17970 			 * => unsafe memory access at 11 would not be caught.
17971 			 */
17972 			if (is_iter_next_insn(env, insn_idx)) {
17973 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17974 					struct bpf_func_state *cur_frame;
17975 					struct bpf_reg_state *iter_state, *iter_reg;
17976 					int spi;
17977 
17978 					cur_frame = cur->frame[cur->curframe];
17979 					/* btf_check_iter_kfuncs() enforces that
17980 					 * iter state pointer is always the first arg
17981 					 */
17982 					iter_reg = &cur_frame->regs[BPF_REG_1];
17983 					/* current state is valid due to states_equal(),
17984 					 * so we can assume valid iter and reg state,
17985 					 * no need for extra (re-)validations
17986 					 */
17987 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17988 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17989 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17990 						update_loop_entry(cur, &sl->state);
17991 						goto hit;
17992 					}
17993 				}
17994 				goto skip_inf_loop_check;
17995 			}
17996 			if (is_may_goto_insn_at(env, insn_idx)) {
17997 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
17998 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17999 					update_loop_entry(cur, &sl->state);
18000 					goto hit;
18001 				}
18002 			}
18003 			if (calls_callback(env, insn_idx)) {
18004 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
18005 					goto hit;
18006 				goto skip_inf_loop_check;
18007 			}
18008 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
18009 			if (states_maybe_looping(&sl->state, cur) &&
18010 			    states_equal(env, &sl->state, cur, EXACT) &&
18011 			    !iter_active_depths_differ(&sl->state, cur) &&
18012 			    sl->state.may_goto_depth == cur->may_goto_depth &&
18013 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
18014 				verbose_linfo(env, insn_idx, "; ");
18015 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
18016 				verbose(env, "cur state:");
18017 				print_verifier_state(env, cur->frame[cur->curframe], true);
18018 				verbose(env, "old state:");
18019 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
18020 				return -EINVAL;
18021 			}
18022 			/* if the verifier is processing a loop, avoid adding new state
18023 			 * too often, since different loop iterations have distinct
18024 			 * states and may not help future pruning.
18025 			 * This threshold shouldn't be too low to make sure that
18026 			 * a loop with large bound will be rejected quickly.
18027 			 * The most abusive loop will be:
18028 			 * r1 += 1
18029 			 * if r1 < 1000000 goto pc-2
18030 			 * 1M insn_procssed limit / 100 == 10k peak states.
18031 			 * This threshold shouldn't be too high either, since states
18032 			 * at the end of the loop are likely to be useful in pruning.
18033 			 */
18034 skip_inf_loop_check:
18035 			if (!force_new_state &&
18036 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
18037 			    env->insn_processed - env->prev_insn_processed < 100)
18038 				add_new_state = false;
18039 			goto miss;
18040 		}
18041 		/* If sl->state is a part of a loop and this loop's entry is a part of
18042 		 * current verification path then states have to be compared exactly.
18043 		 * 'force_exact' is needed to catch the following case:
18044 		 *
18045 		 *                initial     Here state 'succ' was processed first,
18046 		 *                  |         it was eventually tracked to produce a
18047 		 *                  V         state identical to 'hdr'.
18048 		 *     .---------> hdr        All branches from 'succ' had been explored
18049 		 *     |            |         and thus 'succ' has its .branches == 0.
18050 		 *     |            V
18051 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
18052 		 *     |    |       |         to the same instruction + callsites.
18053 		 *     |    V       V         In such case it is necessary to check
18054 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
18055 		 *     |    |       |         If 'succ' and 'cur' are a part of the
18056 		 *     |    V       V         same loop exact flag has to be set.
18057 		 *     |   succ <- cur        To check if that is the case, verify
18058 		 *     |    |                 if loop entry of 'succ' is in current
18059 		 *     |    V                 DFS path.
18060 		 *     |   ...
18061 		 *     |    |
18062 		 *     '----'
18063 		 *
18064 		 * Additional details are in the comment before get_loop_entry().
18065 		 */
18066 		loop_entry = get_loop_entry(&sl->state);
18067 		force_exact = loop_entry && loop_entry->branches > 0;
18068 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
18069 			if (force_exact)
18070 				update_loop_entry(cur, loop_entry);
18071 hit:
18072 			sl->hit_cnt++;
18073 			/* reached equivalent register/stack state,
18074 			 * prune the search.
18075 			 * Registers read by the continuation are read by us.
18076 			 * If we have any write marks in env->cur_state, they
18077 			 * will prevent corresponding reads in the continuation
18078 			 * from reaching our parent (an explored_state).  Our
18079 			 * own state will get the read marks recorded, but
18080 			 * they'll be immediately forgotten as we're pruning
18081 			 * this state and will pop a new one.
18082 			 */
18083 			err = propagate_liveness(env, &sl->state, cur);
18084 
18085 			/* if previous state reached the exit with precision and
18086 			 * current state is equivalent to it (except precision marks)
18087 			 * the precision needs to be propagated back in
18088 			 * the current state.
18089 			 */
18090 			if (is_jmp_point(env, env->insn_idx))
18091 				err = err ? : push_jmp_history(env, cur, 0, 0);
18092 			err = err ? : propagate_precision(env, &sl->state);
18093 			if (err)
18094 				return err;
18095 			return 1;
18096 		}
18097 miss:
18098 		/* when new state is not going to be added do not increase miss count.
18099 		 * Otherwise several loop iterations will remove the state
18100 		 * recorded earlier. The goal of these heuristics is to have
18101 		 * states from some iterations of the loop (some in the beginning
18102 		 * and some at the end) to help pruning.
18103 		 */
18104 		if (add_new_state)
18105 			sl->miss_cnt++;
18106 		/* heuristic to determine whether this state is beneficial
18107 		 * to keep checking from state equivalence point of view.
18108 		 * Higher numbers increase max_states_per_insn and verification time,
18109 		 * but do not meaningfully decrease insn_processed.
18110 		 * 'n' controls how many times state could miss before eviction.
18111 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
18112 		 * too early would hinder iterator convergence.
18113 		 */
18114 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
18115 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
18116 			/* the state is unlikely to be useful. Remove it to
18117 			 * speed up verification
18118 			 */
18119 			*pprev = sl->next;
18120 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
18121 			    !sl->state.used_as_loop_entry) {
18122 				u32 br = sl->state.branches;
18123 
18124 				WARN_ONCE(br,
18125 					  "BUG live_done but branches_to_explore %d\n",
18126 					  br);
18127 				free_verifier_state(&sl->state, false);
18128 				kfree(sl);
18129 				env->peak_states--;
18130 			} else {
18131 				/* cannot free this state, since parentage chain may
18132 				 * walk it later. Add it for free_list instead to
18133 				 * be freed at the end of verification
18134 				 */
18135 				sl->next = env->free_list;
18136 				env->free_list = sl;
18137 			}
18138 			sl = *pprev;
18139 			continue;
18140 		}
18141 next:
18142 		pprev = &sl->next;
18143 		sl = *pprev;
18144 	}
18145 
18146 	if (env->max_states_per_insn < states_cnt)
18147 		env->max_states_per_insn = states_cnt;
18148 
18149 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
18150 		return 0;
18151 
18152 	if (!add_new_state)
18153 		return 0;
18154 
18155 	/* There were no equivalent states, remember the current one.
18156 	 * Technically the current state is not proven to be safe yet,
18157 	 * but it will either reach outer most bpf_exit (which means it's safe)
18158 	 * or it will be rejected. When there are no loops the verifier won't be
18159 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
18160 	 * again on the way to bpf_exit.
18161 	 * When looping the sl->state.branches will be > 0 and this state
18162 	 * will not be considered for equivalence until branches == 0.
18163 	 */
18164 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
18165 	if (!new_sl)
18166 		return -ENOMEM;
18167 	env->total_states++;
18168 	env->peak_states++;
18169 	env->prev_jmps_processed = env->jmps_processed;
18170 	env->prev_insn_processed = env->insn_processed;
18171 
18172 	/* forget precise markings we inherited, see __mark_chain_precision */
18173 	if (env->bpf_capable)
18174 		mark_all_scalars_imprecise(env, cur);
18175 
18176 	/* add new state to the head of linked list */
18177 	new = &new_sl->state;
18178 	err = copy_verifier_state(new, cur);
18179 	if (err) {
18180 		free_verifier_state(new, false);
18181 		kfree(new_sl);
18182 		return err;
18183 	}
18184 	new->insn_idx = insn_idx;
18185 	WARN_ONCE(new->branches != 1,
18186 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
18187 
18188 	cur->parent = new;
18189 	cur->first_insn_idx = insn_idx;
18190 	cur->dfs_depth = new->dfs_depth + 1;
18191 	clear_jmp_history(cur);
18192 	new_sl->next = *explored_state(env, insn_idx);
18193 	*explored_state(env, insn_idx) = new_sl;
18194 	/* connect new state to parentage chain. Current frame needs all
18195 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
18196 	 * to the stack implicitly by JITs) so in callers' frames connect just
18197 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
18198 	 * the state of the call instruction (with WRITTEN set), and r0 comes
18199 	 * from callee with its full parentage chain, anyway.
18200 	 */
18201 	/* clear write marks in current state: the writes we did are not writes
18202 	 * our child did, so they don't screen off its reads from us.
18203 	 * (There are no read marks in current state, because reads always mark
18204 	 * their parent and current state never has children yet.  Only
18205 	 * explored_states can get read marks.)
18206 	 */
18207 	for (j = 0; j <= cur->curframe; j++) {
18208 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
18209 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
18210 		for (i = 0; i < BPF_REG_FP; i++)
18211 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
18212 	}
18213 
18214 	/* all stack frames are accessible from callee, clear them all */
18215 	for (j = 0; j <= cur->curframe; j++) {
18216 		struct bpf_func_state *frame = cur->frame[j];
18217 		struct bpf_func_state *newframe = new->frame[j];
18218 
18219 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
18220 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
18221 			frame->stack[i].spilled_ptr.parent =
18222 						&newframe->stack[i].spilled_ptr;
18223 		}
18224 	}
18225 	return 0;
18226 }
18227 
18228 /* Return true if it's OK to have the same insn return a different type. */
18229 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
18230 {
18231 	switch (base_type(type)) {
18232 	case PTR_TO_CTX:
18233 	case PTR_TO_SOCKET:
18234 	case PTR_TO_SOCK_COMMON:
18235 	case PTR_TO_TCP_SOCK:
18236 	case PTR_TO_XDP_SOCK:
18237 	case PTR_TO_BTF_ID:
18238 	case PTR_TO_ARENA:
18239 		return false;
18240 	default:
18241 		return true;
18242 	}
18243 }
18244 
18245 /* If an instruction was previously used with particular pointer types, then we
18246  * need to be careful to avoid cases such as the below, where it may be ok
18247  * for one branch accessing the pointer, but not ok for the other branch:
18248  *
18249  * R1 = sock_ptr
18250  * goto X;
18251  * ...
18252  * R1 = some_other_valid_ptr;
18253  * goto X;
18254  * ...
18255  * R2 = *(u32 *)(R1 + 0);
18256  */
18257 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
18258 {
18259 	return src != prev && (!reg_type_mismatch_ok(src) ||
18260 			       !reg_type_mismatch_ok(prev));
18261 }
18262 
18263 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
18264 			     bool allow_trust_mismatch)
18265 {
18266 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
18267 
18268 	if (*prev_type == NOT_INIT) {
18269 		/* Saw a valid insn
18270 		 * dst_reg = *(u32 *)(src_reg + off)
18271 		 * save type to validate intersecting paths
18272 		 */
18273 		*prev_type = type;
18274 	} else if (reg_type_mismatch(type, *prev_type)) {
18275 		/* Abuser program is trying to use the same insn
18276 		 * dst_reg = *(u32*) (src_reg + off)
18277 		 * with different pointer types:
18278 		 * src_reg == ctx in one branch and
18279 		 * src_reg == stack|map in some other branch.
18280 		 * Reject it.
18281 		 */
18282 		if (allow_trust_mismatch &&
18283 		    base_type(type) == PTR_TO_BTF_ID &&
18284 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
18285 			/*
18286 			 * Have to support a use case when one path through
18287 			 * the program yields TRUSTED pointer while another
18288 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
18289 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
18290 			 */
18291 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
18292 		} else {
18293 			verbose(env, "same insn cannot be used with different pointers\n");
18294 			return -EINVAL;
18295 		}
18296 	}
18297 
18298 	return 0;
18299 }
18300 
18301 static int do_check(struct bpf_verifier_env *env)
18302 {
18303 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18304 	struct bpf_verifier_state *state = env->cur_state;
18305 	struct bpf_insn *insns = env->prog->insnsi;
18306 	struct bpf_reg_state *regs;
18307 	int insn_cnt = env->prog->len;
18308 	bool do_print_state = false;
18309 	int prev_insn_idx = -1;
18310 
18311 	for (;;) {
18312 		bool exception_exit = false;
18313 		struct bpf_insn *insn;
18314 		u8 class;
18315 		int err;
18316 
18317 		/* reset current history entry on each new instruction */
18318 		env->cur_hist_ent = NULL;
18319 
18320 		env->prev_insn_idx = prev_insn_idx;
18321 		if (env->insn_idx >= insn_cnt) {
18322 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
18323 				env->insn_idx, insn_cnt);
18324 			return -EFAULT;
18325 		}
18326 
18327 		insn = &insns[env->insn_idx];
18328 		class = BPF_CLASS(insn->code);
18329 
18330 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
18331 			verbose(env,
18332 				"BPF program is too large. Processed %d insn\n",
18333 				env->insn_processed);
18334 			return -E2BIG;
18335 		}
18336 
18337 		state->last_insn_idx = env->prev_insn_idx;
18338 
18339 		if (is_prune_point(env, env->insn_idx)) {
18340 			err = is_state_visited(env, env->insn_idx);
18341 			if (err < 0)
18342 				return err;
18343 			if (err == 1) {
18344 				/* found equivalent state, can prune the search */
18345 				if (env->log.level & BPF_LOG_LEVEL) {
18346 					if (do_print_state)
18347 						verbose(env, "\nfrom %d to %d%s: safe\n",
18348 							env->prev_insn_idx, env->insn_idx,
18349 							env->cur_state->speculative ?
18350 							" (speculative execution)" : "");
18351 					else
18352 						verbose(env, "%d: safe\n", env->insn_idx);
18353 				}
18354 				goto process_bpf_exit;
18355 			}
18356 		}
18357 
18358 		if (is_jmp_point(env, env->insn_idx)) {
18359 			err = push_jmp_history(env, state, 0, 0);
18360 			if (err)
18361 				return err;
18362 		}
18363 
18364 		if (signal_pending(current))
18365 			return -EAGAIN;
18366 
18367 		if (need_resched())
18368 			cond_resched();
18369 
18370 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
18371 			verbose(env, "\nfrom %d to %d%s:",
18372 				env->prev_insn_idx, env->insn_idx,
18373 				env->cur_state->speculative ?
18374 				" (speculative execution)" : "");
18375 			print_verifier_state(env, state->frame[state->curframe], true);
18376 			do_print_state = false;
18377 		}
18378 
18379 		if (env->log.level & BPF_LOG_LEVEL) {
18380 			const struct bpf_insn_cbs cbs = {
18381 				.cb_call	= disasm_kfunc_name,
18382 				.cb_print	= verbose,
18383 				.private_data	= env,
18384 			};
18385 
18386 			if (verifier_state_scratched(env))
18387 				print_insn_state(env, state->frame[state->curframe]);
18388 
18389 			verbose_linfo(env, env->insn_idx, "; ");
18390 			env->prev_log_pos = env->log.end_pos;
18391 			verbose(env, "%d: ", env->insn_idx);
18392 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
18393 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
18394 			env->prev_log_pos = env->log.end_pos;
18395 		}
18396 
18397 		if (bpf_prog_is_offloaded(env->prog->aux)) {
18398 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
18399 							   env->prev_insn_idx);
18400 			if (err)
18401 				return err;
18402 		}
18403 
18404 		regs = cur_regs(env);
18405 		sanitize_mark_insn_seen(env);
18406 		prev_insn_idx = env->insn_idx;
18407 
18408 		if (class == BPF_ALU || class == BPF_ALU64) {
18409 			err = check_alu_op(env, insn);
18410 			if (err)
18411 				return err;
18412 
18413 		} else if (class == BPF_LDX) {
18414 			enum bpf_reg_type src_reg_type;
18415 
18416 			/* check for reserved fields is already done */
18417 
18418 			/* check src operand */
18419 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
18420 			if (err)
18421 				return err;
18422 
18423 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
18424 			if (err)
18425 				return err;
18426 
18427 			src_reg_type = regs[insn->src_reg].type;
18428 
18429 			/* check that memory (src_reg + off) is readable,
18430 			 * the state of dst_reg will be updated by this func
18431 			 */
18432 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
18433 					       insn->off, BPF_SIZE(insn->code),
18434 					       BPF_READ, insn->dst_reg, false,
18435 					       BPF_MODE(insn->code) == BPF_MEMSX);
18436 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
18437 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
18438 			if (err)
18439 				return err;
18440 		} else if (class == BPF_STX) {
18441 			enum bpf_reg_type dst_reg_type;
18442 
18443 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
18444 				err = check_atomic(env, env->insn_idx, insn);
18445 				if (err)
18446 					return err;
18447 				env->insn_idx++;
18448 				continue;
18449 			}
18450 
18451 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
18452 				verbose(env, "BPF_STX uses reserved fields\n");
18453 				return -EINVAL;
18454 			}
18455 
18456 			/* check src1 operand */
18457 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
18458 			if (err)
18459 				return err;
18460 			/* check src2 operand */
18461 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18462 			if (err)
18463 				return err;
18464 
18465 			dst_reg_type = regs[insn->dst_reg].type;
18466 
18467 			/* check that memory (dst_reg + off) is writeable */
18468 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
18469 					       insn->off, BPF_SIZE(insn->code),
18470 					       BPF_WRITE, insn->src_reg, false, false);
18471 			if (err)
18472 				return err;
18473 
18474 			err = save_aux_ptr_type(env, dst_reg_type, false);
18475 			if (err)
18476 				return err;
18477 		} else if (class == BPF_ST) {
18478 			enum bpf_reg_type dst_reg_type;
18479 
18480 			if (BPF_MODE(insn->code) != BPF_MEM ||
18481 			    insn->src_reg != BPF_REG_0) {
18482 				verbose(env, "BPF_ST uses reserved fields\n");
18483 				return -EINVAL;
18484 			}
18485 			/* check src operand */
18486 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18487 			if (err)
18488 				return err;
18489 
18490 			dst_reg_type = regs[insn->dst_reg].type;
18491 
18492 			/* check that memory (dst_reg + off) is writeable */
18493 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
18494 					       insn->off, BPF_SIZE(insn->code),
18495 					       BPF_WRITE, -1, false, false);
18496 			if (err)
18497 				return err;
18498 
18499 			err = save_aux_ptr_type(env, dst_reg_type, false);
18500 			if (err)
18501 				return err;
18502 		} else if (class == BPF_JMP || class == BPF_JMP32) {
18503 			u8 opcode = BPF_OP(insn->code);
18504 
18505 			env->jmps_processed++;
18506 			if (opcode == BPF_CALL) {
18507 				if (BPF_SRC(insn->code) != BPF_K ||
18508 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
18509 				     && insn->off != 0) ||
18510 				    (insn->src_reg != BPF_REG_0 &&
18511 				     insn->src_reg != BPF_PSEUDO_CALL &&
18512 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
18513 				    insn->dst_reg != BPF_REG_0 ||
18514 				    class == BPF_JMP32) {
18515 					verbose(env, "BPF_CALL uses reserved fields\n");
18516 					return -EINVAL;
18517 				}
18518 
18519 				if (env->cur_state->active_lock.ptr) {
18520 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
18521 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
18522 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
18523 						verbose(env, "function calls are not allowed while holding a lock\n");
18524 						return -EINVAL;
18525 					}
18526 				}
18527 				if (insn->src_reg == BPF_PSEUDO_CALL) {
18528 					err = check_func_call(env, insn, &env->insn_idx);
18529 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18530 					err = check_kfunc_call(env, insn, &env->insn_idx);
18531 					if (!err && is_bpf_throw_kfunc(insn)) {
18532 						exception_exit = true;
18533 						goto process_bpf_exit_full;
18534 					}
18535 				} else {
18536 					err = check_helper_call(env, insn, &env->insn_idx);
18537 				}
18538 				if (err)
18539 					return err;
18540 
18541 				mark_reg_scratched(env, BPF_REG_0);
18542 			} else if (opcode == BPF_JA) {
18543 				if (BPF_SRC(insn->code) != BPF_K ||
18544 				    insn->src_reg != BPF_REG_0 ||
18545 				    insn->dst_reg != BPF_REG_0 ||
18546 				    (class == BPF_JMP && insn->imm != 0) ||
18547 				    (class == BPF_JMP32 && insn->off != 0)) {
18548 					verbose(env, "BPF_JA uses reserved fields\n");
18549 					return -EINVAL;
18550 				}
18551 
18552 				if (class == BPF_JMP)
18553 					env->insn_idx += insn->off + 1;
18554 				else
18555 					env->insn_idx += insn->imm + 1;
18556 				continue;
18557 
18558 			} else if (opcode == BPF_EXIT) {
18559 				if (BPF_SRC(insn->code) != BPF_K ||
18560 				    insn->imm != 0 ||
18561 				    insn->src_reg != BPF_REG_0 ||
18562 				    insn->dst_reg != BPF_REG_0 ||
18563 				    class == BPF_JMP32) {
18564 					verbose(env, "BPF_EXIT uses reserved fields\n");
18565 					return -EINVAL;
18566 				}
18567 process_bpf_exit_full:
18568 				if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
18569 					verbose(env, "bpf_spin_unlock is missing\n");
18570 					return -EINVAL;
18571 				}
18572 
18573 				if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
18574 					verbose(env, "bpf_rcu_read_unlock is missing\n");
18575 					return -EINVAL;
18576 				}
18577 
18578 				if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) {
18579 					verbose(env, "%d bpf_preempt_enable%s missing\n",
18580 						env->cur_state->active_preempt_lock,
18581 						env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are");
18582 					return -EINVAL;
18583 				}
18584 
18585 				/* We must do check_reference_leak here before
18586 				 * prepare_func_exit to handle the case when
18587 				 * state->curframe > 0, it may be a callback
18588 				 * function, for which reference_state must
18589 				 * match caller reference state when it exits.
18590 				 */
18591 				err = check_reference_leak(env, exception_exit);
18592 				if (err)
18593 					return err;
18594 
18595 				/* The side effect of the prepare_func_exit
18596 				 * which is being skipped is that it frees
18597 				 * bpf_func_state. Typically, process_bpf_exit
18598 				 * will only be hit with outermost exit.
18599 				 * copy_verifier_state in pop_stack will handle
18600 				 * freeing of any extra bpf_func_state left over
18601 				 * from not processing all nested function
18602 				 * exits. We also skip return code checks as
18603 				 * they are not needed for exceptional exits.
18604 				 */
18605 				if (exception_exit)
18606 					goto process_bpf_exit;
18607 
18608 				if (state->curframe) {
18609 					/* exit from nested function */
18610 					err = prepare_func_exit(env, &env->insn_idx);
18611 					if (err)
18612 						return err;
18613 					do_print_state = true;
18614 					continue;
18615 				}
18616 
18617 				err = check_return_code(env, BPF_REG_0, "R0");
18618 				if (err)
18619 					return err;
18620 process_bpf_exit:
18621 				mark_verifier_state_scratched(env);
18622 				update_branch_counts(env, env->cur_state);
18623 				err = pop_stack(env, &prev_insn_idx,
18624 						&env->insn_idx, pop_log);
18625 				if (err < 0) {
18626 					if (err != -ENOENT)
18627 						return err;
18628 					break;
18629 				} else {
18630 					do_print_state = true;
18631 					continue;
18632 				}
18633 			} else {
18634 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
18635 				if (err)
18636 					return err;
18637 			}
18638 		} else if (class == BPF_LD) {
18639 			u8 mode = BPF_MODE(insn->code);
18640 
18641 			if (mode == BPF_ABS || mode == BPF_IND) {
18642 				err = check_ld_abs(env, insn);
18643 				if (err)
18644 					return err;
18645 
18646 			} else if (mode == BPF_IMM) {
18647 				err = check_ld_imm(env, insn);
18648 				if (err)
18649 					return err;
18650 
18651 				env->insn_idx++;
18652 				sanitize_mark_insn_seen(env);
18653 			} else {
18654 				verbose(env, "invalid BPF_LD mode\n");
18655 				return -EINVAL;
18656 			}
18657 		} else {
18658 			verbose(env, "unknown insn class %d\n", class);
18659 			return -EINVAL;
18660 		}
18661 
18662 		env->insn_idx++;
18663 	}
18664 
18665 	return 0;
18666 }
18667 
18668 static int find_btf_percpu_datasec(struct btf *btf)
18669 {
18670 	const struct btf_type *t;
18671 	const char *tname;
18672 	int i, n;
18673 
18674 	/*
18675 	 * Both vmlinux and module each have their own ".data..percpu"
18676 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
18677 	 * types to look at only module's own BTF types.
18678 	 */
18679 	n = btf_nr_types(btf);
18680 	if (btf_is_module(btf))
18681 		i = btf_nr_types(btf_vmlinux);
18682 	else
18683 		i = 1;
18684 
18685 	for(; i < n; i++) {
18686 		t = btf_type_by_id(btf, i);
18687 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
18688 			continue;
18689 
18690 		tname = btf_name_by_offset(btf, t->name_off);
18691 		if (!strcmp(tname, ".data..percpu"))
18692 			return i;
18693 	}
18694 
18695 	return -ENOENT;
18696 }
18697 
18698 /* replace pseudo btf_id with kernel symbol address */
18699 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
18700 			       struct bpf_insn *insn,
18701 			       struct bpf_insn_aux_data *aux)
18702 {
18703 	const struct btf_var_secinfo *vsi;
18704 	const struct btf_type *datasec;
18705 	struct btf_mod_pair *btf_mod;
18706 	const struct btf_type *t;
18707 	const char *sym_name;
18708 	bool percpu = false;
18709 	u32 type, id = insn->imm;
18710 	struct btf *btf;
18711 	s32 datasec_id;
18712 	u64 addr;
18713 	int i, btf_fd, err;
18714 
18715 	btf_fd = insn[1].imm;
18716 	if (btf_fd) {
18717 		btf = btf_get_by_fd(btf_fd);
18718 		if (IS_ERR(btf)) {
18719 			verbose(env, "invalid module BTF object FD specified.\n");
18720 			return -EINVAL;
18721 		}
18722 	} else {
18723 		if (!btf_vmlinux) {
18724 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18725 			return -EINVAL;
18726 		}
18727 		btf = btf_vmlinux;
18728 		btf_get(btf);
18729 	}
18730 
18731 	t = btf_type_by_id(btf, id);
18732 	if (!t) {
18733 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18734 		err = -ENOENT;
18735 		goto err_put;
18736 	}
18737 
18738 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18739 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18740 		err = -EINVAL;
18741 		goto err_put;
18742 	}
18743 
18744 	sym_name = btf_name_by_offset(btf, t->name_off);
18745 	addr = kallsyms_lookup_name(sym_name);
18746 	if (!addr) {
18747 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18748 			sym_name);
18749 		err = -ENOENT;
18750 		goto err_put;
18751 	}
18752 	insn[0].imm = (u32)addr;
18753 	insn[1].imm = addr >> 32;
18754 
18755 	if (btf_type_is_func(t)) {
18756 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18757 		aux->btf_var.mem_size = 0;
18758 		goto check_btf;
18759 	}
18760 
18761 	datasec_id = find_btf_percpu_datasec(btf);
18762 	if (datasec_id > 0) {
18763 		datasec = btf_type_by_id(btf, datasec_id);
18764 		for_each_vsi(i, datasec, vsi) {
18765 			if (vsi->type == id) {
18766 				percpu = true;
18767 				break;
18768 			}
18769 		}
18770 	}
18771 
18772 	type = t->type;
18773 	t = btf_type_skip_modifiers(btf, type, NULL);
18774 	if (percpu) {
18775 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18776 		aux->btf_var.btf = btf;
18777 		aux->btf_var.btf_id = type;
18778 	} else if (!btf_type_is_struct(t)) {
18779 		const struct btf_type *ret;
18780 		const char *tname;
18781 		u32 tsize;
18782 
18783 		/* resolve the type size of ksym. */
18784 		ret = btf_resolve_size(btf, t, &tsize);
18785 		if (IS_ERR(ret)) {
18786 			tname = btf_name_by_offset(btf, t->name_off);
18787 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18788 				tname, PTR_ERR(ret));
18789 			err = -EINVAL;
18790 			goto err_put;
18791 		}
18792 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18793 		aux->btf_var.mem_size = tsize;
18794 	} else {
18795 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
18796 		aux->btf_var.btf = btf;
18797 		aux->btf_var.btf_id = type;
18798 	}
18799 check_btf:
18800 	/* check whether we recorded this BTF (and maybe module) already */
18801 	for (i = 0; i < env->used_btf_cnt; i++) {
18802 		if (env->used_btfs[i].btf == btf) {
18803 			btf_put(btf);
18804 			return 0;
18805 		}
18806 	}
18807 
18808 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
18809 		err = -E2BIG;
18810 		goto err_put;
18811 	}
18812 
18813 	btf_mod = &env->used_btfs[env->used_btf_cnt];
18814 	btf_mod->btf = btf;
18815 	btf_mod->module = NULL;
18816 
18817 	/* if we reference variables from kernel module, bump its refcount */
18818 	if (btf_is_module(btf)) {
18819 		btf_mod->module = btf_try_get_module(btf);
18820 		if (!btf_mod->module) {
18821 			err = -ENXIO;
18822 			goto err_put;
18823 		}
18824 	}
18825 
18826 	env->used_btf_cnt++;
18827 
18828 	return 0;
18829 err_put:
18830 	btf_put(btf);
18831 	return err;
18832 }
18833 
18834 static bool is_tracing_prog_type(enum bpf_prog_type type)
18835 {
18836 	switch (type) {
18837 	case BPF_PROG_TYPE_KPROBE:
18838 	case BPF_PROG_TYPE_TRACEPOINT:
18839 	case BPF_PROG_TYPE_PERF_EVENT:
18840 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
18841 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18842 		return true;
18843 	default:
18844 		return false;
18845 	}
18846 }
18847 
18848 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18849 					struct bpf_map *map,
18850 					struct bpf_prog *prog)
18851 
18852 {
18853 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18854 
18855 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18856 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
18857 		if (is_tracing_prog_type(prog_type)) {
18858 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18859 			return -EINVAL;
18860 		}
18861 	}
18862 
18863 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18864 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18865 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18866 			return -EINVAL;
18867 		}
18868 
18869 		if (is_tracing_prog_type(prog_type)) {
18870 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18871 			return -EINVAL;
18872 		}
18873 	}
18874 
18875 	if (btf_record_has_field(map->record, BPF_TIMER)) {
18876 		if (is_tracing_prog_type(prog_type)) {
18877 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
18878 			return -EINVAL;
18879 		}
18880 	}
18881 
18882 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
18883 		if (is_tracing_prog_type(prog_type)) {
18884 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
18885 			return -EINVAL;
18886 		}
18887 	}
18888 
18889 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18890 	    !bpf_offload_prog_map_match(prog, map)) {
18891 		verbose(env, "offload device mismatch between prog and map\n");
18892 		return -EINVAL;
18893 	}
18894 
18895 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18896 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18897 		return -EINVAL;
18898 	}
18899 
18900 	if (prog->sleepable)
18901 		switch (map->map_type) {
18902 		case BPF_MAP_TYPE_HASH:
18903 		case BPF_MAP_TYPE_LRU_HASH:
18904 		case BPF_MAP_TYPE_ARRAY:
18905 		case BPF_MAP_TYPE_PERCPU_HASH:
18906 		case BPF_MAP_TYPE_PERCPU_ARRAY:
18907 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18908 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18909 		case BPF_MAP_TYPE_HASH_OF_MAPS:
18910 		case BPF_MAP_TYPE_RINGBUF:
18911 		case BPF_MAP_TYPE_USER_RINGBUF:
18912 		case BPF_MAP_TYPE_INODE_STORAGE:
18913 		case BPF_MAP_TYPE_SK_STORAGE:
18914 		case BPF_MAP_TYPE_TASK_STORAGE:
18915 		case BPF_MAP_TYPE_CGRP_STORAGE:
18916 		case BPF_MAP_TYPE_QUEUE:
18917 		case BPF_MAP_TYPE_STACK:
18918 		case BPF_MAP_TYPE_ARENA:
18919 			break;
18920 		default:
18921 			verbose(env,
18922 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18923 			return -EINVAL;
18924 		}
18925 
18926 	return 0;
18927 }
18928 
18929 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18930 {
18931 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18932 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18933 }
18934 
18935 /* Add map behind fd to used maps list, if it's not already there, and return
18936  * its index. Also set *reused to true if this map was already in the list of
18937  * used maps.
18938  * Returns <0 on error, or >= 0 index, on success.
18939  */
18940 static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reused)
18941 {
18942 	CLASS(fd, f)(fd);
18943 	struct bpf_map *map;
18944 	int i;
18945 
18946 	map = __bpf_map_get(f);
18947 	if (IS_ERR(map)) {
18948 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
18949 		return PTR_ERR(map);
18950 	}
18951 
18952 	/* check whether we recorded this map already */
18953 	for (i = 0; i < env->used_map_cnt; i++) {
18954 		if (env->used_maps[i] == map) {
18955 			*reused = true;
18956 			return i;
18957 		}
18958 	}
18959 
18960 	if (env->used_map_cnt >= MAX_USED_MAPS) {
18961 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
18962 			MAX_USED_MAPS);
18963 		return -E2BIG;
18964 	}
18965 
18966 	if (env->prog->sleepable)
18967 		atomic64_inc(&map->sleepable_refcnt);
18968 
18969 	/* hold the map. If the program is rejected by verifier,
18970 	 * the map will be released by release_maps() or it
18971 	 * will be used by the valid program until it's unloaded
18972 	 * and all maps are released in bpf_free_used_maps()
18973 	 */
18974 	bpf_map_inc(map);
18975 
18976 	*reused = false;
18977 	env->used_maps[env->used_map_cnt++] = map;
18978 
18979 	return env->used_map_cnt - 1;
18980 }
18981 
18982 /* find and rewrite pseudo imm in ld_imm64 instructions:
18983  *
18984  * 1. if it accesses map FD, replace it with actual map pointer.
18985  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18986  *
18987  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18988  */
18989 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18990 {
18991 	struct bpf_insn *insn = env->prog->insnsi;
18992 	int insn_cnt = env->prog->len;
18993 	int i, err;
18994 
18995 	err = bpf_prog_calc_tag(env->prog);
18996 	if (err)
18997 		return err;
18998 
18999 	for (i = 0; i < insn_cnt; i++, insn++) {
19000 		if (BPF_CLASS(insn->code) == BPF_LDX &&
19001 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
19002 		    insn->imm != 0)) {
19003 			verbose(env, "BPF_LDX uses reserved fields\n");
19004 			return -EINVAL;
19005 		}
19006 
19007 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
19008 			struct bpf_insn_aux_data *aux;
19009 			struct bpf_map *map;
19010 			int map_idx;
19011 			u64 addr;
19012 			u32 fd;
19013 			bool reused;
19014 
19015 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
19016 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
19017 			    insn[1].off != 0) {
19018 				verbose(env, "invalid bpf_ld_imm64 insn\n");
19019 				return -EINVAL;
19020 			}
19021 
19022 			if (insn[0].src_reg == 0)
19023 				/* valid generic load 64-bit imm */
19024 				goto next_insn;
19025 
19026 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
19027 				aux = &env->insn_aux_data[i];
19028 				err = check_pseudo_btf_id(env, insn, aux);
19029 				if (err)
19030 					return err;
19031 				goto next_insn;
19032 			}
19033 
19034 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
19035 				aux = &env->insn_aux_data[i];
19036 				aux->ptr_type = PTR_TO_FUNC;
19037 				goto next_insn;
19038 			}
19039 
19040 			/* In final convert_pseudo_ld_imm64() step, this is
19041 			 * converted into regular 64-bit imm load insn.
19042 			 */
19043 			switch (insn[0].src_reg) {
19044 			case BPF_PSEUDO_MAP_VALUE:
19045 			case BPF_PSEUDO_MAP_IDX_VALUE:
19046 				break;
19047 			case BPF_PSEUDO_MAP_FD:
19048 			case BPF_PSEUDO_MAP_IDX:
19049 				if (insn[1].imm == 0)
19050 					break;
19051 				fallthrough;
19052 			default:
19053 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
19054 				return -EINVAL;
19055 			}
19056 
19057 			switch (insn[0].src_reg) {
19058 			case BPF_PSEUDO_MAP_IDX_VALUE:
19059 			case BPF_PSEUDO_MAP_IDX:
19060 				if (bpfptr_is_null(env->fd_array)) {
19061 					verbose(env, "fd_idx without fd_array is invalid\n");
19062 					return -EPROTO;
19063 				}
19064 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
19065 							    insn[0].imm * sizeof(fd),
19066 							    sizeof(fd)))
19067 					return -EFAULT;
19068 				break;
19069 			default:
19070 				fd = insn[0].imm;
19071 				break;
19072 			}
19073 
19074 			map_idx = add_used_map_from_fd(env, fd, &reused);
19075 			if (map_idx < 0)
19076 				return map_idx;
19077 			map = env->used_maps[map_idx];
19078 
19079 			aux = &env->insn_aux_data[i];
19080 			aux->map_index = map_idx;
19081 
19082 			err = check_map_prog_compatibility(env, map, env->prog);
19083 			if (err)
19084 				return err;
19085 
19086 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
19087 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
19088 				addr = (unsigned long)map;
19089 			} else {
19090 				u32 off = insn[1].imm;
19091 
19092 				if (off >= BPF_MAX_VAR_OFF) {
19093 					verbose(env, "direct value offset of %u is not allowed\n", off);
19094 					return -EINVAL;
19095 				}
19096 
19097 				if (!map->ops->map_direct_value_addr) {
19098 					verbose(env, "no direct value access support for this map type\n");
19099 					return -EINVAL;
19100 				}
19101 
19102 				err = map->ops->map_direct_value_addr(map, &addr, off);
19103 				if (err) {
19104 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
19105 						map->value_size, off);
19106 					return err;
19107 				}
19108 
19109 				aux->map_off = off;
19110 				addr += off;
19111 			}
19112 
19113 			insn[0].imm = (u32)addr;
19114 			insn[1].imm = addr >> 32;
19115 
19116 			/* proceed with extra checks only if its newly added used map */
19117 			if (reused)
19118 				goto next_insn;
19119 
19120 			if (bpf_map_is_cgroup_storage(map) &&
19121 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
19122 				verbose(env, "only one cgroup storage of each type is allowed\n");
19123 				return -EBUSY;
19124 			}
19125 			if (map->map_type == BPF_MAP_TYPE_ARENA) {
19126 				if (env->prog->aux->arena) {
19127 					verbose(env, "Only one arena per program\n");
19128 					return -EBUSY;
19129 				}
19130 				if (!env->allow_ptr_leaks || !env->bpf_capable) {
19131 					verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
19132 					return -EPERM;
19133 				}
19134 				if (!env->prog->jit_requested) {
19135 					verbose(env, "JIT is required to use arena\n");
19136 					return -EOPNOTSUPP;
19137 				}
19138 				if (!bpf_jit_supports_arena()) {
19139 					verbose(env, "JIT doesn't support arena\n");
19140 					return -EOPNOTSUPP;
19141 				}
19142 				env->prog->aux->arena = (void *)map;
19143 				if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
19144 					verbose(env, "arena's user address must be set via map_extra or mmap()\n");
19145 					return -EINVAL;
19146 				}
19147 			}
19148 
19149 next_insn:
19150 			insn++;
19151 			i++;
19152 			continue;
19153 		}
19154 
19155 		/* Basic sanity check before we invest more work here. */
19156 		if (!bpf_opcode_in_insntable(insn->code)) {
19157 			verbose(env, "unknown opcode %02x\n", insn->code);
19158 			return -EINVAL;
19159 		}
19160 	}
19161 
19162 	/* now all pseudo BPF_LD_IMM64 instructions load valid
19163 	 * 'struct bpf_map *' into a register instead of user map_fd.
19164 	 * These pointers will be used later by verifier to validate map access.
19165 	 */
19166 	return 0;
19167 }
19168 
19169 /* drop refcnt of maps used by the rejected program */
19170 static void release_maps(struct bpf_verifier_env *env)
19171 {
19172 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
19173 			     env->used_map_cnt);
19174 }
19175 
19176 /* drop refcnt of maps used by the rejected program */
19177 static void release_btfs(struct bpf_verifier_env *env)
19178 {
19179 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
19180 }
19181 
19182 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
19183 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
19184 {
19185 	struct bpf_insn *insn = env->prog->insnsi;
19186 	int insn_cnt = env->prog->len;
19187 	int i;
19188 
19189 	for (i = 0; i < insn_cnt; i++, insn++) {
19190 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
19191 			continue;
19192 		if (insn->src_reg == BPF_PSEUDO_FUNC)
19193 			continue;
19194 		insn->src_reg = 0;
19195 	}
19196 }
19197 
19198 /* single env->prog->insni[off] instruction was replaced with the range
19199  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
19200  * [0, off) and [off, end) to new locations, so the patched range stays zero
19201  */
19202 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
19203 				 struct bpf_insn_aux_data *new_data,
19204 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
19205 {
19206 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
19207 	struct bpf_insn *insn = new_prog->insnsi;
19208 	u32 old_seen = old_data[off].seen;
19209 	u32 prog_len;
19210 	int i;
19211 
19212 	/* aux info at OFF always needs adjustment, no matter fast path
19213 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
19214 	 * original insn at old prog.
19215 	 */
19216 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
19217 
19218 	if (cnt == 1)
19219 		return;
19220 	prog_len = new_prog->len;
19221 
19222 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
19223 	memcpy(new_data + off + cnt - 1, old_data + off,
19224 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
19225 	for (i = off; i < off + cnt - 1; i++) {
19226 		/* Expand insni[off]'s seen count to the patched range. */
19227 		new_data[i].seen = old_seen;
19228 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
19229 	}
19230 	env->insn_aux_data = new_data;
19231 	vfree(old_data);
19232 }
19233 
19234 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
19235 {
19236 	int i;
19237 
19238 	if (len == 1)
19239 		return;
19240 	/* NOTE: fake 'exit' subprog should be updated as well. */
19241 	for (i = 0; i <= env->subprog_cnt; i++) {
19242 		if (env->subprog_info[i].start <= off)
19243 			continue;
19244 		env->subprog_info[i].start += len - 1;
19245 	}
19246 }
19247 
19248 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
19249 {
19250 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
19251 	int i, sz = prog->aux->size_poke_tab;
19252 	struct bpf_jit_poke_descriptor *desc;
19253 
19254 	for (i = 0; i < sz; i++) {
19255 		desc = &tab[i];
19256 		if (desc->insn_idx <= off)
19257 			continue;
19258 		desc->insn_idx += len - 1;
19259 	}
19260 }
19261 
19262 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
19263 					    const struct bpf_insn *patch, u32 len)
19264 {
19265 	struct bpf_prog *new_prog;
19266 	struct bpf_insn_aux_data *new_data = NULL;
19267 
19268 	if (len > 1) {
19269 		new_data = vzalloc(array_size(env->prog->len + len - 1,
19270 					      sizeof(struct bpf_insn_aux_data)));
19271 		if (!new_data)
19272 			return NULL;
19273 	}
19274 
19275 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
19276 	if (IS_ERR(new_prog)) {
19277 		if (PTR_ERR(new_prog) == -ERANGE)
19278 			verbose(env,
19279 				"insn %d cannot be patched due to 16-bit range\n",
19280 				env->insn_aux_data[off].orig_idx);
19281 		vfree(new_data);
19282 		return NULL;
19283 	}
19284 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
19285 	adjust_subprog_starts(env, off, len);
19286 	adjust_poke_descs(new_prog, off, len);
19287 	return new_prog;
19288 }
19289 
19290 /*
19291  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
19292  * jump offset by 'delta'.
19293  */
19294 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
19295 {
19296 	struct bpf_insn *insn = prog->insnsi;
19297 	u32 insn_cnt = prog->len, i;
19298 	s32 imm;
19299 	s16 off;
19300 
19301 	for (i = 0; i < insn_cnt; i++, insn++) {
19302 		u8 code = insn->code;
19303 
19304 		if (tgt_idx <= i && i < tgt_idx + delta)
19305 			continue;
19306 
19307 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
19308 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
19309 			continue;
19310 
19311 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
19312 			if (i + 1 + insn->imm != tgt_idx)
19313 				continue;
19314 			if (check_add_overflow(insn->imm, delta, &imm))
19315 				return -ERANGE;
19316 			insn->imm = imm;
19317 		} else {
19318 			if (i + 1 + insn->off != tgt_idx)
19319 				continue;
19320 			if (check_add_overflow(insn->off, delta, &off))
19321 				return -ERANGE;
19322 			insn->off = off;
19323 		}
19324 	}
19325 	return 0;
19326 }
19327 
19328 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
19329 					      u32 off, u32 cnt)
19330 {
19331 	int i, j;
19332 
19333 	/* find first prog starting at or after off (first to remove) */
19334 	for (i = 0; i < env->subprog_cnt; i++)
19335 		if (env->subprog_info[i].start >= off)
19336 			break;
19337 	/* find first prog starting at or after off + cnt (first to stay) */
19338 	for (j = i; j < env->subprog_cnt; j++)
19339 		if (env->subprog_info[j].start >= off + cnt)
19340 			break;
19341 	/* if j doesn't start exactly at off + cnt, we are just removing
19342 	 * the front of previous prog
19343 	 */
19344 	if (env->subprog_info[j].start != off + cnt)
19345 		j--;
19346 
19347 	if (j > i) {
19348 		struct bpf_prog_aux *aux = env->prog->aux;
19349 		int move;
19350 
19351 		/* move fake 'exit' subprog as well */
19352 		move = env->subprog_cnt + 1 - j;
19353 
19354 		memmove(env->subprog_info + i,
19355 			env->subprog_info + j,
19356 			sizeof(*env->subprog_info) * move);
19357 		env->subprog_cnt -= j - i;
19358 
19359 		/* remove func_info */
19360 		if (aux->func_info) {
19361 			move = aux->func_info_cnt - j;
19362 
19363 			memmove(aux->func_info + i,
19364 				aux->func_info + j,
19365 				sizeof(*aux->func_info) * move);
19366 			aux->func_info_cnt -= j - i;
19367 			/* func_info->insn_off is set after all code rewrites,
19368 			 * in adjust_btf_func() - no need to adjust
19369 			 */
19370 		}
19371 	} else {
19372 		/* convert i from "first prog to remove" to "first to adjust" */
19373 		if (env->subprog_info[i].start == off)
19374 			i++;
19375 	}
19376 
19377 	/* update fake 'exit' subprog as well */
19378 	for (; i <= env->subprog_cnt; i++)
19379 		env->subprog_info[i].start -= cnt;
19380 
19381 	return 0;
19382 }
19383 
19384 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
19385 				      u32 cnt)
19386 {
19387 	struct bpf_prog *prog = env->prog;
19388 	u32 i, l_off, l_cnt, nr_linfo;
19389 	struct bpf_line_info *linfo;
19390 
19391 	nr_linfo = prog->aux->nr_linfo;
19392 	if (!nr_linfo)
19393 		return 0;
19394 
19395 	linfo = prog->aux->linfo;
19396 
19397 	/* find first line info to remove, count lines to be removed */
19398 	for (i = 0; i < nr_linfo; i++)
19399 		if (linfo[i].insn_off >= off)
19400 			break;
19401 
19402 	l_off = i;
19403 	l_cnt = 0;
19404 	for (; i < nr_linfo; i++)
19405 		if (linfo[i].insn_off < off + cnt)
19406 			l_cnt++;
19407 		else
19408 			break;
19409 
19410 	/* First live insn doesn't match first live linfo, it needs to "inherit"
19411 	 * last removed linfo.  prog is already modified, so prog->len == off
19412 	 * means no live instructions after (tail of the program was removed).
19413 	 */
19414 	if (prog->len != off && l_cnt &&
19415 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
19416 		l_cnt--;
19417 		linfo[--i].insn_off = off + cnt;
19418 	}
19419 
19420 	/* remove the line info which refer to the removed instructions */
19421 	if (l_cnt) {
19422 		memmove(linfo + l_off, linfo + i,
19423 			sizeof(*linfo) * (nr_linfo - i));
19424 
19425 		prog->aux->nr_linfo -= l_cnt;
19426 		nr_linfo = prog->aux->nr_linfo;
19427 	}
19428 
19429 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
19430 	for (i = l_off; i < nr_linfo; i++)
19431 		linfo[i].insn_off -= cnt;
19432 
19433 	/* fix up all subprogs (incl. 'exit') which start >= off */
19434 	for (i = 0; i <= env->subprog_cnt; i++)
19435 		if (env->subprog_info[i].linfo_idx > l_off) {
19436 			/* program may have started in the removed region but
19437 			 * may not be fully removed
19438 			 */
19439 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
19440 				env->subprog_info[i].linfo_idx -= l_cnt;
19441 			else
19442 				env->subprog_info[i].linfo_idx = l_off;
19443 		}
19444 
19445 	return 0;
19446 }
19447 
19448 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
19449 {
19450 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19451 	unsigned int orig_prog_len = env->prog->len;
19452 	int err;
19453 
19454 	if (bpf_prog_is_offloaded(env->prog->aux))
19455 		bpf_prog_offload_remove_insns(env, off, cnt);
19456 
19457 	err = bpf_remove_insns(env->prog, off, cnt);
19458 	if (err)
19459 		return err;
19460 
19461 	err = adjust_subprog_starts_after_remove(env, off, cnt);
19462 	if (err)
19463 		return err;
19464 
19465 	err = bpf_adj_linfo_after_remove(env, off, cnt);
19466 	if (err)
19467 		return err;
19468 
19469 	memmove(aux_data + off,	aux_data + off + cnt,
19470 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
19471 
19472 	return 0;
19473 }
19474 
19475 /* The verifier does more data flow analysis than llvm and will not
19476  * explore branches that are dead at run time. Malicious programs can
19477  * have dead code too. Therefore replace all dead at-run-time code
19478  * with 'ja -1'.
19479  *
19480  * Just nops are not optimal, e.g. if they would sit at the end of the
19481  * program and through another bug we would manage to jump there, then
19482  * we'd execute beyond program memory otherwise. Returning exception
19483  * code also wouldn't work since we can have subprogs where the dead
19484  * code could be located.
19485  */
19486 static void sanitize_dead_code(struct bpf_verifier_env *env)
19487 {
19488 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19489 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
19490 	struct bpf_insn *insn = env->prog->insnsi;
19491 	const int insn_cnt = env->prog->len;
19492 	int i;
19493 
19494 	for (i = 0; i < insn_cnt; i++) {
19495 		if (aux_data[i].seen)
19496 			continue;
19497 		memcpy(insn + i, &trap, sizeof(trap));
19498 		aux_data[i].zext_dst = false;
19499 	}
19500 }
19501 
19502 static bool insn_is_cond_jump(u8 code)
19503 {
19504 	u8 op;
19505 
19506 	op = BPF_OP(code);
19507 	if (BPF_CLASS(code) == BPF_JMP32)
19508 		return op != BPF_JA;
19509 
19510 	if (BPF_CLASS(code) != BPF_JMP)
19511 		return false;
19512 
19513 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
19514 }
19515 
19516 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
19517 {
19518 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19519 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
19520 	struct bpf_insn *insn = env->prog->insnsi;
19521 	const int insn_cnt = env->prog->len;
19522 	int i;
19523 
19524 	for (i = 0; i < insn_cnt; i++, insn++) {
19525 		if (!insn_is_cond_jump(insn->code))
19526 			continue;
19527 
19528 		if (!aux_data[i + 1].seen)
19529 			ja.off = insn->off;
19530 		else if (!aux_data[i + 1 + insn->off].seen)
19531 			ja.off = 0;
19532 		else
19533 			continue;
19534 
19535 		if (bpf_prog_is_offloaded(env->prog->aux))
19536 			bpf_prog_offload_replace_insn(env, i, &ja);
19537 
19538 		memcpy(insn, &ja, sizeof(ja));
19539 	}
19540 }
19541 
19542 static int opt_remove_dead_code(struct bpf_verifier_env *env)
19543 {
19544 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19545 	int insn_cnt = env->prog->len;
19546 	int i, err;
19547 
19548 	for (i = 0; i < insn_cnt; i++) {
19549 		int j;
19550 
19551 		j = 0;
19552 		while (i + j < insn_cnt && !aux_data[i + j].seen)
19553 			j++;
19554 		if (!j)
19555 			continue;
19556 
19557 		err = verifier_remove_insns(env, i, j);
19558 		if (err)
19559 			return err;
19560 		insn_cnt = env->prog->len;
19561 	}
19562 
19563 	return 0;
19564 }
19565 
19566 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
19567 
19568 static int opt_remove_nops(struct bpf_verifier_env *env)
19569 {
19570 	const struct bpf_insn ja = NOP;
19571 	struct bpf_insn *insn = env->prog->insnsi;
19572 	int insn_cnt = env->prog->len;
19573 	int i, err;
19574 
19575 	for (i = 0; i < insn_cnt; i++) {
19576 		if (memcmp(&insn[i], &ja, sizeof(ja)))
19577 			continue;
19578 
19579 		err = verifier_remove_insns(env, i, 1);
19580 		if (err)
19581 			return err;
19582 		insn_cnt--;
19583 		i--;
19584 	}
19585 
19586 	return 0;
19587 }
19588 
19589 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
19590 					 const union bpf_attr *attr)
19591 {
19592 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
19593 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
19594 	int i, patch_len, delta = 0, len = env->prog->len;
19595 	struct bpf_insn *insns = env->prog->insnsi;
19596 	struct bpf_prog *new_prog;
19597 	bool rnd_hi32;
19598 
19599 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
19600 	zext_patch[1] = BPF_ZEXT_REG(0);
19601 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
19602 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
19603 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
19604 	for (i = 0; i < len; i++) {
19605 		int adj_idx = i + delta;
19606 		struct bpf_insn insn;
19607 		int load_reg;
19608 
19609 		insn = insns[adj_idx];
19610 		load_reg = insn_def_regno(&insn);
19611 		if (!aux[adj_idx].zext_dst) {
19612 			u8 code, class;
19613 			u32 imm_rnd;
19614 
19615 			if (!rnd_hi32)
19616 				continue;
19617 
19618 			code = insn.code;
19619 			class = BPF_CLASS(code);
19620 			if (load_reg == -1)
19621 				continue;
19622 
19623 			/* NOTE: arg "reg" (the fourth one) is only used for
19624 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
19625 			 *       here.
19626 			 */
19627 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
19628 				if (class == BPF_LD &&
19629 				    BPF_MODE(code) == BPF_IMM)
19630 					i++;
19631 				continue;
19632 			}
19633 
19634 			/* ctx load could be transformed into wider load. */
19635 			if (class == BPF_LDX &&
19636 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
19637 				continue;
19638 
19639 			imm_rnd = get_random_u32();
19640 			rnd_hi32_patch[0] = insn;
19641 			rnd_hi32_patch[1].imm = imm_rnd;
19642 			rnd_hi32_patch[3].dst_reg = load_reg;
19643 			patch = rnd_hi32_patch;
19644 			patch_len = 4;
19645 			goto apply_patch_buffer;
19646 		}
19647 
19648 		/* Add in an zero-extend instruction if a) the JIT has requested
19649 		 * it or b) it's a CMPXCHG.
19650 		 *
19651 		 * The latter is because: BPF_CMPXCHG always loads a value into
19652 		 * R0, therefore always zero-extends. However some archs'
19653 		 * equivalent instruction only does this load when the
19654 		 * comparison is successful. This detail of CMPXCHG is
19655 		 * orthogonal to the general zero-extension behaviour of the
19656 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
19657 		 */
19658 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
19659 			continue;
19660 
19661 		/* Zero-extension is done by the caller. */
19662 		if (bpf_pseudo_kfunc_call(&insn))
19663 			continue;
19664 
19665 		if (WARN_ON(load_reg == -1)) {
19666 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
19667 			return -EFAULT;
19668 		}
19669 
19670 		zext_patch[0] = insn;
19671 		zext_patch[1].dst_reg = load_reg;
19672 		zext_patch[1].src_reg = load_reg;
19673 		patch = zext_patch;
19674 		patch_len = 2;
19675 apply_patch_buffer:
19676 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
19677 		if (!new_prog)
19678 			return -ENOMEM;
19679 		env->prog = new_prog;
19680 		insns = new_prog->insnsi;
19681 		aux = env->insn_aux_data;
19682 		delta += patch_len - 1;
19683 	}
19684 
19685 	return 0;
19686 }
19687 
19688 /* convert load instructions that access fields of a context type into a
19689  * sequence of instructions that access fields of the underlying structure:
19690  *     struct __sk_buff    -> struct sk_buff
19691  *     struct bpf_sock_ops -> struct sock
19692  */
19693 static int convert_ctx_accesses(struct bpf_verifier_env *env)
19694 {
19695 	struct bpf_subprog_info *subprogs = env->subprog_info;
19696 	const struct bpf_verifier_ops *ops = env->ops;
19697 	int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0;
19698 	const int insn_cnt = env->prog->len;
19699 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
19700 	struct bpf_insn *insn_buf = env->insn_buf;
19701 	struct bpf_insn *insn;
19702 	u32 target_size, size_default, off;
19703 	struct bpf_prog *new_prog;
19704 	enum bpf_access_type type;
19705 	bool is_narrower_load;
19706 	int epilogue_idx = 0;
19707 
19708 	if (ops->gen_epilogue) {
19709 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
19710 						 -(subprogs[0].stack_depth + 8));
19711 		if (epilogue_cnt >= INSN_BUF_SIZE) {
19712 			verbose(env, "bpf verifier is misconfigured\n");
19713 			return -EINVAL;
19714 		} else if (epilogue_cnt) {
19715 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
19716 			cnt = 0;
19717 			subprogs[0].stack_depth += 8;
19718 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
19719 						      -subprogs[0].stack_depth);
19720 			insn_buf[cnt++] = env->prog->insnsi[0];
19721 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19722 			if (!new_prog)
19723 				return -ENOMEM;
19724 			env->prog = new_prog;
19725 			delta += cnt - 1;
19726 		}
19727 	}
19728 
19729 	if (ops->gen_prologue || env->seen_direct_write) {
19730 		if (!ops->gen_prologue) {
19731 			verbose(env, "bpf verifier is misconfigured\n");
19732 			return -EINVAL;
19733 		}
19734 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
19735 					env->prog);
19736 		if (cnt >= INSN_BUF_SIZE) {
19737 			verbose(env, "bpf verifier is misconfigured\n");
19738 			return -EINVAL;
19739 		} else if (cnt) {
19740 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19741 			if (!new_prog)
19742 				return -ENOMEM;
19743 
19744 			env->prog = new_prog;
19745 			delta += cnt - 1;
19746 		}
19747 	}
19748 
19749 	if (delta)
19750 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
19751 
19752 	if (bpf_prog_is_offloaded(env->prog->aux))
19753 		return 0;
19754 
19755 	insn = env->prog->insnsi + delta;
19756 
19757 	for (i = 0; i < insn_cnt; i++, insn++) {
19758 		bpf_convert_ctx_access_t convert_ctx_access;
19759 		u8 mode;
19760 
19761 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
19762 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
19763 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
19764 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
19765 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
19766 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
19767 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
19768 			type = BPF_READ;
19769 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
19770 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
19771 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
19772 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
19773 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
19774 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
19775 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
19776 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
19777 			type = BPF_WRITE;
19778 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
19779 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
19780 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
19781 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
19782 			env->prog->aux->num_exentries++;
19783 			continue;
19784 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
19785 			   epilogue_cnt &&
19786 			   i + delta < subprogs[1].start) {
19787 			/* Generate epilogue for the main prog */
19788 			if (epilogue_idx) {
19789 				/* jump back to the earlier generated epilogue */
19790 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
19791 				cnt = 1;
19792 			} else {
19793 				memcpy(insn_buf, epilogue_buf,
19794 				       epilogue_cnt * sizeof(*epilogue_buf));
19795 				cnt = epilogue_cnt;
19796 				/* epilogue_idx cannot be 0. It must have at
19797 				 * least one ctx ptr saving insn before the
19798 				 * epilogue.
19799 				 */
19800 				epilogue_idx = i + delta;
19801 			}
19802 			goto patch_insn_buf;
19803 		} else {
19804 			continue;
19805 		}
19806 
19807 		if (type == BPF_WRITE &&
19808 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
19809 			struct bpf_insn patch[] = {
19810 				*insn,
19811 				BPF_ST_NOSPEC(),
19812 			};
19813 
19814 			cnt = ARRAY_SIZE(patch);
19815 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
19816 			if (!new_prog)
19817 				return -ENOMEM;
19818 
19819 			delta    += cnt - 1;
19820 			env->prog = new_prog;
19821 			insn      = new_prog->insnsi + i + delta;
19822 			continue;
19823 		}
19824 
19825 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
19826 		case PTR_TO_CTX:
19827 			if (!ops->convert_ctx_access)
19828 				continue;
19829 			convert_ctx_access = ops->convert_ctx_access;
19830 			break;
19831 		case PTR_TO_SOCKET:
19832 		case PTR_TO_SOCK_COMMON:
19833 			convert_ctx_access = bpf_sock_convert_ctx_access;
19834 			break;
19835 		case PTR_TO_TCP_SOCK:
19836 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
19837 			break;
19838 		case PTR_TO_XDP_SOCK:
19839 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
19840 			break;
19841 		case PTR_TO_BTF_ID:
19842 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
19843 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
19844 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
19845 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
19846 		 * any faults for loads into such types. BPF_WRITE is disallowed
19847 		 * for this case.
19848 		 */
19849 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
19850 			if (type == BPF_READ) {
19851 				if (BPF_MODE(insn->code) == BPF_MEM)
19852 					insn->code = BPF_LDX | BPF_PROBE_MEM |
19853 						     BPF_SIZE((insn)->code);
19854 				else
19855 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
19856 						     BPF_SIZE((insn)->code);
19857 				env->prog->aux->num_exentries++;
19858 			}
19859 			continue;
19860 		case PTR_TO_ARENA:
19861 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
19862 				verbose(env, "sign extending loads from arena are not supported yet\n");
19863 				return -EOPNOTSUPP;
19864 			}
19865 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19866 			env->prog->aux->num_exentries++;
19867 			continue;
19868 		default:
19869 			continue;
19870 		}
19871 
19872 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19873 		size = BPF_LDST_BYTES(insn);
19874 		mode = BPF_MODE(insn->code);
19875 
19876 		/* If the read access is a narrower load of the field,
19877 		 * convert to a 4/8-byte load, to minimum program type specific
19878 		 * convert_ctx_access changes. If conversion is successful,
19879 		 * we will apply proper mask to the result.
19880 		 */
19881 		is_narrower_load = size < ctx_field_size;
19882 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19883 		off = insn->off;
19884 		if (is_narrower_load) {
19885 			u8 size_code;
19886 
19887 			if (type == BPF_WRITE) {
19888 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19889 				return -EINVAL;
19890 			}
19891 
19892 			size_code = BPF_H;
19893 			if (ctx_field_size == 4)
19894 				size_code = BPF_W;
19895 			else if (ctx_field_size == 8)
19896 				size_code = BPF_DW;
19897 
19898 			insn->off = off & ~(size_default - 1);
19899 			insn->code = BPF_LDX | BPF_MEM | size_code;
19900 		}
19901 
19902 		target_size = 0;
19903 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19904 					 &target_size);
19905 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
19906 		    (ctx_field_size && !target_size)) {
19907 			verbose(env, "bpf verifier is misconfigured\n");
19908 			return -EINVAL;
19909 		}
19910 
19911 		if (is_narrower_load && size < target_size) {
19912 			u8 shift = bpf_ctx_narrow_access_offset(
19913 				off, size, size_default) * 8;
19914 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
19915 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19916 				return -EINVAL;
19917 			}
19918 			if (ctx_field_size <= 4) {
19919 				if (shift)
19920 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19921 									insn->dst_reg,
19922 									shift);
19923 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19924 								(1 << size * 8) - 1);
19925 			} else {
19926 				if (shift)
19927 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19928 									insn->dst_reg,
19929 									shift);
19930 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19931 								(1ULL << size * 8) - 1);
19932 			}
19933 		}
19934 		if (mode == BPF_MEMSX)
19935 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19936 						       insn->dst_reg, insn->dst_reg,
19937 						       size * 8, 0);
19938 
19939 patch_insn_buf:
19940 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19941 		if (!new_prog)
19942 			return -ENOMEM;
19943 
19944 		delta += cnt - 1;
19945 
19946 		/* keep walking new program and skip insns we just inserted */
19947 		env->prog = new_prog;
19948 		insn      = new_prog->insnsi + i + delta;
19949 	}
19950 
19951 	return 0;
19952 }
19953 
19954 static int jit_subprogs(struct bpf_verifier_env *env)
19955 {
19956 	struct bpf_prog *prog = env->prog, **func, *tmp;
19957 	int i, j, subprog_start, subprog_end = 0, len, subprog;
19958 	struct bpf_map *map_ptr;
19959 	struct bpf_insn *insn;
19960 	void *old_bpf_func;
19961 	int err, num_exentries;
19962 
19963 	if (env->subprog_cnt <= 1)
19964 		return 0;
19965 
19966 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19967 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19968 			continue;
19969 
19970 		/* Upon error here we cannot fall back to interpreter but
19971 		 * need a hard reject of the program. Thus -EFAULT is
19972 		 * propagated in any case.
19973 		 */
19974 		subprog = find_subprog(env, i + insn->imm + 1);
19975 		if (subprog < 0) {
19976 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19977 				  i + insn->imm + 1);
19978 			return -EFAULT;
19979 		}
19980 		/* temporarily remember subprog id inside insn instead of
19981 		 * aux_data, since next loop will split up all insns into funcs
19982 		 */
19983 		insn->off = subprog;
19984 		/* remember original imm in case JIT fails and fallback
19985 		 * to interpreter will be needed
19986 		 */
19987 		env->insn_aux_data[i].call_imm = insn->imm;
19988 		/* point imm to __bpf_call_base+1 from JITs point of view */
19989 		insn->imm = 1;
19990 		if (bpf_pseudo_func(insn)) {
19991 #if defined(MODULES_VADDR)
19992 			u64 addr = MODULES_VADDR;
19993 #else
19994 			u64 addr = VMALLOC_START;
19995 #endif
19996 			/* jit (e.g. x86_64) may emit fewer instructions
19997 			 * if it learns a u32 imm is the same as a u64 imm.
19998 			 * Set close enough to possible prog address.
19999 			 */
20000 			insn[0].imm = (u32)addr;
20001 			insn[1].imm = addr >> 32;
20002 		}
20003 	}
20004 
20005 	err = bpf_prog_alloc_jited_linfo(prog);
20006 	if (err)
20007 		goto out_undo_insn;
20008 
20009 	err = -ENOMEM;
20010 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
20011 	if (!func)
20012 		goto out_undo_insn;
20013 
20014 	for (i = 0; i < env->subprog_cnt; i++) {
20015 		subprog_start = subprog_end;
20016 		subprog_end = env->subprog_info[i + 1].start;
20017 
20018 		len = subprog_end - subprog_start;
20019 		/* bpf_prog_run() doesn't call subprogs directly,
20020 		 * hence main prog stats include the runtime of subprogs.
20021 		 * subprogs don't have IDs and not reachable via prog_get_next_id
20022 		 * func[i]->stats will never be accessed and stays NULL
20023 		 */
20024 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
20025 		if (!func[i])
20026 			goto out_free;
20027 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
20028 		       len * sizeof(struct bpf_insn));
20029 		func[i]->type = prog->type;
20030 		func[i]->len = len;
20031 		if (bpf_prog_calc_tag(func[i]))
20032 			goto out_free;
20033 		func[i]->is_func = 1;
20034 		func[i]->sleepable = prog->sleepable;
20035 		func[i]->aux->func_idx = i;
20036 		/* Below members will be freed only at prog->aux */
20037 		func[i]->aux->btf = prog->aux->btf;
20038 		func[i]->aux->func_info = prog->aux->func_info;
20039 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
20040 		func[i]->aux->poke_tab = prog->aux->poke_tab;
20041 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
20042 
20043 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
20044 			struct bpf_jit_poke_descriptor *poke;
20045 
20046 			poke = &prog->aux->poke_tab[j];
20047 			if (poke->insn_idx < subprog_end &&
20048 			    poke->insn_idx >= subprog_start)
20049 				poke->aux = func[i]->aux;
20050 		}
20051 
20052 		func[i]->aux->name[0] = 'F';
20053 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
20054 		func[i]->jit_requested = 1;
20055 		func[i]->blinding_requested = prog->blinding_requested;
20056 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
20057 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
20058 		func[i]->aux->linfo = prog->aux->linfo;
20059 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
20060 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
20061 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
20062 		func[i]->aux->arena = prog->aux->arena;
20063 		num_exentries = 0;
20064 		insn = func[i]->insnsi;
20065 		for (j = 0; j < func[i]->len; j++, insn++) {
20066 			if (BPF_CLASS(insn->code) == BPF_LDX &&
20067 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20068 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
20069 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
20070 				num_exentries++;
20071 			if ((BPF_CLASS(insn->code) == BPF_STX ||
20072 			     BPF_CLASS(insn->code) == BPF_ST) &&
20073 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
20074 				num_exentries++;
20075 			if (BPF_CLASS(insn->code) == BPF_STX &&
20076 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
20077 				num_exentries++;
20078 		}
20079 		func[i]->aux->num_exentries = num_exentries;
20080 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
20081 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
20082 		if (!i)
20083 			func[i]->aux->exception_boundary = env->seen_exception;
20084 		func[i] = bpf_int_jit_compile(func[i]);
20085 		if (!func[i]->jited) {
20086 			err = -ENOTSUPP;
20087 			goto out_free;
20088 		}
20089 		cond_resched();
20090 	}
20091 
20092 	/* at this point all bpf functions were successfully JITed
20093 	 * now populate all bpf_calls with correct addresses and
20094 	 * run last pass of JIT
20095 	 */
20096 	for (i = 0; i < env->subprog_cnt; i++) {
20097 		insn = func[i]->insnsi;
20098 		for (j = 0; j < func[i]->len; j++, insn++) {
20099 			if (bpf_pseudo_func(insn)) {
20100 				subprog = insn->off;
20101 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
20102 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
20103 				continue;
20104 			}
20105 			if (!bpf_pseudo_call(insn))
20106 				continue;
20107 			subprog = insn->off;
20108 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
20109 		}
20110 
20111 		/* we use the aux data to keep a list of the start addresses
20112 		 * of the JITed images for each function in the program
20113 		 *
20114 		 * for some architectures, such as powerpc64, the imm field
20115 		 * might not be large enough to hold the offset of the start
20116 		 * address of the callee's JITed image from __bpf_call_base
20117 		 *
20118 		 * in such cases, we can lookup the start address of a callee
20119 		 * by using its subprog id, available from the off field of
20120 		 * the call instruction, as an index for this list
20121 		 */
20122 		func[i]->aux->func = func;
20123 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20124 		func[i]->aux->real_func_cnt = env->subprog_cnt;
20125 	}
20126 	for (i = 0; i < env->subprog_cnt; i++) {
20127 		old_bpf_func = func[i]->bpf_func;
20128 		tmp = bpf_int_jit_compile(func[i]);
20129 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
20130 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
20131 			err = -ENOTSUPP;
20132 			goto out_free;
20133 		}
20134 		cond_resched();
20135 	}
20136 
20137 	/* finally lock prog and jit images for all functions and
20138 	 * populate kallsysm. Begin at the first subprogram, since
20139 	 * bpf_prog_load will add the kallsyms for the main program.
20140 	 */
20141 	for (i = 1; i < env->subprog_cnt; i++) {
20142 		err = bpf_prog_lock_ro(func[i]);
20143 		if (err)
20144 			goto out_free;
20145 	}
20146 
20147 	for (i = 1; i < env->subprog_cnt; i++)
20148 		bpf_prog_kallsyms_add(func[i]);
20149 
20150 	/* Last step: make now unused interpreter insns from main
20151 	 * prog consistent for later dump requests, so they can
20152 	 * later look the same as if they were interpreted only.
20153 	 */
20154 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20155 		if (bpf_pseudo_func(insn)) {
20156 			insn[0].imm = env->insn_aux_data[i].call_imm;
20157 			insn[1].imm = insn->off;
20158 			insn->off = 0;
20159 			continue;
20160 		}
20161 		if (!bpf_pseudo_call(insn))
20162 			continue;
20163 		insn->off = env->insn_aux_data[i].call_imm;
20164 		subprog = find_subprog(env, i + insn->off + 1);
20165 		insn->imm = subprog;
20166 	}
20167 
20168 	prog->jited = 1;
20169 	prog->bpf_func = func[0]->bpf_func;
20170 	prog->jited_len = func[0]->jited_len;
20171 	prog->aux->extable = func[0]->aux->extable;
20172 	prog->aux->num_exentries = func[0]->aux->num_exentries;
20173 	prog->aux->func = func;
20174 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20175 	prog->aux->real_func_cnt = env->subprog_cnt;
20176 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
20177 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
20178 	bpf_prog_jit_attempt_done(prog);
20179 	return 0;
20180 out_free:
20181 	/* We failed JIT'ing, so at this point we need to unregister poke
20182 	 * descriptors from subprogs, so that kernel is not attempting to
20183 	 * patch it anymore as we're freeing the subprog JIT memory.
20184 	 */
20185 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20186 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20187 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
20188 	}
20189 	/* At this point we're guaranteed that poke descriptors are not
20190 	 * live anymore. We can just unlink its descriptor table as it's
20191 	 * released with the main prog.
20192 	 */
20193 	for (i = 0; i < env->subprog_cnt; i++) {
20194 		if (!func[i])
20195 			continue;
20196 		func[i]->aux->poke_tab = NULL;
20197 		bpf_jit_free(func[i]);
20198 	}
20199 	kfree(func);
20200 out_undo_insn:
20201 	/* cleanup main prog to be interpreted */
20202 	prog->jit_requested = 0;
20203 	prog->blinding_requested = 0;
20204 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20205 		if (!bpf_pseudo_call(insn))
20206 			continue;
20207 		insn->off = 0;
20208 		insn->imm = env->insn_aux_data[i].call_imm;
20209 	}
20210 	bpf_prog_jit_attempt_done(prog);
20211 	return err;
20212 }
20213 
20214 static int fixup_call_args(struct bpf_verifier_env *env)
20215 {
20216 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20217 	struct bpf_prog *prog = env->prog;
20218 	struct bpf_insn *insn = prog->insnsi;
20219 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
20220 	int i, depth;
20221 #endif
20222 	int err = 0;
20223 
20224 	if (env->prog->jit_requested &&
20225 	    !bpf_prog_is_offloaded(env->prog->aux)) {
20226 		err = jit_subprogs(env);
20227 		if (err == 0)
20228 			return 0;
20229 		if (err == -EFAULT)
20230 			return err;
20231 	}
20232 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20233 	if (has_kfunc_call) {
20234 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
20235 		return -EINVAL;
20236 	}
20237 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
20238 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
20239 		 * have to be rejected, since interpreter doesn't support them yet.
20240 		 */
20241 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
20242 		return -EINVAL;
20243 	}
20244 	for (i = 0; i < prog->len; i++, insn++) {
20245 		if (bpf_pseudo_func(insn)) {
20246 			/* When JIT fails the progs with callback calls
20247 			 * have to be rejected, since interpreter doesn't support them yet.
20248 			 */
20249 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
20250 			return -EINVAL;
20251 		}
20252 
20253 		if (!bpf_pseudo_call(insn))
20254 			continue;
20255 		depth = get_callee_stack_depth(env, insn, i);
20256 		if (depth < 0)
20257 			return depth;
20258 		bpf_patch_call_args(insn, depth);
20259 	}
20260 	err = 0;
20261 #endif
20262 	return err;
20263 }
20264 
20265 /* replace a generic kfunc with a specialized version if necessary */
20266 static void specialize_kfunc(struct bpf_verifier_env *env,
20267 			     u32 func_id, u16 offset, unsigned long *addr)
20268 {
20269 	struct bpf_prog *prog = env->prog;
20270 	bool seen_direct_write;
20271 	void *xdp_kfunc;
20272 	bool is_rdonly;
20273 
20274 	if (bpf_dev_bound_kfunc_id(func_id)) {
20275 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
20276 		if (xdp_kfunc) {
20277 			*addr = (unsigned long)xdp_kfunc;
20278 			return;
20279 		}
20280 		/* fallback to default kfunc when not supported by netdev */
20281 	}
20282 
20283 	if (offset)
20284 		return;
20285 
20286 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
20287 		seen_direct_write = env->seen_direct_write;
20288 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
20289 
20290 		if (is_rdonly)
20291 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
20292 
20293 		/* restore env->seen_direct_write to its original value, since
20294 		 * may_access_direct_pkt_data mutates it
20295 		 */
20296 		env->seen_direct_write = seen_direct_write;
20297 	}
20298 }
20299 
20300 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
20301 					    u16 struct_meta_reg,
20302 					    u16 node_offset_reg,
20303 					    struct bpf_insn *insn,
20304 					    struct bpf_insn *insn_buf,
20305 					    int *cnt)
20306 {
20307 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
20308 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
20309 
20310 	insn_buf[0] = addr[0];
20311 	insn_buf[1] = addr[1];
20312 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
20313 	insn_buf[3] = *insn;
20314 	*cnt = 4;
20315 }
20316 
20317 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
20318 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
20319 {
20320 	const struct bpf_kfunc_desc *desc;
20321 
20322 	if (!insn->imm) {
20323 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
20324 		return -EINVAL;
20325 	}
20326 
20327 	*cnt = 0;
20328 
20329 	/* insn->imm has the btf func_id. Replace it with an offset relative to
20330 	 * __bpf_call_base, unless the JIT needs to call functions that are
20331 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
20332 	 */
20333 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
20334 	if (!desc) {
20335 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
20336 			insn->imm);
20337 		return -EFAULT;
20338 	}
20339 
20340 	if (!bpf_jit_supports_far_kfunc_call())
20341 		insn->imm = BPF_CALL_IMM(desc->addr);
20342 	if (insn->off)
20343 		return 0;
20344 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
20345 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
20346 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20347 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20348 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
20349 
20350 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
20351 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20352 				insn_idx);
20353 			return -EFAULT;
20354 		}
20355 
20356 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
20357 		insn_buf[1] = addr[0];
20358 		insn_buf[2] = addr[1];
20359 		insn_buf[3] = *insn;
20360 		*cnt = 4;
20361 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
20362 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
20363 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
20364 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20365 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20366 
20367 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
20368 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20369 				insn_idx);
20370 			return -EFAULT;
20371 		}
20372 
20373 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
20374 		    !kptr_struct_meta) {
20375 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20376 				insn_idx);
20377 			return -EFAULT;
20378 		}
20379 
20380 		insn_buf[0] = addr[0];
20381 		insn_buf[1] = addr[1];
20382 		insn_buf[2] = *insn;
20383 		*cnt = 3;
20384 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
20385 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
20386 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20387 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20388 		int struct_meta_reg = BPF_REG_3;
20389 		int node_offset_reg = BPF_REG_4;
20390 
20391 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
20392 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20393 			struct_meta_reg = BPF_REG_4;
20394 			node_offset_reg = BPF_REG_5;
20395 		}
20396 
20397 		if (!kptr_struct_meta) {
20398 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20399 				insn_idx);
20400 			return -EFAULT;
20401 		}
20402 
20403 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
20404 						node_offset_reg, insn, insn_buf, cnt);
20405 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
20406 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
20407 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
20408 		*cnt = 1;
20409 	} else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
20410 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
20411 
20412 		insn_buf[0] = ld_addrs[0];
20413 		insn_buf[1] = ld_addrs[1];
20414 		insn_buf[2] = *insn;
20415 		*cnt = 3;
20416 	}
20417 	return 0;
20418 }
20419 
20420 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
20421 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
20422 {
20423 	struct bpf_subprog_info *info = env->subprog_info;
20424 	int cnt = env->subprog_cnt;
20425 	struct bpf_prog *prog;
20426 
20427 	/* We only reserve one slot for hidden subprogs in subprog_info. */
20428 	if (env->hidden_subprog_cnt) {
20429 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
20430 		return -EFAULT;
20431 	}
20432 	/* We're not patching any existing instruction, just appending the new
20433 	 * ones for the hidden subprog. Hence all of the adjustment operations
20434 	 * in bpf_patch_insn_data are no-ops.
20435 	 */
20436 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
20437 	if (!prog)
20438 		return -ENOMEM;
20439 	env->prog = prog;
20440 	info[cnt + 1].start = info[cnt].start;
20441 	info[cnt].start = prog->len - len + 1;
20442 	env->subprog_cnt++;
20443 	env->hidden_subprog_cnt++;
20444 	return 0;
20445 }
20446 
20447 /* Do various post-verification rewrites in a single program pass.
20448  * These rewrites simplify JIT and interpreter implementations.
20449  */
20450 static int do_misc_fixups(struct bpf_verifier_env *env)
20451 {
20452 	struct bpf_prog *prog = env->prog;
20453 	enum bpf_attach_type eatype = prog->expected_attach_type;
20454 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20455 	struct bpf_insn *insn = prog->insnsi;
20456 	const struct bpf_func_proto *fn;
20457 	const int insn_cnt = prog->len;
20458 	const struct bpf_map_ops *ops;
20459 	struct bpf_insn_aux_data *aux;
20460 	struct bpf_insn *insn_buf = env->insn_buf;
20461 	struct bpf_prog *new_prog;
20462 	struct bpf_map *map_ptr;
20463 	int i, ret, cnt, delta = 0, cur_subprog = 0;
20464 	struct bpf_subprog_info *subprogs = env->subprog_info;
20465 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
20466 	u16 stack_depth_extra = 0;
20467 
20468 	if (env->seen_exception && !env->exception_callback_subprog) {
20469 		struct bpf_insn patch[] = {
20470 			env->prog->insnsi[insn_cnt - 1],
20471 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
20472 			BPF_EXIT_INSN(),
20473 		};
20474 
20475 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
20476 		if (ret < 0)
20477 			return ret;
20478 		prog = env->prog;
20479 		insn = prog->insnsi;
20480 
20481 		env->exception_callback_subprog = env->subprog_cnt - 1;
20482 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
20483 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
20484 	}
20485 
20486 	for (i = 0; i < insn_cnt;) {
20487 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
20488 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
20489 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
20490 				/* convert to 32-bit mov that clears upper 32-bit */
20491 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
20492 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
20493 				insn->off = 0;
20494 				insn->imm = 0;
20495 			} /* cast from as(0) to as(1) should be handled by JIT */
20496 			goto next_insn;
20497 		}
20498 
20499 		if (env->insn_aux_data[i + delta].needs_zext)
20500 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
20501 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
20502 
20503 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
20504 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
20505 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
20506 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
20507 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
20508 		    insn->off == 1 && insn->imm == -1) {
20509 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
20510 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
20511 			struct bpf_insn *patchlet;
20512 			struct bpf_insn chk_and_sdiv[] = {
20513 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20514 					     BPF_NEG | BPF_K, insn->dst_reg,
20515 					     0, 0, 0),
20516 			};
20517 			struct bpf_insn chk_and_smod[] = {
20518 				BPF_MOV32_IMM(insn->dst_reg, 0),
20519 			};
20520 
20521 			patchlet = isdiv ? chk_and_sdiv : chk_and_smod;
20522 			cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod);
20523 
20524 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
20525 			if (!new_prog)
20526 				return -ENOMEM;
20527 
20528 			delta    += cnt - 1;
20529 			env->prog = prog = new_prog;
20530 			insn      = new_prog->insnsi + i + delta;
20531 			goto next_insn;
20532 		}
20533 
20534 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
20535 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
20536 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
20537 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
20538 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
20539 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
20540 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
20541 			bool is_sdiv = isdiv && insn->off == 1;
20542 			bool is_smod = !isdiv && insn->off == 1;
20543 			struct bpf_insn *patchlet;
20544 			struct bpf_insn chk_and_div[] = {
20545 				/* [R,W]x div 0 -> 0 */
20546 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20547 					     BPF_JNE | BPF_K, insn->src_reg,
20548 					     0, 2, 0),
20549 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
20550 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20551 				*insn,
20552 			};
20553 			struct bpf_insn chk_and_mod[] = {
20554 				/* [R,W]x mod 0 -> [R,W]x */
20555 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20556 					     BPF_JEQ | BPF_K, insn->src_reg,
20557 					     0, 1 + (is64 ? 0 : 1), 0),
20558 				*insn,
20559 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20560 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
20561 			};
20562 			struct bpf_insn chk_and_sdiv[] = {
20563 				/* [R,W]x sdiv 0 -> 0
20564 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
20565 				 * INT_MIN sdiv -1 -> INT_MIN
20566 				 */
20567 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
20568 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20569 					     BPF_ADD | BPF_K, BPF_REG_AX,
20570 					     0, 0, 1),
20571 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20572 					     BPF_JGT | BPF_K, BPF_REG_AX,
20573 					     0, 4, 1),
20574 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20575 					     BPF_JEQ | BPF_K, BPF_REG_AX,
20576 					     0, 1, 0),
20577 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20578 					     BPF_MOV | BPF_K, insn->dst_reg,
20579 					     0, 0, 0),
20580 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
20581 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20582 					     BPF_NEG | BPF_K, insn->dst_reg,
20583 					     0, 0, 0),
20584 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20585 				*insn,
20586 			};
20587 			struct bpf_insn chk_and_smod[] = {
20588 				/* [R,W]x mod 0 -> [R,W]x */
20589 				/* [R,W]x mod -1 -> 0 */
20590 				BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
20591 				BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20592 					     BPF_ADD | BPF_K, BPF_REG_AX,
20593 					     0, 0, 1),
20594 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20595 					     BPF_JGT | BPF_K, BPF_REG_AX,
20596 					     0, 3, 1),
20597 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20598 					     BPF_JEQ | BPF_K, BPF_REG_AX,
20599 					     0, 3 + (is64 ? 0 : 1), 1),
20600 				BPF_MOV32_IMM(insn->dst_reg, 0),
20601 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20602 				*insn,
20603 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20604 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
20605 			};
20606 
20607 			if (is_sdiv) {
20608 				patchlet = chk_and_sdiv;
20609 				cnt = ARRAY_SIZE(chk_and_sdiv);
20610 			} else if (is_smod) {
20611 				patchlet = chk_and_smod;
20612 				cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0);
20613 			} else {
20614 				patchlet = isdiv ? chk_and_div : chk_and_mod;
20615 				cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
20616 					      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
20617 			}
20618 
20619 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
20620 			if (!new_prog)
20621 				return -ENOMEM;
20622 
20623 			delta    += cnt - 1;
20624 			env->prog = prog = new_prog;
20625 			insn      = new_prog->insnsi + i + delta;
20626 			goto next_insn;
20627 		}
20628 
20629 		/* Make it impossible to de-reference a userspace address */
20630 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20631 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20632 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
20633 			struct bpf_insn *patch = &insn_buf[0];
20634 			u64 uaddress_limit = bpf_arch_uaddress_limit();
20635 
20636 			if (!uaddress_limit)
20637 				goto next_insn;
20638 
20639 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
20640 			if (insn->off)
20641 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
20642 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
20643 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
20644 			*patch++ = *insn;
20645 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
20646 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
20647 
20648 			cnt = patch - insn_buf;
20649 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20650 			if (!new_prog)
20651 				return -ENOMEM;
20652 
20653 			delta    += cnt - 1;
20654 			env->prog = prog = new_prog;
20655 			insn      = new_prog->insnsi + i + delta;
20656 			goto next_insn;
20657 		}
20658 
20659 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
20660 		if (BPF_CLASS(insn->code) == BPF_LD &&
20661 		    (BPF_MODE(insn->code) == BPF_ABS ||
20662 		     BPF_MODE(insn->code) == BPF_IND)) {
20663 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
20664 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
20665 				verbose(env, "bpf verifier is misconfigured\n");
20666 				return -EINVAL;
20667 			}
20668 
20669 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20670 			if (!new_prog)
20671 				return -ENOMEM;
20672 
20673 			delta    += cnt - 1;
20674 			env->prog = prog = new_prog;
20675 			insn      = new_prog->insnsi + i + delta;
20676 			goto next_insn;
20677 		}
20678 
20679 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
20680 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
20681 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
20682 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
20683 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
20684 			struct bpf_insn *patch = &insn_buf[0];
20685 			bool issrc, isneg, isimm;
20686 			u32 off_reg;
20687 
20688 			aux = &env->insn_aux_data[i + delta];
20689 			if (!aux->alu_state ||
20690 			    aux->alu_state == BPF_ALU_NON_POINTER)
20691 				goto next_insn;
20692 
20693 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
20694 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
20695 				BPF_ALU_SANITIZE_SRC;
20696 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
20697 
20698 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
20699 			if (isimm) {
20700 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20701 			} else {
20702 				if (isneg)
20703 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20704 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20705 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
20706 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
20707 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
20708 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
20709 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
20710 			}
20711 			if (!issrc)
20712 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
20713 			insn->src_reg = BPF_REG_AX;
20714 			if (isneg)
20715 				insn->code = insn->code == code_add ?
20716 					     code_sub : code_add;
20717 			*patch++ = *insn;
20718 			if (issrc && isneg && !isimm)
20719 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20720 			cnt = patch - insn_buf;
20721 
20722 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20723 			if (!new_prog)
20724 				return -ENOMEM;
20725 
20726 			delta    += cnt - 1;
20727 			env->prog = prog = new_prog;
20728 			insn      = new_prog->insnsi + i + delta;
20729 			goto next_insn;
20730 		}
20731 
20732 		if (is_may_goto_insn(insn)) {
20733 			int stack_off = -stack_depth - 8;
20734 
20735 			stack_depth_extra = 8;
20736 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
20737 			if (insn->off >= 0)
20738 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
20739 			else
20740 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
20741 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
20742 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
20743 			cnt = 4;
20744 
20745 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20746 			if (!new_prog)
20747 				return -ENOMEM;
20748 
20749 			delta += cnt - 1;
20750 			env->prog = prog = new_prog;
20751 			insn = new_prog->insnsi + i + delta;
20752 			goto next_insn;
20753 		}
20754 
20755 		if (insn->code != (BPF_JMP | BPF_CALL))
20756 			goto next_insn;
20757 		if (insn->src_reg == BPF_PSEUDO_CALL)
20758 			goto next_insn;
20759 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20760 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
20761 			if (ret)
20762 				return ret;
20763 			if (cnt == 0)
20764 				goto next_insn;
20765 
20766 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20767 			if (!new_prog)
20768 				return -ENOMEM;
20769 
20770 			delta	 += cnt - 1;
20771 			env->prog = prog = new_prog;
20772 			insn	  = new_prog->insnsi + i + delta;
20773 			goto next_insn;
20774 		}
20775 
20776 		/* Skip inlining the helper call if the JIT does it. */
20777 		if (bpf_jit_inlines_helper_call(insn->imm))
20778 			goto next_insn;
20779 
20780 		if (insn->imm == BPF_FUNC_get_route_realm)
20781 			prog->dst_needed = 1;
20782 		if (insn->imm == BPF_FUNC_get_prandom_u32)
20783 			bpf_user_rnd_init_once();
20784 		if (insn->imm == BPF_FUNC_override_return)
20785 			prog->kprobe_override = 1;
20786 		if (insn->imm == BPF_FUNC_tail_call) {
20787 			/* If we tail call into other programs, we
20788 			 * cannot make any assumptions since they can
20789 			 * be replaced dynamically during runtime in
20790 			 * the program array.
20791 			 */
20792 			prog->cb_access = 1;
20793 			if (!allow_tail_call_in_subprogs(env))
20794 				prog->aux->stack_depth = MAX_BPF_STACK;
20795 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
20796 
20797 			/* mark bpf_tail_call as different opcode to avoid
20798 			 * conditional branch in the interpreter for every normal
20799 			 * call and to prevent accidental JITing by JIT compiler
20800 			 * that doesn't support bpf_tail_call yet
20801 			 */
20802 			insn->imm = 0;
20803 			insn->code = BPF_JMP | BPF_TAIL_CALL;
20804 
20805 			aux = &env->insn_aux_data[i + delta];
20806 			if (env->bpf_capable && !prog->blinding_requested &&
20807 			    prog->jit_requested &&
20808 			    !bpf_map_key_poisoned(aux) &&
20809 			    !bpf_map_ptr_poisoned(aux) &&
20810 			    !bpf_map_ptr_unpriv(aux)) {
20811 				struct bpf_jit_poke_descriptor desc = {
20812 					.reason = BPF_POKE_REASON_TAIL_CALL,
20813 					.tail_call.map = aux->map_ptr_state.map_ptr,
20814 					.tail_call.key = bpf_map_key_immediate(aux),
20815 					.insn_idx = i + delta,
20816 				};
20817 
20818 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
20819 				if (ret < 0) {
20820 					verbose(env, "adding tail call poke descriptor failed\n");
20821 					return ret;
20822 				}
20823 
20824 				insn->imm = ret + 1;
20825 				goto next_insn;
20826 			}
20827 
20828 			if (!bpf_map_ptr_unpriv(aux))
20829 				goto next_insn;
20830 
20831 			/* instead of changing every JIT dealing with tail_call
20832 			 * emit two extra insns:
20833 			 * if (index >= max_entries) goto out;
20834 			 * index &= array->index_mask;
20835 			 * to avoid out-of-bounds cpu speculation
20836 			 */
20837 			if (bpf_map_ptr_poisoned(aux)) {
20838 				verbose(env, "tail_call abusing map_ptr\n");
20839 				return -EINVAL;
20840 			}
20841 
20842 			map_ptr = aux->map_ptr_state.map_ptr;
20843 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
20844 						  map_ptr->max_entries, 2);
20845 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
20846 						    container_of(map_ptr,
20847 								 struct bpf_array,
20848 								 map)->index_mask);
20849 			insn_buf[2] = *insn;
20850 			cnt = 3;
20851 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20852 			if (!new_prog)
20853 				return -ENOMEM;
20854 
20855 			delta    += cnt - 1;
20856 			env->prog = prog = new_prog;
20857 			insn      = new_prog->insnsi + i + delta;
20858 			goto next_insn;
20859 		}
20860 
20861 		if (insn->imm == BPF_FUNC_timer_set_callback) {
20862 			/* The verifier will process callback_fn as many times as necessary
20863 			 * with different maps and the register states prepared by
20864 			 * set_timer_callback_state will be accurate.
20865 			 *
20866 			 * The following use case is valid:
20867 			 *   map1 is shared by prog1, prog2, prog3.
20868 			 *   prog1 calls bpf_timer_init for some map1 elements
20869 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
20870 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
20871 			 *   prog3 calls bpf_timer_start for some map1 elements.
20872 			 *     Those that were not both bpf_timer_init-ed and
20873 			 *     bpf_timer_set_callback-ed will return -EINVAL.
20874 			 */
20875 			struct bpf_insn ld_addrs[2] = {
20876 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
20877 			};
20878 
20879 			insn_buf[0] = ld_addrs[0];
20880 			insn_buf[1] = ld_addrs[1];
20881 			insn_buf[2] = *insn;
20882 			cnt = 3;
20883 
20884 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20885 			if (!new_prog)
20886 				return -ENOMEM;
20887 
20888 			delta    += cnt - 1;
20889 			env->prog = prog = new_prog;
20890 			insn      = new_prog->insnsi + i + delta;
20891 			goto patch_call_imm;
20892 		}
20893 
20894 		if (is_storage_get_function(insn->imm)) {
20895 			if (!in_sleepable(env) ||
20896 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
20897 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
20898 			else
20899 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
20900 			insn_buf[1] = *insn;
20901 			cnt = 2;
20902 
20903 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20904 			if (!new_prog)
20905 				return -ENOMEM;
20906 
20907 			delta += cnt - 1;
20908 			env->prog = prog = new_prog;
20909 			insn = new_prog->insnsi + i + delta;
20910 			goto patch_call_imm;
20911 		}
20912 
20913 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
20914 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
20915 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
20916 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
20917 			 */
20918 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
20919 			insn_buf[1] = *insn;
20920 			cnt = 2;
20921 
20922 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20923 			if (!new_prog)
20924 				return -ENOMEM;
20925 
20926 			delta += cnt - 1;
20927 			env->prog = prog = new_prog;
20928 			insn = new_prog->insnsi + i + delta;
20929 			goto patch_call_imm;
20930 		}
20931 
20932 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
20933 		 * and other inlining handlers are currently limited to 64 bit
20934 		 * only.
20935 		 */
20936 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20937 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
20938 		     insn->imm == BPF_FUNC_map_update_elem ||
20939 		     insn->imm == BPF_FUNC_map_delete_elem ||
20940 		     insn->imm == BPF_FUNC_map_push_elem   ||
20941 		     insn->imm == BPF_FUNC_map_pop_elem    ||
20942 		     insn->imm == BPF_FUNC_map_peek_elem   ||
20943 		     insn->imm == BPF_FUNC_redirect_map    ||
20944 		     insn->imm == BPF_FUNC_for_each_map_elem ||
20945 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
20946 			aux = &env->insn_aux_data[i + delta];
20947 			if (bpf_map_ptr_poisoned(aux))
20948 				goto patch_call_imm;
20949 
20950 			map_ptr = aux->map_ptr_state.map_ptr;
20951 			ops = map_ptr->ops;
20952 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
20953 			    ops->map_gen_lookup) {
20954 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
20955 				if (cnt == -EOPNOTSUPP)
20956 					goto patch_map_ops_generic;
20957 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
20958 					verbose(env, "bpf verifier is misconfigured\n");
20959 					return -EINVAL;
20960 				}
20961 
20962 				new_prog = bpf_patch_insn_data(env, i + delta,
20963 							       insn_buf, cnt);
20964 				if (!new_prog)
20965 					return -ENOMEM;
20966 
20967 				delta    += cnt - 1;
20968 				env->prog = prog = new_prog;
20969 				insn      = new_prog->insnsi + i + delta;
20970 				goto next_insn;
20971 			}
20972 
20973 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
20974 				     (void *(*)(struct bpf_map *map, void *key))NULL));
20975 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
20976 				     (long (*)(struct bpf_map *map, void *key))NULL));
20977 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
20978 				     (long (*)(struct bpf_map *map, void *key, void *value,
20979 					      u64 flags))NULL));
20980 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
20981 				     (long (*)(struct bpf_map *map, void *value,
20982 					      u64 flags))NULL));
20983 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
20984 				     (long (*)(struct bpf_map *map, void *value))NULL));
20985 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
20986 				     (long (*)(struct bpf_map *map, void *value))NULL));
20987 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
20988 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
20989 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
20990 				     (long (*)(struct bpf_map *map,
20991 					      bpf_callback_t callback_fn,
20992 					      void *callback_ctx,
20993 					      u64 flags))NULL));
20994 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
20995 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
20996 
20997 patch_map_ops_generic:
20998 			switch (insn->imm) {
20999 			case BPF_FUNC_map_lookup_elem:
21000 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
21001 				goto next_insn;
21002 			case BPF_FUNC_map_update_elem:
21003 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
21004 				goto next_insn;
21005 			case BPF_FUNC_map_delete_elem:
21006 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
21007 				goto next_insn;
21008 			case BPF_FUNC_map_push_elem:
21009 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
21010 				goto next_insn;
21011 			case BPF_FUNC_map_pop_elem:
21012 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
21013 				goto next_insn;
21014 			case BPF_FUNC_map_peek_elem:
21015 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
21016 				goto next_insn;
21017 			case BPF_FUNC_redirect_map:
21018 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
21019 				goto next_insn;
21020 			case BPF_FUNC_for_each_map_elem:
21021 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
21022 				goto next_insn;
21023 			case BPF_FUNC_map_lookup_percpu_elem:
21024 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
21025 				goto next_insn;
21026 			}
21027 
21028 			goto patch_call_imm;
21029 		}
21030 
21031 		/* Implement bpf_jiffies64 inline. */
21032 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21033 		    insn->imm == BPF_FUNC_jiffies64) {
21034 			struct bpf_insn ld_jiffies_addr[2] = {
21035 				BPF_LD_IMM64(BPF_REG_0,
21036 					     (unsigned long)&jiffies),
21037 			};
21038 
21039 			insn_buf[0] = ld_jiffies_addr[0];
21040 			insn_buf[1] = ld_jiffies_addr[1];
21041 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
21042 						  BPF_REG_0, 0);
21043 			cnt = 3;
21044 
21045 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
21046 						       cnt);
21047 			if (!new_prog)
21048 				return -ENOMEM;
21049 
21050 			delta    += cnt - 1;
21051 			env->prog = prog = new_prog;
21052 			insn      = new_prog->insnsi + i + delta;
21053 			goto next_insn;
21054 		}
21055 
21056 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
21057 		/* Implement bpf_get_smp_processor_id() inline. */
21058 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
21059 		    verifier_inlines_helper_call(env, insn->imm)) {
21060 			/* BPF_FUNC_get_smp_processor_id inlining is an
21061 			 * optimization, so if pcpu_hot.cpu_number is ever
21062 			 * changed in some incompatible and hard to support
21063 			 * way, it's fine to back out this inlining logic
21064 			 */
21065 			insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
21066 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
21067 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
21068 			cnt = 3;
21069 
21070 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21071 			if (!new_prog)
21072 				return -ENOMEM;
21073 
21074 			delta    += cnt - 1;
21075 			env->prog = prog = new_prog;
21076 			insn      = new_prog->insnsi + i + delta;
21077 			goto next_insn;
21078 		}
21079 #endif
21080 		/* Implement bpf_get_func_arg inline. */
21081 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21082 		    insn->imm == BPF_FUNC_get_func_arg) {
21083 			/* Load nr_args from ctx - 8 */
21084 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21085 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
21086 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
21087 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
21088 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
21089 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21090 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
21091 			insn_buf[7] = BPF_JMP_A(1);
21092 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21093 			cnt = 9;
21094 
21095 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21096 			if (!new_prog)
21097 				return -ENOMEM;
21098 
21099 			delta    += cnt - 1;
21100 			env->prog = prog = new_prog;
21101 			insn      = new_prog->insnsi + i + delta;
21102 			goto next_insn;
21103 		}
21104 
21105 		/* Implement bpf_get_func_ret inline. */
21106 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21107 		    insn->imm == BPF_FUNC_get_func_ret) {
21108 			if (eatype == BPF_TRACE_FEXIT ||
21109 			    eatype == BPF_MODIFY_RETURN) {
21110 				/* Load nr_args from ctx - 8 */
21111 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21112 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
21113 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
21114 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21115 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
21116 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
21117 				cnt = 6;
21118 			} else {
21119 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
21120 				cnt = 1;
21121 			}
21122 
21123 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21124 			if (!new_prog)
21125 				return -ENOMEM;
21126 
21127 			delta    += cnt - 1;
21128 			env->prog = prog = new_prog;
21129 			insn      = new_prog->insnsi + i + delta;
21130 			goto next_insn;
21131 		}
21132 
21133 		/* Implement get_func_arg_cnt inline. */
21134 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21135 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
21136 			/* Load nr_args from ctx - 8 */
21137 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21138 
21139 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21140 			if (!new_prog)
21141 				return -ENOMEM;
21142 
21143 			env->prog = prog = new_prog;
21144 			insn      = new_prog->insnsi + i + delta;
21145 			goto next_insn;
21146 		}
21147 
21148 		/* Implement bpf_get_func_ip inline. */
21149 		if (prog_type == BPF_PROG_TYPE_TRACING &&
21150 		    insn->imm == BPF_FUNC_get_func_ip) {
21151 			/* Load IP address from ctx - 16 */
21152 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
21153 
21154 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21155 			if (!new_prog)
21156 				return -ENOMEM;
21157 
21158 			env->prog = prog = new_prog;
21159 			insn      = new_prog->insnsi + i + delta;
21160 			goto next_insn;
21161 		}
21162 
21163 		/* Implement bpf_get_branch_snapshot inline. */
21164 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
21165 		    prog->jit_requested && BITS_PER_LONG == 64 &&
21166 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
21167 			/* We are dealing with the following func protos:
21168 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
21169 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
21170 			 */
21171 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
21172 
21173 			/* struct perf_branch_entry is part of UAPI and is
21174 			 * used as an array element, so extremely unlikely to
21175 			 * ever grow or shrink
21176 			 */
21177 			BUILD_BUG_ON(br_entry_size != 24);
21178 
21179 			/* if (unlikely(flags)) return -EINVAL */
21180 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
21181 
21182 			/* Transform size (bytes) into number of entries (cnt = size / 24).
21183 			 * But to avoid expensive division instruction, we implement
21184 			 * divide-by-3 through multiplication, followed by further
21185 			 * division by 8 through 3-bit right shift.
21186 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
21187 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
21188 			 *
21189 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
21190 			 */
21191 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
21192 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
21193 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
21194 
21195 			/* call perf_snapshot_branch_stack implementation */
21196 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
21197 			/* if (entry_cnt == 0) return -ENOENT */
21198 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
21199 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
21200 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
21201 			insn_buf[7] = BPF_JMP_A(3);
21202 			/* return -EINVAL; */
21203 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21204 			insn_buf[9] = BPF_JMP_A(1);
21205 			/* return -ENOENT; */
21206 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
21207 			cnt = 11;
21208 
21209 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21210 			if (!new_prog)
21211 				return -ENOMEM;
21212 
21213 			delta    += cnt - 1;
21214 			env->prog = prog = new_prog;
21215 			insn      = new_prog->insnsi + i + delta;
21216 			continue;
21217 		}
21218 
21219 		/* Implement bpf_kptr_xchg inline */
21220 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
21221 		    insn->imm == BPF_FUNC_kptr_xchg &&
21222 		    bpf_jit_supports_ptr_xchg()) {
21223 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
21224 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
21225 			cnt = 2;
21226 
21227 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21228 			if (!new_prog)
21229 				return -ENOMEM;
21230 
21231 			delta    += cnt - 1;
21232 			env->prog = prog = new_prog;
21233 			insn      = new_prog->insnsi + i + delta;
21234 			goto next_insn;
21235 		}
21236 patch_call_imm:
21237 		fn = env->ops->get_func_proto(insn->imm, env->prog);
21238 		/* all functions that have prototype and verifier allowed
21239 		 * programs to call them, must be real in-kernel functions
21240 		 */
21241 		if (!fn->func) {
21242 			verbose(env,
21243 				"kernel subsystem misconfigured func %s#%d\n",
21244 				func_id_name(insn->imm), insn->imm);
21245 			return -EFAULT;
21246 		}
21247 		insn->imm = fn->func - __bpf_call_base;
21248 next_insn:
21249 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21250 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
21251 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
21252 			cur_subprog++;
21253 			stack_depth = subprogs[cur_subprog].stack_depth;
21254 			stack_depth_extra = 0;
21255 		}
21256 		i++;
21257 		insn++;
21258 	}
21259 
21260 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
21261 	for (i = 0; i < env->subprog_cnt; i++) {
21262 		int subprog_start = subprogs[i].start;
21263 		int stack_slots = subprogs[i].stack_extra / 8;
21264 
21265 		if (!stack_slots)
21266 			continue;
21267 		if (stack_slots > 1) {
21268 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
21269 			return -EFAULT;
21270 		}
21271 
21272 		/* Add ST insn to subprog prologue to init extra stack */
21273 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
21274 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
21275 		/* Copy first actual insn to preserve it */
21276 		insn_buf[1] = env->prog->insnsi[subprog_start];
21277 
21278 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
21279 		if (!new_prog)
21280 			return -ENOMEM;
21281 		env->prog = prog = new_prog;
21282 		/*
21283 		 * If may_goto is a first insn of a prog there could be a jmp
21284 		 * insn that points to it, hence adjust all such jmps to point
21285 		 * to insn after BPF_ST that inits may_goto count.
21286 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
21287 		 */
21288 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1));
21289 	}
21290 
21291 	/* Since poke tab is now finalized, publish aux to tracker. */
21292 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21293 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21294 		if (!map_ptr->ops->map_poke_track ||
21295 		    !map_ptr->ops->map_poke_untrack ||
21296 		    !map_ptr->ops->map_poke_run) {
21297 			verbose(env, "bpf verifier is misconfigured\n");
21298 			return -EINVAL;
21299 		}
21300 
21301 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
21302 		if (ret < 0) {
21303 			verbose(env, "tracking tail call prog failed\n");
21304 			return ret;
21305 		}
21306 	}
21307 
21308 	sort_kfunc_descs_by_imm_off(env->prog);
21309 
21310 	return 0;
21311 }
21312 
21313 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
21314 					int position,
21315 					s32 stack_base,
21316 					u32 callback_subprogno,
21317 					u32 *total_cnt)
21318 {
21319 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
21320 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
21321 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
21322 	int reg_loop_max = BPF_REG_6;
21323 	int reg_loop_cnt = BPF_REG_7;
21324 	int reg_loop_ctx = BPF_REG_8;
21325 
21326 	struct bpf_insn *insn_buf = env->insn_buf;
21327 	struct bpf_prog *new_prog;
21328 	u32 callback_start;
21329 	u32 call_insn_offset;
21330 	s32 callback_offset;
21331 	u32 cnt = 0;
21332 
21333 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
21334 	 * be careful to modify this code in sync.
21335 	 */
21336 
21337 	/* Return error and jump to the end of the patch if
21338 	 * expected number of iterations is too big.
21339 	 */
21340 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
21341 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
21342 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
21343 	/* spill R6, R7, R8 to use these as loop vars */
21344 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
21345 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
21346 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
21347 	/* initialize loop vars */
21348 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
21349 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
21350 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
21351 	/* loop header,
21352 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
21353 	 */
21354 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
21355 	/* callback call,
21356 	 * correct callback offset would be set after patching
21357 	 */
21358 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
21359 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
21360 	insn_buf[cnt++] = BPF_CALL_REL(0);
21361 	/* increment loop counter */
21362 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
21363 	/* jump to loop header if callback returned 0 */
21364 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
21365 	/* return value of bpf_loop,
21366 	 * set R0 to the number of iterations
21367 	 */
21368 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
21369 	/* restore original values of R6, R7, R8 */
21370 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
21371 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
21372 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
21373 
21374 	*total_cnt = cnt;
21375 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
21376 	if (!new_prog)
21377 		return new_prog;
21378 
21379 	/* callback start is known only after patching */
21380 	callback_start = env->subprog_info[callback_subprogno].start;
21381 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
21382 	call_insn_offset = position + 12;
21383 	callback_offset = callback_start - call_insn_offset - 1;
21384 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
21385 
21386 	return new_prog;
21387 }
21388 
21389 static bool is_bpf_loop_call(struct bpf_insn *insn)
21390 {
21391 	return insn->code == (BPF_JMP | BPF_CALL) &&
21392 		insn->src_reg == 0 &&
21393 		insn->imm == BPF_FUNC_loop;
21394 }
21395 
21396 /* For all sub-programs in the program (including main) check
21397  * insn_aux_data to see if there are bpf_loop calls that require
21398  * inlining. If such calls are found the calls are replaced with a
21399  * sequence of instructions produced by `inline_bpf_loop` function and
21400  * subprog stack_depth is increased by the size of 3 registers.
21401  * This stack space is used to spill values of the R6, R7, R8.  These
21402  * registers are used to store the loop bound, counter and context
21403  * variables.
21404  */
21405 static int optimize_bpf_loop(struct bpf_verifier_env *env)
21406 {
21407 	struct bpf_subprog_info *subprogs = env->subprog_info;
21408 	int i, cur_subprog = 0, cnt, delta = 0;
21409 	struct bpf_insn *insn = env->prog->insnsi;
21410 	int insn_cnt = env->prog->len;
21411 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
21412 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21413 	u16 stack_depth_extra = 0;
21414 
21415 	for (i = 0; i < insn_cnt; i++, insn++) {
21416 		struct bpf_loop_inline_state *inline_state =
21417 			&env->insn_aux_data[i + delta].loop_inline_state;
21418 
21419 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
21420 			struct bpf_prog *new_prog;
21421 
21422 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
21423 			new_prog = inline_bpf_loop(env,
21424 						   i + delta,
21425 						   -(stack_depth + stack_depth_extra),
21426 						   inline_state->callback_subprogno,
21427 						   &cnt);
21428 			if (!new_prog)
21429 				return -ENOMEM;
21430 
21431 			delta     += cnt - 1;
21432 			env->prog  = new_prog;
21433 			insn       = new_prog->insnsi + i + delta;
21434 		}
21435 
21436 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21437 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
21438 			cur_subprog++;
21439 			stack_depth = subprogs[cur_subprog].stack_depth;
21440 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21441 			stack_depth_extra = 0;
21442 		}
21443 	}
21444 
21445 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21446 
21447 	return 0;
21448 }
21449 
21450 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
21451  * adjust subprograms stack depth when possible.
21452  */
21453 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
21454 {
21455 	struct bpf_subprog_info *subprog = env->subprog_info;
21456 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21457 	struct bpf_insn *insn = env->prog->insnsi;
21458 	int insn_cnt = env->prog->len;
21459 	u32 spills_num;
21460 	bool modified = false;
21461 	int i, j;
21462 
21463 	for (i = 0; i < insn_cnt; i++, insn++) {
21464 		if (aux[i].fastcall_spills_num > 0) {
21465 			spills_num = aux[i].fastcall_spills_num;
21466 			/* NOPs would be removed by opt_remove_nops() */
21467 			for (j = 1; j <= spills_num; ++j) {
21468 				*(insn - j) = NOP;
21469 				*(insn + j) = NOP;
21470 			}
21471 			modified = true;
21472 		}
21473 		if ((subprog + 1)->start == i + 1) {
21474 			if (modified && !subprog->keep_fastcall_stack)
21475 				subprog->stack_depth = -subprog->fastcall_stack_off;
21476 			subprog++;
21477 			modified = false;
21478 		}
21479 	}
21480 
21481 	return 0;
21482 }
21483 
21484 static void free_states(struct bpf_verifier_env *env)
21485 {
21486 	struct bpf_verifier_state_list *sl, *sln;
21487 	int i;
21488 
21489 	sl = env->free_list;
21490 	while (sl) {
21491 		sln = sl->next;
21492 		free_verifier_state(&sl->state, false);
21493 		kfree(sl);
21494 		sl = sln;
21495 	}
21496 	env->free_list = NULL;
21497 
21498 	if (!env->explored_states)
21499 		return;
21500 
21501 	for (i = 0; i < state_htab_size(env); i++) {
21502 		sl = env->explored_states[i];
21503 
21504 		while (sl) {
21505 			sln = sl->next;
21506 			free_verifier_state(&sl->state, false);
21507 			kfree(sl);
21508 			sl = sln;
21509 		}
21510 		env->explored_states[i] = NULL;
21511 	}
21512 }
21513 
21514 static int do_check_common(struct bpf_verifier_env *env, int subprog)
21515 {
21516 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21517 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
21518 	struct bpf_verifier_state *state;
21519 	struct bpf_reg_state *regs;
21520 	int ret, i;
21521 
21522 	env->prev_linfo = NULL;
21523 	env->pass_cnt++;
21524 
21525 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
21526 	if (!state)
21527 		return -ENOMEM;
21528 	state->curframe = 0;
21529 	state->speculative = false;
21530 	state->branches = 1;
21531 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
21532 	if (!state->frame[0]) {
21533 		kfree(state);
21534 		return -ENOMEM;
21535 	}
21536 	env->cur_state = state;
21537 	init_func_state(env, state->frame[0],
21538 			BPF_MAIN_FUNC /* callsite */,
21539 			0 /* frameno */,
21540 			subprog);
21541 	state->first_insn_idx = env->subprog_info[subprog].start;
21542 	state->last_insn_idx = -1;
21543 
21544 	regs = state->frame[state->curframe]->regs;
21545 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
21546 		const char *sub_name = subprog_name(env, subprog);
21547 		struct bpf_subprog_arg_info *arg;
21548 		struct bpf_reg_state *reg;
21549 
21550 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
21551 		ret = btf_prepare_func_args(env, subprog);
21552 		if (ret)
21553 			goto out;
21554 
21555 		if (subprog_is_exc_cb(env, subprog)) {
21556 			state->frame[0]->in_exception_callback_fn = true;
21557 			/* We have already ensured that the callback returns an integer, just
21558 			 * like all global subprogs. We need to determine it only has a single
21559 			 * scalar argument.
21560 			 */
21561 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
21562 				verbose(env, "exception cb only supports single integer argument\n");
21563 				ret = -EINVAL;
21564 				goto out;
21565 			}
21566 		}
21567 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
21568 			arg = &sub->args[i - BPF_REG_1];
21569 			reg = &regs[i];
21570 
21571 			if (arg->arg_type == ARG_PTR_TO_CTX) {
21572 				reg->type = PTR_TO_CTX;
21573 				mark_reg_known_zero(env, regs, i);
21574 			} else if (arg->arg_type == ARG_ANYTHING) {
21575 				reg->type = SCALAR_VALUE;
21576 				mark_reg_unknown(env, regs, i);
21577 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
21578 				/* assume unspecial LOCAL dynptr type */
21579 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
21580 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
21581 				reg->type = PTR_TO_MEM;
21582 				if (arg->arg_type & PTR_MAYBE_NULL)
21583 					reg->type |= PTR_MAYBE_NULL;
21584 				mark_reg_known_zero(env, regs, i);
21585 				reg->mem_size = arg->mem_size;
21586 				reg->id = ++env->id_gen;
21587 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
21588 				reg->type = PTR_TO_BTF_ID;
21589 				if (arg->arg_type & PTR_MAYBE_NULL)
21590 					reg->type |= PTR_MAYBE_NULL;
21591 				if (arg->arg_type & PTR_UNTRUSTED)
21592 					reg->type |= PTR_UNTRUSTED;
21593 				if (arg->arg_type & PTR_TRUSTED)
21594 					reg->type |= PTR_TRUSTED;
21595 				mark_reg_known_zero(env, regs, i);
21596 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
21597 				reg->btf_id = arg->btf_id;
21598 				reg->id = ++env->id_gen;
21599 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
21600 				/* caller can pass either PTR_TO_ARENA or SCALAR */
21601 				mark_reg_unknown(env, regs, i);
21602 			} else {
21603 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
21604 					  i - BPF_REG_1, arg->arg_type);
21605 				ret = -EFAULT;
21606 				goto out;
21607 			}
21608 		}
21609 	} else {
21610 		/* if main BPF program has associated BTF info, validate that
21611 		 * it's matching expected signature, and otherwise mark BTF
21612 		 * info for main program as unreliable
21613 		 */
21614 		if (env->prog->aux->func_info_aux) {
21615 			ret = btf_prepare_func_args(env, 0);
21616 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
21617 				env->prog->aux->func_info_aux[0].unreliable = true;
21618 		}
21619 
21620 		/* 1st arg to a function */
21621 		regs[BPF_REG_1].type = PTR_TO_CTX;
21622 		mark_reg_known_zero(env, regs, BPF_REG_1);
21623 	}
21624 
21625 	ret = do_check(env);
21626 out:
21627 	/* check for NULL is necessary, since cur_state can be freed inside
21628 	 * do_check() under memory pressure.
21629 	 */
21630 	if (env->cur_state) {
21631 		free_verifier_state(env->cur_state, true);
21632 		env->cur_state = NULL;
21633 	}
21634 	while (!pop_stack(env, NULL, NULL, false));
21635 	if (!ret && pop_log)
21636 		bpf_vlog_reset(&env->log, 0);
21637 	free_states(env);
21638 	return ret;
21639 }
21640 
21641 /* Lazily verify all global functions based on their BTF, if they are called
21642  * from main BPF program or any of subprograms transitively.
21643  * BPF global subprogs called from dead code are not validated.
21644  * All callable global functions must pass verification.
21645  * Otherwise the whole program is rejected.
21646  * Consider:
21647  * int bar(int);
21648  * int foo(int f)
21649  * {
21650  *    return bar(f);
21651  * }
21652  * int bar(int b)
21653  * {
21654  *    ...
21655  * }
21656  * foo() will be verified first for R1=any_scalar_value. During verification it
21657  * will be assumed that bar() already verified successfully and call to bar()
21658  * from foo() will be checked for type match only. Later bar() will be verified
21659  * independently to check that it's safe for R1=any_scalar_value.
21660  */
21661 static int do_check_subprogs(struct bpf_verifier_env *env)
21662 {
21663 	struct bpf_prog_aux *aux = env->prog->aux;
21664 	struct bpf_func_info_aux *sub_aux;
21665 	int i, ret, new_cnt;
21666 
21667 	if (!aux->func_info)
21668 		return 0;
21669 
21670 	/* exception callback is presumed to be always called */
21671 	if (env->exception_callback_subprog)
21672 		subprog_aux(env, env->exception_callback_subprog)->called = true;
21673 
21674 again:
21675 	new_cnt = 0;
21676 	for (i = 1; i < env->subprog_cnt; i++) {
21677 		if (!subprog_is_global(env, i))
21678 			continue;
21679 
21680 		sub_aux = subprog_aux(env, i);
21681 		if (!sub_aux->called || sub_aux->verified)
21682 			continue;
21683 
21684 		env->insn_idx = env->subprog_info[i].start;
21685 		WARN_ON_ONCE(env->insn_idx == 0);
21686 		ret = do_check_common(env, i);
21687 		if (ret) {
21688 			return ret;
21689 		} else if (env->log.level & BPF_LOG_LEVEL) {
21690 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
21691 				i, subprog_name(env, i));
21692 		}
21693 
21694 		/* We verified new global subprog, it might have called some
21695 		 * more global subprogs that we haven't verified yet, so we
21696 		 * need to do another pass over subprogs to verify those.
21697 		 */
21698 		sub_aux->verified = true;
21699 		new_cnt++;
21700 	}
21701 
21702 	/* We can't loop forever as we verify at least one global subprog on
21703 	 * each pass.
21704 	 */
21705 	if (new_cnt)
21706 		goto again;
21707 
21708 	return 0;
21709 }
21710 
21711 static int do_check_main(struct bpf_verifier_env *env)
21712 {
21713 	int ret;
21714 
21715 	env->insn_idx = 0;
21716 	ret = do_check_common(env, 0);
21717 	if (!ret)
21718 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21719 	return ret;
21720 }
21721 
21722 
21723 static void print_verification_stats(struct bpf_verifier_env *env)
21724 {
21725 	int i;
21726 
21727 	if (env->log.level & BPF_LOG_STATS) {
21728 		verbose(env, "verification time %lld usec\n",
21729 			div_u64(env->verification_time, 1000));
21730 		verbose(env, "stack depth ");
21731 		for (i = 0; i < env->subprog_cnt; i++) {
21732 			u32 depth = env->subprog_info[i].stack_depth;
21733 
21734 			verbose(env, "%d", depth);
21735 			if (i + 1 < env->subprog_cnt)
21736 				verbose(env, "+");
21737 		}
21738 		verbose(env, "\n");
21739 	}
21740 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
21741 		"total_states %d peak_states %d mark_read %d\n",
21742 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
21743 		env->max_states_per_insn, env->total_states,
21744 		env->peak_states, env->longest_mark_read_walk);
21745 }
21746 
21747 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
21748 {
21749 	const struct btf_type *t, *func_proto;
21750 	const struct bpf_struct_ops_desc *st_ops_desc;
21751 	const struct bpf_struct_ops *st_ops;
21752 	const struct btf_member *member;
21753 	struct bpf_prog *prog = env->prog;
21754 	u32 btf_id, member_idx;
21755 	struct btf *btf;
21756 	const char *mname;
21757 	int err;
21758 
21759 	if (!prog->gpl_compatible) {
21760 		verbose(env, "struct ops programs must have a GPL compatible license\n");
21761 		return -EINVAL;
21762 	}
21763 
21764 	if (!prog->aux->attach_btf_id)
21765 		return -ENOTSUPP;
21766 
21767 	btf = prog->aux->attach_btf;
21768 	if (btf_is_module(btf)) {
21769 		/* Make sure st_ops is valid through the lifetime of env */
21770 		env->attach_btf_mod = btf_try_get_module(btf);
21771 		if (!env->attach_btf_mod) {
21772 			verbose(env, "struct_ops module %s is not found\n",
21773 				btf_get_name(btf));
21774 			return -ENOTSUPP;
21775 		}
21776 	}
21777 
21778 	btf_id = prog->aux->attach_btf_id;
21779 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
21780 	if (!st_ops_desc) {
21781 		verbose(env, "attach_btf_id %u is not a supported struct\n",
21782 			btf_id);
21783 		return -ENOTSUPP;
21784 	}
21785 	st_ops = st_ops_desc->st_ops;
21786 
21787 	t = st_ops_desc->type;
21788 	member_idx = prog->expected_attach_type;
21789 	if (member_idx >= btf_type_vlen(t)) {
21790 		verbose(env, "attach to invalid member idx %u of struct %s\n",
21791 			member_idx, st_ops->name);
21792 		return -EINVAL;
21793 	}
21794 
21795 	member = &btf_type_member(t)[member_idx];
21796 	mname = btf_name_by_offset(btf, member->name_off);
21797 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
21798 					       NULL);
21799 	if (!func_proto) {
21800 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
21801 			mname, member_idx, st_ops->name);
21802 		return -EINVAL;
21803 	}
21804 
21805 	err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8);
21806 	if (err) {
21807 		verbose(env, "attach to unsupported member %s of struct %s\n",
21808 			mname, st_ops->name);
21809 		return err;
21810 	}
21811 
21812 	if (st_ops->check_member) {
21813 		err = st_ops->check_member(t, member, prog);
21814 
21815 		if (err) {
21816 			verbose(env, "attach to unsupported member %s of struct %s\n",
21817 				mname, st_ops->name);
21818 			return err;
21819 		}
21820 	}
21821 
21822 	/* btf_ctx_access() used this to provide argument type info */
21823 	prog->aux->ctx_arg_info =
21824 		st_ops_desc->arg_info[member_idx].info;
21825 	prog->aux->ctx_arg_info_size =
21826 		st_ops_desc->arg_info[member_idx].cnt;
21827 
21828 	prog->aux->attach_func_proto = func_proto;
21829 	prog->aux->attach_func_name = mname;
21830 	env->ops = st_ops->verifier_ops;
21831 
21832 	return 0;
21833 }
21834 #define SECURITY_PREFIX "security_"
21835 
21836 static int check_attach_modify_return(unsigned long addr, const char *func_name)
21837 {
21838 	if (within_error_injection_list(addr) ||
21839 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
21840 		return 0;
21841 
21842 	return -EINVAL;
21843 }
21844 
21845 /* list of non-sleepable functions that are otherwise on
21846  * ALLOW_ERROR_INJECTION list
21847  */
21848 BTF_SET_START(btf_non_sleepable_error_inject)
21849 /* Three functions below can be called from sleepable and non-sleepable context.
21850  * Assume non-sleepable from bpf safety point of view.
21851  */
21852 BTF_ID(func, __filemap_add_folio)
21853 #ifdef CONFIG_FAIL_PAGE_ALLOC
21854 BTF_ID(func, should_fail_alloc_page)
21855 #endif
21856 #ifdef CONFIG_FAILSLAB
21857 BTF_ID(func, should_failslab)
21858 #endif
21859 BTF_SET_END(btf_non_sleepable_error_inject)
21860 
21861 static int check_non_sleepable_error_inject(u32 btf_id)
21862 {
21863 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
21864 }
21865 
21866 int bpf_check_attach_target(struct bpf_verifier_log *log,
21867 			    const struct bpf_prog *prog,
21868 			    const struct bpf_prog *tgt_prog,
21869 			    u32 btf_id,
21870 			    struct bpf_attach_target_info *tgt_info)
21871 {
21872 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
21873 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
21874 	char trace_symbol[KSYM_SYMBOL_LEN];
21875 	const char prefix[] = "btf_trace_";
21876 	struct bpf_raw_event_map *btp;
21877 	int ret = 0, subprog = -1, i;
21878 	const struct btf_type *t;
21879 	bool conservative = true;
21880 	const char *tname, *fname;
21881 	struct btf *btf;
21882 	long addr = 0;
21883 	struct module *mod = NULL;
21884 
21885 	if (!btf_id) {
21886 		bpf_log(log, "Tracing programs must provide btf_id\n");
21887 		return -EINVAL;
21888 	}
21889 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
21890 	if (!btf) {
21891 		bpf_log(log,
21892 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
21893 		return -EINVAL;
21894 	}
21895 	t = btf_type_by_id(btf, btf_id);
21896 	if (!t) {
21897 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
21898 		return -EINVAL;
21899 	}
21900 	tname = btf_name_by_offset(btf, t->name_off);
21901 	if (!tname) {
21902 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
21903 		return -EINVAL;
21904 	}
21905 	if (tgt_prog) {
21906 		struct bpf_prog_aux *aux = tgt_prog->aux;
21907 
21908 		if (bpf_prog_is_dev_bound(prog->aux) &&
21909 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
21910 			bpf_log(log, "Target program bound device mismatch");
21911 			return -EINVAL;
21912 		}
21913 
21914 		for (i = 0; i < aux->func_info_cnt; i++)
21915 			if (aux->func_info[i].type_id == btf_id) {
21916 				subprog = i;
21917 				break;
21918 			}
21919 		if (subprog == -1) {
21920 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
21921 			return -EINVAL;
21922 		}
21923 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
21924 			bpf_log(log,
21925 				"%s programs cannot attach to exception callback\n",
21926 				prog_extension ? "Extension" : "FENTRY/FEXIT");
21927 			return -EINVAL;
21928 		}
21929 		conservative = aux->func_info_aux[subprog].unreliable;
21930 		if (prog_extension) {
21931 			if (conservative) {
21932 				bpf_log(log,
21933 					"Cannot replace static functions\n");
21934 				return -EINVAL;
21935 			}
21936 			if (!prog->jit_requested) {
21937 				bpf_log(log,
21938 					"Extension programs should be JITed\n");
21939 				return -EINVAL;
21940 			}
21941 		}
21942 		if (!tgt_prog->jited) {
21943 			bpf_log(log, "Can attach to only JITed progs\n");
21944 			return -EINVAL;
21945 		}
21946 		if (prog_tracing) {
21947 			if (aux->attach_tracing_prog) {
21948 				/*
21949 				 * Target program is an fentry/fexit which is already attached
21950 				 * to another tracing program. More levels of nesting
21951 				 * attachment are not allowed.
21952 				 */
21953 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
21954 				return -EINVAL;
21955 			}
21956 		} else if (tgt_prog->type == prog->type) {
21957 			/*
21958 			 * To avoid potential call chain cycles, prevent attaching of a
21959 			 * program extension to another extension. It's ok to attach
21960 			 * fentry/fexit to extension program.
21961 			 */
21962 			bpf_log(log, "Cannot recursively attach\n");
21963 			return -EINVAL;
21964 		}
21965 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
21966 		    prog_extension &&
21967 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
21968 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
21969 			/* Program extensions can extend all program types
21970 			 * except fentry/fexit. The reason is the following.
21971 			 * The fentry/fexit programs are used for performance
21972 			 * analysis, stats and can be attached to any program
21973 			 * type. When extension program is replacing XDP function
21974 			 * it is necessary to allow performance analysis of all
21975 			 * functions. Both original XDP program and its program
21976 			 * extension. Hence attaching fentry/fexit to
21977 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
21978 			 * fentry/fexit was allowed it would be possible to create
21979 			 * long call chain fentry->extension->fentry->extension
21980 			 * beyond reasonable stack size. Hence extending fentry
21981 			 * is not allowed.
21982 			 */
21983 			bpf_log(log, "Cannot extend fentry/fexit\n");
21984 			return -EINVAL;
21985 		}
21986 	} else {
21987 		if (prog_extension) {
21988 			bpf_log(log, "Cannot replace kernel functions\n");
21989 			return -EINVAL;
21990 		}
21991 	}
21992 
21993 	switch (prog->expected_attach_type) {
21994 	case BPF_TRACE_RAW_TP:
21995 		if (tgt_prog) {
21996 			bpf_log(log,
21997 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
21998 			return -EINVAL;
21999 		}
22000 		if (!btf_type_is_typedef(t)) {
22001 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
22002 				btf_id);
22003 			return -EINVAL;
22004 		}
22005 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
22006 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22007 				btf_id, tname);
22008 			return -EINVAL;
22009 		}
22010 		tname += sizeof(prefix) - 1;
22011 
22012 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22013 		 * names. Thus using bpf_raw_event_map to get argument names.
22014 		 */
22015 		btp = bpf_get_raw_tracepoint(tname);
22016 		if (!btp)
22017 			return -EINVAL;
22018 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22019 					trace_symbol);
22020 		bpf_put_raw_tracepoint(btp);
22021 
22022 		if (fname)
22023 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22024 
22025 		if (!fname || ret < 0) {
22026 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22027 				prefix, tname);
22028 			t = btf_type_by_id(btf, t->type);
22029 			if (!btf_type_is_ptr(t))
22030 				/* should never happen in valid vmlinux build */
22031 				return -EINVAL;
22032 		} else {
22033 			t = btf_type_by_id(btf, ret);
22034 			if (!btf_type_is_func(t))
22035 				/* should never happen in valid vmlinux build */
22036 				return -EINVAL;
22037 		}
22038 
22039 		t = btf_type_by_id(btf, t->type);
22040 		if (!btf_type_is_func_proto(t))
22041 			/* should never happen in valid vmlinux build */
22042 			return -EINVAL;
22043 
22044 		break;
22045 	case BPF_TRACE_ITER:
22046 		if (!btf_type_is_func(t)) {
22047 			bpf_log(log, "attach_btf_id %u is not a function\n",
22048 				btf_id);
22049 			return -EINVAL;
22050 		}
22051 		t = btf_type_by_id(btf, t->type);
22052 		if (!btf_type_is_func_proto(t))
22053 			return -EINVAL;
22054 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22055 		if (ret)
22056 			return ret;
22057 		break;
22058 	default:
22059 		if (!prog_extension)
22060 			return -EINVAL;
22061 		fallthrough;
22062 	case BPF_MODIFY_RETURN:
22063 	case BPF_LSM_MAC:
22064 	case BPF_LSM_CGROUP:
22065 	case BPF_TRACE_FENTRY:
22066 	case BPF_TRACE_FEXIT:
22067 		if (!btf_type_is_func(t)) {
22068 			bpf_log(log, "attach_btf_id %u is not a function\n",
22069 				btf_id);
22070 			return -EINVAL;
22071 		}
22072 		if (prog_extension &&
22073 		    btf_check_type_match(log, prog, btf, t))
22074 			return -EINVAL;
22075 		t = btf_type_by_id(btf, t->type);
22076 		if (!btf_type_is_func_proto(t))
22077 			return -EINVAL;
22078 
22079 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22080 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22081 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22082 			return -EINVAL;
22083 
22084 		if (tgt_prog && conservative)
22085 			t = NULL;
22086 
22087 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22088 		if (ret < 0)
22089 			return ret;
22090 
22091 		if (tgt_prog) {
22092 			if (subprog == 0)
22093 				addr = (long) tgt_prog->bpf_func;
22094 			else
22095 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
22096 		} else {
22097 			if (btf_is_module(btf)) {
22098 				mod = btf_try_get_module(btf);
22099 				if (mod)
22100 					addr = find_kallsyms_symbol_value(mod, tname);
22101 				else
22102 					addr = 0;
22103 			} else {
22104 				addr = kallsyms_lookup_name(tname);
22105 			}
22106 			if (!addr) {
22107 				module_put(mod);
22108 				bpf_log(log,
22109 					"The address of function %s cannot be found\n",
22110 					tname);
22111 				return -ENOENT;
22112 			}
22113 		}
22114 
22115 		if (prog->sleepable) {
22116 			ret = -EINVAL;
22117 			switch (prog->type) {
22118 			case BPF_PROG_TYPE_TRACING:
22119 
22120 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
22121 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
22122 				 */
22123 				if (!check_non_sleepable_error_inject(btf_id) &&
22124 				    within_error_injection_list(addr))
22125 					ret = 0;
22126 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
22127 				 * in the fmodret id set with the KF_SLEEPABLE flag.
22128 				 */
22129 				else {
22130 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
22131 										prog);
22132 
22133 					if (flags && (*flags & KF_SLEEPABLE))
22134 						ret = 0;
22135 				}
22136 				break;
22137 			case BPF_PROG_TYPE_LSM:
22138 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
22139 				 * Only some of them are sleepable.
22140 				 */
22141 				if (bpf_lsm_is_sleepable_hook(btf_id))
22142 					ret = 0;
22143 				break;
22144 			default:
22145 				break;
22146 			}
22147 			if (ret) {
22148 				module_put(mod);
22149 				bpf_log(log, "%s is not sleepable\n", tname);
22150 				return ret;
22151 			}
22152 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
22153 			if (tgt_prog) {
22154 				module_put(mod);
22155 				bpf_log(log, "can't modify return codes of BPF programs\n");
22156 				return -EINVAL;
22157 			}
22158 			ret = -EINVAL;
22159 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
22160 			    !check_attach_modify_return(addr, tname))
22161 				ret = 0;
22162 			if (ret) {
22163 				module_put(mod);
22164 				bpf_log(log, "%s() is not modifiable\n", tname);
22165 				return ret;
22166 			}
22167 		}
22168 
22169 		break;
22170 	}
22171 	tgt_info->tgt_addr = addr;
22172 	tgt_info->tgt_name = tname;
22173 	tgt_info->tgt_type = t;
22174 	tgt_info->tgt_mod = mod;
22175 	return 0;
22176 }
22177 
22178 BTF_SET_START(btf_id_deny)
22179 BTF_ID_UNUSED
22180 #ifdef CONFIG_SMP
22181 BTF_ID(func, migrate_disable)
22182 BTF_ID(func, migrate_enable)
22183 #endif
22184 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
22185 BTF_ID(func, rcu_read_unlock_strict)
22186 #endif
22187 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
22188 BTF_ID(func, preempt_count_add)
22189 BTF_ID(func, preempt_count_sub)
22190 #endif
22191 #ifdef CONFIG_PREEMPT_RCU
22192 BTF_ID(func, __rcu_read_lock)
22193 BTF_ID(func, __rcu_read_unlock)
22194 #endif
22195 BTF_SET_END(btf_id_deny)
22196 
22197 static bool can_be_sleepable(struct bpf_prog *prog)
22198 {
22199 	if (prog->type == BPF_PROG_TYPE_TRACING) {
22200 		switch (prog->expected_attach_type) {
22201 		case BPF_TRACE_FENTRY:
22202 		case BPF_TRACE_FEXIT:
22203 		case BPF_MODIFY_RETURN:
22204 		case BPF_TRACE_ITER:
22205 			return true;
22206 		default:
22207 			return false;
22208 		}
22209 	}
22210 	return prog->type == BPF_PROG_TYPE_LSM ||
22211 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
22212 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
22213 }
22214 
22215 static int check_attach_btf_id(struct bpf_verifier_env *env)
22216 {
22217 	struct bpf_prog *prog = env->prog;
22218 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
22219 	struct bpf_attach_target_info tgt_info = {};
22220 	u32 btf_id = prog->aux->attach_btf_id;
22221 	struct bpf_trampoline *tr;
22222 	int ret;
22223 	u64 key;
22224 
22225 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
22226 		if (prog->sleepable)
22227 			/* attach_btf_id checked to be zero already */
22228 			return 0;
22229 		verbose(env, "Syscall programs can only be sleepable\n");
22230 		return -EINVAL;
22231 	}
22232 
22233 	if (prog->sleepable && !can_be_sleepable(prog)) {
22234 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
22235 		return -EINVAL;
22236 	}
22237 
22238 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
22239 		return check_struct_ops_btf_id(env);
22240 
22241 	if (prog->type != BPF_PROG_TYPE_TRACING &&
22242 	    prog->type != BPF_PROG_TYPE_LSM &&
22243 	    prog->type != BPF_PROG_TYPE_EXT)
22244 		return 0;
22245 
22246 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
22247 	if (ret)
22248 		return ret;
22249 
22250 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
22251 		/* to make freplace equivalent to their targets, they need to
22252 		 * inherit env->ops and expected_attach_type for the rest of the
22253 		 * verification
22254 		 */
22255 		env->ops = bpf_verifier_ops[tgt_prog->type];
22256 		prog->expected_attach_type = tgt_prog->expected_attach_type;
22257 	}
22258 
22259 	/* store info about the attachment target that will be used later */
22260 	prog->aux->attach_func_proto = tgt_info.tgt_type;
22261 	prog->aux->attach_func_name = tgt_info.tgt_name;
22262 	prog->aux->mod = tgt_info.tgt_mod;
22263 
22264 	if (tgt_prog) {
22265 		prog->aux->saved_dst_prog_type = tgt_prog->type;
22266 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
22267 	}
22268 
22269 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
22270 		prog->aux->attach_btf_trace = true;
22271 		return 0;
22272 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
22273 		if (!bpf_iter_prog_supported(prog))
22274 			return -EINVAL;
22275 		return 0;
22276 	}
22277 
22278 	if (prog->type == BPF_PROG_TYPE_LSM) {
22279 		ret = bpf_lsm_verify_prog(&env->log, prog);
22280 		if (ret < 0)
22281 			return ret;
22282 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
22283 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
22284 		return -EINVAL;
22285 	}
22286 
22287 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
22288 	tr = bpf_trampoline_get(key, &tgt_info);
22289 	if (!tr)
22290 		return -ENOMEM;
22291 
22292 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
22293 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
22294 
22295 	prog->aux->dst_trampoline = tr;
22296 	return 0;
22297 }
22298 
22299 struct btf *bpf_get_btf_vmlinux(void)
22300 {
22301 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
22302 		mutex_lock(&bpf_verifier_lock);
22303 		if (!btf_vmlinux)
22304 			btf_vmlinux = btf_parse_vmlinux();
22305 		mutex_unlock(&bpf_verifier_lock);
22306 	}
22307 	return btf_vmlinux;
22308 }
22309 
22310 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
22311 {
22312 	u64 start_time = ktime_get_ns();
22313 	struct bpf_verifier_env *env;
22314 	int i, len, ret = -EINVAL, err;
22315 	u32 log_true_size;
22316 	bool is_priv;
22317 
22318 	/* no program is valid */
22319 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
22320 		return -EINVAL;
22321 
22322 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
22323 	 * allocate/free it every time bpf_check() is called
22324 	 */
22325 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
22326 	if (!env)
22327 		return -ENOMEM;
22328 
22329 	env->bt.env = env;
22330 
22331 	len = (*prog)->len;
22332 	env->insn_aux_data =
22333 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
22334 	ret = -ENOMEM;
22335 	if (!env->insn_aux_data)
22336 		goto err_free_env;
22337 	for (i = 0; i < len; i++)
22338 		env->insn_aux_data[i].orig_idx = i;
22339 	env->prog = *prog;
22340 	env->ops = bpf_verifier_ops[env->prog->type];
22341 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
22342 
22343 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
22344 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
22345 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
22346 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
22347 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
22348 
22349 	bpf_get_btf_vmlinux();
22350 
22351 	/* grab the mutex to protect few globals used by verifier */
22352 	if (!is_priv)
22353 		mutex_lock(&bpf_verifier_lock);
22354 
22355 	/* user could have requested verbose verifier output
22356 	 * and supplied buffer to store the verification trace
22357 	 */
22358 	ret = bpf_vlog_init(&env->log, attr->log_level,
22359 			    (char __user *) (unsigned long) attr->log_buf,
22360 			    attr->log_size);
22361 	if (ret)
22362 		goto err_unlock;
22363 
22364 	mark_verifier_state_clean(env);
22365 
22366 	if (IS_ERR(btf_vmlinux)) {
22367 		/* Either gcc or pahole or kernel are broken. */
22368 		verbose(env, "in-kernel BTF is malformed\n");
22369 		ret = PTR_ERR(btf_vmlinux);
22370 		goto skip_full_check;
22371 	}
22372 
22373 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
22374 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
22375 		env->strict_alignment = true;
22376 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
22377 		env->strict_alignment = false;
22378 
22379 	if (is_priv)
22380 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
22381 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
22382 
22383 	env->explored_states = kvcalloc(state_htab_size(env),
22384 				       sizeof(struct bpf_verifier_state_list *),
22385 				       GFP_USER);
22386 	ret = -ENOMEM;
22387 	if (!env->explored_states)
22388 		goto skip_full_check;
22389 
22390 	ret = check_btf_info_early(env, attr, uattr);
22391 	if (ret < 0)
22392 		goto skip_full_check;
22393 
22394 	ret = add_subprog_and_kfunc(env);
22395 	if (ret < 0)
22396 		goto skip_full_check;
22397 
22398 	ret = check_subprogs(env);
22399 	if (ret < 0)
22400 		goto skip_full_check;
22401 
22402 	ret = check_btf_info(env, attr, uattr);
22403 	if (ret < 0)
22404 		goto skip_full_check;
22405 
22406 	ret = check_attach_btf_id(env);
22407 	if (ret)
22408 		goto skip_full_check;
22409 
22410 	ret = resolve_pseudo_ldimm64(env);
22411 	if (ret < 0)
22412 		goto skip_full_check;
22413 
22414 	if (bpf_prog_is_offloaded(env->prog->aux)) {
22415 		ret = bpf_prog_offload_verifier_prep(env->prog);
22416 		if (ret)
22417 			goto skip_full_check;
22418 	}
22419 
22420 	ret = check_cfg(env);
22421 	if (ret < 0)
22422 		goto skip_full_check;
22423 
22424 	ret = mark_fastcall_patterns(env);
22425 	if (ret < 0)
22426 		goto skip_full_check;
22427 
22428 	ret = do_check_main(env);
22429 	ret = ret ?: do_check_subprogs(env);
22430 
22431 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
22432 		ret = bpf_prog_offload_finalize(env);
22433 
22434 skip_full_check:
22435 	kvfree(env->explored_states);
22436 
22437 	/* might decrease stack depth, keep it before passes that
22438 	 * allocate additional slots.
22439 	 */
22440 	if (ret == 0)
22441 		ret = remove_fastcall_spills_fills(env);
22442 
22443 	if (ret == 0)
22444 		ret = check_max_stack_depth(env);
22445 
22446 	/* instruction rewrites happen after this point */
22447 	if (ret == 0)
22448 		ret = optimize_bpf_loop(env);
22449 
22450 	if (is_priv) {
22451 		if (ret == 0)
22452 			opt_hard_wire_dead_code_branches(env);
22453 		if (ret == 0)
22454 			ret = opt_remove_dead_code(env);
22455 		if (ret == 0)
22456 			ret = opt_remove_nops(env);
22457 	} else {
22458 		if (ret == 0)
22459 			sanitize_dead_code(env);
22460 	}
22461 
22462 	if (ret == 0)
22463 		/* program is valid, convert *(u32*)(ctx + off) accesses */
22464 		ret = convert_ctx_accesses(env);
22465 
22466 	if (ret == 0)
22467 		ret = do_misc_fixups(env);
22468 
22469 	/* do 32-bit optimization after insn patching has done so those patched
22470 	 * insns could be handled correctly.
22471 	 */
22472 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
22473 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
22474 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
22475 								     : false;
22476 	}
22477 
22478 	if (ret == 0)
22479 		ret = fixup_call_args(env);
22480 
22481 	env->verification_time = ktime_get_ns() - start_time;
22482 	print_verification_stats(env);
22483 	env->prog->aux->verified_insns = env->insn_processed;
22484 
22485 	/* preserve original error even if log finalization is successful */
22486 	err = bpf_vlog_finalize(&env->log, &log_true_size);
22487 	if (err)
22488 		ret = err;
22489 
22490 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
22491 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
22492 				  &log_true_size, sizeof(log_true_size))) {
22493 		ret = -EFAULT;
22494 		goto err_release_maps;
22495 	}
22496 
22497 	if (ret)
22498 		goto err_release_maps;
22499 
22500 	if (env->used_map_cnt) {
22501 		/* if program passed verifier, update used_maps in bpf_prog_info */
22502 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
22503 							  sizeof(env->used_maps[0]),
22504 							  GFP_KERNEL);
22505 
22506 		if (!env->prog->aux->used_maps) {
22507 			ret = -ENOMEM;
22508 			goto err_release_maps;
22509 		}
22510 
22511 		memcpy(env->prog->aux->used_maps, env->used_maps,
22512 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
22513 		env->prog->aux->used_map_cnt = env->used_map_cnt;
22514 	}
22515 	if (env->used_btf_cnt) {
22516 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
22517 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
22518 							  sizeof(env->used_btfs[0]),
22519 							  GFP_KERNEL);
22520 		if (!env->prog->aux->used_btfs) {
22521 			ret = -ENOMEM;
22522 			goto err_release_maps;
22523 		}
22524 
22525 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
22526 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
22527 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
22528 	}
22529 	if (env->used_map_cnt || env->used_btf_cnt) {
22530 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
22531 		 * bpf_ld_imm64 instructions
22532 		 */
22533 		convert_pseudo_ld_imm64(env);
22534 	}
22535 
22536 	adjust_btf_func(env);
22537 
22538 err_release_maps:
22539 	if (!env->prog->aux->used_maps)
22540 		/* if we didn't copy map pointers into bpf_prog_info, release
22541 		 * them now. Otherwise free_used_maps() will release them.
22542 		 */
22543 		release_maps(env);
22544 	if (!env->prog->aux->used_btfs)
22545 		release_btfs(env);
22546 
22547 	/* extension progs temporarily inherit the attach_type of their targets
22548 	   for verification purposes, so set it back to zero before returning
22549 	 */
22550 	if (env->prog->type == BPF_PROG_TYPE_EXT)
22551 		env->prog->expected_attach_type = 0;
22552 
22553 	*prog = env->prog;
22554 
22555 	module_put(env->attach_btf_mod);
22556 err_unlock:
22557 	if (!is_priv)
22558 		mutex_unlock(&bpf_verifier_lock);
22559 	vfree(env->insn_aux_data);
22560 err_free_env:
22561 	kvfree(env);
22562 	return ret;
22563 }
22564