xref: /openbmc/linux/kernel/bpf/verifier.c (revision aaa746ad)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 
28 #include "disasm.h"
29 
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 	[_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 	/* length of verifier log at the time this state was pushed on stack */
177 	u32 log_pos;
178 };
179 
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
181 #define BPF_COMPLEXITY_LIMIT_STATES	64
182 
183 #define BPF_MAP_KEY_POISON	(1ULL << 63)
184 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
185 
186 #define BPF_MAP_PTR_UNPRIV	1UL
187 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
188 					  POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198 
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203 
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 			      const struct bpf_map *map, bool unpriv)
206 {
207 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 	unpriv |= bpf_map_ptr_unpriv(aux);
209 	aux->map_ptr_state = (unsigned long)map |
210 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212 
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215 	return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217 
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222 
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227 
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230 	bool poisoned = bpf_map_key_poisoned(aux);
231 
232 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235 
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238 	return insn->code == (BPF_JMP | BPF_CALL) &&
239 	       insn->src_reg == BPF_PSEUDO_CALL;
240 }
241 
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244 	return insn->code == (BPF_JMP | BPF_CALL) &&
245 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247 
248 struct bpf_call_arg_meta {
249 	struct bpf_map *map_ptr;
250 	bool raw_mode;
251 	bool pkt_access;
252 	u8 release_regno;
253 	int regno;
254 	int access_size;
255 	int mem_size;
256 	u64 msize_max_value;
257 	int ref_obj_id;
258 	int map_uid;
259 	int func_id;
260 	struct btf *btf;
261 	u32 btf_id;
262 	struct btf *ret_btf;
263 	u32 ret_btf_id;
264 	u32 subprogno;
265 	struct btf_field *kptr_field;
266 	u8 uninit_dynptr_regno;
267 };
268 
269 struct btf *btf_vmlinux;
270 
271 static DEFINE_MUTEX(bpf_verifier_lock);
272 
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276 	const struct bpf_line_info *linfo;
277 	const struct bpf_prog *prog;
278 	u32 i, nr_linfo;
279 
280 	prog = env->prog;
281 	nr_linfo = prog->aux->nr_linfo;
282 
283 	if (!nr_linfo || insn_off >= prog->len)
284 		return NULL;
285 
286 	linfo = prog->aux->linfo;
287 	for (i = 1; i < nr_linfo; i++)
288 		if (insn_off < linfo[i].insn_off)
289 			break;
290 
291 	return &linfo[i - 1];
292 }
293 
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295 		       va_list args)
296 {
297 	unsigned int n;
298 
299 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300 
301 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 		  "verifier log line truncated - local buffer too short\n");
303 
304 	if (log->level == BPF_LOG_KERNEL) {
305 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306 
307 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308 		return;
309 	}
310 
311 	n = min(log->len_total - log->len_used - 1, n);
312 	log->kbuf[n] = '\0';
313 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 		log->len_used += n;
315 	else
316 		log->ubuf = NULL;
317 }
318 
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321 	char zero = 0;
322 
323 	if (!bpf_verifier_log_needed(log))
324 		return;
325 
326 	log->len_used = new_pos;
327 	if (put_user(zero, log->ubuf + new_pos))
328 		log->ubuf = NULL;
329 }
330 
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 					   const char *fmt, ...)
337 {
338 	va_list args;
339 
340 	if (!bpf_verifier_log_needed(&env->log))
341 		return;
342 
343 	va_start(args, fmt);
344 	bpf_verifier_vlog(&env->log, fmt, args);
345 	va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348 
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351 	struct bpf_verifier_env *env = private_data;
352 	va_list args;
353 
354 	if (!bpf_verifier_log_needed(&env->log))
355 		return;
356 
357 	va_start(args, fmt);
358 	bpf_verifier_vlog(&env->log, fmt, args);
359 	va_end(args);
360 }
361 
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 			    const char *fmt, ...)
364 {
365 	va_list args;
366 
367 	if (!bpf_verifier_log_needed(log))
368 		return;
369 
370 	va_start(args, fmt);
371 	bpf_verifier_vlog(log, fmt, args);
372 	va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375 
376 static const char *ltrim(const char *s)
377 {
378 	while (isspace(*s))
379 		s++;
380 
381 	return s;
382 }
383 
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385 					 u32 insn_off,
386 					 const char *prefix_fmt, ...)
387 {
388 	const struct bpf_line_info *linfo;
389 
390 	if (!bpf_verifier_log_needed(&env->log))
391 		return;
392 
393 	linfo = find_linfo(env, insn_off);
394 	if (!linfo || linfo == env->prev_linfo)
395 		return;
396 
397 	if (prefix_fmt) {
398 		va_list args;
399 
400 		va_start(args, prefix_fmt);
401 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 		va_end(args);
403 	}
404 
405 	verbose(env, "%s\n",
406 		ltrim(btf_name_by_offset(env->prog->aux->btf,
407 					 linfo->line_off)));
408 
409 	env->prev_linfo = linfo;
410 }
411 
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 				   struct bpf_reg_state *reg,
414 				   struct tnum *range, const char *ctx,
415 				   const char *reg_name)
416 {
417 	char tn_buf[48];
418 
419 	verbose(env, "At %s the register %s ", ctx, reg_name);
420 	if (!tnum_is_unknown(reg->var_off)) {
421 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 		verbose(env, "has value %s", tn_buf);
423 	} else {
424 		verbose(env, "has unknown scalar value");
425 	}
426 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 	verbose(env, " should have been in %s\n", tn_buf);
428 }
429 
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432 	type = base_type(type);
433 	return type == PTR_TO_PACKET ||
434 	       type == PTR_TO_PACKET_META;
435 }
436 
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439 	return type == PTR_TO_SOCKET ||
440 		type == PTR_TO_SOCK_COMMON ||
441 		type == PTR_TO_TCP_SOCK ||
442 		type == PTR_TO_XDP_SOCK;
443 }
444 
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447 	return type == PTR_TO_SOCKET ||
448 		type == PTR_TO_TCP_SOCK ||
449 		type == PTR_TO_MAP_VALUE ||
450 		type == PTR_TO_MAP_KEY ||
451 		type == PTR_TO_SOCK_COMMON;
452 }
453 
454 static bool type_is_ptr_alloc_obj(u32 type)
455 {
456 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
457 }
458 
459 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
460 {
461 	struct btf_record *rec = NULL;
462 	struct btf_struct_meta *meta;
463 
464 	if (reg->type == PTR_TO_MAP_VALUE) {
465 		rec = reg->map_ptr->record;
466 	} else if (type_is_ptr_alloc_obj(reg->type)) {
467 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
468 		if (meta)
469 			rec = meta->record;
470 	}
471 	return rec;
472 }
473 
474 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
475 {
476 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
477 }
478 
479 static bool type_is_rdonly_mem(u32 type)
480 {
481 	return type & MEM_RDONLY;
482 }
483 
484 static bool type_may_be_null(u32 type)
485 {
486 	return type & PTR_MAYBE_NULL;
487 }
488 
489 static bool is_acquire_function(enum bpf_func_id func_id,
490 				const struct bpf_map *map)
491 {
492 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
493 
494 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
495 	    func_id == BPF_FUNC_sk_lookup_udp ||
496 	    func_id == BPF_FUNC_skc_lookup_tcp ||
497 	    func_id == BPF_FUNC_ringbuf_reserve ||
498 	    func_id == BPF_FUNC_kptr_xchg)
499 		return true;
500 
501 	if (func_id == BPF_FUNC_map_lookup_elem &&
502 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
503 	     map_type == BPF_MAP_TYPE_SOCKHASH))
504 		return true;
505 
506 	return false;
507 }
508 
509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
510 {
511 	return func_id == BPF_FUNC_tcp_sock ||
512 		func_id == BPF_FUNC_sk_fullsock ||
513 		func_id == BPF_FUNC_skc_to_tcp_sock ||
514 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
515 		func_id == BPF_FUNC_skc_to_udp6_sock ||
516 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
517 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
518 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
519 }
520 
521 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
522 {
523 	return func_id == BPF_FUNC_dynptr_data;
524 }
525 
526 static bool is_callback_calling_function(enum bpf_func_id func_id)
527 {
528 	return func_id == BPF_FUNC_for_each_map_elem ||
529 	       func_id == BPF_FUNC_timer_set_callback ||
530 	       func_id == BPF_FUNC_find_vma ||
531 	       func_id == BPF_FUNC_loop ||
532 	       func_id == BPF_FUNC_user_ringbuf_drain;
533 }
534 
535 static bool is_storage_get_function(enum bpf_func_id func_id)
536 {
537 	return func_id == BPF_FUNC_sk_storage_get ||
538 	       func_id == BPF_FUNC_inode_storage_get ||
539 	       func_id == BPF_FUNC_task_storage_get ||
540 	       func_id == BPF_FUNC_cgrp_storage_get;
541 }
542 
543 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
544 					const struct bpf_map *map)
545 {
546 	int ref_obj_uses = 0;
547 
548 	if (is_ptr_cast_function(func_id))
549 		ref_obj_uses++;
550 	if (is_acquire_function(func_id, map))
551 		ref_obj_uses++;
552 	if (is_dynptr_ref_function(func_id))
553 		ref_obj_uses++;
554 
555 	return ref_obj_uses > 1;
556 }
557 
558 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
559 {
560 	return BPF_CLASS(insn->code) == BPF_STX &&
561 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
562 	       insn->imm == BPF_CMPXCHG;
563 }
564 
565 /* string representation of 'enum bpf_reg_type'
566  *
567  * Note that reg_type_str() can not appear more than once in a single verbose()
568  * statement.
569  */
570 static const char *reg_type_str(struct bpf_verifier_env *env,
571 				enum bpf_reg_type type)
572 {
573 	char postfix[16] = {0}, prefix[64] = {0};
574 	static const char * const str[] = {
575 		[NOT_INIT]		= "?",
576 		[SCALAR_VALUE]		= "scalar",
577 		[PTR_TO_CTX]		= "ctx",
578 		[CONST_PTR_TO_MAP]	= "map_ptr",
579 		[PTR_TO_MAP_VALUE]	= "map_value",
580 		[PTR_TO_STACK]		= "fp",
581 		[PTR_TO_PACKET]		= "pkt",
582 		[PTR_TO_PACKET_META]	= "pkt_meta",
583 		[PTR_TO_PACKET_END]	= "pkt_end",
584 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
585 		[PTR_TO_SOCKET]		= "sock",
586 		[PTR_TO_SOCK_COMMON]	= "sock_common",
587 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
588 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
589 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
590 		[PTR_TO_BTF_ID]		= "ptr_",
591 		[PTR_TO_MEM]		= "mem",
592 		[PTR_TO_BUF]		= "buf",
593 		[PTR_TO_FUNC]		= "func",
594 		[PTR_TO_MAP_KEY]	= "map_key",
595 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
596 	};
597 
598 	if (type & PTR_MAYBE_NULL) {
599 		if (base_type(type) == PTR_TO_BTF_ID)
600 			strncpy(postfix, "or_null_", 16);
601 		else
602 			strncpy(postfix, "_or_null", 16);
603 	}
604 
605 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
606 		 type & MEM_RDONLY ? "rdonly_" : "",
607 		 type & MEM_RINGBUF ? "ringbuf_" : "",
608 		 type & MEM_USER ? "user_" : "",
609 		 type & MEM_PERCPU ? "percpu_" : "",
610 		 type & MEM_RCU ? "rcu_" : "",
611 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
612 		 type & PTR_TRUSTED ? "trusted_" : ""
613 	);
614 
615 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
616 		 prefix, str[base_type(type)], postfix);
617 	return env->type_str_buf;
618 }
619 
620 static char slot_type_char[] = {
621 	[STACK_INVALID]	= '?',
622 	[STACK_SPILL]	= 'r',
623 	[STACK_MISC]	= 'm',
624 	[STACK_ZERO]	= '0',
625 	[STACK_DYNPTR]	= 'd',
626 };
627 
628 static void print_liveness(struct bpf_verifier_env *env,
629 			   enum bpf_reg_liveness live)
630 {
631 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
632 	    verbose(env, "_");
633 	if (live & REG_LIVE_READ)
634 		verbose(env, "r");
635 	if (live & REG_LIVE_WRITTEN)
636 		verbose(env, "w");
637 	if (live & REG_LIVE_DONE)
638 		verbose(env, "D");
639 }
640 
641 static int get_spi(s32 off)
642 {
643 	return (-off - 1) / BPF_REG_SIZE;
644 }
645 
646 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
647 {
648 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
649 
650 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
651 	 * within [0, allocated_stack).
652 	 *
653 	 * Please note that the spi grows downwards. For example, a dynptr
654 	 * takes the size of two stack slots; the first slot will be at
655 	 * spi and the second slot will be at spi - 1.
656 	 */
657 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
658 }
659 
660 static struct bpf_func_state *func(struct bpf_verifier_env *env,
661 				   const struct bpf_reg_state *reg)
662 {
663 	struct bpf_verifier_state *cur = env->cur_state;
664 
665 	return cur->frame[reg->frameno];
666 }
667 
668 static const char *kernel_type_name(const struct btf* btf, u32 id)
669 {
670 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
671 }
672 
673 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
674 {
675 	env->scratched_regs |= 1U << regno;
676 }
677 
678 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
679 {
680 	env->scratched_stack_slots |= 1ULL << spi;
681 }
682 
683 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
684 {
685 	return (env->scratched_regs >> regno) & 1;
686 }
687 
688 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
689 {
690 	return (env->scratched_stack_slots >> regno) & 1;
691 }
692 
693 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
694 {
695 	return env->scratched_regs || env->scratched_stack_slots;
696 }
697 
698 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
699 {
700 	env->scratched_regs = 0U;
701 	env->scratched_stack_slots = 0ULL;
702 }
703 
704 /* Used for printing the entire verifier state. */
705 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
706 {
707 	env->scratched_regs = ~0U;
708 	env->scratched_stack_slots = ~0ULL;
709 }
710 
711 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
712 {
713 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
714 	case DYNPTR_TYPE_LOCAL:
715 		return BPF_DYNPTR_TYPE_LOCAL;
716 	case DYNPTR_TYPE_RINGBUF:
717 		return BPF_DYNPTR_TYPE_RINGBUF;
718 	default:
719 		return BPF_DYNPTR_TYPE_INVALID;
720 	}
721 }
722 
723 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
724 {
725 	return type == BPF_DYNPTR_TYPE_RINGBUF;
726 }
727 
728 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
729 			      enum bpf_dynptr_type type,
730 			      bool first_slot);
731 
732 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
733 				struct bpf_reg_state *reg);
734 
735 static void mark_dynptr_stack_regs(struct bpf_reg_state *sreg1,
736 				   struct bpf_reg_state *sreg2,
737 				   enum bpf_dynptr_type type)
738 {
739 	__mark_dynptr_reg(sreg1, type, true);
740 	__mark_dynptr_reg(sreg2, type, false);
741 }
742 
743 static void mark_dynptr_cb_reg(struct bpf_reg_state *reg,
744 			       enum bpf_dynptr_type type)
745 {
746 	__mark_dynptr_reg(reg, type, true);
747 }
748 
749 
750 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
751 				   enum bpf_arg_type arg_type, int insn_idx)
752 {
753 	struct bpf_func_state *state = func(env, reg);
754 	enum bpf_dynptr_type type;
755 	int spi, i, id;
756 
757 	spi = get_spi(reg->off);
758 
759 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
760 		return -EINVAL;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
764 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765 	}
766 
767 	type = arg_to_dynptr_type(arg_type);
768 	if (type == BPF_DYNPTR_TYPE_INVALID)
769 		return -EINVAL;
770 
771 	mark_dynptr_stack_regs(&state->stack[spi].spilled_ptr,
772 			       &state->stack[spi - 1].spilled_ptr, type);
773 
774 	if (dynptr_type_refcounted(type)) {
775 		/* The id is used to track proper releasing */
776 		id = acquire_reference_state(env, insn_idx);
777 		if (id < 0)
778 			return id;
779 
780 		state->stack[spi].spilled_ptr.ref_obj_id = id;
781 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
782 	}
783 
784 	return 0;
785 }
786 
787 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
788 {
789 	struct bpf_func_state *state = func(env, reg);
790 	int spi, i;
791 
792 	spi = get_spi(reg->off);
793 
794 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
795 		return -EINVAL;
796 
797 	for (i = 0; i < BPF_REG_SIZE; i++) {
798 		state->stack[spi].slot_type[i] = STACK_INVALID;
799 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
800 	}
801 
802 	/* Invalidate any slices associated with this dynptr */
803 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
804 		WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
805 
806 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
807 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
808 	return 0;
809 }
810 
811 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
812 {
813 	struct bpf_func_state *state = func(env, reg);
814 	int spi, i;
815 
816 	if (reg->type == CONST_PTR_TO_DYNPTR)
817 		return false;
818 
819 	spi = get_spi(reg->off);
820 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
821 		return true;
822 
823 	for (i = 0; i < BPF_REG_SIZE; i++) {
824 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
825 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
826 			return false;
827 	}
828 
829 	return true;
830 }
831 
832 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
833 {
834 	struct bpf_func_state *state = func(env, reg);
835 	int spi;
836 	int i;
837 
838 	/* This already represents first slot of initialized bpf_dynptr */
839 	if (reg->type == CONST_PTR_TO_DYNPTR)
840 		return true;
841 
842 	spi = get_spi(reg->off);
843 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
844 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
845 		return false;
846 
847 	for (i = 0; i < BPF_REG_SIZE; i++) {
848 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
849 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
850 			return false;
851 	}
852 
853 	return true;
854 }
855 
856 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
857 				    enum bpf_arg_type arg_type)
858 {
859 	struct bpf_func_state *state = func(env, reg);
860 	enum bpf_dynptr_type dynptr_type;
861 	int spi;
862 
863 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
864 	if (arg_type == ARG_PTR_TO_DYNPTR)
865 		return true;
866 
867 	dynptr_type = arg_to_dynptr_type(arg_type);
868 	if (reg->type == CONST_PTR_TO_DYNPTR) {
869 		return reg->dynptr.type == dynptr_type;
870 	} else {
871 		spi = get_spi(reg->off);
872 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
873 	}
874 }
875 
876 /* The reg state of a pointer or a bounded scalar was saved when
877  * it was spilled to the stack.
878  */
879 static bool is_spilled_reg(const struct bpf_stack_state *stack)
880 {
881 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
882 }
883 
884 static void scrub_spilled_slot(u8 *stype)
885 {
886 	if (*stype != STACK_INVALID)
887 		*stype = STACK_MISC;
888 }
889 
890 static void print_verifier_state(struct bpf_verifier_env *env,
891 				 const struct bpf_func_state *state,
892 				 bool print_all)
893 {
894 	const struct bpf_reg_state *reg;
895 	enum bpf_reg_type t;
896 	int i;
897 
898 	if (state->frameno)
899 		verbose(env, " frame%d:", state->frameno);
900 	for (i = 0; i < MAX_BPF_REG; i++) {
901 		reg = &state->regs[i];
902 		t = reg->type;
903 		if (t == NOT_INIT)
904 			continue;
905 		if (!print_all && !reg_scratched(env, i))
906 			continue;
907 		verbose(env, " R%d", i);
908 		print_liveness(env, reg->live);
909 		verbose(env, "=");
910 		if (t == SCALAR_VALUE && reg->precise)
911 			verbose(env, "P");
912 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
913 		    tnum_is_const(reg->var_off)) {
914 			/* reg->off should be 0 for SCALAR_VALUE */
915 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
916 			verbose(env, "%lld", reg->var_off.value + reg->off);
917 		} else {
918 			const char *sep = "";
919 
920 			verbose(env, "%s", reg_type_str(env, t));
921 			if (base_type(t) == PTR_TO_BTF_ID)
922 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
923 			verbose(env, "(");
924 /*
925  * _a stands for append, was shortened to avoid multiline statements below.
926  * This macro is used to output a comma separated list of attributes.
927  */
928 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
929 
930 			if (reg->id)
931 				verbose_a("id=%d", reg->id);
932 			if (reg->ref_obj_id)
933 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
934 			if (t != SCALAR_VALUE)
935 				verbose_a("off=%d", reg->off);
936 			if (type_is_pkt_pointer(t))
937 				verbose_a("r=%d", reg->range);
938 			else if (base_type(t) == CONST_PTR_TO_MAP ||
939 				 base_type(t) == PTR_TO_MAP_KEY ||
940 				 base_type(t) == PTR_TO_MAP_VALUE)
941 				verbose_a("ks=%d,vs=%d",
942 					  reg->map_ptr->key_size,
943 					  reg->map_ptr->value_size);
944 			if (tnum_is_const(reg->var_off)) {
945 				/* Typically an immediate SCALAR_VALUE, but
946 				 * could be a pointer whose offset is too big
947 				 * for reg->off
948 				 */
949 				verbose_a("imm=%llx", reg->var_off.value);
950 			} else {
951 				if (reg->smin_value != reg->umin_value &&
952 				    reg->smin_value != S64_MIN)
953 					verbose_a("smin=%lld", (long long)reg->smin_value);
954 				if (reg->smax_value != reg->umax_value &&
955 				    reg->smax_value != S64_MAX)
956 					verbose_a("smax=%lld", (long long)reg->smax_value);
957 				if (reg->umin_value != 0)
958 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
959 				if (reg->umax_value != U64_MAX)
960 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
961 				if (!tnum_is_unknown(reg->var_off)) {
962 					char tn_buf[48];
963 
964 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
965 					verbose_a("var_off=%s", tn_buf);
966 				}
967 				if (reg->s32_min_value != reg->smin_value &&
968 				    reg->s32_min_value != S32_MIN)
969 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
970 				if (reg->s32_max_value != reg->smax_value &&
971 				    reg->s32_max_value != S32_MAX)
972 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
973 				if (reg->u32_min_value != reg->umin_value &&
974 				    reg->u32_min_value != U32_MIN)
975 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
976 				if (reg->u32_max_value != reg->umax_value &&
977 				    reg->u32_max_value != U32_MAX)
978 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
979 			}
980 #undef verbose_a
981 
982 			verbose(env, ")");
983 		}
984 	}
985 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
986 		char types_buf[BPF_REG_SIZE + 1];
987 		bool valid = false;
988 		int j;
989 
990 		for (j = 0; j < BPF_REG_SIZE; j++) {
991 			if (state->stack[i].slot_type[j] != STACK_INVALID)
992 				valid = true;
993 			types_buf[j] = slot_type_char[
994 					state->stack[i].slot_type[j]];
995 		}
996 		types_buf[BPF_REG_SIZE] = 0;
997 		if (!valid)
998 			continue;
999 		if (!print_all && !stack_slot_scratched(env, i))
1000 			continue;
1001 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1002 		print_liveness(env, state->stack[i].spilled_ptr.live);
1003 		if (is_spilled_reg(&state->stack[i])) {
1004 			reg = &state->stack[i].spilled_ptr;
1005 			t = reg->type;
1006 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1007 			if (t == SCALAR_VALUE && reg->precise)
1008 				verbose(env, "P");
1009 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1010 				verbose(env, "%lld", reg->var_off.value + reg->off);
1011 		} else {
1012 			verbose(env, "=%s", types_buf);
1013 		}
1014 	}
1015 	if (state->acquired_refs && state->refs[0].id) {
1016 		verbose(env, " refs=%d", state->refs[0].id);
1017 		for (i = 1; i < state->acquired_refs; i++)
1018 			if (state->refs[i].id)
1019 				verbose(env, ",%d", state->refs[i].id);
1020 	}
1021 	if (state->in_callback_fn)
1022 		verbose(env, " cb");
1023 	if (state->in_async_callback_fn)
1024 		verbose(env, " async_cb");
1025 	verbose(env, "\n");
1026 	mark_verifier_state_clean(env);
1027 }
1028 
1029 static inline u32 vlog_alignment(u32 pos)
1030 {
1031 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1032 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1033 }
1034 
1035 static void print_insn_state(struct bpf_verifier_env *env,
1036 			     const struct bpf_func_state *state)
1037 {
1038 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1039 		/* remove new line character */
1040 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1041 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1042 	} else {
1043 		verbose(env, "%d:", env->insn_idx);
1044 	}
1045 	print_verifier_state(env, state, false);
1046 }
1047 
1048 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1049  * small to hold src. This is different from krealloc since we don't want to preserve
1050  * the contents of dst.
1051  *
1052  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1053  * not be allocated.
1054  */
1055 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1056 {
1057 	size_t bytes;
1058 
1059 	if (ZERO_OR_NULL_PTR(src))
1060 		goto out;
1061 
1062 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1063 		return NULL;
1064 
1065 	if (ksize(dst) < ksize(src)) {
1066 		kfree(dst);
1067 		dst = kmalloc_track_caller(kmalloc_size_roundup(bytes), flags);
1068 		if (!dst)
1069 			return NULL;
1070 	}
1071 
1072 	memcpy(dst, src, bytes);
1073 out:
1074 	return dst ? dst : ZERO_SIZE_PTR;
1075 }
1076 
1077 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1078  * small to hold new_n items. new items are zeroed out if the array grows.
1079  *
1080  * Contrary to krealloc_array, does not free arr if new_n is zero.
1081  */
1082 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1083 {
1084 	size_t alloc_size;
1085 	void *new_arr;
1086 
1087 	if (!new_n || old_n == new_n)
1088 		goto out;
1089 
1090 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1091 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1092 	if (!new_arr) {
1093 		kfree(arr);
1094 		return NULL;
1095 	}
1096 	arr = new_arr;
1097 
1098 	if (new_n > old_n)
1099 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1100 
1101 out:
1102 	return arr ? arr : ZERO_SIZE_PTR;
1103 }
1104 
1105 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1106 {
1107 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1108 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1109 	if (!dst->refs)
1110 		return -ENOMEM;
1111 
1112 	dst->acquired_refs = src->acquired_refs;
1113 	return 0;
1114 }
1115 
1116 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1117 {
1118 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1119 
1120 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1121 				GFP_KERNEL);
1122 	if (!dst->stack)
1123 		return -ENOMEM;
1124 
1125 	dst->allocated_stack = src->allocated_stack;
1126 	return 0;
1127 }
1128 
1129 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1130 {
1131 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1132 				    sizeof(struct bpf_reference_state));
1133 	if (!state->refs)
1134 		return -ENOMEM;
1135 
1136 	state->acquired_refs = n;
1137 	return 0;
1138 }
1139 
1140 static int grow_stack_state(struct bpf_func_state *state, int size)
1141 {
1142 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1143 
1144 	if (old_n >= n)
1145 		return 0;
1146 
1147 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1148 	if (!state->stack)
1149 		return -ENOMEM;
1150 
1151 	state->allocated_stack = size;
1152 	return 0;
1153 }
1154 
1155 /* Acquire a pointer id from the env and update the state->refs to include
1156  * this new pointer reference.
1157  * On success, returns a valid pointer id to associate with the register
1158  * On failure, returns a negative errno.
1159  */
1160 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1161 {
1162 	struct bpf_func_state *state = cur_func(env);
1163 	int new_ofs = state->acquired_refs;
1164 	int id, err;
1165 
1166 	err = resize_reference_state(state, state->acquired_refs + 1);
1167 	if (err)
1168 		return err;
1169 	id = ++env->id_gen;
1170 	state->refs[new_ofs].id = id;
1171 	state->refs[new_ofs].insn_idx = insn_idx;
1172 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1173 
1174 	return id;
1175 }
1176 
1177 /* release function corresponding to acquire_reference_state(). Idempotent. */
1178 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1179 {
1180 	int i, last_idx;
1181 
1182 	last_idx = state->acquired_refs - 1;
1183 	for (i = 0; i < state->acquired_refs; i++) {
1184 		if (state->refs[i].id == ptr_id) {
1185 			/* Cannot release caller references in callbacks */
1186 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1187 				return -EINVAL;
1188 			if (last_idx && i != last_idx)
1189 				memcpy(&state->refs[i], &state->refs[last_idx],
1190 				       sizeof(*state->refs));
1191 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1192 			state->acquired_refs--;
1193 			return 0;
1194 		}
1195 	}
1196 	return -EINVAL;
1197 }
1198 
1199 static void free_func_state(struct bpf_func_state *state)
1200 {
1201 	if (!state)
1202 		return;
1203 	kfree(state->refs);
1204 	kfree(state->stack);
1205 	kfree(state);
1206 }
1207 
1208 static void clear_jmp_history(struct bpf_verifier_state *state)
1209 {
1210 	kfree(state->jmp_history);
1211 	state->jmp_history = NULL;
1212 	state->jmp_history_cnt = 0;
1213 }
1214 
1215 static void free_verifier_state(struct bpf_verifier_state *state,
1216 				bool free_self)
1217 {
1218 	int i;
1219 
1220 	for (i = 0; i <= state->curframe; i++) {
1221 		free_func_state(state->frame[i]);
1222 		state->frame[i] = NULL;
1223 	}
1224 	clear_jmp_history(state);
1225 	if (free_self)
1226 		kfree(state);
1227 }
1228 
1229 /* copy verifier state from src to dst growing dst stack space
1230  * when necessary to accommodate larger src stack
1231  */
1232 static int copy_func_state(struct bpf_func_state *dst,
1233 			   const struct bpf_func_state *src)
1234 {
1235 	int err;
1236 
1237 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1238 	err = copy_reference_state(dst, src);
1239 	if (err)
1240 		return err;
1241 	return copy_stack_state(dst, src);
1242 }
1243 
1244 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1245 			       const struct bpf_verifier_state *src)
1246 {
1247 	struct bpf_func_state *dst;
1248 	int i, err;
1249 
1250 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1251 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1252 					    GFP_USER);
1253 	if (!dst_state->jmp_history)
1254 		return -ENOMEM;
1255 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1256 
1257 	/* if dst has more stack frames then src frame, free them */
1258 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1259 		free_func_state(dst_state->frame[i]);
1260 		dst_state->frame[i] = NULL;
1261 	}
1262 	dst_state->speculative = src->speculative;
1263 	dst_state->active_rcu_lock = src->active_rcu_lock;
1264 	dst_state->curframe = src->curframe;
1265 	dst_state->active_lock.ptr = src->active_lock.ptr;
1266 	dst_state->active_lock.id = src->active_lock.id;
1267 	dst_state->branches = src->branches;
1268 	dst_state->parent = src->parent;
1269 	dst_state->first_insn_idx = src->first_insn_idx;
1270 	dst_state->last_insn_idx = src->last_insn_idx;
1271 	for (i = 0; i <= src->curframe; i++) {
1272 		dst = dst_state->frame[i];
1273 		if (!dst) {
1274 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1275 			if (!dst)
1276 				return -ENOMEM;
1277 			dst_state->frame[i] = dst;
1278 		}
1279 		err = copy_func_state(dst, src->frame[i]);
1280 		if (err)
1281 			return err;
1282 	}
1283 	return 0;
1284 }
1285 
1286 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1287 {
1288 	while (st) {
1289 		u32 br = --st->branches;
1290 
1291 		/* WARN_ON(br > 1) technically makes sense here,
1292 		 * but see comment in push_stack(), hence:
1293 		 */
1294 		WARN_ONCE((int)br < 0,
1295 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1296 			  br);
1297 		if (br)
1298 			break;
1299 		st = st->parent;
1300 	}
1301 }
1302 
1303 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1304 		     int *insn_idx, bool pop_log)
1305 {
1306 	struct bpf_verifier_state *cur = env->cur_state;
1307 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1308 	int err;
1309 
1310 	if (env->head == NULL)
1311 		return -ENOENT;
1312 
1313 	if (cur) {
1314 		err = copy_verifier_state(cur, &head->st);
1315 		if (err)
1316 			return err;
1317 	}
1318 	if (pop_log)
1319 		bpf_vlog_reset(&env->log, head->log_pos);
1320 	if (insn_idx)
1321 		*insn_idx = head->insn_idx;
1322 	if (prev_insn_idx)
1323 		*prev_insn_idx = head->prev_insn_idx;
1324 	elem = head->next;
1325 	free_verifier_state(&head->st, false);
1326 	kfree(head);
1327 	env->head = elem;
1328 	env->stack_size--;
1329 	return 0;
1330 }
1331 
1332 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1333 					     int insn_idx, int prev_insn_idx,
1334 					     bool speculative)
1335 {
1336 	struct bpf_verifier_state *cur = env->cur_state;
1337 	struct bpf_verifier_stack_elem *elem;
1338 	int err;
1339 
1340 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1341 	if (!elem)
1342 		goto err;
1343 
1344 	elem->insn_idx = insn_idx;
1345 	elem->prev_insn_idx = prev_insn_idx;
1346 	elem->next = env->head;
1347 	elem->log_pos = env->log.len_used;
1348 	env->head = elem;
1349 	env->stack_size++;
1350 	err = copy_verifier_state(&elem->st, cur);
1351 	if (err)
1352 		goto err;
1353 	elem->st.speculative |= speculative;
1354 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1355 		verbose(env, "The sequence of %d jumps is too complex.\n",
1356 			env->stack_size);
1357 		goto err;
1358 	}
1359 	if (elem->st.parent) {
1360 		++elem->st.parent->branches;
1361 		/* WARN_ON(branches > 2) technically makes sense here,
1362 		 * but
1363 		 * 1. speculative states will bump 'branches' for non-branch
1364 		 * instructions
1365 		 * 2. is_state_visited() heuristics may decide not to create
1366 		 * a new state for a sequence of branches and all such current
1367 		 * and cloned states will be pointing to a single parent state
1368 		 * which might have large 'branches' count.
1369 		 */
1370 	}
1371 	return &elem->st;
1372 err:
1373 	free_verifier_state(env->cur_state, true);
1374 	env->cur_state = NULL;
1375 	/* pop all elements and return */
1376 	while (!pop_stack(env, NULL, NULL, false));
1377 	return NULL;
1378 }
1379 
1380 #define CALLER_SAVED_REGS 6
1381 static const int caller_saved[CALLER_SAVED_REGS] = {
1382 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1383 };
1384 
1385 /* This helper doesn't clear reg->id */
1386 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1387 {
1388 	reg->var_off = tnum_const(imm);
1389 	reg->smin_value = (s64)imm;
1390 	reg->smax_value = (s64)imm;
1391 	reg->umin_value = imm;
1392 	reg->umax_value = imm;
1393 
1394 	reg->s32_min_value = (s32)imm;
1395 	reg->s32_max_value = (s32)imm;
1396 	reg->u32_min_value = (u32)imm;
1397 	reg->u32_max_value = (u32)imm;
1398 }
1399 
1400 /* Mark the unknown part of a register (variable offset or scalar value) as
1401  * known to have the value @imm.
1402  */
1403 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1404 {
1405 	/* Clear id, off, and union(map_ptr, range) */
1406 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1407 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1408 	___mark_reg_known(reg, imm);
1409 }
1410 
1411 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1412 {
1413 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1414 	reg->s32_min_value = (s32)imm;
1415 	reg->s32_max_value = (s32)imm;
1416 	reg->u32_min_value = (u32)imm;
1417 	reg->u32_max_value = (u32)imm;
1418 }
1419 
1420 /* Mark the 'variable offset' part of a register as zero.  This should be
1421  * used only on registers holding a pointer type.
1422  */
1423 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1424 {
1425 	__mark_reg_known(reg, 0);
1426 }
1427 
1428 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1429 {
1430 	__mark_reg_known(reg, 0);
1431 	reg->type = SCALAR_VALUE;
1432 }
1433 
1434 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1435 				struct bpf_reg_state *regs, u32 regno)
1436 {
1437 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1438 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1439 		/* Something bad happened, let's kill all regs */
1440 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1441 			__mark_reg_not_init(env, regs + regno);
1442 		return;
1443 	}
1444 	__mark_reg_known_zero(regs + regno);
1445 }
1446 
1447 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1448 			      bool first_slot)
1449 {
1450 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1451 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1452 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1453 	 */
1454 	__mark_reg_known_zero(reg);
1455 	reg->type = CONST_PTR_TO_DYNPTR;
1456 	reg->dynptr.type = type;
1457 	reg->dynptr.first_slot = first_slot;
1458 }
1459 
1460 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1461 {
1462 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1463 		const struct bpf_map *map = reg->map_ptr;
1464 
1465 		if (map->inner_map_meta) {
1466 			reg->type = CONST_PTR_TO_MAP;
1467 			reg->map_ptr = map->inner_map_meta;
1468 			/* transfer reg's id which is unique for every map_lookup_elem
1469 			 * as UID of the inner map.
1470 			 */
1471 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1472 				reg->map_uid = reg->id;
1473 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1474 			reg->type = PTR_TO_XDP_SOCK;
1475 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1476 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1477 			reg->type = PTR_TO_SOCKET;
1478 		} else {
1479 			reg->type = PTR_TO_MAP_VALUE;
1480 		}
1481 		return;
1482 	}
1483 
1484 	reg->type &= ~PTR_MAYBE_NULL;
1485 }
1486 
1487 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1488 {
1489 	return type_is_pkt_pointer(reg->type);
1490 }
1491 
1492 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1493 {
1494 	return reg_is_pkt_pointer(reg) ||
1495 	       reg->type == PTR_TO_PACKET_END;
1496 }
1497 
1498 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1499 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1500 				    enum bpf_reg_type which)
1501 {
1502 	/* The register can already have a range from prior markings.
1503 	 * This is fine as long as it hasn't been advanced from its
1504 	 * origin.
1505 	 */
1506 	return reg->type == which &&
1507 	       reg->id == 0 &&
1508 	       reg->off == 0 &&
1509 	       tnum_equals_const(reg->var_off, 0);
1510 }
1511 
1512 /* Reset the min/max bounds of a register */
1513 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1514 {
1515 	reg->smin_value = S64_MIN;
1516 	reg->smax_value = S64_MAX;
1517 	reg->umin_value = 0;
1518 	reg->umax_value = U64_MAX;
1519 
1520 	reg->s32_min_value = S32_MIN;
1521 	reg->s32_max_value = S32_MAX;
1522 	reg->u32_min_value = 0;
1523 	reg->u32_max_value = U32_MAX;
1524 }
1525 
1526 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1527 {
1528 	reg->smin_value = S64_MIN;
1529 	reg->smax_value = S64_MAX;
1530 	reg->umin_value = 0;
1531 	reg->umax_value = U64_MAX;
1532 }
1533 
1534 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1535 {
1536 	reg->s32_min_value = S32_MIN;
1537 	reg->s32_max_value = S32_MAX;
1538 	reg->u32_min_value = 0;
1539 	reg->u32_max_value = U32_MAX;
1540 }
1541 
1542 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1543 {
1544 	struct tnum var32_off = tnum_subreg(reg->var_off);
1545 
1546 	/* min signed is max(sign bit) | min(other bits) */
1547 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1548 			var32_off.value | (var32_off.mask & S32_MIN));
1549 	/* max signed is min(sign bit) | max(other bits) */
1550 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1551 			var32_off.value | (var32_off.mask & S32_MAX));
1552 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1553 	reg->u32_max_value = min(reg->u32_max_value,
1554 				 (u32)(var32_off.value | var32_off.mask));
1555 }
1556 
1557 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1558 {
1559 	/* min signed is max(sign bit) | min(other bits) */
1560 	reg->smin_value = max_t(s64, reg->smin_value,
1561 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1562 	/* max signed is min(sign bit) | max(other bits) */
1563 	reg->smax_value = min_t(s64, reg->smax_value,
1564 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1565 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1566 	reg->umax_value = min(reg->umax_value,
1567 			      reg->var_off.value | reg->var_off.mask);
1568 }
1569 
1570 static void __update_reg_bounds(struct bpf_reg_state *reg)
1571 {
1572 	__update_reg32_bounds(reg);
1573 	__update_reg64_bounds(reg);
1574 }
1575 
1576 /* Uses signed min/max values to inform unsigned, and vice-versa */
1577 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1578 {
1579 	/* Learn sign from signed bounds.
1580 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1581 	 * are the same, so combine.  This works even in the negative case, e.g.
1582 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1583 	 */
1584 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1585 		reg->s32_min_value = reg->u32_min_value =
1586 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1587 		reg->s32_max_value = reg->u32_max_value =
1588 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1589 		return;
1590 	}
1591 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1592 	 * boundary, so we must be careful.
1593 	 */
1594 	if ((s32)reg->u32_max_value >= 0) {
1595 		/* Positive.  We can't learn anything from the smin, but smax
1596 		 * is positive, hence safe.
1597 		 */
1598 		reg->s32_min_value = reg->u32_min_value;
1599 		reg->s32_max_value = reg->u32_max_value =
1600 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1601 	} else if ((s32)reg->u32_min_value < 0) {
1602 		/* Negative.  We can't learn anything from the smax, but smin
1603 		 * is negative, hence safe.
1604 		 */
1605 		reg->s32_min_value = reg->u32_min_value =
1606 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1607 		reg->s32_max_value = reg->u32_max_value;
1608 	}
1609 }
1610 
1611 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1612 {
1613 	/* Learn sign from signed bounds.
1614 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1615 	 * are the same, so combine.  This works even in the negative case, e.g.
1616 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1617 	 */
1618 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1619 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1620 							  reg->umin_value);
1621 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1622 							  reg->umax_value);
1623 		return;
1624 	}
1625 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1626 	 * boundary, so we must be careful.
1627 	 */
1628 	if ((s64)reg->umax_value >= 0) {
1629 		/* Positive.  We can't learn anything from the smin, but smax
1630 		 * is positive, hence safe.
1631 		 */
1632 		reg->smin_value = reg->umin_value;
1633 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1634 							  reg->umax_value);
1635 	} else if ((s64)reg->umin_value < 0) {
1636 		/* Negative.  We can't learn anything from the smax, but smin
1637 		 * is negative, hence safe.
1638 		 */
1639 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1640 							  reg->umin_value);
1641 		reg->smax_value = reg->umax_value;
1642 	}
1643 }
1644 
1645 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1646 {
1647 	__reg32_deduce_bounds(reg);
1648 	__reg64_deduce_bounds(reg);
1649 }
1650 
1651 /* Attempts to improve var_off based on unsigned min/max information */
1652 static void __reg_bound_offset(struct bpf_reg_state *reg)
1653 {
1654 	struct tnum var64_off = tnum_intersect(reg->var_off,
1655 					       tnum_range(reg->umin_value,
1656 							  reg->umax_value));
1657 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1658 						tnum_range(reg->u32_min_value,
1659 							   reg->u32_max_value));
1660 
1661 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1662 }
1663 
1664 static void reg_bounds_sync(struct bpf_reg_state *reg)
1665 {
1666 	/* We might have learned new bounds from the var_off. */
1667 	__update_reg_bounds(reg);
1668 	/* We might have learned something about the sign bit. */
1669 	__reg_deduce_bounds(reg);
1670 	/* We might have learned some bits from the bounds. */
1671 	__reg_bound_offset(reg);
1672 	/* Intersecting with the old var_off might have improved our bounds
1673 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1674 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1675 	 */
1676 	__update_reg_bounds(reg);
1677 }
1678 
1679 static bool __reg32_bound_s64(s32 a)
1680 {
1681 	return a >= 0 && a <= S32_MAX;
1682 }
1683 
1684 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1685 {
1686 	reg->umin_value = reg->u32_min_value;
1687 	reg->umax_value = reg->u32_max_value;
1688 
1689 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1690 	 * be positive otherwise set to worse case bounds and refine later
1691 	 * from tnum.
1692 	 */
1693 	if (__reg32_bound_s64(reg->s32_min_value) &&
1694 	    __reg32_bound_s64(reg->s32_max_value)) {
1695 		reg->smin_value = reg->s32_min_value;
1696 		reg->smax_value = reg->s32_max_value;
1697 	} else {
1698 		reg->smin_value = 0;
1699 		reg->smax_value = U32_MAX;
1700 	}
1701 }
1702 
1703 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1704 {
1705 	/* special case when 64-bit register has upper 32-bit register
1706 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1707 	 * allowing us to use 32-bit bounds directly,
1708 	 */
1709 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1710 		__reg_assign_32_into_64(reg);
1711 	} else {
1712 		/* Otherwise the best we can do is push lower 32bit known and
1713 		 * unknown bits into register (var_off set from jmp logic)
1714 		 * then learn as much as possible from the 64-bit tnum
1715 		 * known and unknown bits. The previous smin/smax bounds are
1716 		 * invalid here because of jmp32 compare so mark them unknown
1717 		 * so they do not impact tnum bounds calculation.
1718 		 */
1719 		__mark_reg64_unbounded(reg);
1720 	}
1721 	reg_bounds_sync(reg);
1722 }
1723 
1724 static bool __reg64_bound_s32(s64 a)
1725 {
1726 	return a >= S32_MIN && a <= S32_MAX;
1727 }
1728 
1729 static bool __reg64_bound_u32(u64 a)
1730 {
1731 	return a >= U32_MIN && a <= U32_MAX;
1732 }
1733 
1734 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1735 {
1736 	__mark_reg32_unbounded(reg);
1737 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1738 		reg->s32_min_value = (s32)reg->smin_value;
1739 		reg->s32_max_value = (s32)reg->smax_value;
1740 	}
1741 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1742 		reg->u32_min_value = (u32)reg->umin_value;
1743 		reg->u32_max_value = (u32)reg->umax_value;
1744 	}
1745 	reg_bounds_sync(reg);
1746 }
1747 
1748 /* Mark a register as having a completely unknown (scalar) value. */
1749 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1750 			       struct bpf_reg_state *reg)
1751 {
1752 	/*
1753 	 * Clear type, id, off, and union(map_ptr, range) and
1754 	 * padding between 'type' and union
1755 	 */
1756 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1757 	reg->type = SCALAR_VALUE;
1758 	reg->var_off = tnum_unknown;
1759 	reg->frameno = 0;
1760 	reg->precise = !env->bpf_capable;
1761 	__mark_reg_unbounded(reg);
1762 }
1763 
1764 static void mark_reg_unknown(struct bpf_verifier_env *env,
1765 			     struct bpf_reg_state *regs, u32 regno)
1766 {
1767 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1768 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1769 		/* Something bad happened, let's kill all regs except FP */
1770 		for (regno = 0; regno < BPF_REG_FP; regno++)
1771 			__mark_reg_not_init(env, regs + regno);
1772 		return;
1773 	}
1774 	__mark_reg_unknown(env, regs + regno);
1775 }
1776 
1777 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1778 				struct bpf_reg_state *reg)
1779 {
1780 	__mark_reg_unknown(env, reg);
1781 	reg->type = NOT_INIT;
1782 }
1783 
1784 static void mark_reg_not_init(struct bpf_verifier_env *env,
1785 			      struct bpf_reg_state *regs, u32 regno)
1786 {
1787 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1788 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1789 		/* Something bad happened, let's kill all regs except FP */
1790 		for (regno = 0; regno < BPF_REG_FP; regno++)
1791 			__mark_reg_not_init(env, regs + regno);
1792 		return;
1793 	}
1794 	__mark_reg_not_init(env, regs + regno);
1795 }
1796 
1797 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1798 			    struct bpf_reg_state *regs, u32 regno,
1799 			    enum bpf_reg_type reg_type,
1800 			    struct btf *btf, u32 btf_id,
1801 			    enum bpf_type_flag flag)
1802 {
1803 	if (reg_type == SCALAR_VALUE) {
1804 		mark_reg_unknown(env, regs, regno);
1805 		return;
1806 	}
1807 	mark_reg_known_zero(env, regs, regno);
1808 	regs[regno].type = PTR_TO_BTF_ID | flag;
1809 	regs[regno].btf = btf;
1810 	regs[regno].btf_id = btf_id;
1811 }
1812 
1813 #define DEF_NOT_SUBREG	(0)
1814 static void init_reg_state(struct bpf_verifier_env *env,
1815 			   struct bpf_func_state *state)
1816 {
1817 	struct bpf_reg_state *regs = state->regs;
1818 	int i;
1819 
1820 	for (i = 0; i < MAX_BPF_REG; i++) {
1821 		mark_reg_not_init(env, regs, i);
1822 		regs[i].live = REG_LIVE_NONE;
1823 		regs[i].parent = NULL;
1824 		regs[i].subreg_def = DEF_NOT_SUBREG;
1825 	}
1826 
1827 	/* frame pointer */
1828 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1829 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1830 	regs[BPF_REG_FP].frameno = state->frameno;
1831 }
1832 
1833 #define BPF_MAIN_FUNC (-1)
1834 static void init_func_state(struct bpf_verifier_env *env,
1835 			    struct bpf_func_state *state,
1836 			    int callsite, int frameno, int subprogno)
1837 {
1838 	state->callsite = callsite;
1839 	state->frameno = frameno;
1840 	state->subprogno = subprogno;
1841 	state->callback_ret_range = tnum_range(0, 0);
1842 	init_reg_state(env, state);
1843 	mark_verifier_state_scratched(env);
1844 }
1845 
1846 /* Similar to push_stack(), but for async callbacks */
1847 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1848 						int insn_idx, int prev_insn_idx,
1849 						int subprog)
1850 {
1851 	struct bpf_verifier_stack_elem *elem;
1852 	struct bpf_func_state *frame;
1853 
1854 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1855 	if (!elem)
1856 		goto err;
1857 
1858 	elem->insn_idx = insn_idx;
1859 	elem->prev_insn_idx = prev_insn_idx;
1860 	elem->next = env->head;
1861 	elem->log_pos = env->log.len_used;
1862 	env->head = elem;
1863 	env->stack_size++;
1864 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1865 		verbose(env,
1866 			"The sequence of %d jumps is too complex for async cb.\n",
1867 			env->stack_size);
1868 		goto err;
1869 	}
1870 	/* Unlike push_stack() do not copy_verifier_state().
1871 	 * The caller state doesn't matter.
1872 	 * This is async callback. It starts in a fresh stack.
1873 	 * Initialize it similar to do_check_common().
1874 	 */
1875 	elem->st.branches = 1;
1876 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1877 	if (!frame)
1878 		goto err;
1879 	init_func_state(env, frame,
1880 			BPF_MAIN_FUNC /* callsite */,
1881 			0 /* frameno within this callchain */,
1882 			subprog /* subprog number within this prog */);
1883 	elem->st.frame[0] = frame;
1884 	return &elem->st;
1885 err:
1886 	free_verifier_state(env->cur_state, true);
1887 	env->cur_state = NULL;
1888 	/* pop all elements and return */
1889 	while (!pop_stack(env, NULL, NULL, false));
1890 	return NULL;
1891 }
1892 
1893 
1894 enum reg_arg_type {
1895 	SRC_OP,		/* register is used as source operand */
1896 	DST_OP,		/* register is used as destination operand */
1897 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1898 };
1899 
1900 static int cmp_subprogs(const void *a, const void *b)
1901 {
1902 	return ((struct bpf_subprog_info *)a)->start -
1903 	       ((struct bpf_subprog_info *)b)->start;
1904 }
1905 
1906 static int find_subprog(struct bpf_verifier_env *env, int off)
1907 {
1908 	struct bpf_subprog_info *p;
1909 
1910 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1911 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1912 	if (!p)
1913 		return -ENOENT;
1914 	return p - env->subprog_info;
1915 
1916 }
1917 
1918 static int add_subprog(struct bpf_verifier_env *env, int off)
1919 {
1920 	int insn_cnt = env->prog->len;
1921 	int ret;
1922 
1923 	if (off >= insn_cnt || off < 0) {
1924 		verbose(env, "call to invalid destination\n");
1925 		return -EINVAL;
1926 	}
1927 	ret = find_subprog(env, off);
1928 	if (ret >= 0)
1929 		return ret;
1930 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1931 		verbose(env, "too many subprograms\n");
1932 		return -E2BIG;
1933 	}
1934 	/* determine subprog starts. The end is one before the next starts */
1935 	env->subprog_info[env->subprog_cnt++].start = off;
1936 	sort(env->subprog_info, env->subprog_cnt,
1937 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1938 	return env->subprog_cnt - 1;
1939 }
1940 
1941 #define MAX_KFUNC_DESCS 256
1942 #define MAX_KFUNC_BTFS	256
1943 
1944 struct bpf_kfunc_desc {
1945 	struct btf_func_model func_model;
1946 	u32 func_id;
1947 	s32 imm;
1948 	u16 offset;
1949 };
1950 
1951 struct bpf_kfunc_btf {
1952 	struct btf *btf;
1953 	struct module *module;
1954 	u16 offset;
1955 };
1956 
1957 struct bpf_kfunc_desc_tab {
1958 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1959 	u32 nr_descs;
1960 };
1961 
1962 struct bpf_kfunc_btf_tab {
1963 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1964 	u32 nr_descs;
1965 };
1966 
1967 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1968 {
1969 	const struct bpf_kfunc_desc *d0 = a;
1970 	const struct bpf_kfunc_desc *d1 = b;
1971 
1972 	/* func_id is not greater than BTF_MAX_TYPE */
1973 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1974 }
1975 
1976 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1977 {
1978 	const struct bpf_kfunc_btf *d0 = a;
1979 	const struct bpf_kfunc_btf *d1 = b;
1980 
1981 	return d0->offset - d1->offset;
1982 }
1983 
1984 static const struct bpf_kfunc_desc *
1985 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1986 {
1987 	struct bpf_kfunc_desc desc = {
1988 		.func_id = func_id,
1989 		.offset = offset,
1990 	};
1991 	struct bpf_kfunc_desc_tab *tab;
1992 
1993 	tab = prog->aux->kfunc_tab;
1994 	return bsearch(&desc, tab->descs, tab->nr_descs,
1995 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1996 }
1997 
1998 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1999 					 s16 offset)
2000 {
2001 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2002 	struct bpf_kfunc_btf_tab *tab;
2003 	struct bpf_kfunc_btf *b;
2004 	struct module *mod;
2005 	struct btf *btf;
2006 	int btf_fd;
2007 
2008 	tab = env->prog->aux->kfunc_btf_tab;
2009 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2010 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2011 	if (!b) {
2012 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2013 			verbose(env, "too many different module BTFs\n");
2014 			return ERR_PTR(-E2BIG);
2015 		}
2016 
2017 		if (bpfptr_is_null(env->fd_array)) {
2018 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2019 			return ERR_PTR(-EPROTO);
2020 		}
2021 
2022 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2023 					    offset * sizeof(btf_fd),
2024 					    sizeof(btf_fd)))
2025 			return ERR_PTR(-EFAULT);
2026 
2027 		btf = btf_get_by_fd(btf_fd);
2028 		if (IS_ERR(btf)) {
2029 			verbose(env, "invalid module BTF fd specified\n");
2030 			return btf;
2031 		}
2032 
2033 		if (!btf_is_module(btf)) {
2034 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2035 			btf_put(btf);
2036 			return ERR_PTR(-EINVAL);
2037 		}
2038 
2039 		mod = btf_try_get_module(btf);
2040 		if (!mod) {
2041 			btf_put(btf);
2042 			return ERR_PTR(-ENXIO);
2043 		}
2044 
2045 		b = &tab->descs[tab->nr_descs++];
2046 		b->btf = btf;
2047 		b->module = mod;
2048 		b->offset = offset;
2049 
2050 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2051 		     kfunc_btf_cmp_by_off, NULL);
2052 	}
2053 	return b->btf;
2054 }
2055 
2056 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2057 {
2058 	if (!tab)
2059 		return;
2060 
2061 	while (tab->nr_descs--) {
2062 		module_put(tab->descs[tab->nr_descs].module);
2063 		btf_put(tab->descs[tab->nr_descs].btf);
2064 	}
2065 	kfree(tab);
2066 }
2067 
2068 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2069 {
2070 	if (offset) {
2071 		if (offset < 0) {
2072 			/* In the future, this can be allowed to increase limit
2073 			 * of fd index into fd_array, interpreted as u16.
2074 			 */
2075 			verbose(env, "negative offset disallowed for kernel module function call\n");
2076 			return ERR_PTR(-EINVAL);
2077 		}
2078 
2079 		return __find_kfunc_desc_btf(env, offset);
2080 	}
2081 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2082 }
2083 
2084 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2085 {
2086 	const struct btf_type *func, *func_proto;
2087 	struct bpf_kfunc_btf_tab *btf_tab;
2088 	struct bpf_kfunc_desc_tab *tab;
2089 	struct bpf_prog_aux *prog_aux;
2090 	struct bpf_kfunc_desc *desc;
2091 	const char *func_name;
2092 	struct btf *desc_btf;
2093 	unsigned long call_imm;
2094 	unsigned long addr;
2095 	int err;
2096 
2097 	prog_aux = env->prog->aux;
2098 	tab = prog_aux->kfunc_tab;
2099 	btf_tab = prog_aux->kfunc_btf_tab;
2100 	if (!tab) {
2101 		if (!btf_vmlinux) {
2102 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2103 			return -ENOTSUPP;
2104 		}
2105 
2106 		if (!env->prog->jit_requested) {
2107 			verbose(env, "JIT is required for calling kernel function\n");
2108 			return -ENOTSUPP;
2109 		}
2110 
2111 		if (!bpf_jit_supports_kfunc_call()) {
2112 			verbose(env, "JIT does not support calling kernel function\n");
2113 			return -ENOTSUPP;
2114 		}
2115 
2116 		if (!env->prog->gpl_compatible) {
2117 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2118 			return -EINVAL;
2119 		}
2120 
2121 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2122 		if (!tab)
2123 			return -ENOMEM;
2124 		prog_aux->kfunc_tab = tab;
2125 	}
2126 
2127 	/* func_id == 0 is always invalid, but instead of returning an error, be
2128 	 * conservative and wait until the code elimination pass before returning
2129 	 * error, so that invalid calls that get pruned out can be in BPF programs
2130 	 * loaded from userspace.  It is also required that offset be untouched
2131 	 * for such calls.
2132 	 */
2133 	if (!func_id && !offset)
2134 		return 0;
2135 
2136 	if (!btf_tab && offset) {
2137 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2138 		if (!btf_tab)
2139 			return -ENOMEM;
2140 		prog_aux->kfunc_btf_tab = btf_tab;
2141 	}
2142 
2143 	desc_btf = find_kfunc_desc_btf(env, offset);
2144 	if (IS_ERR(desc_btf)) {
2145 		verbose(env, "failed to find BTF for kernel function\n");
2146 		return PTR_ERR(desc_btf);
2147 	}
2148 
2149 	if (find_kfunc_desc(env->prog, func_id, offset))
2150 		return 0;
2151 
2152 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2153 		verbose(env, "too many different kernel function calls\n");
2154 		return -E2BIG;
2155 	}
2156 
2157 	func = btf_type_by_id(desc_btf, func_id);
2158 	if (!func || !btf_type_is_func(func)) {
2159 		verbose(env, "kernel btf_id %u is not a function\n",
2160 			func_id);
2161 		return -EINVAL;
2162 	}
2163 	func_proto = btf_type_by_id(desc_btf, func->type);
2164 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2165 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2166 			func_id);
2167 		return -EINVAL;
2168 	}
2169 
2170 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2171 	addr = kallsyms_lookup_name(func_name);
2172 	if (!addr) {
2173 		verbose(env, "cannot find address for kernel function %s\n",
2174 			func_name);
2175 		return -EINVAL;
2176 	}
2177 
2178 	call_imm = BPF_CALL_IMM(addr);
2179 	/* Check whether or not the relative offset overflows desc->imm */
2180 	if ((unsigned long)(s32)call_imm != call_imm) {
2181 		verbose(env, "address of kernel function %s is out of range\n",
2182 			func_name);
2183 		return -EINVAL;
2184 	}
2185 
2186 	desc = &tab->descs[tab->nr_descs++];
2187 	desc->func_id = func_id;
2188 	desc->imm = call_imm;
2189 	desc->offset = offset;
2190 	err = btf_distill_func_proto(&env->log, desc_btf,
2191 				     func_proto, func_name,
2192 				     &desc->func_model);
2193 	if (!err)
2194 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2195 		     kfunc_desc_cmp_by_id_off, NULL);
2196 	return err;
2197 }
2198 
2199 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2200 {
2201 	const struct bpf_kfunc_desc *d0 = a;
2202 	const struct bpf_kfunc_desc *d1 = b;
2203 
2204 	if (d0->imm > d1->imm)
2205 		return 1;
2206 	else if (d0->imm < d1->imm)
2207 		return -1;
2208 	return 0;
2209 }
2210 
2211 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2212 {
2213 	struct bpf_kfunc_desc_tab *tab;
2214 
2215 	tab = prog->aux->kfunc_tab;
2216 	if (!tab)
2217 		return;
2218 
2219 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2220 	     kfunc_desc_cmp_by_imm, NULL);
2221 }
2222 
2223 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2224 {
2225 	return !!prog->aux->kfunc_tab;
2226 }
2227 
2228 const struct btf_func_model *
2229 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2230 			 const struct bpf_insn *insn)
2231 {
2232 	const struct bpf_kfunc_desc desc = {
2233 		.imm = insn->imm,
2234 	};
2235 	const struct bpf_kfunc_desc *res;
2236 	struct bpf_kfunc_desc_tab *tab;
2237 
2238 	tab = prog->aux->kfunc_tab;
2239 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2240 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2241 
2242 	return res ? &res->func_model : NULL;
2243 }
2244 
2245 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2246 {
2247 	struct bpf_subprog_info *subprog = env->subprog_info;
2248 	struct bpf_insn *insn = env->prog->insnsi;
2249 	int i, ret, insn_cnt = env->prog->len;
2250 
2251 	/* Add entry function. */
2252 	ret = add_subprog(env, 0);
2253 	if (ret)
2254 		return ret;
2255 
2256 	for (i = 0; i < insn_cnt; i++, insn++) {
2257 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2258 		    !bpf_pseudo_kfunc_call(insn))
2259 			continue;
2260 
2261 		if (!env->bpf_capable) {
2262 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2263 			return -EPERM;
2264 		}
2265 
2266 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2267 			ret = add_subprog(env, i + insn->imm + 1);
2268 		else
2269 			ret = add_kfunc_call(env, insn->imm, insn->off);
2270 
2271 		if (ret < 0)
2272 			return ret;
2273 	}
2274 
2275 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2276 	 * logic. 'subprog_cnt' should not be increased.
2277 	 */
2278 	subprog[env->subprog_cnt].start = insn_cnt;
2279 
2280 	if (env->log.level & BPF_LOG_LEVEL2)
2281 		for (i = 0; i < env->subprog_cnt; i++)
2282 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2283 
2284 	return 0;
2285 }
2286 
2287 static int check_subprogs(struct bpf_verifier_env *env)
2288 {
2289 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2290 	struct bpf_subprog_info *subprog = env->subprog_info;
2291 	struct bpf_insn *insn = env->prog->insnsi;
2292 	int insn_cnt = env->prog->len;
2293 
2294 	/* now check that all jumps are within the same subprog */
2295 	subprog_start = subprog[cur_subprog].start;
2296 	subprog_end = subprog[cur_subprog + 1].start;
2297 	for (i = 0; i < insn_cnt; i++) {
2298 		u8 code = insn[i].code;
2299 
2300 		if (code == (BPF_JMP | BPF_CALL) &&
2301 		    insn[i].imm == BPF_FUNC_tail_call &&
2302 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2303 			subprog[cur_subprog].has_tail_call = true;
2304 		if (BPF_CLASS(code) == BPF_LD &&
2305 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2306 			subprog[cur_subprog].has_ld_abs = true;
2307 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2308 			goto next;
2309 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2310 			goto next;
2311 		off = i + insn[i].off + 1;
2312 		if (off < subprog_start || off >= subprog_end) {
2313 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2314 			return -EINVAL;
2315 		}
2316 next:
2317 		if (i == subprog_end - 1) {
2318 			/* to avoid fall-through from one subprog into another
2319 			 * the last insn of the subprog should be either exit
2320 			 * or unconditional jump back
2321 			 */
2322 			if (code != (BPF_JMP | BPF_EXIT) &&
2323 			    code != (BPF_JMP | BPF_JA)) {
2324 				verbose(env, "last insn is not an exit or jmp\n");
2325 				return -EINVAL;
2326 			}
2327 			subprog_start = subprog_end;
2328 			cur_subprog++;
2329 			if (cur_subprog < env->subprog_cnt)
2330 				subprog_end = subprog[cur_subprog + 1].start;
2331 		}
2332 	}
2333 	return 0;
2334 }
2335 
2336 /* Parentage chain of this register (or stack slot) should take care of all
2337  * issues like callee-saved registers, stack slot allocation time, etc.
2338  */
2339 static int mark_reg_read(struct bpf_verifier_env *env,
2340 			 const struct bpf_reg_state *state,
2341 			 struct bpf_reg_state *parent, u8 flag)
2342 {
2343 	bool writes = parent == state->parent; /* Observe write marks */
2344 	int cnt = 0;
2345 
2346 	while (parent) {
2347 		/* if read wasn't screened by an earlier write ... */
2348 		if (writes && state->live & REG_LIVE_WRITTEN)
2349 			break;
2350 		if (parent->live & REG_LIVE_DONE) {
2351 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2352 				reg_type_str(env, parent->type),
2353 				parent->var_off.value, parent->off);
2354 			return -EFAULT;
2355 		}
2356 		/* The first condition is more likely to be true than the
2357 		 * second, checked it first.
2358 		 */
2359 		if ((parent->live & REG_LIVE_READ) == flag ||
2360 		    parent->live & REG_LIVE_READ64)
2361 			/* The parentage chain never changes and
2362 			 * this parent was already marked as LIVE_READ.
2363 			 * There is no need to keep walking the chain again and
2364 			 * keep re-marking all parents as LIVE_READ.
2365 			 * This case happens when the same register is read
2366 			 * multiple times without writes into it in-between.
2367 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2368 			 * then no need to set the weak REG_LIVE_READ32.
2369 			 */
2370 			break;
2371 		/* ... then we depend on parent's value */
2372 		parent->live |= flag;
2373 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2374 		if (flag == REG_LIVE_READ64)
2375 			parent->live &= ~REG_LIVE_READ32;
2376 		state = parent;
2377 		parent = state->parent;
2378 		writes = true;
2379 		cnt++;
2380 	}
2381 
2382 	if (env->longest_mark_read_walk < cnt)
2383 		env->longest_mark_read_walk = cnt;
2384 	return 0;
2385 }
2386 
2387 /* This function is supposed to be used by the following 32-bit optimization
2388  * code only. It returns TRUE if the source or destination register operates
2389  * on 64-bit, otherwise return FALSE.
2390  */
2391 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2392 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2393 {
2394 	u8 code, class, op;
2395 
2396 	code = insn->code;
2397 	class = BPF_CLASS(code);
2398 	op = BPF_OP(code);
2399 	if (class == BPF_JMP) {
2400 		/* BPF_EXIT for "main" will reach here. Return TRUE
2401 		 * conservatively.
2402 		 */
2403 		if (op == BPF_EXIT)
2404 			return true;
2405 		if (op == BPF_CALL) {
2406 			/* BPF to BPF call will reach here because of marking
2407 			 * caller saved clobber with DST_OP_NO_MARK for which we
2408 			 * don't care the register def because they are anyway
2409 			 * marked as NOT_INIT already.
2410 			 */
2411 			if (insn->src_reg == BPF_PSEUDO_CALL)
2412 				return false;
2413 			/* Helper call will reach here because of arg type
2414 			 * check, conservatively return TRUE.
2415 			 */
2416 			if (t == SRC_OP)
2417 				return true;
2418 
2419 			return false;
2420 		}
2421 	}
2422 
2423 	if (class == BPF_ALU64 || class == BPF_JMP ||
2424 	    /* BPF_END always use BPF_ALU class. */
2425 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2426 		return true;
2427 
2428 	if (class == BPF_ALU || class == BPF_JMP32)
2429 		return false;
2430 
2431 	if (class == BPF_LDX) {
2432 		if (t != SRC_OP)
2433 			return BPF_SIZE(code) == BPF_DW;
2434 		/* LDX source must be ptr. */
2435 		return true;
2436 	}
2437 
2438 	if (class == BPF_STX) {
2439 		/* BPF_STX (including atomic variants) has multiple source
2440 		 * operands, one of which is a ptr. Check whether the caller is
2441 		 * asking about it.
2442 		 */
2443 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2444 			return true;
2445 		return BPF_SIZE(code) == BPF_DW;
2446 	}
2447 
2448 	if (class == BPF_LD) {
2449 		u8 mode = BPF_MODE(code);
2450 
2451 		/* LD_IMM64 */
2452 		if (mode == BPF_IMM)
2453 			return true;
2454 
2455 		/* Both LD_IND and LD_ABS return 32-bit data. */
2456 		if (t != SRC_OP)
2457 			return  false;
2458 
2459 		/* Implicit ctx ptr. */
2460 		if (regno == BPF_REG_6)
2461 			return true;
2462 
2463 		/* Explicit source could be any width. */
2464 		return true;
2465 	}
2466 
2467 	if (class == BPF_ST)
2468 		/* The only source register for BPF_ST is a ptr. */
2469 		return true;
2470 
2471 	/* Conservatively return true at default. */
2472 	return true;
2473 }
2474 
2475 /* Return the regno defined by the insn, or -1. */
2476 static int insn_def_regno(const struct bpf_insn *insn)
2477 {
2478 	switch (BPF_CLASS(insn->code)) {
2479 	case BPF_JMP:
2480 	case BPF_JMP32:
2481 	case BPF_ST:
2482 		return -1;
2483 	case BPF_STX:
2484 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2485 		    (insn->imm & BPF_FETCH)) {
2486 			if (insn->imm == BPF_CMPXCHG)
2487 				return BPF_REG_0;
2488 			else
2489 				return insn->src_reg;
2490 		} else {
2491 			return -1;
2492 		}
2493 	default:
2494 		return insn->dst_reg;
2495 	}
2496 }
2497 
2498 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2499 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2500 {
2501 	int dst_reg = insn_def_regno(insn);
2502 
2503 	if (dst_reg == -1)
2504 		return false;
2505 
2506 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2507 }
2508 
2509 static void mark_insn_zext(struct bpf_verifier_env *env,
2510 			   struct bpf_reg_state *reg)
2511 {
2512 	s32 def_idx = reg->subreg_def;
2513 
2514 	if (def_idx == DEF_NOT_SUBREG)
2515 		return;
2516 
2517 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2518 	/* The dst will be zero extended, so won't be sub-register anymore. */
2519 	reg->subreg_def = DEF_NOT_SUBREG;
2520 }
2521 
2522 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2523 			 enum reg_arg_type t)
2524 {
2525 	struct bpf_verifier_state *vstate = env->cur_state;
2526 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2527 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2528 	struct bpf_reg_state *reg, *regs = state->regs;
2529 	bool rw64;
2530 
2531 	if (regno >= MAX_BPF_REG) {
2532 		verbose(env, "R%d is invalid\n", regno);
2533 		return -EINVAL;
2534 	}
2535 
2536 	mark_reg_scratched(env, regno);
2537 
2538 	reg = &regs[regno];
2539 	rw64 = is_reg64(env, insn, regno, reg, t);
2540 	if (t == SRC_OP) {
2541 		/* check whether register used as source operand can be read */
2542 		if (reg->type == NOT_INIT) {
2543 			verbose(env, "R%d !read_ok\n", regno);
2544 			return -EACCES;
2545 		}
2546 		/* We don't need to worry about FP liveness because it's read-only */
2547 		if (regno == BPF_REG_FP)
2548 			return 0;
2549 
2550 		if (rw64)
2551 			mark_insn_zext(env, reg);
2552 
2553 		return mark_reg_read(env, reg, reg->parent,
2554 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2555 	} else {
2556 		/* check whether register used as dest operand can be written to */
2557 		if (regno == BPF_REG_FP) {
2558 			verbose(env, "frame pointer is read only\n");
2559 			return -EACCES;
2560 		}
2561 		reg->live |= REG_LIVE_WRITTEN;
2562 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2563 		if (t == DST_OP)
2564 			mark_reg_unknown(env, regs, regno);
2565 	}
2566 	return 0;
2567 }
2568 
2569 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2570 {
2571 	env->insn_aux_data[idx].jmp_point = true;
2572 }
2573 
2574 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2575 {
2576 	return env->insn_aux_data[insn_idx].jmp_point;
2577 }
2578 
2579 /* for any branch, call, exit record the history of jmps in the given state */
2580 static int push_jmp_history(struct bpf_verifier_env *env,
2581 			    struct bpf_verifier_state *cur)
2582 {
2583 	u32 cnt = cur->jmp_history_cnt;
2584 	struct bpf_idx_pair *p;
2585 	size_t alloc_size;
2586 
2587 	if (!is_jmp_point(env, env->insn_idx))
2588 		return 0;
2589 
2590 	cnt++;
2591 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2592 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2593 	if (!p)
2594 		return -ENOMEM;
2595 	p[cnt - 1].idx = env->insn_idx;
2596 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2597 	cur->jmp_history = p;
2598 	cur->jmp_history_cnt = cnt;
2599 	return 0;
2600 }
2601 
2602 /* Backtrack one insn at a time. If idx is not at the top of recorded
2603  * history then previous instruction came from straight line execution.
2604  */
2605 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2606 			     u32 *history)
2607 {
2608 	u32 cnt = *history;
2609 
2610 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2611 		i = st->jmp_history[cnt - 1].prev_idx;
2612 		(*history)--;
2613 	} else {
2614 		i--;
2615 	}
2616 	return i;
2617 }
2618 
2619 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2620 {
2621 	const struct btf_type *func;
2622 	struct btf *desc_btf;
2623 
2624 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2625 		return NULL;
2626 
2627 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2628 	if (IS_ERR(desc_btf))
2629 		return "<error>";
2630 
2631 	func = btf_type_by_id(desc_btf, insn->imm);
2632 	return btf_name_by_offset(desc_btf, func->name_off);
2633 }
2634 
2635 /* For given verifier state backtrack_insn() is called from the last insn to
2636  * the first insn. Its purpose is to compute a bitmask of registers and
2637  * stack slots that needs precision in the parent verifier state.
2638  */
2639 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2640 			  u32 *reg_mask, u64 *stack_mask)
2641 {
2642 	const struct bpf_insn_cbs cbs = {
2643 		.cb_call	= disasm_kfunc_name,
2644 		.cb_print	= verbose,
2645 		.private_data	= env,
2646 	};
2647 	struct bpf_insn *insn = env->prog->insnsi + idx;
2648 	u8 class = BPF_CLASS(insn->code);
2649 	u8 opcode = BPF_OP(insn->code);
2650 	u8 mode = BPF_MODE(insn->code);
2651 	u32 dreg = 1u << insn->dst_reg;
2652 	u32 sreg = 1u << insn->src_reg;
2653 	u32 spi;
2654 
2655 	if (insn->code == 0)
2656 		return 0;
2657 	if (env->log.level & BPF_LOG_LEVEL2) {
2658 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2659 		verbose(env, "%d: ", idx);
2660 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2661 	}
2662 
2663 	if (class == BPF_ALU || class == BPF_ALU64) {
2664 		if (!(*reg_mask & dreg))
2665 			return 0;
2666 		if (opcode == BPF_MOV) {
2667 			if (BPF_SRC(insn->code) == BPF_X) {
2668 				/* dreg = sreg
2669 				 * dreg needs precision after this insn
2670 				 * sreg needs precision before this insn
2671 				 */
2672 				*reg_mask &= ~dreg;
2673 				*reg_mask |= sreg;
2674 			} else {
2675 				/* dreg = K
2676 				 * dreg needs precision after this insn.
2677 				 * Corresponding register is already marked
2678 				 * as precise=true in this verifier state.
2679 				 * No further markings in parent are necessary
2680 				 */
2681 				*reg_mask &= ~dreg;
2682 			}
2683 		} else {
2684 			if (BPF_SRC(insn->code) == BPF_X) {
2685 				/* dreg += sreg
2686 				 * both dreg and sreg need precision
2687 				 * before this insn
2688 				 */
2689 				*reg_mask |= sreg;
2690 			} /* else dreg += K
2691 			   * dreg still needs precision before this insn
2692 			   */
2693 		}
2694 	} else if (class == BPF_LDX) {
2695 		if (!(*reg_mask & dreg))
2696 			return 0;
2697 		*reg_mask &= ~dreg;
2698 
2699 		/* scalars can only be spilled into stack w/o losing precision.
2700 		 * Load from any other memory can be zero extended.
2701 		 * The desire to keep that precision is already indicated
2702 		 * by 'precise' mark in corresponding register of this state.
2703 		 * No further tracking necessary.
2704 		 */
2705 		if (insn->src_reg != BPF_REG_FP)
2706 			return 0;
2707 
2708 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2709 		 * that [fp - off] slot contains scalar that needs to be
2710 		 * tracked with precision
2711 		 */
2712 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2713 		if (spi >= 64) {
2714 			verbose(env, "BUG spi %d\n", spi);
2715 			WARN_ONCE(1, "verifier backtracking bug");
2716 			return -EFAULT;
2717 		}
2718 		*stack_mask |= 1ull << spi;
2719 	} else if (class == BPF_STX || class == BPF_ST) {
2720 		if (*reg_mask & dreg)
2721 			/* stx & st shouldn't be using _scalar_ dst_reg
2722 			 * to access memory. It means backtracking
2723 			 * encountered a case of pointer subtraction.
2724 			 */
2725 			return -ENOTSUPP;
2726 		/* scalars can only be spilled into stack */
2727 		if (insn->dst_reg != BPF_REG_FP)
2728 			return 0;
2729 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2730 		if (spi >= 64) {
2731 			verbose(env, "BUG spi %d\n", spi);
2732 			WARN_ONCE(1, "verifier backtracking bug");
2733 			return -EFAULT;
2734 		}
2735 		if (!(*stack_mask & (1ull << spi)))
2736 			return 0;
2737 		*stack_mask &= ~(1ull << spi);
2738 		if (class == BPF_STX)
2739 			*reg_mask |= sreg;
2740 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2741 		if (opcode == BPF_CALL) {
2742 			if (insn->src_reg == BPF_PSEUDO_CALL)
2743 				return -ENOTSUPP;
2744 			/* BPF helpers that invoke callback subprogs are
2745 			 * equivalent to BPF_PSEUDO_CALL above
2746 			 */
2747 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2748 				return -ENOTSUPP;
2749 			/* regular helper call sets R0 */
2750 			*reg_mask &= ~1;
2751 			if (*reg_mask & 0x3f) {
2752 				/* if backtracing was looking for registers R1-R5
2753 				 * they should have been found already.
2754 				 */
2755 				verbose(env, "BUG regs %x\n", *reg_mask);
2756 				WARN_ONCE(1, "verifier backtracking bug");
2757 				return -EFAULT;
2758 			}
2759 		} else if (opcode == BPF_EXIT) {
2760 			return -ENOTSUPP;
2761 		}
2762 	} else if (class == BPF_LD) {
2763 		if (!(*reg_mask & dreg))
2764 			return 0;
2765 		*reg_mask &= ~dreg;
2766 		/* It's ld_imm64 or ld_abs or ld_ind.
2767 		 * For ld_imm64 no further tracking of precision
2768 		 * into parent is necessary
2769 		 */
2770 		if (mode == BPF_IND || mode == BPF_ABS)
2771 			/* to be analyzed */
2772 			return -ENOTSUPP;
2773 	}
2774 	return 0;
2775 }
2776 
2777 /* the scalar precision tracking algorithm:
2778  * . at the start all registers have precise=false.
2779  * . scalar ranges are tracked as normal through alu and jmp insns.
2780  * . once precise value of the scalar register is used in:
2781  *   .  ptr + scalar alu
2782  *   . if (scalar cond K|scalar)
2783  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2784  *   backtrack through the verifier states and mark all registers and
2785  *   stack slots with spilled constants that these scalar regisers
2786  *   should be precise.
2787  * . during state pruning two registers (or spilled stack slots)
2788  *   are equivalent if both are not precise.
2789  *
2790  * Note the verifier cannot simply walk register parentage chain,
2791  * since many different registers and stack slots could have been
2792  * used to compute single precise scalar.
2793  *
2794  * The approach of starting with precise=true for all registers and then
2795  * backtrack to mark a register as not precise when the verifier detects
2796  * that program doesn't care about specific value (e.g., when helper
2797  * takes register as ARG_ANYTHING parameter) is not safe.
2798  *
2799  * It's ok to walk single parentage chain of the verifier states.
2800  * It's possible that this backtracking will go all the way till 1st insn.
2801  * All other branches will be explored for needing precision later.
2802  *
2803  * The backtracking needs to deal with cases like:
2804  *   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)
2805  * r9 -= r8
2806  * r5 = r9
2807  * if r5 > 0x79f goto pc+7
2808  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2809  * r5 += 1
2810  * ...
2811  * call bpf_perf_event_output#25
2812  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2813  *
2814  * and this case:
2815  * r6 = 1
2816  * call foo // uses callee's r6 inside to compute r0
2817  * r0 += r6
2818  * if r0 == 0 goto
2819  *
2820  * to track above reg_mask/stack_mask needs to be independent for each frame.
2821  *
2822  * Also if parent's curframe > frame where backtracking started,
2823  * the verifier need to mark registers in both frames, otherwise callees
2824  * may incorrectly prune callers. This is similar to
2825  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2826  *
2827  * For now backtracking falls back into conservative marking.
2828  */
2829 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2830 				     struct bpf_verifier_state *st)
2831 {
2832 	struct bpf_func_state *func;
2833 	struct bpf_reg_state *reg;
2834 	int i, j;
2835 
2836 	/* big hammer: mark all scalars precise in this path.
2837 	 * pop_stack may still get !precise scalars.
2838 	 * We also skip current state and go straight to first parent state,
2839 	 * because precision markings in current non-checkpointed state are
2840 	 * not needed. See why in the comment in __mark_chain_precision below.
2841 	 */
2842 	for (st = st->parent; st; st = st->parent) {
2843 		for (i = 0; i <= st->curframe; i++) {
2844 			func = st->frame[i];
2845 			for (j = 0; j < BPF_REG_FP; j++) {
2846 				reg = &func->regs[j];
2847 				if (reg->type != SCALAR_VALUE)
2848 					continue;
2849 				reg->precise = true;
2850 			}
2851 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2852 				if (!is_spilled_reg(&func->stack[j]))
2853 					continue;
2854 				reg = &func->stack[j].spilled_ptr;
2855 				if (reg->type != SCALAR_VALUE)
2856 					continue;
2857 				reg->precise = true;
2858 			}
2859 		}
2860 	}
2861 }
2862 
2863 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2864 {
2865 	struct bpf_func_state *func;
2866 	struct bpf_reg_state *reg;
2867 	int i, j;
2868 
2869 	for (i = 0; i <= st->curframe; i++) {
2870 		func = st->frame[i];
2871 		for (j = 0; j < BPF_REG_FP; j++) {
2872 			reg = &func->regs[j];
2873 			if (reg->type != SCALAR_VALUE)
2874 				continue;
2875 			reg->precise = false;
2876 		}
2877 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2878 			if (!is_spilled_reg(&func->stack[j]))
2879 				continue;
2880 			reg = &func->stack[j].spilled_ptr;
2881 			if (reg->type != SCALAR_VALUE)
2882 				continue;
2883 			reg->precise = false;
2884 		}
2885 	}
2886 }
2887 
2888 /*
2889  * __mark_chain_precision() backtracks BPF program instruction sequence and
2890  * chain of verifier states making sure that register *regno* (if regno >= 0)
2891  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2892  * SCALARS, as well as any other registers and slots that contribute to
2893  * a tracked state of given registers/stack slots, depending on specific BPF
2894  * assembly instructions (see backtrack_insns() for exact instruction handling
2895  * logic). This backtracking relies on recorded jmp_history and is able to
2896  * traverse entire chain of parent states. This process ends only when all the
2897  * necessary registers/slots and their transitive dependencies are marked as
2898  * precise.
2899  *
2900  * One important and subtle aspect is that precise marks *do not matter* in
2901  * the currently verified state (current state). It is important to understand
2902  * why this is the case.
2903  *
2904  * First, note that current state is the state that is not yet "checkpointed",
2905  * i.e., it is not yet put into env->explored_states, and it has no children
2906  * states as well. It's ephemeral, and can end up either a) being discarded if
2907  * compatible explored state is found at some point or BPF_EXIT instruction is
2908  * reached or b) checkpointed and put into env->explored_states, branching out
2909  * into one or more children states.
2910  *
2911  * In the former case, precise markings in current state are completely
2912  * ignored by state comparison code (see regsafe() for details). Only
2913  * checkpointed ("old") state precise markings are important, and if old
2914  * state's register/slot is precise, regsafe() assumes current state's
2915  * register/slot as precise and checks value ranges exactly and precisely. If
2916  * states turn out to be compatible, current state's necessary precise
2917  * markings and any required parent states' precise markings are enforced
2918  * after the fact with propagate_precision() logic, after the fact. But it's
2919  * important to realize that in this case, even after marking current state
2920  * registers/slots as precise, we immediately discard current state. So what
2921  * actually matters is any of the precise markings propagated into current
2922  * state's parent states, which are always checkpointed (due to b) case above).
2923  * As such, for scenario a) it doesn't matter if current state has precise
2924  * markings set or not.
2925  *
2926  * Now, for the scenario b), checkpointing and forking into child(ren)
2927  * state(s). Note that before current state gets to checkpointing step, any
2928  * processed instruction always assumes precise SCALAR register/slot
2929  * knowledge: if precise value or range is useful to prune jump branch, BPF
2930  * verifier takes this opportunity enthusiastically. Similarly, when
2931  * register's value is used to calculate offset or memory address, exact
2932  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2933  * what we mentioned above about state comparison ignoring precise markings
2934  * during state comparison, BPF verifier ignores and also assumes precise
2935  * markings *at will* during instruction verification process. But as verifier
2936  * assumes precision, it also propagates any precision dependencies across
2937  * parent states, which are not yet finalized, so can be further restricted
2938  * based on new knowledge gained from restrictions enforced by their children
2939  * states. This is so that once those parent states are finalized, i.e., when
2940  * they have no more active children state, state comparison logic in
2941  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2942  * required for correctness.
2943  *
2944  * To build a bit more intuition, note also that once a state is checkpointed,
2945  * the path we took to get to that state is not important. This is crucial
2946  * property for state pruning. When state is checkpointed and finalized at
2947  * some instruction index, it can be correctly and safely used to "short
2948  * circuit" any *compatible* state that reaches exactly the same instruction
2949  * index. I.e., if we jumped to that instruction from a completely different
2950  * code path than original finalized state was derived from, it doesn't
2951  * matter, current state can be discarded because from that instruction
2952  * forward having a compatible state will ensure we will safely reach the
2953  * exit. States describe preconditions for further exploration, but completely
2954  * forget the history of how we got here.
2955  *
2956  * This also means that even if we needed precise SCALAR range to get to
2957  * finalized state, but from that point forward *that same* SCALAR register is
2958  * never used in a precise context (i.e., it's precise value is not needed for
2959  * correctness), it's correct and safe to mark such register as "imprecise"
2960  * (i.e., precise marking set to false). This is what we rely on when we do
2961  * not set precise marking in current state. If no child state requires
2962  * precision for any given SCALAR register, it's safe to dictate that it can
2963  * be imprecise. If any child state does require this register to be precise,
2964  * we'll mark it precise later retroactively during precise markings
2965  * propagation from child state to parent states.
2966  *
2967  * Skipping precise marking setting in current state is a mild version of
2968  * relying on the above observation. But we can utilize this property even
2969  * more aggressively by proactively forgetting any precise marking in the
2970  * current state (which we inherited from the parent state), right before we
2971  * checkpoint it and branch off into new child state. This is done by
2972  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2973  * finalized states which help in short circuiting more future states.
2974  */
2975 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2976 				  int spi)
2977 {
2978 	struct bpf_verifier_state *st = env->cur_state;
2979 	int first_idx = st->first_insn_idx;
2980 	int last_idx = env->insn_idx;
2981 	struct bpf_func_state *func;
2982 	struct bpf_reg_state *reg;
2983 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2984 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2985 	bool skip_first = true;
2986 	bool new_marks = false;
2987 	int i, err;
2988 
2989 	if (!env->bpf_capable)
2990 		return 0;
2991 
2992 	/* Do sanity checks against current state of register and/or stack
2993 	 * slot, but don't set precise flag in current state, as precision
2994 	 * tracking in the current state is unnecessary.
2995 	 */
2996 	func = st->frame[frame];
2997 	if (regno >= 0) {
2998 		reg = &func->regs[regno];
2999 		if (reg->type != SCALAR_VALUE) {
3000 			WARN_ONCE(1, "backtracing misuse");
3001 			return -EFAULT;
3002 		}
3003 		new_marks = true;
3004 	}
3005 
3006 	while (spi >= 0) {
3007 		if (!is_spilled_reg(&func->stack[spi])) {
3008 			stack_mask = 0;
3009 			break;
3010 		}
3011 		reg = &func->stack[spi].spilled_ptr;
3012 		if (reg->type != SCALAR_VALUE) {
3013 			stack_mask = 0;
3014 			break;
3015 		}
3016 		new_marks = true;
3017 		break;
3018 	}
3019 
3020 	if (!new_marks)
3021 		return 0;
3022 	if (!reg_mask && !stack_mask)
3023 		return 0;
3024 
3025 	for (;;) {
3026 		DECLARE_BITMAP(mask, 64);
3027 		u32 history = st->jmp_history_cnt;
3028 
3029 		if (env->log.level & BPF_LOG_LEVEL2)
3030 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3031 
3032 		if (last_idx < 0) {
3033 			/* we are at the entry into subprog, which
3034 			 * is expected for global funcs, but only if
3035 			 * requested precise registers are R1-R5
3036 			 * (which are global func's input arguments)
3037 			 */
3038 			if (st->curframe == 0 &&
3039 			    st->frame[0]->subprogno > 0 &&
3040 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
3041 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3042 				bitmap_from_u64(mask, reg_mask);
3043 				for_each_set_bit(i, mask, 32) {
3044 					reg = &st->frame[0]->regs[i];
3045 					if (reg->type != SCALAR_VALUE) {
3046 						reg_mask &= ~(1u << i);
3047 						continue;
3048 					}
3049 					reg->precise = true;
3050 				}
3051 				return 0;
3052 			}
3053 
3054 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3055 				st->frame[0]->subprogno, reg_mask, stack_mask);
3056 			WARN_ONCE(1, "verifier backtracking bug");
3057 			return -EFAULT;
3058 		}
3059 
3060 		for (i = last_idx;;) {
3061 			if (skip_first) {
3062 				err = 0;
3063 				skip_first = false;
3064 			} else {
3065 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3066 			}
3067 			if (err == -ENOTSUPP) {
3068 				mark_all_scalars_precise(env, st);
3069 				return 0;
3070 			} else if (err) {
3071 				return err;
3072 			}
3073 			if (!reg_mask && !stack_mask)
3074 				/* Found assignment(s) into tracked register in this state.
3075 				 * Since this state is already marked, just return.
3076 				 * Nothing to be tracked further in the parent state.
3077 				 */
3078 				return 0;
3079 			if (i == first_idx)
3080 				break;
3081 			i = get_prev_insn_idx(st, i, &history);
3082 			if (i >= env->prog->len) {
3083 				/* This can happen if backtracking reached insn 0
3084 				 * and there are still reg_mask or stack_mask
3085 				 * to backtrack.
3086 				 * It means the backtracking missed the spot where
3087 				 * particular register was initialized with a constant.
3088 				 */
3089 				verbose(env, "BUG backtracking idx %d\n", i);
3090 				WARN_ONCE(1, "verifier backtracking bug");
3091 				return -EFAULT;
3092 			}
3093 		}
3094 		st = st->parent;
3095 		if (!st)
3096 			break;
3097 
3098 		new_marks = false;
3099 		func = st->frame[frame];
3100 		bitmap_from_u64(mask, reg_mask);
3101 		for_each_set_bit(i, mask, 32) {
3102 			reg = &func->regs[i];
3103 			if (reg->type != SCALAR_VALUE) {
3104 				reg_mask &= ~(1u << i);
3105 				continue;
3106 			}
3107 			if (!reg->precise)
3108 				new_marks = true;
3109 			reg->precise = true;
3110 		}
3111 
3112 		bitmap_from_u64(mask, stack_mask);
3113 		for_each_set_bit(i, mask, 64) {
3114 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
3115 				/* the sequence of instructions:
3116 				 * 2: (bf) r3 = r10
3117 				 * 3: (7b) *(u64 *)(r3 -8) = r0
3118 				 * 4: (79) r4 = *(u64 *)(r10 -8)
3119 				 * doesn't contain jmps. It's backtracked
3120 				 * as a single block.
3121 				 * During backtracking insn 3 is not recognized as
3122 				 * stack access, so at the end of backtracking
3123 				 * stack slot fp-8 is still marked in stack_mask.
3124 				 * However the parent state may not have accessed
3125 				 * fp-8 and it's "unallocated" stack space.
3126 				 * In such case fallback to conservative.
3127 				 */
3128 				mark_all_scalars_precise(env, st);
3129 				return 0;
3130 			}
3131 
3132 			if (!is_spilled_reg(&func->stack[i])) {
3133 				stack_mask &= ~(1ull << i);
3134 				continue;
3135 			}
3136 			reg = &func->stack[i].spilled_ptr;
3137 			if (reg->type != SCALAR_VALUE) {
3138 				stack_mask &= ~(1ull << i);
3139 				continue;
3140 			}
3141 			if (!reg->precise)
3142 				new_marks = true;
3143 			reg->precise = true;
3144 		}
3145 		if (env->log.level & BPF_LOG_LEVEL2) {
3146 			verbose(env, "parent %s regs=%x stack=%llx marks:",
3147 				new_marks ? "didn't have" : "already had",
3148 				reg_mask, stack_mask);
3149 			print_verifier_state(env, func, true);
3150 		}
3151 
3152 		if (!reg_mask && !stack_mask)
3153 			break;
3154 		if (!new_marks)
3155 			break;
3156 
3157 		last_idx = st->last_insn_idx;
3158 		first_idx = st->first_insn_idx;
3159 	}
3160 	return 0;
3161 }
3162 
3163 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3164 {
3165 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3166 }
3167 
3168 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3169 {
3170 	return __mark_chain_precision(env, frame, regno, -1);
3171 }
3172 
3173 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3174 {
3175 	return __mark_chain_precision(env, frame, -1, spi);
3176 }
3177 
3178 static bool is_spillable_regtype(enum bpf_reg_type type)
3179 {
3180 	switch (base_type(type)) {
3181 	case PTR_TO_MAP_VALUE:
3182 	case PTR_TO_STACK:
3183 	case PTR_TO_CTX:
3184 	case PTR_TO_PACKET:
3185 	case PTR_TO_PACKET_META:
3186 	case PTR_TO_PACKET_END:
3187 	case PTR_TO_FLOW_KEYS:
3188 	case CONST_PTR_TO_MAP:
3189 	case PTR_TO_SOCKET:
3190 	case PTR_TO_SOCK_COMMON:
3191 	case PTR_TO_TCP_SOCK:
3192 	case PTR_TO_XDP_SOCK:
3193 	case PTR_TO_BTF_ID:
3194 	case PTR_TO_BUF:
3195 	case PTR_TO_MEM:
3196 	case PTR_TO_FUNC:
3197 	case PTR_TO_MAP_KEY:
3198 		return true;
3199 	default:
3200 		return false;
3201 	}
3202 }
3203 
3204 /* Does this register contain a constant zero? */
3205 static bool register_is_null(struct bpf_reg_state *reg)
3206 {
3207 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3208 }
3209 
3210 static bool register_is_const(struct bpf_reg_state *reg)
3211 {
3212 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3213 }
3214 
3215 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3216 {
3217 	return tnum_is_unknown(reg->var_off) &&
3218 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3219 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3220 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3221 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3222 }
3223 
3224 static bool register_is_bounded(struct bpf_reg_state *reg)
3225 {
3226 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3227 }
3228 
3229 static bool __is_pointer_value(bool allow_ptr_leaks,
3230 			       const struct bpf_reg_state *reg)
3231 {
3232 	if (allow_ptr_leaks)
3233 		return false;
3234 
3235 	return reg->type != SCALAR_VALUE;
3236 }
3237 
3238 static void save_register_state(struct bpf_func_state *state,
3239 				int spi, struct bpf_reg_state *reg,
3240 				int size)
3241 {
3242 	int i;
3243 
3244 	state->stack[spi].spilled_ptr = *reg;
3245 	if (size == BPF_REG_SIZE)
3246 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3247 
3248 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3249 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3250 
3251 	/* size < 8 bytes spill */
3252 	for (; i; i--)
3253 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3254 }
3255 
3256 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3257  * stack boundary and alignment are checked in check_mem_access()
3258  */
3259 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3260 				       /* stack frame we're writing to */
3261 				       struct bpf_func_state *state,
3262 				       int off, int size, int value_regno,
3263 				       int insn_idx)
3264 {
3265 	struct bpf_func_state *cur; /* state of the current function */
3266 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3267 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3268 	struct bpf_reg_state *reg = NULL;
3269 
3270 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3271 	if (err)
3272 		return err;
3273 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3274 	 * so it's aligned access and [off, off + size) are within stack limits
3275 	 */
3276 	if (!env->allow_ptr_leaks &&
3277 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3278 	    size != BPF_REG_SIZE) {
3279 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3280 		return -EACCES;
3281 	}
3282 
3283 	cur = env->cur_state->frame[env->cur_state->curframe];
3284 	if (value_regno >= 0)
3285 		reg = &cur->regs[value_regno];
3286 	if (!env->bypass_spec_v4) {
3287 		bool sanitize = reg && is_spillable_regtype(reg->type);
3288 
3289 		for (i = 0; i < size; i++) {
3290 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3291 				sanitize = true;
3292 				break;
3293 			}
3294 		}
3295 
3296 		if (sanitize)
3297 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3298 	}
3299 
3300 	mark_stack_slot_scratched(env, spi);
3301 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3302 	    !register_is_null(reg) && env->bpf_capable) {
3303 		if (dst_reg != BPF_REG_FP) {
3304 			/* The backtracking logic can only recognize explicit
3305 			 * stack slot address like [fp - 8]. Other spill of
3306 			 * scalar via different register has to be conservative.
3307 			 * Backtrack from here and mark all registers as precise
3308 			 * that contributed into 'reg' being a constant.
3309 			 */
3310 			err = mark_chain_precision(env, value_regno);
3311 			if (err)
3312 				return err;
3313 		}
3314 		save_register_state(state, spi, reg, size);
3315 	} else if (reg && is_spillable_regtype(reg->type)) {
3316 		/* register containing pointer is being spilled into stack */
3317 		if (size != BPF_REG_SIZE) {
3318 			verbose_linfo(env, insn_idx, "; ");
3319 			verbose(env, "invalid size of register spill\n");
3320 			return -EACCES;
3321 		}
3322 		if (state != cur && reg->type == PTR_TO_STACK) {
3323 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3324 			return -EINVAL;
3325 		}
3326 		save_register_state(state, spi, reg, size);
3327 	} else {
3328 		u8 type = STACK_MISC;
3329 
3330 		/* regular write of data into stack destroys any spilled ptr */
3331 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3332 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3333 		if (is_spilled_reg(&state->stack[spi]))
3334 			for (i = 0; i < BPF_REG_SIZE; i++)
3335 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3336 
3337 		/* only mark the slot as written if all 8 bytes were written
3338 		 * otherwise read propagation may incorrectly stop too soon
3339 		 * when stack slots are partially written.
3340 		 * This heuristic means that read propagation will be
3341 		 * conservative, since it will add reg_live_read marks
3342 		 * to stack slots all the way to first state when programs
3343 		 * writes+reads less than 8 bytes
3344 		 */
3345 		if (size == BPF_REG_SIZE)
3346 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3347 
3348 		/* when we zero initialize stack slots mark them as such */
3349 		if (reg && register_is_null(reg)) {
3350 			/* backtracking doesn't work for STACK_ZERO yet. */
3351 			err = mark_chain_precision(env, value_regno);
3352 			if (err)
3353 				return err;
3354 			type = STACK_ZERO;
3355 		}
3356 
3357 		/* Mark slots affected by this stack write. */
3358 		for (i = 0; i < size; i++)
3359 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3360 				type;
3361 	}
3362 	return 0;
3363 }
3364 
3365 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3366  * known to contain a variable offset.
3367  * This function checks whether the write is permitted and conservatively
3368  * tracks the effects of the write, considering that each stack slot in the
3369  * dynamic range is potentially written to.
3370  *
3371  * 'off' includes 'regno->off'.
3372  * 'value_regno' can be -1, meaning that an unknown value is being written to
3373  * the stack.
3374  *
3375  * Spilled pointers in range are not marked as written because we don't know
3376  * what's going to be actually written. This means that read propagation for
3377  * future reads cannot be terminated by this write.
3378  *
3379  * For privileged programs, uninitialized stack slots are considered
3380  * initialized by this write (even though we don't know exactly what offsets
3381  * are going to be written to). The idea is that we don't want the verifier to
3382  * reject future reads that access slots written to through variable offsets.
3383  */
3384 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3385 				     /* func where register points to */
3386 				     struct bpf_func_state *state,
3387 				     int ptr_regno, int off, int size,
3388 				     int value_regno, int insn_idx)
3389 {
3390 	struct bpf_func_state *cur; /* state of the current function */
3391 	int min_off, max_off;
3392 	int i, err;
3393 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3394 	bool writing_zero = false;
3395 	/* set if the fact that we're writing a zero is used to let any
3396 	 * stack slots remain STACK_ZERO
3397 	 */
3398 	bool zero_used = false;
3399 
3400 	cur = env->cur_state->frame[env->cur_state->curframe];
3401 	ptr_reg = &cur->regs[ptr_regno];
3402 	min_off = ptr_reg->smin_value + off;
3403 	max_off = ptr_reg->smax_value + off + size;
3404 	if (value_regno >= 0)
3405 		value_reg = &cur->regs[value_regno];
3406 	if (value_reg && register_is_null(value_reg))
3407 		writing_zero = true;
3408 
3409 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3410 	if (err)
3411 		return err;
3412 
3413 
3414 	/* Variable offset writes destroy any spilled pointers in range. */
3415 	for (i = min_off; i < max_off; i++) {
3416 		u8 new_type, *stype;
3417 		int slot, spi;
3418 
3419 		slot = -i - 1;
3420 		spi = slot / BPF_REG_SIZE;
3421 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3422 		mark_stack_slot_scratched(env, spi);
3423 
3424 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3425 			/* Reject the write if range we may write to has not
3426 			 * been initialized beforehand. If we didn't reject
3427 			 * here, the ptr status would be erased below (even
3428 			 * though not all slots are actually overwritten),
3429 			 * possibly opening the door to leaks.
3430 			 *
3431 			 * We do however catch STACK_INVALID case below, and
3432 			 * only allow reading possibly uninitialized memory
3433 			 * later for CAP_PERFMON, as the write may not happen to
3434 			 * that slot.
3435 			 */
3436 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3437 				insn_idx, i);
3438 			return -EINVAL;
3439 		}
3440 
3441 		/* Erase all spilled pointers. */
3442 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3443 
3444 		/* Update the slot type. */
3445 		new_type = STACK_MISC;
3446 		if (writing_zero && *stype == STACK_ZERO) {
3447 			new_type = STACK_ZERO;
3448 			zero_used = true;
3449 		}
3450 		/* If the slot is STACK_INVALID, we check whether it's OK to
3451 		 * pretend that it will be initialized by this write. The slot
3452 		 * might not actually be written to, and so if we mark it as
3453 		 * initialized future reads might leak uninitialized memory.
3454 		 * For privileged programs, we will accept such reads to slots
3455 		 * that may or may not be written because, if we're reject
3456 		 * them, the error would be too confusing.
3457 		 */
3458 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3459 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3460 					insn_idx, i);
3461 			return -EINVAL;
3462 		}
3463 		*stype = new_type;
3464 	}
3465 	if (zero_used) {
3466 		/* backtracking doesn't work for STACK_ZERO yet. */
3467 		err = mark_chain_precision(env, value_regno);
3468 		if (err)
3469 			return err;
3470 	}
3471 	return 0;
3472 }
3473 
3474 /* When register 'dst_regno' is assigned some values from stack[min_off,
3475  * max_off), we set the register's type according to the types of the
3476  * respective stack slots. If all the stack values are known to be zeros, then
3477  * so is the destination reg. Otherwise, the register is considered to be
3478  * SCALAR. This function does not deal with register filling; the caller must
3479  * ensure that all spilled registers in the stack range have been marked as
3480  * read.
3481  */
3482 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3483 				/* func where src register points to */
3484 				struct bpf_func_state *ptr_state,
3485 				int min_off, int max_off, int dst_regno)
3486 {
3487 	struct bpf_verifier_state *vstate = env->cur_state;
3488 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3489 	int i, slot, spi;
3490 	u8 *stype;
3491 	int zeros = 0;
3492 
3493 	for (i = min_off; i < max_off; i++) {
3494 		slot = -i - 1;
3495 		spi = slot / BPF_REG_SIZE;
3496 		stype = ptr_state->stack[spi].slot_type;
3497 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3498 			break;
3499 		zeros++;
3500 	}
3501 	if (zeros == max_off - min_off) {
3502 		/* any access_size read into register is zero extended,
3503 		 * so the whole register == const_zero
3504 		 */
3505 		__mark_reg_const_zero(&state->regs[dst_regno]);
3506 		/* backtracking doesn't support STACK_ZERO yet,
3507 		 * so mark it precise here, so that later
3508 		 * backtracking can stop here.
3509 		 * Backtracking may not need this if this register
3510 		 * doesn't participate in pointer adjustment.
3511 		 * Forward propagation of precise flag is not
3512 		 * necessary either. This mark is only to stop
3513 		 * backtracking. Any register that contributed
3514 		 * to const 0 was marked precise before spill.
3515 		 */
3516 		state->regs[dst_regno].precise = true;
3517 	} else {
3518 		/* have read misc data from the stack */
3519 		mark_reg_unknown(env, state->regs, dst_regno);
3520 	}
3521 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3522 }
3523 
3524 /* Read the stack at 'off' and put the results into the register indicated by
3525  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3526  * spilled reg.
3527  *
3528  * 'dst_regno' can be -1, meaning that the read value is not going to a
3529  * register.
3530  *
3531  * The access is assumed to be within the current stack bounds.
3532  */
3533 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3534 				      /* func where src register points to */
3535 				      struct bpf_func_state *reg_state,
3536 				      int off, int size, int dst_regno)
3537 {
3538 	struct bpf_verifier_state *vstate = env->cur_state;
3539 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3540 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3541 	struct bpf_reg_state *reg;
3542 	u8 *stype, type;
3543 
3544 	stype = reg_state->stack[spi].slot_type;
3545 	reg = &reg_state->stack[spi].spilled_ptr;
3546 
3547 	if (is_spilled_reg(&reg_state->stack[spi])) {
3548 		u8 spill_size = 1;
3549 
3550 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3551 			spill_size++;
3552 
3553 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3554 			if (reg->type != SCALAR_VALUE) {
3555 				verbose_linfo(env, env->insn_idx, "; ");
3556 				verbose(env, "invalid size of register fill\n");
3557 				return -EACCES;
3558 			}
3559 
3560 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3561 			if (dst_regno < 0)
3562 				return 0;
3563 
3564 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3565 				/* The earlier check_reg_arg() has decided the
3566 				 * subreg_def for this insn.  Save it first.
3567 				 */
3568 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3569 
3570 				state->regs[dst_regno] = *reg;
3571 				state->regs[dst_regno].subreg_def = subreg_def;
3572 			} else {
3573 				for (i = 0; i < size; i++) {
3574 					type = stype[(slot - i) % BPF_REG_SIZE];
3575 					if (type == STACK_SPILL)
3576 						continue;
3577 					if (type == STACK_MISC)
3578 						continue;
3579 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3580 						off, i, size);
3581 					return -EACCES;
3582 				}
3583 				mark_reg_unknown(env, state->regs, dst_regno);
3584 			}
3585 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3586 			return 0;
3587 		}
3588 
3589 		if (dst_regno >= 0) {
3590 			/* restore register state from stack */
3591 			state->regs[dst_regno] = *reg;
3592 			/* mark reg as written since spilled pointer state likely
3593 			 * has its liveness marks cleared by is_state_visited()
3594 			 * which resets stack/reg liveness for state transitions
3595 			 */
3596 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3597 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3598 			/* If dst_regno==-1, the caller is asking us whether
3599 			 * it is acceptable to use this value as a SCALAR_VALUE
3600 			 * (e.g. for XADD).
3601 			 * We must not allow unprivileged callers to do that
3602 			 * with spilled pointers.
3603 			 */
3604 			verbose(env, "leaking pointer from stack off %d\n",
3605 				off);
3606 			return -EACCES;
3607 		}
3608 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3609 	} else {
3610 		for (i = 0; i < size; i++) {
3611 			type = stype[(slot - i) % BPF_REG_SIZE];
3612 			if (type == STACK_MISC)
3613 				continue;
3614 			if (type == STACK_ZERO)
3615 				continue;
3616 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3617 				off, i, size);
3618 			return -EACCES;
3619 		}
3620 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3621 		if (dst_regno >= 0)
3622 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3623 	}
3624 	return 0;
3625 }
3626 
3627 enum bpf_access_src {
3628 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3629 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3630 };
3631 
3632 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3633 					 int regno, int off, int access_size,
3634 					 bool zero_size_allowed,
3635 					 enum bpf_access_src type,
3636 					 struct bpf_call_arg_meta *meta);
3637 
3638 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3639 {
3640 	return cur_regs(env) + regno;
3641 }
3642 
3643 /* Read the stack at 'ptr_regno + off' and put the result into the register
3644  * 'dst_regno'.
3645  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3646  * but not its variable offset.
3647  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3648  *
3649  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3650  * filling registers (i.e. reads of spilled register cannot be detected when
3651  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3652  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3653  * offset; for a fixed offset check_stack_read_fixed_off should be used
3654  * instead.
3655  */
3656 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3657 				    int ptr_regno, int off, int size, int dst_regno)
3658 {
3659 	/* The state of the source register. */
3660 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3661 	struct bpf_func_state *ptr_state = func(env, reg);
3662 	int err;
3663 	int min_off, max_off;
3664 
3665 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3666 	 */
3667 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3668 					    false, ACCESS_DIRECT, NULL);
3669 	if (err)
3670 		return err;
3671 
3672 	min_off = reg->smin_value + off;
3673 	max_off = reg->smax_value + off;
3674 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3675 	return 0;
3676 }
3677 
3678 /* check_stack_read dispatches to check_stack_read_fixed_off or
3679  * check_stack_read_var_off.
3680  *
3681  * The caller must ensure that the offset falls within the allocated stack
3682  * bounds.
3683  *
3684  * 'dst_regno' is a register which will receive the value from the stack. It
3685  * can be -1, meaning that the read value is not going to a register.
3686  */
3687 static int check_stack_read(struct bpf_verifier_env *env,
3688 			    int ptr_regno, int off, int size,
3689 			    int dst_regno)
3690 {
3691 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3692 	struct bpf_func_state *state = func(env, reg);
3693 	int err;
3694 	/* Some accesses are only permitted with a static offset. */
3695 	bool var_off = !tnum_is_const(reg->var_off);
3696 
3697 	/* The offset is required to be static when reads don't go to a
3698 	 * register, in order to not leak pointers (see
3699 	 * check_stack_read_fixed_off).
3700 	 */
3701 	if (dst_regno < 0 && var_off) {
3702 		char tn_buf[48];
3703 
3704 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3705 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3706 			tn_buf, off, size);
3707 		return -EACCES;
3708 	}
3709 	/* Variable offset is prohibited for unprivileged mode for simplicity
3710 	 * since it requires corresponding support in Spectre masking for stack
3711 	 * ALU. See also retrieve_ptr_limit().
3712 	 */
3713 	if (!env->bypass_spec_v1 && var_off) {
3714 		char tn_buf[48];
3715 
3716 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3717 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3718 				ptr_regno, tn_buf);
3719 		return -EACCES;
3720 	}
3721 
3722 	if (!var_off) {
3723 		off += reg->var_off.value;
3724 		err = check_stack_read_fixed_off(env, state, off, size,
3725 						 dst_regno);
3726 	} else {
3727 		/* Variable offset stack reads need more conservative handling
3728 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3729 		 * branch.
3730 		 */
3731 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3732 					       dst_regno);
3733 	}
3734 	return err;
3735 }
3736 
3737 
3738 /* check_stack_write dispatches to check_stack_write_fixed_off or
3739  * check_stack_write_var_off.
3740  *
3741  * 'ptr_regno' is the register used as a pointer into the stack.
3742  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3743  * 'value_regno' is the register whose value we're writing to the stack. It can
3744  * be -1, meaning that we're not writing from a register.
3745  *
3746  * The caller must ensure that the offset falls within the maximum stack size.
3747  */
3748 static int check_stack_write(struct bpf_verifier_env *env,
3749 			     int ptr_regno, int off, int size,
3750 			     int value_regno, int insn_idx)
3751 {
3752 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3753 	struct bpf_func_state *state = func(env, reg);
3754 	int err;
3755 
3756 	if (tnum_is_const(reg->var_off)) {
3757 		off += reg->var_off.value;
3758 		err = check_stack_write_fixed_off(env, state, off, size,
3759 						  value_regno, insn_idx);
3760 	} else {
3761 		/* Variable offset stack reads need more conservative handling
3762 		 * than fixed offset ones.
3763 		 */
3764 		err = check_stack_write_var_off(env, state,
3765 						ptr_regno, off, size,
3766 						value_regno, insn_idx);
3767 	}
3768 	return err;
3769 }
3770 
3771 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3772 				 int off, int size, enum bpf_access_type type)
3773 {
3774 	struct bpf_reg_state *regs = cur_regs(env);
3775 	struct bpf_map *map = regs[regno].map_ptr;
3776 	u32 cap = bpf_map_flags_to_cap(map);
3777 
3778 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3779 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3780 			map->value_size, off, size);
3781 		return -EACCES;
3782 	}
3783 
3784 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3785 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3786 			map->value_size, off, size);
3787 		return -EACCES;
3788 	}
3789 
3790 	return 0;
3791 }
3792 
3793 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3794 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3795 			      int off, int size, u32 mem_size,
3796 			      bool zero_size_allowed)
3797 {
3798 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3799 	struct bpf_reg_state *reg;
3800 
3801 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3802 		return 0;
3803 
3804 	reg = &cur_regs(env)[regno];
3805 	switch (reg->type) {
3806 	case PTR_TO_MAP_KEY:
3807 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3808 			mem_size, off, size);
3809 		break;
3810 	case PTR_TO_MAP_VALUE:
3811 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3812 			mem_size, off, size);
3813 		break;
3814 	case PTR_TO_PACKET:
3815 	case PTR_TO_PACKET_META:
3816 	case PTR_TO_PACKET_END:
3817 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3818 			off, size, regno, reg->id, off, mem_size);
3819 		break;
3820 	case PTR_TO_MEM:
3821 	default:
3822 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3823 			mem_size, off, size);
3824 	}
3825 
3826 	return -EACCES;
3827 }
3828 
3829 /* check read/write into a memory region with possible variable offset */
3830 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3831 				   int off, int size, u32 mem_size,
3832 				   bool zero_size_allowed)
3833 {
3834 	struct bpf_verifier_state *vstate = env->cur_state;
3835 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3836 	struct bpf_reg_state *reg = &state->regs[regno];
3837 	int err;
3838 
3839 	/* We may have adjusted the register pointing to memory region, so we
3840 	 * need to try adding each of min_value and max_value to off
3841 	 * to make sure our theoretical access will be safe.
3842 	 *
3843 	 * The minimum value is only important with signed
3844 	 * comparisons where we can't assume the floor of a
3845 	 * value is 0.  If we are using signed variables for our
3846 	 * index'es we need to make sure that whatever we use
3847 	 * will have a set floor within our range.
3848 	 */
3849 	if (reg->smin_value < 0 &&
3850 	    (reg->smin_value == S64_MIN ||
3851 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3852 	      reg->smin_value + off < 0)) {
3853 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3854 			regno);
3855 		return -EACCES;
3856 	}
3857 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3858 				 mem_size, zero_size_allowed);
3859 	if (err) {
3860 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3861 			regno);
3862 		return err;
3863 	}
3864 
3865 	/* If we haven't set a max value then we need to bail since we can't be
3866 	 * sure we won't do bad things.
3867 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3868 	 */
3869 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3870 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3871 			regno);
3872 		return -EACCES;
3873 	}
3874 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3875 				 mem_size, zero_size_allowed);
3876 	if (err) {
3877 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3878 			regno);
3879 		return err;
3880 	}
3881 
3882 	return 0;
3883 }
3884 
3885 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3886 			       const struct bpf_reg_state *reg, int regno,
3887 			       bool fixed_off_ok)
3888 {
3889 	/* Access to this pointer-typed register or passing it to a helper
3890 	 * is only allowed in its original, unmodified form.
3891 	 */
3892 
3893 	if (reg->off < 0) {
3894 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3895 			reg_type_str(env, reg->type), regno, reg->off);
3896 		return -EACCES;
3897 	}
3898 
3899 	if (!fixed_off_ok && reg->off) {
3900 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3901 			reg_type_str(env, reg->type), regno, reg->off);
3902 		return -EACCES;
3903 	}
3904 
3905 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3906 		char tn_buf[48];
3907 
3908 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3909 		verbose(env, "variable %s access var_off=%s disallowed\n",
3910 			reg_type_str(env, reg->type), tn_buf);
3911 		return -EACCES;
3912 	}
3913 
3914 	return 0;
3915 }
3916 
3917 int check_ptr_off_reg(struct bpf_verifier_env *env,
3918 		      const struct bpf_reg_state *reg, int regno)
3919 {
3920 	return __check_ptr_off_reg(env, reg, regno, false);
3921 }
3922 
3923 static int map_kptr_match_type(struct bpf_verifier_env *env,
3924 			       struct btf_field *kptr_field,
3925 			       struct bpf_reg_state *reg, u32 regno)
3926 {
3927 	const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3928 	int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3929 	const char *reg_name = "";
3930 
3931 	/* Only unreferenced case accepts untrusted pointers */
3932 	if (kptr_field->type == BPF_KPTR_UNREF)
3933 		perm_flags |= PTR_UNTRUSTED;
3934 
3935 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3936 		goto bad_type;
3937 
3938 	if (!btf_is_kernel(reg->btf)) {
3939 		verbose(env, "R%d must point to kernel BTF\n", regno);
3940 		return -EINVAL;
3941 	}
3942 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3943 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3944 
3945 	/* For ref_ptr case, release function check should ensure we get one
3946 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3947 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3948 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3949 	 * reg->off and reg->ref_obj_id are not needed here.
3950 	 */
3951 	if (__check_ptr_off_reg(env, reg, regno, true))
3952 		return -EACCES;
3953 
3954 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3955 	 * we also need to take into account the reg->off.
3956 	 *
3957 	 * We want to support cases like:
3958 	 *
3959 	 * struct foo {
3960 	 *         struct bar br;
3961 	 *         struct baz bz;
3962 	 * };
3963 	 *
3964 	 * struct foo *v;
3965 	 * v = func();	      // PTR_TO_BTF_ID
3966 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3967 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3968 	 *                    // first member type of struct after comparison fails
3969 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3970 	 *                    // to match type
3971 	 *
3972 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3973 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3974 	 * the struct to match type against first member of struct, i.e. reject
3975 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3976 	 * strict mode to true for type match.
3977 	 */
3978 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3979 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3980 				  kptr_field->type == BPF_KPTR_REF))
3981 		goto bad_type;
3982 	return 0;
3983 bad_type:
3984 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3985 		reg_type_str(env, reg->type), reg_name);
3986 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3987 	if (kptr_field->type == BPF_KPTR_UNREF)
3988 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3989 			targ_name);
3990 	else
3991 		verbose(env, "\n");
3992 	return -EINVAL;
3993 }
3994 
3995 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3996 				 int value_regno, int insn_idx,
3997 				 struct btf_field *kptr_field)
3998 {
3999 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4000 	int class = BPF_CLASS(insn->code);
4001 	struct bpf_reg_state *val_reg;
4002 
4003 	/* Things we already checked for in check_map_access and caller:
4004 	 *  - Reject cases where variable offset may touch kptr
4005 	 *  - size of access (must be BPF_DW)
4006 	 *  - tnum_is_const(reg->var_off)
4007 	 *  - kptr_field->offset == off + reg->var_off.value
4008 	 */
4009 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4010 	if (BPF_MODE(insn->code) != BPF_MEM) {
4011 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4012 		return -EACCES;
4013 	}
4014 
4015 	/* We only allow loading referenced kptr, since it will be marked as
4016 	 * untrusted, similar to unreferenced kptr.
4017 	 */
4018 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4019 		verbose(env, "store to referenced kptr disallowed\n");
4020 		return -EACCES;
4021 	}
4022 
4023 	if (class == BPF_LDX) {
4024 		val_reg = reg_state(env, value_regno);
4025 		/* We can simply mark the value_regno receiving the pointer
4026 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4027 		 */
4028 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4029 				kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4030 		/* For mark_ptr_or_null_reg */
4031 		val_reg->id = ++env->id_gen;
4032 	} else if (class == BPF_STX) {
4033 		val_reg = reg_state(env, value_regno);
4034 		if (!register_is_null(val_reg) &&
4035 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4036 			return -EACCES;
4037 	} else if (class == BPF_ST) {
4038 		if (insn->imm) {
4039 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4040 				kptr_field->offset);
4041 			return -EACCES;
4042 		}
4043 	} else {
4044 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4045 		return -EACCES;
4046 	}
4047 	return 0;
4048 }
4049 
4050 /* check read/write into a map element with possible variable offset */
4051 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4052 			    int off, int size, bool zero_size_allowed,
4053 			    enum bpf_access_src src)
4054 {
4055 	struct bpf_verifier_state *vstate = env->cur_state;
4056 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4057 	struct bpf_reg_state *reg = &state->regs[regno];
4058 	struct bpf_map *map = reg->map_ptr;
4059 	struct btf_record *rec;
4060 	int err, i;
4061 
4062 	err = check_mem_region_access(env, regno, off, size, map->value_size,
4063 				      zero_size_allowed);
4064 	if (err)
4065 		return err;
4066 
4067 	if (IS_ERR_OR_NULL(map->record))
4068 		return 0;
4069 	rec = map->record;
4070 	for (i = 0; i < rec->cnt; i++) {
4071 		struct btf_field *field = &rec->fields[i];
4072 		u32 p = field->offset;
4073 
4074 		/* If any part of a field  can be touched by load/store, reject
4075 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4076 		 * it is sufficient to check x1 < y2 && y1 < x2.
4077 		 */
4078 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4079 		    p < reg->umax_value + off + size) {
4080 			switch (field->type) {
4081 			case BPF_KPTR_UNREF:
4082 			case BPF_KPTR_REF:
4083 				if (src != ACCESS_DIRECT) {
4084 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
4085 					return -EACCES;
4086 				}
4087 				if (!tnum_is_const(reg->var_off)) {
4088 					verbose(env, "kptr access cannot have variable offset\n");
4089 					return -EACCES;
4090 				}
4091 				if (p != off + reg->var_off.value) {
4092 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4093 						p, off + reg->var_off.value);
4094 					return -EACCES;
4095 				}
4096 				if (size != bpf_size_to_bytes(BPF_DW)) {
4097 					verbose(env, "kptr access size must be BPF_DW\n");
4098 					return -EACCES;
4099 				}
4100 				break;
4101 			default:
4102 				verbose(env, "%s cannot be accessed directly by load/store\n",
4103 					btf_field_type_name(field->type));
4104 				return -EACCES;
4105 			}
4106 		}
4107 	}
4108 	return 0;
4109 }
4110 
4111 #define MAX_PACKET_OFF 0xffff
4112 
4113 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4114 				       const struct bpf_call_arg_meta *meta,
4115 				       enum bpf_access_type t)
4116 {
4117 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4118 
4119 	switch (prog_type) {
4120 	/* Program types only with direct read access go here! */
4121 	case BPF_PROG_TYPE_LWT_IN:
4122 	case BPF_PROG_TYPE_LWT_OUT:
4123 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4124 	case BPF_PROG_TYPE_SK_REUSEPORT:
4125 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4126 	case BPF_PROG_TYPE_CGROUP_SKB:
4127 		if (t == BPF_WRITE)
4128 			return false;
4129 		fallthrough;
4130 
4131 	/* Program types with direct read + write access go here! */
4132 	case BPF_PROG_TYPE_SCHED_CLS:
4133 	case BPF_PROG_TYPE_SCHED_ACT:
4134 	case BPF_PROG_TYPE_XDP:
4135 	case BPF_PROG_TYPE_LWT_XMIT:
4136 	case BPF_PROG_TYPE_SK_SKB:
4137 	case BPF_PROG_TYPE_SK_MSG:
4138 		if (meta)
4139 			return meta->pkt_access;
4140 
4141 		env->seen_direct_write = true;
4142 		return true;
4143 
4144 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4145 		if (t == BPF_WRITE)
4146 			env->seen_direct_write = true;
4147 
4148 		return true;
4149 
4150 	default:
4151 		return false;
4152 	}
4153 }
4154 
4155 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4156 			       int size, bool zero_size_allowed)
4157 {
4158 	struct bpf_reg_state *regs = cur_regs(env);
4159 	struct bpf_reg_state *reg = &regs[regno];
4160 	int err;
4161 
4162 	/* We may have added a variable offset to the packet pointer; but any
4163 	 * reg->range we have comes after that.  We are only checking the fixed
4164 	 * offset.
4165 	 */
4166 
4167 	/* We don't allow negative numbers, because we aren't tracking enough
4168 	 * detail to prove they're safe.
4169 	 */
4170 	if (reg->smin_value < 0) {
4171 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4172 			regno);
4173 		return -EACCES;
4174 	}
4175 
4176 	err = reg->range < 0 ? -EINVAL :
4177 	      __check_mem_access(env, regno, off, size, reg->range,
4178 				 zero_size_allowed);
4179 	if (err) {
4180 		verbose(env, "R%d offset is outside of the packet\n", regno);
4181 		return err;
4182 	}
4183 
4184 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4185 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4186 	 * otherwise find_good_pkt_pointers would have refused to set range info
4187 	 * that __check_mem_access would have rejected this pkt access.
4188 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4189 	 */
4190 	env->prog->aux->max_pkt_offset =
4191 		max_t(u32, env->prog->aux->max_pkt_offset,
4192 		      off + reg->umax_value + size - 1);
4193 
4194 	return err;
4195 }
4196 
4197 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4198 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4199 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
4200 			    struct btf **btf, u32 *btf_id)
4201 {
4202 	struct bpf_insn_access_aux info = {
4203 		.reg_type = *reg_type,
4204 		.log = &env->log,
4205 	};
4206 
4207 	if (env->ops->is_valid_access &&
4208 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4209 		/* A non zero info.ctx_field_size indicates that this field is a
4210 		 * candidate for later verifier transformation to load the whole
4211 		 * field and then apply a mask when accessed with a narrower
4212 		 * access than actual ctx access size. A zero info.ctx_field_size
4213 		 * will only allow for whole field access and rejects any other
4214 		 * type of narrower access.
4215 		 */
4216 		*reg_type = info.reg_type;
4217 
4218 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4219 			*btf = info.btf;
4220 			*btf_id = info.btf_id;
4221 		} else {
4222 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4223 		}
4224 		/* remember the offset of last byte accessed in ctx */
4225 		if (env->prog->aux->max_ctx_offset < off + size)
4226 			env->prog->aux->max_ctx_offset = off + size;
4227 		return 0;
4228 	}
4229 
4230 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4231 	return -EACCES;
4232 }
4233 
4234 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4235 				  int size)
4236 {
4237 	if (size < 0 || off < 0 ||
4238 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4239 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4240 			off, size);
4241 		return -EACCES;
4242 	}
4243 	return 0;
4244 }
4245 
4246 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4247 			     u32 regno, int off, int size,
4248 			     enum bpf_access_type t)
4249 {
4250 	struct bpf_reg_state *regs = cur_regs(env);
4251 	struct bpf_reg_state *reg = &regs[regno];
4252 	struct bpf_insn_access_aux info = {};
4253 	bool valid;
4254 
4255 	if (reg->smin_value < 0) {
4256 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4257 			regno);
4258 		return -EACCES;
4259 	}
4260 
4261 	switch (reg->type) {
4262 	case PTR_TO_SOCK_COMMON:
4263 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4264 		break;
4265 	case PTR_TO_SOCKET:
4266 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4267 		break;
4268 	case PTR_TO_TCP_SOCK:
4269 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4270 		break;
4271 	case PTR_TO_XDP_SOCK:
4272 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4273 		break;
4274 	default:
4275 		valid = false;
4276 	}
4277 
4278 
4279 	if (valid) {
4280 		env->insn_aux_data[insn_idx].ctx_field_size =
4281 			info.ctx_field_size;
4282 		return 0;
4283 	}
4284 
4285 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4286 		regno, reg_type_str(env, reg->type), off, size);
4287 
4288 	return -EACCES;
4289 }
4290 
4291 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4292 {
4293 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4294 }
4295 
4296 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4297 {
4298 	const struct bpf_reg_state *reg = reg_state(env, regno);
4299 
4300 	return reg->type == PTR_TO_CTX;
4301 }
4302 
4303 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4304 {
4305 	const struct bpf_reg_state *reg = reg_state(env, regno);
4306 
4307 	return type_is_sk_pointer(reg->type);
4308 }
4309 
4310 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4311 {
4312 	const struct bpf_reg_state *reg = reg_state(env, regno);
4313 
4314 	return type_is_pkt_pointer(reg->type);
4315 }
4316 
4317 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4318 {
4319 	const struct bpf_reg_state *reg = reg_state(env, regno);
4320 
4321 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4322 	return reg->type == PTR_TO_FLOW_KEYS;
4323 }
4324 
4325 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4326 {
4327 	/* A referenced register is always trusted. */
4328 	if (reg->ref_obj_id)
4329 		return true;
4330 
4331 	/* If a register is not referenced, it is trusted if it has the
4332 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4333 	 * other type modifiers may be safe, but we elect to take an opt-in
4334 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4335 	 * not.
4336 	 *
4337 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4338 	 * for whether a register is trusted.
4339 	 */
4340 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4341 	       !bpf_type_has_unsafe_modifiers(reg->type);
4342 }
4343 
4344 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4345 {
4346 	return reg->type & MEM_RCU;
4347 }
4348 
4349 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4350 				   const struct bpf_reg_state *reg,
4351 				   int off, int size, bool strict)
4352 {
4353 	struct tnum reg_off;
4354 	int ip_align;
4355 
4356 	/* Byte size accesses are always allowed. */
4357 	if (!strict || size == 1)
4358 		return 0;
4359 
4360 	/* For platforms that do not have a Kconfig enabling
4361 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4362 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4363 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4364 	 * to this code only in strict mode where we want to emulate
4365 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4366 	 * unconditional IP align value of '2'.
4367 	 */
4368 	ip_align = 2;
4369 
4370 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4371 	if (!tnum_is_aligned(reg_off, size)) {
4372 		char tn_buf[48];
4373 
4374 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4375 		verbose(env,
4376 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4377 			ip_align, tn_buf, reg->off, off, size);
4378 		return -EACCES;
4379 	}
4380 
4381 	return 0;
4382 }
4383 
4384 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4385 				       const struct bpf_reg_state *reg,
4386 				       const char *pointer_desc,
4387 				       int off, int size, bool strict)
4388 {
4389 	struct tnum reg_off;
4390 
4391 	/* Byte size accesses are always allowed. */
4392 	if (!strict || size == 1)
4393 		return 0;
4394 
4395 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4396 	if (!tnum_is_aligned(reg_off, size)) {
4397 		char tn_buf[48];
4398 
4399 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4400 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4401 			pointer_desc, tn_buf, reg->off, off, size);
4402 		return -EACCES;
4403 	}
4404 
4405 	return 0;
4406 }
4407 
4408 static int check_ptr_alignment(struct bpf_verifier_env *env,
4409 			       const struct bpf_reg_state *reg, int off,
4410 			       int size, bool strict_alignment_once)
4411 {
4412 	bool strict = env->strict_alignment || strict_alignment_once;
4413 	const char *pointer_desc = "";
4414 
4415 	switch (reg->type) {
4416 	case PTR_TO_PACKET:
4417 	case PTR_TO_PACKET_META:
4418 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4419 		 * right in front, treat it the very same way.
4420 		 */
4421 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4422 	case PTR_TO_FLOW_KEYS:
4423 		pointer_desc = "flow keys ";
4424 		break;
4425 	case PTR_TO_MAP_KEY:
4426 		pointer_desc = "key ";
4427 		break;
4428 	case PTR_TO_MAP_VALUE:
4429 		pointer_desc = "value ";
4430 		break;
4431 	case PTR_TO_CTX:
4432 		pointer_desc = "context ";
4433 		break;
4434 	case PTR_TO_STACK:
4435 		pointer_desc = "stack ";
4436 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4437 		 * and check_stack_read_fixed_off() relies on stack accesses being
4438 		 * aligned.
4439 		 */
4440 		strict = true;
4441 		break;
4442 	case PTR_TO_SOCKET:
4443 		pointer_desc = "sock ";
4444 		break;
4445 	case PTR_TO_SOCK_COMMON:
4446 		pointer_desc = "sock_common ";
4447 		break;
4448 	case PTR_TO_TCP_SOCK:
4449 		pointer_desc = "tcp_sock ";
4450 		break;
4451 	case PTR_TO_XDP_SOCK:
4452 		pointer_desc = "xdp_sock ";
4453 		break;
4454 	default:
4455 		break;
4456 	}
4457 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4458 					   strict);
4459 }
4460 
4461 static int update_stack_depth(struct bpf_verifier_env *env,
4462 			      const struct bpf_func_state *func,
4463 			      int off)
4464 {
4465 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4466 
4467 	if (stack >= -off)
4468 		return 0;
4469 
4470 	/* update known max for given subprogram */
4471 	env->subprog_info[func->subprogno].stack_depth = -off;
4472 	return 0;
4473 }
4474 
4475 /* starting from main bpf function walk all instructions of the function
4476  * and recursively walk all callees that given function can call.
4477  * Ignore jump and exit insns.
4478  * Since recursion is prevented by check_cfg() this algorithm
4479  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4480  */
4481 static int check_max_stack_depth(struct bpf_verifier_env *env)
4482 {
4483 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4484 	struct bpf_subprog_info *subprog = env->subprog_info;
4485 	struct bpf_insn *insn = env->prog->insnsi;
4486 	bool tail_call_reachable = false;
4487 	int ret_insn[MAX_CALL_FRAMES];
4488 	int ret_prog[MAX_CALL_FRAMES];
4489 	int j;
4490 
4491 process_func:
4492 	/* protect against potential stack overflow that might happen when
4493 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4494 	 * depth for such case down to 256 so that the worst case scenario
4495 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4496 	 * 8k).
4497 	 *
4498 	 * To get the idea what might happen, see an example:
4499 	 * func1 -> sub rsp, 128
4500 	 *  subfunc1 -> sub rsp, 256
4501 	 *  tailcall1 -> add rsp, 256
4502 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4503 	 *   subfunc2 -> sub rsp, 64
4504 	 *   subfunc22 -> sub rsp, 128
4505 	 *   tailcall2 -> add rsp, 128
4506 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4507 	 *
4508 	 * tailcall will unwind the current stack frame but it will not get rid
4509 	 * of caller's stack as shown on the example above.
4510 	 */
4511 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4512 		verbose(env,
4513 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4514 			depth);
4515 		return -EACCES;
4516 	}
4517 	/* round up to 32-bytes, since this is granularity
4518 	 * of interpreter stack size
4519 	 */
4520 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4521 	if (depth > MAX_BPF_STACK) {
4522 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4523 			frame + 1, depth);
4524 		return -EACCES;
4525 	}
4526 continue_func:
4527 	subprog_end = subprog[idx + 1].start;
4528 	for (; i < subprog_end; i++) {
4529 		int next_insn;
4530 
4531 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4532 			continue;
4533 		/* remember insn and function to return to */
4534 		ret_insn[frame] = i + 1;
4535 		ret_prog[frame] = idx;
4536 
4537 		/* find the callee */
4538 		next_insn = i + insn[i].imm + 1;
4539 		idx = find_subprog(env, next_insn);
4540 		if (idx < 0) {
4541 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4542 				  next_insn);
4543 			return -EFAULT;
4544 		}
4545 		if (subprog[idx].is_async_cb) {
4546 			if (subprog[idx].has_tail_call) {
4547 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4548 				return -EFAULT;
4549 			}
4550 			 /* async callbacks don't increase bpf prog stack size */
4551 			continue;
4552 		}
4553 		i = next_insn;
4554 
4555 		if (subprog[idx].has_tail_call)
4556 			tail_call_reachable = true;
4557 
4558 		frame++;
4559 		if (frame >= MAX_CALL_FRAMES) {
4560 			verbose(env, "the call stack of %d frames is too deep !\n",
4561 				frame);
4562 			return -E2BIG;
4563 		}
4564 		goto process_func;
4565 	}
4566 	/* if tail call got detected across bpf2bpf calls then mark each of the
4567 	 * currently present subprog frames as tail call reachable subprogs;
4568 	 * this info will be utilized by JIT so that we will be preserving the
4569 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4570 	 */
4571 	if (tail_call_reachable)
4572 		for (j = 0; j < frame; j++)
4573 			subprog[ret_prog[j]].tail_call_reachable = true;
4574 	if (subprog[0].tail_call_reachable)
4575 		env->prog->aux->tail_call_reachable = true;
4576 
4577 	/* end of for() loop means the last insn of the 'subprog'
4578 	 * was reached. Doesn't matter whether it was JA or EXIT
4579 	 */
4580 	if (frame == 0)
4581 		return 0;
4582 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4583 	frame--;
4584 	i = ret_insn[frame];
4585 	idx = ret_prog[frame];
4586 	goto continue_func;
4587 }
4588 
4589 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4590 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4591 				  const struct bpf_insn *insn, int idx)
4592 {
4593 	int start = idx + insn->imm + 1, subprog;
4594 
4595 	subprog = find_subprog(env, start);
4596 	if (subprog < 0) {
4597 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4598 			  start);
4599 		return -EFAULT;
4600 	}
4601 	return env->subprog_info[subprog].stack_depth;
4602 }
4603 #endif
4604 
4605 static int __check_buffer_access(struct bpf_verifier_env *env,
4606 				 const char *buf_info,
4607 				 const struct bpf_reg_state *reg,
4608 				 int regno, int off, int size)
4609 {
4610 	if (off < 0) {
4611 		verbose(env,
4612 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4613 			regno, buf_info, off, size);
4614 		return -EACCES;
4615 	}
4616 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4617 		char tn_buf[48];
4618 
4619 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4620 		verbose(env,
4621 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4622 			regno, off, tn_buf);
4623 		return -EACCES;
4624 	}
4625 
4626 	return 0;
4627 }
4628 
4629 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4630 				  const struct bpf_reg_state *reg,
4631 				  int regno, int off, int size)
4632 {
4633 	int err;
4634 
4635 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4636 	if (err)
4637 		return err;
4638 
4639 	if (off + size > env->prog->aux->max_tp_access)
4640 		env->prog->aux->max_tp_access = off + size;
4641 
4642 	return 0;
4643 }
4644 
4645 static int check_buffer_access(struct bpf_verifier_env *env,
4646 			       const struct bpf_reg_state *reg,
4647 			       int regno, int off, int size,
4648 			       bool zero_size_allowed,
4649 			       u32 *max_access)
4650 {
4651 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4652 	int err;
4653 
4654 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4655 	if (err)
4656 		return err;
4657 
4658 	if (off + size > *max_access)
4659 		*max_access = off + size;
4660 
4661 	return 0;
4662 }
4663 
4664 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4665 static void zext_32_to_64(struct bpf_reg_state *reg)
4666 {
4667 	reg->var_off = tnum_subreg(reg->var_off);
4668 	__reg_assign_32_into_64(reg);
4669 }
4670 
4671 /* truncate register to smaller size (in bytes)
4672  * must be called with size < BPF_REG_SIZE
4673  */
4674 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4675 {
4676 	u64 mask;
4677 
4678 	/* clear high bits in bit representation */
4679 	reg->var_off = tnum_cast(reg->var_off, size);
4680 
4681 	/* fix arithmetic bounds */
4682 	mask = ((u64)1 << (size * 8)) - 1;
4683 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4684 		reg->umin_value &= mask;
4685 		reg->umax_value &= mask;
4686 	} else {
4687 		reg->umin_value = 0;
4688 		reg->umax_value = mask;
4689 	}
4690 	reg->smin_value = reg->umin_value;
4691 	reg->smax_value = reg->umax_value;
4692 
4693 	/* If size is smaller than 32bit register the 32bit register
4694 	 * values are also truncated so we push 64-bit bounds into
4695 	 * 32-bit bounds. Above were truncated < 32-bits already.
4696 	 */
4697 	if (size >= 4)
4698 		return;
4699 	__reg_combine_64_into_32(reg);
4700 }
4701 
4702 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4703 {
4704 	/* A map is considered read-only if the following condition are true:
4705 	 *
4706 	 * 1) BPF program side cannot change any of the map content. The
4707 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4708 	 *    and was set at map creation time.
4709 	 * 2) The map value(s) have been initialized from user space by a
4710 	 *    loader and then "frozen", such that no new map update/delete
4711 	 *    operations from syscall side are possible for the rest of
4712 	 *    the map's lifetime from that point onwards.
4713 	 * 3) Any parallel/pending map update/delete operations from syscall
4714 	 *    side have been completed. Only after that point, it's safe to
4715 	 *    assume that map value(s) are immutable.
4716 	 */
4717 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4718 	       READ_ONCE(map->frozen) &&
4719 	       !bpf_map_write_active(map);
4720 }
4721 
4722 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4723 {
4724 	void *ptr;
4725 	u64 addr;
4726 	int err;
4727 
4728 	err = map->ops->map_direct_value_addr(map, &addr, off);
4729 	if (err)
4730 		return err;
4731 	ptr = (void *)(long)addr + off;
4732 
4733 	switch (size) {
4734 	case sizeof(u8):
4735 		*val = (u64)*(u8 *)ptr;
4736 		break;
4737 	case sizeof(u16):
4738 		*val = (u64)*(u16 *)ptr;
4739 		break;
4740 	case sizeof(u32):
4741 		*val = (u64)*(u32 *)ptr;
4742 		break;
4743 	case sizeof(u64):
4744 		*val = *(u64 *)ptr;
4745 		break;
4746 	default:
4747 		return -EINVAL;
4748 	}
4749 	return 0;
4750 }
4751 
4752 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4753 				   struct bpf_reg_state *regs,
4754 				   int regno, int off, int size,
4755 				   enum bpf_access_type atype,
4756 				   int value_regno)
4757 {
4758 	struct bpf_reg_state *reg = regs + regno;
4759 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4760 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4761 	enum bpf_type_flag flag = 0;
4762 	u32 btf_id;
4763 	int ret;
4764 
4765 	if (!env->allow_ptr_leaks) {
4766 		verbose(env,
4767 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4768 			tname);
4769 		return -EPERM;
4770 	}
4771 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
4772 		verbose(env,
4773 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
4774 			tname);
4775 		return -EINVAL;
4776 	}
4777 	if (off < 0) {
4778 		verbose(env,
4779 			"R%d is ptr_%s invalid negative access: off=%d\n",
4780 			regno, tname, off);
4781 		return -EACCES;
4782 	}
4783 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4784 		char tn_buf[48];
4785 
4786 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4787 		verbose(env,
4788 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4789 			regno, tname, off, tn_buf);
4790 		return -EACCES;
4791 	}
4792 
4793 	if (reg->type & MEM_USER) {
4794 		verbose(env,
4795 			"R%d is ptr_%s access user memory: off=%d\n",
4796 			regno, tname, off);
4797 		return -EACCES;
4798 	}
4799 
4800 	if (reg->type & MEM_PERCPU) {
4801 		verbose(env,
4802 			"R%d is ptr_%s access percpu memory: off=%d\n",
4803 			regno, tname, off);
4804 		return -EACCES;
4805 	}
4806 
4807 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4808 		if (!btf_is_kernel(reg->btf)) {
4809 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4810 			return -EFAULT;
4811 		}
4812 		ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4813 	} else {
4814 		/* Writes are permitted with default btf_struct_access for
4815 		 * program allocated objects (which always have ref_obj_id > 0),
4816 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4817 		 */
4818 		if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4819 			verbose(env, "only read is supported\n");
4820 			return -EACCES;
4821 		}
4822 
4823 		if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4824 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4825 			return -EFAULT;
4826 		}
4827 
4828 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4829 	}
4830 
4831 	if (ret < 0)
4832 		return ret;
4833 
4834 	/* If this is an untrusted pointer, all pointers formed by walking it
4835 	 * also inherit the untrusted flag.
4836 	 */
4837 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4838 		flag |= PTR_UNTRUSTED;
4839 
4840 	/* By default any pointer obtained from walking a trusted pointer is
4841 	 * no longer trusted except the rcu case below.
4842 	 */
4843 	flag &= ~PTR_TRUSTED;
4844 
4845 	if (flag & MEM_RCU) {
4846 		/* Mark value register as MEM_RCU only if it is protected by
4847 		 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU
4848 		 * itself can already indicate trustedness inside the rcu
4849 		 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since
4850 		 * it could be null in some cases.
4851 		 */
4852 		if (!env->cur_state->active_rcu_lock ||
4853 		    !(is_trusted_reg(reg) || is_rcu_reg(reg)))
4854 			flag &= ~MEM_RCU;
4855 		else
4856 			flag |= PTR_MAYBE_NULL;
4857 	} else if (reg->type & MEM_RCU) {
4858 		/* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged
4859 		 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively.
4860 		 */
4861 		flag |= PTR_UNTRUSTED;
4862 	}
4863 
4864 	if (atype == BPF_READ && value_regno >= 0)
4865 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4866 
4867 	return 0;
4868 }
4869 
4870 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4871 				   struct bpf_reg_state *regs,
4872 				   int regno, int off, int size,
4873 				   enum bpf_access_type atype,
4874 				   int value_regno)
4875 {
4876 	struct bpf_reg_state *reg = regs + regno;
4877 	struct bpf_map *map = reg->map_ptr;
4878 	struct bpf_reg_state map_reg;
4879 	enum bpf_type_flag flag = 0;
4880 	const struct btf_type *t;
4881 	const char *tname;
4882 	u32 btf_id;
4883 	int ret;
4884 
4885 	if (!btf_vmlinux) {
4886 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4887 		return -ENOTSUPP;
4888 	}
4889 
4890 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4891 		verbose(env, "map_ptr access not supported for map type %d\n",
4892 			map->map_type);
4893 		return -ENOTSUPP;
4894 	}
4895 
4896 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4897 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4898 
4899 	if (!env->allow_ptr_leaks) {
4900 		verbose(env,
4901 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4902 			tname);
4903 		return -EPERM;
4904 	}
4905 
4906 	if (off < 0) {
4907 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4908 			regno, tname, off);
4909 		return -EACCES;
4910 	}
4911 
4912 	if (atype != BPF_READ) {
4913 		verbose(env, "only read from %s is supported\n", tname);
4914 		return -EACCES;
4915 	}
4916 
4917 	/* Simulate access to a PTR_TO_BTF_ID */
4918 	memset(&map_reg, 0, sizeof(map_reg));
4919 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4920 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4921 	if (ret < 0)
4922 		return ret;
4923 
4924 	if (value_regno >= 0)
4925 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4926 
4927 	return 0;
4928 }
4929 
4930 /* Check that the stack access at the given offset is within bounds. The
4931  * maximum valid offset is -1.
4932  *
4933  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4934  * -state->allocated_stack for reads.
4935  */
4936 static int check_stack_slot_within_bounds(int off,
4937 					  struct bpf_func_state *state,
4938 					  enum bpf_access_type t)
4939 {
4940 	int min_valid_off;
4941 
4942 	if (t == BPF_WRITE)
4943 		min_valid_off = -MAX_BPF_STACK;
4944 	else
4945 		min_valid_off = -state->allocated_stack;
4946 
4947 	if (off < min_valid_off || off > -1)
4948 		return -EACCES;
4949 	return 0;
4950 }
4951 
4952 /* Check that the stack access at 'regno + off' falls within the maximum stack
4953  * bounds.
4954  *
4955  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4956  */
4957 static int check_stack_access_within_bounds(
4958 		struct bpf_verifier_env *env,
4959 		int regno, int off, int access_size,
4960 		enum bpf_access_src src, enum bpf_access_type type)
4961 {
4962 	struct bpf_reg_state *regs = cur_regs(env);
4963 	struct bpf_reg_state *reg = regs + regno;
4964 	struct bpf_func_state *state = func(env, reg);
4965 	int min_off, max_off;
4966 	int err;
4967 	char *err_extra;
4968 
4969 	if (src == ACCESS_HELPER)
4970 		/* We don't know if helpers are reading or writing (or both). */
4971 		err_extra = " indirect access to";
4972 	else if (type == BPF_READ)
4973 		err_extra = " read from";
4974 	else
4975 		err_extra = " write to";
4976 
4977 	if (tnum_is_const(reg->var_off)) {
4978 		min_off = reg->var_off.value + off;
4979 		if (access_size > 0)
4980 			max_off = min_off + access_size - 1;
4981 		else
4982 			max_off = min_off;
4983 	} else {
4984 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4985 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4986 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4987 				err_extra, regno);
4988 			return -EACCES;
4989 		}
4990 		min_off = reg->smin_value + off;
4991 		if (access_size > 0)
4992 			max_off = reg->smax_value + off + access_size - 1;
4993 		else
4994 			max_off = min_off;
4995 	}
4996 
4997 	err = check_stack_slot_within_bounds(min_off, state, type);
4998 	if (!err)
4999 		err = check_stack_slot_within_bounds(max_off, state, type);
5000 
5001 	if (err) {
5002 		if (tnum_is_const(reg->var_off)) {
5003 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5004 				err_extra, regno, off, access_size);
5005 		} else {
5006 			char tn_buf[48];
5007 
5008 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5009 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5010 				err_extra, regno, tn_buf, access_size);
5011 		}
5012 	}
5013 	return err;
5014 }
5015 
5016 /* check whether memory at (regno + off) is accessible for t = (read | write)
5017  * if t==write, value_regno is a register which value is stored into memory
5018  * if t==read, value_regno is a register which will receive the value from memory
5019  * if t==write && value_regno==-1, some unknown value is stored into memory
5020  * if t==read && value_regno==-1, don't care what we read from memory
5021  */
5022 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5023 			    int off, int bpf_size, enum bpf_access_type t,
5024 			    int value_regno, bool strict_alignment_once)
5025 {
5026 	struct bpf_reg_state *regs = cur_regs(env);
5027 	struct bpf_reg_state *reg = regs + regno;
5028 	struct bpf_func_state *state;
5029 	int size, err = 0;
5030 
5031 	size = bpf_size_to_bytes(bpf_size);
5032 	if (size < 0)
5033 		return size;
5034 
5035 	/* alignment checks will add in reg->off themselves */
5036 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5037 	if (err)
5038 		return err;
5039 
5040 	/* for access checks, reg->off is just part of off */
5041 	off += reg->off;
5042 
5043 	if (reg->type == PTR_TO_MAP_KEY) {
5044 		if (t == BPF_WRITE) {
5045 			verbose(env, "write to change key R%d not allowed\n", regno);
5046 			return -EACCES;
5047 		}
5048 
5049 		err = check_mem_region_access(env, regno, off, size,
5050 					      reg->map_ptr->key_size, false);
5051 		if (err)
5052 			return err;
5053 		if (value_regno >= 0)
5054 			mark_reg_unknown(env, regs, value_regno);
5055 	} else if (reg->type == PTR_TO_MAP_VALUE) {
5056 		struct btf_field *kptr_field = NULL;
5057 
5058 		if (t == BPF_WRITE && value_regno >= 0 &&
5059 		    is_pointer_value(env, value_regno)) {
5060 			verbose(env, "R%d leaks addr into map\n", value_regno);
5061 			return -EACCES;
5062 		}
5063 		err = check_map_access_type(env, regno, off, size, t);
5064 		if (err)
5065 			return err;
5066 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5067 		if (err)
5068 			return err;
5069 		if (tnum_is_const(reg->var_off))
5070 			kptr_field = btf_record_find(reg->map_ptr->record,
5071 						     off + reg->var_off.value, BPF_KPTR);
5072 		if (kptr_field) {
5073 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5074 		} else if (t == BPF_READ && value_regno >= 0) {
5075 			struct bpf_map *map = reg->map_ptr;
5076 
5077 			/* if map is read-only, track its contents as scalars */
5078 			if (tnum_is_const(reg->var_off) &&
5079 			    bpf_map_is_rdonly(map) &&
5080 			    map->ops->map_direct_value_addr) {
5081 				int map_off = off + reg->var_off.value;
5082 				u64 val = 0;
5083 
5084 				err = bpf_map_direct_read(map, map_off, size,
5085 							  &val);
5086 				if (err)
5087 					return err;
5088 
5089 				regs[value_regno].type = SCALAR_VALUE;
5090 				__mark_reg_known(&regs[value_regno], val);
5091 			} else {
5092 				mark_reg_unknown(env, regs, value_regno);
5093 			}
5094 		}
5095 	} else if (base_type(reg->type) == PTR_TO_MEM) {
5096 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5097 
5098 		if (type_may_be_null(reg->type)) {
5099 			verbose(env, "R%d invalid mem access '%s'\n", regno,
5100 				reg_type_str(env, reg->type));
5101 			return -EACCES;
5102 		}
5103 
5104 		if (t == BPF_WRITE && rdonly_mem) {
5105 			verbose(env, "R%d cannot write into %s\n",
5106 				regno, reg_type_str(env, reg->type));
5107 			return -EACCES;
5108 		}
5109 
5110 		if (t == BPF_WRITE && value_regno >= 0 &&
5111 		    is_pointer_value(env, value_regno)) {
5112 			verbose(env, "R%d leaks addr into mem\n", value_regno);
5113 			return -EACCES;
5114 		}
5115 
5116 		err = check_mem_region_access(env, regno, off, size,
5117 					      reg->mem_size, false);
5118 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5119 			mark_reg_unknown(env, regs, value_regno);
5120 	} else if (reg->type == PTR_TO_CTX) {
5121 		enum bpf_reg_type reg_type = SCALAR_VALUE;
5122 		struct btf *btf = NULL;
5123 		u32 btf_id = 0;
5124 
5125 		if (t == BPF_WRITE && value_regno >= 0 &&
5126 		    is_pointer_value(env, value_regno)) {
5127 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
5128 			return -EACCES;
5129 		}
5130 
5131 		err = check_ptr_off_reg(env, reg, regno);
5132 		if (err < 0)
5133 			return err;
5134 
5135 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5136 				       &btf_id);
5137 		if (err)
5138 			verbose_linfo(env, insn_idx, "; ");
5139 		if (!err && t == BPF_READ && value_regno >= 0) {
5140 			/* ctx access returns either a scalar, or a
5141 			 * PTR_TO_PACKET[_META,_END]. In the latter
5142 			 * case, we know the offset is zero.
5143 			 */
5144 			if (reg_type == SCALAR_VALUE) {
5145 				mark_reg_unknown(env, regs, value_regno);
5146 			} else {
5147 				mark_reg_known_zero(env, regs,
5148 						    value_regno);
5149 				if (type_may_be_null(reg_type))
5150 					regs[value_regno].id = ++env->id_gen;
5151 				/* A load of ctx field could have different
5152 				 * actual load size with the one encoded in the
5153 				 * insn. When the dst is PTR, it is for sure not
5154 				 * a sub-register.
5155 				 */
5156 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5157 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
5158 					regs[value_regno].btf = btf;
5159 					regs[value_regno].btf_id = btf_id;
5160 				}
5161 			}
5162 			regs[value_regno].type = reg_type;
5163 		}
5164 
5165 	} else if (reg->type == PTR_TO_STACK) {
5166 		/* Basic bounds checks. */
5167 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5168 		if (err)
5169 			return err;
5170 
5171 		state = func(env, reg);
5172 		err = update_stack_depth(env, state, off);
5173 		if (err)
5174 			return err;
5175 
5176 		if (t == BPF_READ)
5177 			err = check_stack_read(env, regno, off, size,
5178 					       value_regno);
5179 		else
5180 			err = check_stack_write(env, regno, off, size,
5181 						value_regno, insn_idx);
5182 	} else if (reg_is_pkt_pointer(reg)) {
5183 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5184 			verbose(env, "cannot write into packet\n");
5185 			return -EACCES;
5186 		}
5187 		if (t == BPF_WRITE && value_regno >= 0 &&
5188 		    is_pointer_value(env, value_regno)) {
5189 			verbose(env, "R%d leaks addr into packet\n",
5190 				value_regno);
5191 			return -EACCES;
5192 		}
5193 		err = check_packet_access(env, regno, off, size, false);
5194 		if (!err && t == BPF_READ && value_regno >= 0)
5195 			mark_reg_unknown(env, regs, value_regno);
5196 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
5197 		if (t == BPF_WRITE && value_regno >= 0 &&
5198 		    is_pointer_value(env, value_regno)) {
5199 			verbose(env, "R%d leaks addr into flow keys\n",
5200 				value_regno);
5201 			return -EACCES;
5202 		}
5203 
5204 		err = check_flow_keys_access(env, off, size);
5205 		if (!err && t == BPF_READ && value_regno >= 0)
5206 			mark_reg_unknown(env, regs, value_regno);
5207 	} else if (type_is_sk_pointer(reg->type)) {
5208 		if (t == BPF_WRITE) {
5209 			verbose(env, "R%d cannot write into %s\n",
5210 				regno, reg_type_str(env, reg->type));
5211 			return -EACCES;
5212 		}
5213 		err = check_sock_access(env, insn_idx, regno, off, size, t);
5214 		if (!err && value_regno >= 0)
5215 			mark_reg_unknown(env, regs, value_regno);
5216 	} else if (reg->type == PTR_TO_TP_BUFFER) {
5217 		err = check_tp_buffer_access(env, reg, regno, off, size);
5218 		if (!err && t == BPF_READ && value_regno >= 0)
5219 			mark_reg_unknown(env, regs, value_regno);
5220 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5221 		   !type_may_be_null(reg->type)) {
5222 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5223 					      value_regno);
5224 	} else if (reg->type == CONST_PTR_TO_MAP) {
5225 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5226 					      value_regno);
5227 	} else if (base_type(reg->type) == PTR_TO_BUF) {
5228 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
5229 		u32 *max_access;
5230 
5231 		if (rdonly_mem) {
5232 			if (t == BPF_WRITE) {
5233 				verbose(env, "R%d cannot write into %s\n",
5234 					regno, reg_type_str(env, reg->type));
5235 				return -EACCES;
5236 			}
5237 			max_access = &env->prog->aux->max_rdonly_access;
5238 		} else {
5239 			max_access = &env->prog->aux->max_rdwr_access;
5240 		}
5241 
5242 		err = check_buffer_access(env, reg, regno, off, size, false,
5243 					  max_access);
5244 
5245 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5246 			mark_reg_unknown(env, regs, value_regno);
5247 	} else {
5248 		verbose(env, "R%d invalid mem access '%s'\n", regno,
5249 			reg_type_str(env, reg->type));
5250 		return -EACCES;
5251 	}
5252 
5253 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5254 	    regs[value_regno].type == SCALAR_VALUE) {
5255 		/* b/h/w load zero-extends, mark upper bits as known 0 */
5256 		coerce_reg_to_size(&regs[value_regno], size);
5257 	}
5258 	return err;
5259 }
5260 
5261 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5262 {
5263 	int load_reg;
5264 	int err;
5265 
5266 	switch (insn->imm) {
5267 	case BPF_ADD:
5268 	case BPF_ADD | BPF_FETCH:
5269 	case BPF_AND:
5270 	case BPF_AND | BPF_FETCH:
5271 	case BPF_OR:
5272 	case BPF_OR | BPF_FETCH:
5273 	case BPF_XOR:
5274 	case BPF_XOR | BPF_FETCH:
5275 	case BPF_XCHG:
5276 	case BPF_CMPXCHG:
5277 		break;
5278 	default:
5279 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5280 		return -EINVAL;
5281 	}
5282 
5283 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5284 		verbose(env, "invalid atomic operand size\n");
5285 		return -EINVAL;
5286 	}
5287 
5288 	/* check src1 operand */
5289 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5290 	if (err)
5291 		return err;
5292 
5293 	/* check src2 operand */
5294 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5295 	if (err)
5296 		return err;
5297 
5298 	if (insn->imm == BPF_CMPXCHG) {
5299 		/* Check comparison of R0 with memory location */
5300 		const u32 aux_reg = BPF_REG_0;
5301 
5302 		err = check_reg_arg(env, aux_reg, SRC_OP);
5303 		if (err)
5304 			return err;
5305 
5306 		if (is_pointer_value(env, aux_reg)) {
5307 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5308 			return -EACCES;
5309 		}
5310 	}
5311 
5312 	if (is_pointer_value(env, insn->src_reg)) {
5313 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5314 		return -EACCES;
5315 	}
5316 
5317 	if (is_ctx_reg(env, insn->dst_reg) ||
5318 	    is_pkt_reg(env, insn->dst_reg) ||
5319 	    is_flow_key_reg(env, insn->dst_reg) ||
5320 	    is_sk_reg(env, insn->dst_reg)) {
5321 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5322 			insn->dst_reg,
5323 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5324 		return -EACCES;
5325 	}
5326 
5327 	if (insn->imm & BPF_FETCH) {
5328 		if (insn->imm == BPF_CMPXCHG)
5329 			load_reg = BPF_REG_0;
5330 		else
5331 			load_reg = insn->src_reg;
5332 
5333 		/* check and record load of old value */
5334 		err = check_reg_arg(env, load_reg, DST_OP);
5335 		if (err)
5336 			return err;
5337 	} else {
5338 		/* This instruction accesses a memory location but doesn't
5339 		 * actually load it into a register.
5340 		 */
5341 		load_reg = -1;
5342 	}
5343 
5344 	/* Check whether we can read the memory, with second call for fetch
5345 	 * case to simulate the register fill.
5346 	 */
5347 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5348 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5349 	if (!err && load_reg >= 0)
5350 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5351 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5352 				       true);
5353 	if (err)
5354 		return err;
5355 
5356 	/* Check whether we can write into the same memory. */
5357 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5358 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5359 	if (err)
5360 		return err;
5361 
5362 	return 0;
5363 }
5364 
5365 /* When register 'regno' is used to read the stack (either directly or through
5366  * a helper function) make sure that it's within stack boundary and, depending
5367  * on the access type, that all elements of the stack are initialized.
5368  *
5369  * 'off' includes 'regno->off', but not its dynamic part (if any).
5370  *
5371  * All registers that have been spilled on the stack in the slots within the
5372  * read offsets are marked as read.
5373  */
5374 static int check_stack_range_initialized(
5375 		struct bpf_verifier_env *env, int regno, int off,
5376 		int access_size, bool zero_size_allowed,
5377 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5378 {
5379 	struct bpf_reg_state *reg = reg_state(env, regno);
5380 	struct bpf_func_state *state = func(env, reg);
5381 	int err, min_off, max_off, i, j, slot, spi;
5382 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5383 	enum bpf_access_type bounds_check_type;
5384 	/* Some accesses can write anything into the stack, others are
5385 	 * read-only.
5386 	 */
5387 	bool clobber = false;
5388 
5389 	if (access_size == 0 && !zero_size_allowed) {
5390 		verbose(env, "invalid zero-sized read\n");
5391 		return -EACCES;
5392 	}
5393 
5394 	if (type == ACCESS_HELPER) {
5395 		/* The bounds checks for writes are more permissive than for
5396 		 * reads. However, if raw_mode is not set, we'll do extra
5397 		 * checks below.
5398 		 */
5399 		bounds_check_type = BPF_WRITE;
5400 		clobber = true;
5401 	} else {
5402 		bounds_check_type = BPF_READ;
5403 	}
5404 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5405 					       type, bounds_check_type);
5406 	if (err)
5407 		return err;
5408 
5409 
5410 	if (tnum_is_const(reg->var_off)) {
5411 		min_off = max_off = reg->var_off.value + off;
5412 	} else {
5413 		/* Variable offset is prohibited for unprivileged mode for
5414 		 * simplicity since it requires corresponding support in
5415 		 * Spectre masking for stack ALU.
5416 		 * See also retrieve_ptr_limit().
5417 		 */
5418 		if (!env->bypass_spec_v1) {
5419 			char tn_buf[48];
5420 
5421 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5422 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5423 				regno, err_extra, tn_buf);
5424 			return -EACCES;
5425 		}
5426 		/* Only initialized buffer on stack is allowed to be accessed
5427 		 * with variable offset. With uninitialized buffer it's hard to
5428 		 * guarantee that whole memory is marked as initialized on
5429 		 * helper return since specific bounds are unknown what may
5430 		 * cause uninitialized stack leaking.
5431 		 */
5432 		if (meta && meta->raw_mode)
5433 			meta = NULL;
5434 
5435 		min_off = reg->smin_value + off;
5436 		max_off = reg->smax_value + off;
5437 	}
5438 
5439 	if (meta && meta->raw_mode) {
5440 		meta->access_size = access_size;
5441 		meta->regno = regno;
5442 		return 0;
5443 	}
5444 
5445 	for (i = min_off; i < max_off + access_size; i++) {
5446 		u8 *stype;
5447 
5448 		slot = -i - 1;
5449 		spi = slot / BPF_REG_SIZE;
5450 		if (state->allocated_stack <= slot)
5451 			goto err;
5452 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5453 		if (*stype == STACK_MISC)
5454 			goto mark;
5455 		if (*stype == STACK_ZERO) {
5456 			if (clobber) {
5457 				/* helper can write anything into the stack */
5458 				*stype = STACK_MISC;
5459 			}
5460 			goto mark;
5461 		}
5462 
5463 		if (is_spilled_reg(&state->stack[spi]) &&
5464 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5465 		     env->allow_ptr_leaks)) {
5466 			if (clobber) {
5467 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5468 				for (j = 0; j < BPF_REG_SIZE; j++)
5469 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5470 			}
5471 			goto mark;
5472 		}
5473 
5474 err:
5475 		if (tnum_is_const(reg->var_off)) {
5476 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5477 				err_extra, regno, min_off, i - min_off, access_size);
5478 		} else {
5479 			char tn_buf[48];
5480 
5481 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5482 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5483 				err_extra, regno, tn_buf, i - min_off, access_size);
5484 		}
5485 		return -EACCES;
5486 mark:
5487 		/* reading any byte out of 8-byte 'spill_slot' will cause
5488 		 * the whole slot to be marked as 'read'
5489 		 */
5490 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5491 			      state->stack[spi].spilled_ptr.parent,
5492 			      REG_LIVE_READ64);
5493 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5494 		 * be sure that whether stack slot is written to or not. Hence,
5495 		 * we must still conservatively propagate reads upwards even if
5496 		 * helper may write to the entire memory range.
5497 		 */
5498 	}
5499 	return update_stack_depth(env, state, min_off);
5500 }
5501 
5502 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5503 				   int access_size, bool zero_size_allowed,
5504 				   struct bpf_call_arg_meta *meta)
5505 {
5506 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5507 	u32 *max_access;
5508 
5509 	switch (base_type(reg->type)) {
5510 	case PTR_TO_PACKET:
5511 	case PTR_TO_PACKET_META:
5512 		return check_packet_access(env, regno, reg->off, access_size,
5513 					   zero_size_allowed);
5514 	case PTR_TO_MAP_KEY:
5515 		if (meta && meta->raw_mode) {
5516 			verbose(env, "R%d cannot write into %s\n", regno,
5517 				reg_type_str(env, reg->type));
5518 			return -EACCES;
5519 		}
5520 		return check_mem_region_access(env, regno, reg->off, access_size,
5521 					       reg->map_ptr->key_size, false);
5522 	case PTR_TO_MAP_VALUE:
5523 		if (check_map_access_type(env, regno, reg->off, access_size,
5524 					  meta && meta->raw_mode ? BPF_WRITE :
5525 					  BPF_READ))
5526 			return -EACCES;
5527 		return check_map_access(env, regno, reg->off, access_size,
5528 					zero_size_allowed, ACCESS_HELPER);
5529 	case PTR_TO_MEM:
5530 		if (type_is_rdonly_mem(reg->type)) {
5531 			if (meta && meta->raw_mode) {
5532 				verbose(env, "R%d cannot write into %s\n", regno,
5533 					reg_type_str(env, reg->type));
5534 				return -EACCES;
5535 			}
5536 		}
5537 		return check_mem_region_access(env, regno, reg->off,
5538 					       access_size, reg->mem_size,
5539 					       zero_size_allowed);
5540 	case PTR_TO_BUF:
5541 		if (type_is_rdonly_mem(reg->type)) {
5542 			if (meta && meta->raw_mode) {
5543 				verbose(env, "R%d cannot write into %s\n", regno,
5544 					reg_type_str(env, reg->type));
5545 				return -EACCES;
5546 			}
5547 
5548 			max_access = &env->prog->aux->max_rdonly_access;
5549 		} else {
5550 			max_access = &env->prog->aux->max_rdwr_access;
5551 		}
5552 		return check_buffer_access(env, reg, regno, reg->off,
5553 					   access_size, zero_size_allowed,
5554 					   max_access);
5555 	case PTR_TO_STACK:
5556 		return check_stack_range_initialized(
5557 				env,
5558 				regno, reg->off, access_size,
5559 				zero_size_allowed, ACCESS_HELPER, meta);
5560 	case PTR_TO_CTX:
5561 		/* in case the function doesn't know how to access the context,
5562 		 * (because we are in a program of type SYSCALL for example), we
5563 		 * can not statically check its size.
5564 		 * Dynamically check it now.
5565 		 */
5566 		if (!env->ops->convert_ctx_access) {
5567 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5568 			int offset = access_size - 1;
5569 
5570 			/* Allow zero-byte read from PTR_TO_CTX */
5571 			if (access_size == 0)
5572 				return zero_size_allowed ? 0 : -EACCES;
5573 
5574 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5575 						atype, -1, false);
5576 		}
5577 
5578 		fallthrough;
5579 	default: /* scalar_value or invalid ptr */
5580 		/* Allow zero-byte read from NULL, regardless of pointer type */
5581 		if (zero_size_allowed && access_size == 0 &&
5582 		    register_is_null(reg))
5583 			return 0;
5584 
5585 		verbose(env, "R%d type=%s ", regno,
5586 			reg_type_str(env, reg->type));
5587 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5588 		return -EACCES;
5589 	}
5590 }
5591 
5592 static int check_mem_size_reg(struct bpf_verifier_env *env,
5593 			      struct bpf_reg_state *reg, u32 regno,
5594 			      bool zero_size_allowed,
5595 			      struct bpf_call_arg_meta *meta)
5596 {
5597 	int err;
5598 
5599 	/* This is used to refine r0 return value bounds for helpers
5600 	 * that enforce this value as an upper bound on return values.
5601 	 * See do_refine_retval_range() for helpers that can refine
5602 	 * the return value. C type of helper is u32 so we pull register
5603 	 * bound from umax_value however, if negative verifier errors
5604 	 * out. Only upper bounds can be learned because retval is an
5605 	 * int type and negative retvals are allowed.
5606 	 */
5607 	meta->msize_max_value = reg->umax_value;
5608 
5609 	/* The register is SCALAR_VALUE; the access check
5610 	 * happens using its boundaries.
5611 	 */
5612 	if (!tnum_is_const(reg->var_off))
5613 		/* For unprivileged variable accesses, disable raw
5614 		 * mode so that the program is required to
5615 		 * initialize all the memory that the helper could
5616 		 * just partially fill up.
5617 		 */
5618 		meta = NULL;
5619 
5620 	if (reg->smin_value < 0) {
5621 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5622 			regno);
5623 		return -EACCES;
5624 	}
5625 
5626 	if (reg->umin_value == 0) {
5627 		err = check_helper_mem_access(env, regno - 1, 0,
5628 					      zero_size_allowed,
5629 					      meta);
5630 		if (err)
5631 			return err;
5632 	}
5633 
5634 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5635 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5636 			regno);
5637 		return -EACCES;
5638 	}
5639 	err = check_helper_mem_access(env, regno - 1,
5640 				      reg->umax_value,
5641 				      zero_size_allowed, meta);
5642 	if (!err)
5643 		err = mark_chain_precision(env, regno);
5644 	return err;
5645 }
5646 
5647 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5648 		   u32 regno, u32 mem_size)
5649 {
5650 	bool may_be_null = type_may_be_null(reg->type);
5651 	struct bpf_reg_state saved_reg;
5652 	struct bpf_call_arg_meta meta;
5653 	int err;
5654 
5655 	if (register_is_null(reg))
5656 		return 0;
5657 
5658 	memset(&meta, 0, sizeof(meta));
5659 	/* Assuming that the register contains a value check if the memory
5660 	 * access is safe. Temporarily save and restore the register's state as
5661 	 * the conversion shouldn't be visible to a caller.
5662 	 */
5663 	if (may_be_null) {
5664 		saved_reg = *reg;
5665 		mark_ptr_not_null_reg(reg);
5666 	}
5667 
5668 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5669 	/* Check access for BPF_WRITE */
5670 	meta.raw_mode = true;
5671 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5672 
5673 	if (may_be_null)
5674 		*reg = saved_reg;
5675 
5676 	return err;
5677 }
5678 
5679 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5680 				    u32 regno)
5681 {
5682 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5683 	bool may_be_null = type_may_be_null(mem_reg->type);
5684 	struct bpf_reg_state saved_reg;
5685 	struct bpf_call_arg_meta meta;
5686 	int err;
5687 
5688 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5689 
5690 	memset(&meta, 0, sizeof(meta));
5691 
5692 	if (may_be_null) {
5693 		saved_reg = *mem_reg;
5694 		mark_ptr_not_null_reg(mem_reg);
5695 	}
5696 
5697 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5698 	/* Check access for BPF_WRITE */
5699 	meta.raw_mode = true;
5700 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5701 
5702 	if (may_be_null)
5703 		*mem_reg = saved_reg;
5704 	return err;
5705 }
5706 
5707 /* Implementation details:
5708  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5709  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5710  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5711  * Two separate bpf_obj_new will also have different reg->id.
5712  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5713  * clears reg->id after value_or_null->value transition, since the verifier only
5714  * cares about the range of access to valid map value pointer and doesn't care
5715  * about actual address of the map element.
5716  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5717  * reg->id > 0 after value_or_null->value transition. By doing so
5718  * two bpf_map_lookups will be considered two different pointers that
5719  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5720  * returned from bpf_obj_new.
5721  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5722  * dead-locks.
5723  * Since only one bpf_spin_lock is allowed the checks are simpler than
5724  * reg_is_refcounted() logic. The verifier needs to remember only
5725  * one spin_lock instead of array of acquired_refs.
5726  * cur_state->active_lock remembers which map value element or allocated
5727  * object got locked and clears it after bpf_spin_unlock.
5728  */
5729 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5730 			     bool is_lock)
5731 {
5732 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5733 	struct bpf_verifier_state *cur = env->cur_state;
5734 	bool is_const = tnum_is_const(reg->var_off);
5735 	u64 val = reg->var_off.value;
5736 	struct bpf_map *map = NULL;
5737 	struct btf *btf = NULL;
5738 	struct btf_record *rec;
5739 
5740 	if (!is_const) {
5741 		verbose(env,
5742 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5743 			regno);
5744 		return -EINVAL;
5745 	}
5746 	if (reg->type == PTR_TO_MAP_VALUE) {
5747 		map = reg->map_ptr;
5748 		if (!map->btf) {
5749 			verbose(env,
5750 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5751 				map->name);
5752 			return -EINVAL;
5753 		}
5754 	} else {
5755 		btf = reg->btf;
5756 	}
5757 
5758 	rec = reg_btf_record(reg);
5759 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5760 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5761 			map ? map->name : "kptr");
5762 		return -EINVAL;
5763 	}
5764 	if (rec->spin_lock_off != val + reg->off) {
5765 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5766 			val + reg->off, rec->spin_lock_off);
5767 		return -EINVAL;
5768 	}
5769 	if (is_lock) {
5770 		if (cur->active_lock.ptr) {
5771 			verbose(env,
5772 				"Locking two bpf_spin_locks are not allowed\n");
5773 			return -EINVAL;
5774 		}
5775 		if (map)
5776 			cur->active_lock.ptr = map;
5777 		else
5778 			cur->active_lock.ptr = btf;
5779 		cur->active_lock.id = reg->id;
5780 	} else {
5781 		struct bpf_func_state *fstate = cur_func(env);
5782 		void *ptr;
5783 		int i;
5784 
5785 		if (map)
5786 			ptr = map;
5787 		else
5788 			ptr = btf;
5789 
5790 		if (!cur->active_lock.ptr) {
5791 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5792 			return -EINVAL;
5793 		}
5794 		if (cur->active_lock.ptr != ptr ||
5795 		    cur->active_lock.id != reg->id) {
5796 			verbose(env, "bpf_spin_unlock of different lock\n");
5797 			return -EINVAL;
5798 		}
5799 		cur->active_lock.ptr = NULL;
5800 		cur->active_lock.id = 0;
5801 
5802 		for (i = fstate->acquired_refs - 1; i >= 0; i--) {
5803 			int err;
5804 
5805 			/* Complain on error because this reference state cannot
5806 			 * be freed before this point, as bpf_spin_lock critical
5807 			 * section does not allow functions that release the
5808 			 * allocated object immediately.
5809 			 */
5810 			if (!fstate->refs[i].release_on_unlock)
5811 				continue;
5812 			err = release_reference(env, fstate->refs[i].id);
5813 			if (err) {
5814 				verbose(env, "failed to release release_on_unlock reference");
5815 				return err;
5816 			}
5817 		}
5818 	}
5819 	return 0;
5820 }
5821 
5822 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5823 			      struct bpf_call_arg_meta *meta)
5824 {
5825 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5826 	bool is_const = tnum_is_const(reg->var_off);
5827 	struct bpf_map *map = reg->map_ptr;
5828 	u64 val = reg->var_off.value;
5829 
5830 	if (!is_const) {
5831 		verbose(env,
5832 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5833 			regno);
5834 		return -EINVAL;
5835 	}
5836 	if (!map->btf) {
5837 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5838 			map->name);
5839 		return -EINVAL;
5840 	}
5841 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
5842 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5843 		return -EINVAL;
5844 	}
5845 	if (map->record->timer_off != val + reg->off) {
5846 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5847 			val + reg->off, map->record->timer_off);
5848 		return -EINVAL;
5849 	}
5850 	if (meta->map_ptr) {
5851 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5852 		return -EFAULT;
5853 	}
5854 	meta->map_uid = reg->map_uid;
5855 	meta->map_ptr = map;
5856 	return 0;
5857 }
5858 
5859 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5860 			     struct bpf_call_arg_meta *meta)
5861 {
5862 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5863 	struct bpf_map *map_ptr = reg->map_ptr;
5864 	struct btf_field *kptr_field;
5865 	u32 kptr_off;
5866 
5867 	if (!tnum_is_const(reg->var_off)) {
5868 		verbose(env,
5869 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5870 			regno);
5871 		return -EINVAL;
5872 	}
5873 	if (!map_ptr->btf) {
5874 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5875 			map_ptr->name);
5876 		return -EINVAL;
5877 	}
5878 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5879 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5880 		return -EINVAL;
5881 	}
5882 
5883 	meta->map_ptr = map_ptr;
5884 	kptr_off = reg->off + reg->var_off.value;
5885 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5886 	if (!kptr_field) {
5887 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5888 		return -EACCES;
5889 	}
5890 	if (kptr_field->type != BPF_KPTR_REF) {
5891 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5892 		return -EACCES;
5893 	}
5894 	meta->kptr_field = kptr_field;
5895 	return 0;
5896 }
5897 
5898 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
5899  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
5900  *
5901  * In both cases we deal with the first 8 bytes, but need to mark the next 8
5902  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
5903  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
5904  *
5905  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
5906  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
5907  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
5908  * mutate the view of the dynptr and also possibly destroy it. In the latter
5909  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
5910  * memory that dynptr points to.
5911  *
5912  * The verifier will keep track both levels of mutation (bpf_dynptr's in
5913  * reg->type and the memory's in reg->dynptr.type), but there is no support for
5914  * readonly dynptr view yet, hence only the first case is tracked and checked.
5915  *
5916  * This is consistent with how C applies the const modifier to a struct object,
5917  * where the pointer itself inside bpf_dynptr becomes const but not what it
5918  * points to.
5919  *
5920  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
5921  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
5922  */
5923 int process_dynptr_func(struct bpf_verifier_env *env, int regno,
5924 			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
5925 {
5926 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5927 
5928 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
5929 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
5930 	 */
5931 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
5932 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
5933 		return -EFAULT;
5934 	}
5935 	/* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
5936 	 * check_func_arg_reg_off's logic. We only need to check offset
5937 	 * alignment for PTR_TO_STACK.
5938 	 */
5939 	if (reg->type == PTR_TO_STACK && (reg->off % BPF_REG_SIZE)) {
5940 		verbose(env, "cannot pass in dynptr at an offset=%d\n", reg->off);
5941 		return -EINVAL;
5942 	}
5943 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
5944 	 *		 constructing a mutable bpf_dynptr object.
5945 	 *
5946 	 *		 Currently, this is only possible with PTR_TO_STACK
5947 	 *		 pointing to a region of at least 16 bytes which doesn't
5948 	 *		 contain an existing bpf_dynptr.
5949 	 *
5950 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
5951 	 *		 mutated or destroyed. However, the memory it points to
5952 	 *		 may be mutated.
5953 	 *
5954 	 *  None       - Points to a initialized dynptr that can be mutated and
5955 	 *		 destroyed, including mutation of the memory it points
5956 	 *		 to.
5957 	 */
5958 	if (arg_type & MEM_UNINIT) {
5959 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
5960 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
5961 			return -EINVAL;
5962 		}
5963 
5964 		/* We only support one dynptr being uninitialized at the moment,
5965 		 * which is sufficient for the helper functions we have right now.
5966 		 */
5967 		if (meta->uninit_dynptr_regno) {
5968 			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
5969 			return -EFAULT;
5970 		}
5971 
5972 		meta->uninit_dynptr_regno = regno;
5973 	} else /* MEM_RDONLY and None case from above */ {
5974 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
5975 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
5976 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
5977 			return -EINVAL;
5978 		}
5979 
5980 		if (!is_dynptr_reg_valid_init(env, reg)) {
5981 			verbose(env,
5982 				"Expected an initialized dynptr as arg #%d\n",
5983 				regno);
5984 			return -EINVAL;
5985 		}
5986 
5987 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
5988 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
5989 			const char *err_extra = "";
5990 
5991 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
5992 			case DYNPTR_TYPE_LOCAL:
5993 				err_extra = "local";
5994 				break;
5995 			case DYNPTR_TYPE_RINGBUF:
5996 				err_extra = "ringbuf";
5997 				break;
5998 			default:
5999 				err_extra = "<unknown>";
6000 				break;
6001 			}
6002 			verbose(env,
6003 				"Expected a dynptr of type %s as arg #%d\n",
6004 				err_extra, regno);
6005 			return -EINVAL;
6006 		}
6007 	}
6008 	return 0;
6009 }
6010 
6011 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6012 {
6013 	return type == ARG_CONST_SIZE ||
6014 	       type == ARG_CONST_SIZE_OR_ZERO;
6015 }
6016 
6017 static bool arg_type_is_release(enum bpf_arg_type type)
6018 {
6019 	return type & OBJ_RELEASE;
6020 }
6021 
6022 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6023 {
6024 	return base_type(type) == ARG_PTR_TO_DYNPTR;
6025 }
6026 
6027 static int int_ptr_type_to_size(enum bpf_arg_type type)
6028 {
6029 	if (type == ARG_PTR_TO_INT)
6030 		return sizeof(u32);
6031 	else if (type == ARG_PTR_TO_LONG)
6032 		return sizeof(u64);
6033 
6034 	return -EINVAL;
6035 }
6036 
6037 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6038 				 const struct bpf_call_arg_meta *meta,
6039 				 enum bpf_arg_type *arg_type)
6040 {
6041 	if (!meta->map_ptr) {
6042 		/* kernel subsystem misconfigured verifier */
6043 		verbose(env, "invalid map_ptr to access map->type\n");
6044 		return -EACCES;
6045 	}
6046 
6047 	switch (meta->map_ptr->map_type) {
6048 	case BPF_MAP_TYPE_SOCKMAP:
6049 	case BPF_MAP_TYPE_SOCKHASH:
6050 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6051 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6052 		} else {
6053 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
6054 			return -EINVAL;
6055 		}
6056 		break;
6057 	case BPF_MAP_TYPE_BLOOM_FILTER:
6058 		if (meta->func_id == BPF_FUNC_map_peek_elem)
6059 			*arg_type = ARG_PTR_TO_MAP_VALUE;
6060 		break;
6061 	default:
6062 		break;
6063 	}
6064 	return 0;
6065 }
6066 
6067 struct bpf_reg_types {
6068 	const enum bpf_reg_type types[10];
6069 	u32 *btf_id;
6070 };
6071 
6072 static const struct bpf_reg_types sock_types = {
6073 	.types = {
6074 		PTR_TO_SOCK_COMMON,
6075 		PTR_TO_SOCKET,
6076 		PTR_TO_TCP_SOCK,
6077 		PTR_TO_XDP_SOCK,
6078 	},
6079 };
6080 
6081 #ifdef CONFIG_NET
6082 static const struct bpf_reg_types btf_id_sock_common_types = {
6083 	.types = {
6084 		PTR_TO_SOCK_COMMON,
6085 		PTR_TO_SOCKET,
6086 		PTR_TO_TCP_SOCK,
6087 		PTR_TO_XDP_SOCK,
6088 		PTR_TO_BTF_ID,
6089 		PTR_TO_BTF_ID | PTR_TRUSTED,
6090 	},
6091 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6092 };
6093 #endif
6094 
6095 static const struct bpf_reg_types mem_types = {
6096 	.types = {
6097 		PTR_TO_STACK,
6098 		PTR_TO_PACKET,
6099 		PTR_TO_PACKET_META,
6100 		PTR_TO_MAP_KEY,
6101 		PTR_TO_MAP_VALUE,
6102 		PTR_TO_MEM,
6103 		PTR_TO_MEM | MEM_RINGBUF,
6104 		PTR_TO_BUF,
6105 	},
6106 };
6107 
6108 static const struct bpf_reg_types int_ptr_types = {
6109 	.types = {
6110 		PTR_TO_STACK,
6111 		PTR_TO_PACKET,
6112 		PTR_TO_PACKET_META,
6113 		PTR_TO_MAP_KEY,
6114 		PTR_TO_MAP_VALUE,
6115 	},
6116 };
6117 
6118 static const struct bpf_reg_types spin_lock_types = {
6119 	.types = {
6120 		PTR_TO_MAP_VALUE,
6121 		PTR_TO_BTF_ID | MEM_ALLOC,
6122 	}
6123 };
6124 
6125 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6126 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6127 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6128 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6129 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6130 static const struct bpf_reg_types btf_ptr_types = {
6131 	.types = {
6132 		PTR_TO_BTF_ID,
6133 		PTR_TO_BTF_ID | PTR_TRUSTED,
6134 		PTR_TO_BTF_ID | MEM_RCU,
6135 	},
6136 };
6137 static const struct bpf_reg_types percpu_btf_ptr_types = {
6138 	.types = {
6139 		PTR_TO_BTF_ID | MEM_PERCPU,
6140 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6141 	}
6142 };
6143 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6144 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6145 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6146 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6147 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6148 static const struct bpf_reg_types dynptr_types = {
6149 	.types = {
6150 		PTR_TO_STACK,
6151 		CONST_PTR_TO_DYNPTR,
6152 	}
6153 };
6154 
6155 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6156 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
6157 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
6158 	[ARG_CONST_SIZE]		= &scalar_types,
6159 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
6160 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
6161 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
6162 	[ARG_PTR_TO_CTX]		= &context_types,
6163 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
6164 #ifdef CONFIG_NET
6165 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
6166 #endif
6167 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
6168 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
6169 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
6170 	[ARG_PTR_TO_MEM]		= &mem_types,
6171 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
6172 	[ARG_PTR_TO_INT]		= &int_ptr_types,
6173 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
6174 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
6175 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
6176 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
6177 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
6178 	[ARG_PTR_TO_TIMER]		= &timer_types,
6179 	[ARG_PTR_TO_KPTR]		= &kptr_types,
6180 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
6181 };
6182 
6183 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6184 			  enum bpf_arg_type arg_type,
6185 			  const u32 *arg_btf_id,
6186 			  struct bpf_call_arg_meta *meta)
6187 {
6188 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6189 	enum bpf_reg_type expected, type = reg->type;
6190 	const struct bpf_reg_types *compatible;
6191 	int i, j;
6192 
6193 	compatible = compatible_reg_types[base_type(arg_type)];
6194 	if (!compatible) {
6195 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6196 		return -EFAULT;
6197 	}
6198 
6199 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6200 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6201 	 *
6202 	 * Same for MAYBE_NULL:
6203 	 *
6204 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6205 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6206 	 *
6207 	 * Therefore we fold these flags depending on the arg_type before comparison.
6208 	 */
6209 	if (arg_type & MEM_RDONLY)
6210 		type &= ~MEM_RDONLY;
6211 	if (arg_type & PTR_MAYBE_NULL)
6212 		type &= ~PTR_MAYBE_NULL;
6213 
6214 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6215 		expected = compatible->types[i];
6216 		if (expected == NOT_INIT)
6217 			break;
6218 
6219 		if (type == expected)
6220 			goto found;
6221 	}
6222 
6223 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6224 	for (j = 0; j + 1 < i; j++)
6225 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6226 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6227 	return -EACCES;
6228 
6229 found:
6230 	if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
6231 		/* For bpf_sk_release, it needs to match against first member
6232 		 * 'struct sock_common', hence make an exception for it. This
6233 		 * allows bpf_sk_release to work for multiple socket types.
6234 		 */
6235 		bool strict_type_match = arg_type_is_release(arg_type) &&
6236 					 meta->func_id != BPF_FUNC_sk_release;
6237 
6238 		if (!arg_btf_id) {
6239 			if (!compatible->btf_id) {
6240 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6241 				return -EFAULT;
6242 			}
6243 			arg_btf_id = compatible->btf_id;
6244 		}
6245 
6246 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
6247 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6248 				return -EACCES;
6249 		} else {
6250 			if (arg_btf_id == BPF_PTR_POISON) {
6251 				verbose(env, "verifier internal error:");
6252 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6253 					regno);
6254 				return -EACCES;
6255 			}
6256 
6257 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6258 						  btf_vmlinux, *arg_btf_id,
6259 						  strict_type_match)) {
6260 				verbose(env, "R%d is of type %s but %s is expected\n",
6261 					regno, kernel_type_name(reg->btf, reg->btf_id),
6262 					kernel_type_name(btf_vmlinux, *arg_btf_id));
6263 				return -EACCES;
6264 			}
6265 		}
6266 	} else if (type_is_alloc(reg->type)) {
6267 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6268 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6269 			return -EFAULT;
6270 		}
6271 	}
6272 
6273 	return 0;
6274 }
6275 
6276 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6277 			   const struct bpf_reg_state *reg, int regno,
6278 			   enum bpf_arg_type arg_type)
6279 {
6280 	u32 type = reg->type;
6281 
6282 	/* When referenced register is passed to release function, its fixed
6283 	 * offset must be 0.
6284 	 *
6285 	 * We will check arg_type_is_release reg has ref_obj_id when storing
6286 	 * meta->release_regno.
6287 	 */
6288 	if (arg_type_is_release(arg_type)) {
6289 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6290 		 * may not directly point to the object being released, but to
6291 		 * dynptr pointing to such object, which might be at some offset
6292 		 * on the stack. In that case, we simply to fallback to the
6293 		 * default handling.
6294 		 */
6295 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6296 			return 0;
6297 		/* Doing check_ptr_off_reg check for the offset will catch this
6298 		 * because fixed_off_ok is false, but checking here allows us
6299 		 * to give the user a better error message.
6300 		 */
6301 		if (reg->off) {
6302 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6303 				regno);
6304 			return -EINVAL;
6305 		}
6306 		return __check_ptr_off_reg(env, reg, regno, false);
6307 	}
6308 
6309 	switch (type) {
6310 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
6311 	case PTR_TO_STACK:
6312 	case PTR_TO_PACKET:
6313 	case PTR_TO_PACKET_META:
6314 	case PTR_TO_MAP_KEY:
6315 	case PTR_TO_MAP_VALUE:
6316 	case PTR_TO_MEM:
6317 	case PTR_TO_MEM | MEM_RDONLY:
6318 	case PTR_TO_MEM | MEM_RINGBUF:
6319 	case PTR_TO_BUF:
6320 	case PTR_TO_BUF | MEM_RDONLY:
6321 	case SCALAR_VALUE:
6322 		return 0;
6323 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6324 	 * fixed offset.
6325 	 */
6326 	case PTR_TO_BTF_ID:
6327 	case PTR_TO_BTF_ID | MEM_ALLOC:
6328 	case PTR_TO_BTF_ID | PTR_TRUSTED:
6329 	case PTR_TO_BTF_ID | MEM_RCU:
6330 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6331 		/* When referenced PTR_TO_BTF_ID is passed to release function,
6332 		 * its fixed offset must be 0. In the other cases, fixed offset
6333 		 * can be non-zero. This was already checked above. So pass
6334 		 * fixed_off_ok as true to allow fixed offset for all other
6335 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6336 		 * still need to do checks instead of returning.
6337 		 */
6338 		return __check_ptr_off_reg(env, reg, regno, true);
6339 	default:
6340 		return __check_ptr_off_reg(env, reg, regno, false);
6341 	}
6342 }
6343 
6344 static u32 dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6345 {
6346 	struct bpf_func_state *state = func(env, reg);
6347 	int spi;
6348 
6349 	if (reg->type == CONST_PTR_TO_DYNPTR)
6350 		return reg->ref_obj_id;
6351 
6352 	spi = get_spi(reg->off);
6353 	return state->stack[spi].spilled_ptr.ref_obj_id;
6354 }
6355 
6356 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6357 			  struct bpf_call_arg_meta *meta,
6358 			  const struct bpf_func_proto *fn)
6359 {
6360 	u32 regno = BPF_REG_1 + arg;
6361 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6362 	enum bpf_arg_type arg_type = fn->arg_type[arg];
6363 	enum bpf_reg_type type = reg->type;
6364 	u32 *arg_btf_id = NULL;
6365 	int err = 0;
6366 
6367 	if (arg_type == ARG_DONTCARE)
6368 		return 0;
6369 
6370 	err = check_reg_arg(env, regno, SRC_OP);
6371 	if (err)
6372 		return err;
6373 
6374 	if (arg_type == ARG_ANYTHING) {
6375 		if (is_pointer_value(env, regno)) {
6376 			verbose(env, "R%d leaks addr into helper function\n",
6377 				regno);
6378 			return -EACCES;
6379 		}
6380 		return 0;
6381 	}
6382 
6383 	if (type_is_pkt_pointer(type) &&
6384 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6385 		verbose(env, "helper access to the packet is not allowed\n");
6386 		return -EACCES;
6387 	}
6388 
6389 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6390 		err = resolve_map_arg_type(env, meta, &arg_type);
6391 		if (err)
6392 			return err;
6393 	}
6394 
6395 	if (register_is_null(reg) && type_may_be_null(arg_type))
6396 		/* A NULL register has a SCALAR_VALUE type, so skip
6397 		 * type checking.
6398 		 */
6399 		goto skip_type_check;
6400 
6401 	/* arg_btf_id and arg_size are in a union. */
6402 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6403 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6404 		arg_btf_id = fn->arg_btf_id[arg];
6405 
6406 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6407 	if (err)
6408 		return err;
6409 
6410 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
6411 	if (err)
6412 		return err;
6413 
6414 skip_type_check:
6415 	if (arg_type_is_release(arg_type)) {
6416 		if (arg_type_is_dynptr(arg_type)) {
6417 			struct bpf_func_state *state = func(env, reg);
6418 			int spi;
6419 
6420 			/* Only dynptr created on stack can be released, thus
6421 			 * the get_spi and stack state checks for spilled_ptr
6422 			 * should only be done before process_dynptr_func for
6423 			 * PTR_TO_STACK.
6424 			 */
6425 			if (reg->type == PTR_TO_STACK) {
6426 				spi = get_spi(reg->off);
6427 				if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6428 				    !state->stack[spi].spilled_ptr.ref_obj_id) {
6429 					verbose(env, "arg %d is an unacquired reference\n", regno);
6430 					return -EINVAL;
6431 				}
6432 			} else {
6433 				verbose(env, "cannot release unowned const bpf_dynptr\n");
6434 				return -EINVAL;
6435 			}
6436 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
6437 			verbose(env, "R%d must be referenced when passed to release function\n",
6438 				regno);
6439 			return -EINVAL;
6440 		}
6441 		if (meta->release_regno) {
6442 			verbose(env, "verifier internal error: more than one release argument\n");
6443 			return -EFAULT;
6444 		}
6445 		meta->release_regno = regno;
6446 	}
6447 
6448 	if (reg->ref_obj_id) {
6449 		if (meta->ref_obj_id) {
6450 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6451 				regno, reg->ref_obj_id,
6452 				meta->ref_obj_id);
6453 			return -EFAULT;
6454 		}
6455 		meta->ref_obj_id = reg->ref_obj_id;
6456 	}
6457 
6458 	switch (base_type(arg_type)) {
6459 	case ARG_CONST_MAP_PTR:
6460 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6461 		if (meta->map_ptr) {
6462 			/* Use map_uid (which is unique id of inner map) to reject:
6463 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6464 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6465 			 * if (inner_map1 && inner_map2) {
6466 			 *     timer = bpf_map_lookup_elem(inner_map1);
6467 			 *     if (timer)
6468 			 *         // mismatch would have been allowed
6469 			 *         bpf_timer_init(timer, inner_map2);
6470 			 * }
6471 			 *
6472 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6473 			 */
6474 			if (meta->map_ptr != reg->map_ptr ||
6475 			    meta->map_uid != reg->map_uid) {
6476 				verbose(env,
6477 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6478 					meta->map_uid, reg->map_uid);
6479 				return -EINVAL;
6480 			}
6481 		}
6482 		meta->map_ptr = reg->map_ptr;
6483 		meta->map_uid = reg->map_uid;
6484 		break;
6485 	case ARG_PTR_TO_MAP_KEY:
6486 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6487 		 * check that [key, key + map->key_size) are within
6488 		 * stack limits and initialized
6489 		 */
6490 		if (!meta->map_ptr) {
6491 			/* in function declaration map_ptr must come before
6492 			 * map_key, so that it's verified and known before
6493 			 * we have to check map_key here. Otherwise it means
6494 			 * that kernel subsystem misconfigured verifier
6495 			 */
6496 			verbose(env, "invalid map_ptr to access map->key\n");
6497 			return -EACCES;
6498 		}
6499 		err = check_helper_mem_access(env, regno,
6500 					      meta->map_ptr->key_size, false,
6501 					      NULL);
6502 		break;
6503 	case ARG_PTR_TO_MAP_VALUE:
6504 		if (type_may_be_null(arg_type) && register_is_null(reg))
6505 			return 0;
6506 
6507 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6508 		 * check [value, value + map->value_size) validity
6509 		 */
6510 		if (!meta->map_ptr) {
6511 			/* kernel subsystem misconfigured verifier */
6512 			verbose(env, "invalid map_ptr to access map->value\n");
6513 			return -EACCES;
6514 		}
6515 		meta->raw_mode = arg_type & MEM_UNINIT;
6516 		err = check_helper_mem_access(env, regno,
6517 					      meta->map_ptr->value_size, false,
6518 					      meta);
6519 		break;
6520 	case ARG_PTR_TO_PERCPU_BTF_ID:
6521 		if (!reg->btf_id) {
6522 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6523 			return -EACCES;
6524 		}
6525 		meta->ret_btf = reg->btf;
6526 		meta->ret_btf_id = reg->btf_id;
6527 		break;
6528 	case ARG_PTR_TO_SPIN_LOCK:
6529 		if (meta->func_id == BPF_FUNC_spin_lock) {
6530 			err = process_spin_lock(env, regno, true);
6531 			if (err)
6532 				return err;
6533 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6534 			err = process_spin_lock(env, regno, false);
6535 			if (err)
6536 				return err;
6537 		} else {
6538 			verbose(env, "verifier internal error\n");
6539 			return -EFAULT;
6540 		}
6541 		break;
6542 	case ARG_PTR_TO_TIMER:
6543 		err = process_timer_func(env, regno, meta);
6544 		if (err)
6545 			return err;
6546 		break;
6547 	case ARG_PTR_TO_FUNC:
6548 		meta->subprogno = reg->subprogno;
6549 		break;
6550 	case ARG_PTR_TO_MEM:
6551 		/* The access to this pointer is only checked when we hit the
6552 		 * next is_mem_size argument below.
6553 		 */
6554 		meta->raw_mode = arg_type & MEM_UNINIT;
6555 		if (arg_type & MEM_FIXED_SIZE) {
6556 			err = check_helper_mem_access(env, regno,
6557 						      fn->arg_size[arg], false,
6558 						      meta);
6559 		}
6560 		break;
6561 	case ARG_CONST_SIZE:
6562 		err = check_mem_size_reg(env, reg, regno, false, meta);
6563 		break;
6564 	case ARG_CONST_SIZE_OR_ZERO:
6565 		err = check_mem_size_reg(env, reg, regno, true, meta);
6566 		break;
6567 	case ARG_PTR_TO_DYNPTR:
6568 		err = process_dynptr_func(env, regno, arg_type, meta);
6569 		if (err)
6570 			return err;
6571 		break;
6572 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6573 		if (!tnum_is_const(reg->var_off)) {
6574 			verbose(env, "R%d is not a known constant'\n",
6575 				regno);
6576 			return -EACCES;
6577 		}
6578 		meta->mem_size = reg->var_off.value;
6579 		err = mark_chain_precision(env, regno);
6580 		if (err)
6581 			return err;
6582 		break;
6583 	case ARG_PTR_TO_INT:
6584 	case ARG_PTR_TO_LONG:
6585 	{
6586 		int size = int_ptr_type_to_size(arg_type);
6587 
6588 		err = check_helper_mem_access(env, regno, size, false, meta);
6589 		if (err)
6590 			return err;
6591 		err = check_ptr_alignment(env, reg, 0, size, true);
6592 		break;
6593 	}
6594 	case ARG_PTR_TO_CONST_STR:
6595 	{
6596 		struct bpf_map *map = reg->map_ptr;
6597 		int map_off;
6598 		u64 map_addr;
6599 		char *str_ptr;
6600 
6601 		if (!bpf_map_is_rdonly(map)) {
6602 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6603 			return -EACCES;
6604 		}
6605 
6606 		if (!tnum_is_const(reg->var_off)) {
6607 			verbose(env, "R%d is not a constant address'\n", regno);
6608 			return -EACCES;
6609 		}
6610 
6611 		if (!map->ops->map_direct_value_addr) {
6612 			verbose(env, "no direct value access support for this map type\n");
6613 			return -EACCES;
6614 		}
6615 
6616 		err = check_map_access(env, regno, reg->off,
6617 				       map->value_size - reg->off, false,
6618 				       ACCESS_HELPER);
6619 		if (err)
6620 			return err;
6621 
6622 		map_off = reg->off + reg->var_off.value;
6623 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6624 		if (err) {
6625 			verbose(env, "direct value access on string failed\n");
6626 			return err;
6627 		}
6628 
6629 		str_ptr = (char *)(long)(map_addr);
6630 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6631 			verbose(env, "string is not zero-terminated\n");
6632 			return -EINVAL;
6633 		}
6634 		break;
6635 	}
6636 	case ARG_PTR_TO_KPTR:
6637 		err = process_kptr_func(env, regno, meta);
6638 		if (err)
6639 			return err;
6640 		break;
6641 	}
6642 
6643 	return err;
6644 }
6645 
6646 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6647 {
6648 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6649 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6650 
6651 	if (func_id != BPF_FUNC_map_update_elem)
6652 		return false;
6653 
6654 	/* It's not possible to get access to a locked struct sock in these
6655 	 * contexts, so updating is safe.
6656 	 */
6657 	switch (type) {
6658 	case BPF_PROG_TYPE_TRACING:
6659 		if (eatype == BPF_TRACE_ITER)
6660 			return true;
6661 		break;
6662 	case BPF_PROG_TYPE_SOCKET_FILTER:
6663 	case BPF_PROG_TYPE_SCHED_CLS:
6664 	case BPF_PROG_TYPE_SCHED_ACT:
6665 	case BPF_PROG_TYPE_XDP:
6666 	case BPF_PROG_TYPE_SK_REUSEPORT:
6667 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6668 	case BPF_PROG_TYPE_SK_LOOKUP:
6669 		return true;
6670 	default:
6671 		break;
6672 	}
6673 
6674 	verbose(env, "cannot update sockmap in this context\n");
6675 	return false;
6676 }
6677 
6678 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6679 {
6680 	return env->prog->jit_requested &&
6681 	       bpf_jit_supports_subprog_tailcalls();
6682 }
6683 
6684 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6685 					struct bpf_map *map, int func_id)
6686 {
6687 	if (!map)
6688 		return 0;
6689 
6690 	/* We need a two way check, first is from map perspective ... */
6691 	switch (map->map_type) {
6692 	case BPF_MAP_TYPE_PROG_ARRAY:
6693 		if (func_id != BPF_FUNC_tail_call)
6694 			goto error;
6695 		break;
6696 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6697 		if (func_id != BPF_FUNC_perf_event_read &&
6698 		    func_id != BPF_FUNC_perf_event_output &&
6699 		    func_id != BPF_FUNC_skb_output &&
6700 		    func_id != BPF_FUNC_perf_event_read_value &&
6701 		    func_id != BPF_FUNC_xdp_output)
6702 			goto error;
6703 		break;
6704 	case BPF_MAP_TYPE_RINGBUF:
6705 		if (func_id != BPF_FUNC_ringbuf_output &&
6706 		    func_id != BPF_FUNC_ringbuf_reserve &&
6707 		    func_id != BPF_FUNC_ringbuf_query &&
6708 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6709 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6710 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6711 			goto error;
6712 		break;
6713 	case BPF_MAP_TYPE_USER_RINGBUF:
6714 		if (func_id != BPF_FUNC_user_ringbuf_drain)
6715 			goto error;
6716 		break;
6717 	case BPF_MAP_TYPE_STACK_TRACE:
6718 		if (func_id != BPF_FUNC_get_stackid)
6719 			goto error;
6720 		break;
6721 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6722 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6723 		    func_id != BPF_FUNC_current_task_under_cgroup)
6724 			goto error;
6725 		break;
6726 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6727 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6728 		if (func_id != BPF_FUNC_get_local_storage)
6729 			goto error;
6730 		break;
6731 	case BPF_MAP_TYPE_DEVMAP:
6732 	case BPF_MAP_TYPE_DEVMAP_HASH:
6733 		if (func_id != BPF_FUNC_redirect_map &&
6734 		    func_id != BPF_FUNC_map_lookup_elem)
6735 			goto error;
6736 		break;
6737 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6738 	 * appear.
6739 	 */
6740 	case BPF_MAP_TYPE_CPUMAP:
6741 		if (func_id != BPF_FUNC_redirect_map)
6742 			goto error;
6743 		break;
6744 	case BPF_MAP_TYPE_XSKMAP:
6745 		if (func_id != BPF_FUNC_redirect_map &&
6746 		    func_id != BPF_FUNC_map_lookup_elem)
6747 			goto error;
6748 		break;
6749 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6750 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6751 		if (func_id != BPF_FUNC_map_lookup_elem)
6752 			goto error;
6753 		break;
6754 	case BPF_MAP_TYPE_SOCKMAP:
6755 		if (func_id != BPF_FUNC_sk_redirect_map &&
6756 		    func_id != BPF_FUNC_sock_map_update &&
6757 		    func_id != BPF_FUNC_map_delete_elem &&
6758 		    func_id != BPF_FUNC_msg_redirect_map &&
6759 		    func_id != BPF_FUNC_sk_select_reuseport &&
6760 		    func_id != BPF_FUNC_map_lookup_elem &&
6761 		    !may_update_sockmap(env, func_id))
6762 			goto error;
6763 		break;
6764 	case BPF_MAP_TYPE_SOCKHASH:
6765 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6766 		    func_id != BPF_FUNC_sock_hash_update &&
6767 		    func_id != BPF_FUNC_map_delete_elem &&
6768 		    func_id != BPF_FUNC_msg_redirect_hash &&
6769 		    func_id != BPF_FUNC_sk_select_reuseport &&
6770 		    func_id != BPF_FUNC_map_lookup_elem &&
6771 		    !may_update_sockmap(env, func_id))
6772 			goto error;
6773 		break;
6774 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6775 		if (func_id != BPF_FUNC_sk_select_reuseport)
6776 			goto error;
6777 		break;
6778 	case BPF_MAP_TYPE_QUEUE:
6779 	case BPF_MAP_TYPE_STACK:
6780 		if (func_id != BPF_FUNC_map_peek_elem &&
6781 		    func_id != BPF_FUNC_map_pop_elem &&
6782 		    func_id != BPF_FUNC_map_push_elem)
6783 			goto error;
6784 		break;
6785 	case BPF_MAP_TYPE_SK_STORAGE:
6786 		if (func_id != BPF_FUNC_sk_storage_get &&
6787 		    func_id != BPF_FUNC_sk_storage_delete)
6788 			goto error;
6789 		break;
6790 	case BPF_MAP_TYPE_INODE_STORAGE:
6791 		if (func_id != BPF_FUNC_inode_storage_get &&
6792 		    func_id != BPF_FUNC_inode_storage_delete)
6793 			goto error;
6794 		break;
6795 	case BPF_MAP_TYPE_TASK_STORAGE:
6796 		if (func_id != BPF_FUNC_task_storage_get &&
6797 		    func_id != BPF_FUNC_task_storage_delete)
6798 			goto error;
6799 		break;
6800 	case BPF_MAP_TYPE_CGRP_STORAGE:
6801 		if (func_id != BPF_FUNC_cgrp_storage_get &&
6802 		    func_id != BPF_FUNC_cgrp_storage_delete)
6803 			goto error;
6804 		break;
6805 	case BPF_MAP_TYPE_BLOOM_FILTER:
6806 		if (func_id != BPF_FUNC_map_peek_elem &&
6807 		    func_id != BPF_FUNC_map_push_elem)
6808 			goto error;
6809 		break;
6810 	default:
6811 		break;
6812 	}
6813 
6814 	/* ... and second from the function itself. */
6815 	switch (func_id) {
6816 	case BPF_FUNC_tail_call:
6817 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6818 			goto error;
6819 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6820 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6821 			return -EINVAL;
6822 		}
6823 		break;
6824 	case BPF_FUNC_perf_event_read:
6825 	case BPF_FUNC_perf_event_output:
6826 	case BPF_FUNC_perf_event_read_value:
6827 	case BPF_FUNC_skb_output:
6828 	case BPF_FUNC_xdp_output:
6829 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6830 			goto error;
6831 		break;
6832 	case BPF_FUNC_ringbuf_output:
6833 	case BPF_FUNC_ringbuf_reserve:
6834 	case BPF_FUNC_ringbuf_query:
6835 	case BPF_FUNC_ringbuf_reserve_dynptr:
6836 	case BPF_FUNC_ringbuf_submit_dynptr:
6837 	case BPF_FUNC_ringbuf_discard_dynptr:
6838 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6839 			goto error;
6840 		break;
6841 	case BPF_FUNC_user_ringbuf_drain:
6842 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6843 			goto error;
6844 		break;
6845 	case BPF_FUNC_get_stackid:
6846 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6847 			goto error;
6848 		break;
6849 	case BPF_FUNC_current_task_under_cgroup:
6850 	case BPF_FUNC_skb_under_cgroup:
6851 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6852 			goto error;
6853 		break;
6854 	case BPF_FUNC_redirect_map:
6855 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6856 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6857 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6858 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6859 			goto error;
6860 		break;
6861 	case BPF_FUNC_sk_redirect_map:
6862 	case BPF_FUNC_msg_redirect_map:
6863 	case BPF_FUNC_sock_map_update:
6864 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6865 			goto error;
6866 		break;
6867 	case BPF_FUNC_sk_redirect_hash:
6868 	case BPF_FUNC_msg_redirect_hash:
6869 	case BPF_FUNC_sock_hash_update:
6870 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6871 			goto error;
6872 		break;
6873 	case BPF_FUNC_get_local_storage:
6874 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6875 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6876 			goto error;
6877 		break;
6878 	case BPF_FUNC_sk_select_reuseport:
6879 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6880 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6881 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6882 			goto error;
6883 		break;
6884 	case BPF_FUNC_map_pop_elem:
6885 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6886 		    map->map_type != BPF_MAP_TYPE_STACK)
6887 			goto error;
6888 		break;
6889 	case BPF_FUNC_map_peek_elem:
6890 	case BPF_FUNC_map_push_elem:
6891 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6892 		    map->map_type != BPF_MAP_TYPE_STACK &&
6893 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6894 			goto error;
6895 		break;
6896 	case BPF_FUNC_map_lookup_percpu_elem:
6897 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6898 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6899 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6900 			goto error;
6901 		break;
6902 	case BPF_FUNC_sk_storage_get:
6903 	case BPF_FUNC_sk_storage_delete:
6904 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6905 			goto error;
6906 		break;
6907 	case BPF_FUNC_inode_storage_get:
6908 	case BPF_FUNC_inode_storage_delete:
6909 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6910 			goto error;
6911 		break;
6912 	case BPF_FUNC_task_storage_get:
6913 	case BPF_FUNC_task_storage_delete:
6914 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6915 			goto error;
6916 		break;
6917 	case BPF_FUNC_cgrp_storage_get:
6918 	case BPF_FUNC_cgrp_storage_delete:
6919 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6920 			goto error;
6921 		break;
6922 	default:
6923 		break;
6924 	}
6925 
6926 	return 0;
6927 error:
6928 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6929 		map->map_type, func_id_name(func_id), func_id);
6930 	return -EINVAL;
6931 }
6932 
6933 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6934 {
6935 	int count = 0;
6936 
6937 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6938 		count++;
6939 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6940 		count++;
6941 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6942 		count++;
6943 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6944 		count++;
6945 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6946 		count++;
6947 
6948 	/* We only support one arg being in raw mode at the moment,
6949 	 * which is sufficient for the helper functions we have
6950 	 * right now.
6951 	 */
6952 	return count <= 1;
6953 }
6954 
6955 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6956 {
6957 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6958 	bool has_size = fn->arg_size[arg] != 0;
6959 	bool is_next_size = false;
6960 
6961 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6962 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6963 
6964 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6965 		return is_next_size;
6966 
6967 	return has_size == is_next_size || is_next_size == is_fixed;
6968 }
6969 
6970 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6971 {
6972 	/* bpf_xxx(..., buf, len) call will access 'len'
6973 	 * bytes from memory 'buf'. Both arg types need
6974 	 * to be paired, so make sure there's no buggy
6975 	 * helper function specification.
6976 	 */
6977 	if (arg_type_is_mem_size(fn->arg1_type) ||
6978 	    check_args_pair_invalid(fn, 0) ||
6979 	    check_args_pair_invalid(fn, 1) ||
6980 	    check_args_pair_invalid(fn, 2) ||
6981 	    check_args_pair_invalid(fn, 3) ||
6982 	    check_args_pair_invalid(fn, 4))
6983 		return false;
6984 
6985 	return true;
6986 }
6987 
6988 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6989 {
6990 	int i;
6991 
6992 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6993 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
6994 			return !!fn->arg_btf_id[i];
6995 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
6996 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
6997 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6998 		    /* arg_btf_id and arg_size are in a union. */
6999 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7000 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7001 			return false;
7002 	}
7003 
7004 	return true;
7005 }
7006 
7007 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7008 {
7009 	return check_raw_mode_ok(fn) &&
7010 	       check_arg_pair_ok(fn) &&
7011 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
7012 }
7013 
7014 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7015  * are now invalid, so turn them into unknown SCALAR_VALUE.
7016  */
7017 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7018 {
7019 	struct bpf_func_state *state;
7020 	struct bpf_reg_state *reg;
7021 
7022 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7023 		if (reg_is_pkt_pointer_any(reg))
7024 			__mark_reg_unknown(env, reg);
7025 	}));
7026 }
7027 
7028 enum {
7029 	AT_PKT_END = -1,
7030 	BEYOND_PKT_END = -2,
7031 };
7032 
7033 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7034 {
7035 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7036 	struct bpf_reg_state *reg = &state->regs[regn];
7037 
7038 	if (reg->type != PTR_TO_PACKET)
7039 		/* PTR_TO_PACKET_META is not supported yet */
7040 		return;
7041 
7042 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7043 	 * How far beyond pkt_end it goes is unknown.
7044 	 * if (!range_open) it's the case of pkt >= pkt_end
7045 	 * if (range_open) it's the case of pkt > pkt_end
7046 	 * hence this pointer is at least 1 byte bigger than pkt_end
7047 	 */
7048 	if (range_open)
7049 		reg->range = BEYOND_PKT_END;
7050 	else
7051 		reg->range = AT_PKT_END;
7052 }
7053 
7054 /* The pointer with the specified id has released its reference to kernel
7055  * resources. Identify all copies of the same pointer and clear the reference.
7056  */
7057 static int release_reference(struct bpf_verifier_env *env,
7058 			     int ref_obj_id)
7059 {
7060 	struct bpf_func_state *state;
7061 	struct bpf_reg_state *reg;
7062 	int err;
7063 
7064 	err = release_reference_state(cur_func(env), ref_obj_id);
7065 	if (err)
7066 		return err;
7067 
7068 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7069 		if (reg->ref_obj_id == ref_obj_id) {
7070 			if (!env->allow_ptr_leaks)
7071 				__mark_reg_not_init(env, reg);
7072 			else
7073 				__mark_reg_unknown(env, reg);
7074 		}
7075 	}));
7076 
7077 	return 0;
7078 }
7079 
7080 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7081 				    struct bpf_reg_state *regs)
7082 {
7083 	int i;
7084 
7085 	/* after the call registers r0 - r5 were scratched */
7086 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7087 		mark_reg_not_init(env, regs, caller_saved[i]);
7088 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7089 	}
7090 }
7091 
7092 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7093 				   struct bpf_func_state *caller,
7094 				   struct bpf_func_state *callee,
7095 				   int insn_idx);
7096 
7097 static int set_callee_state(struct bpf_verifier_env *env,
7098 			    struct bpf_func_state *caller,
7099 			    struct bpf_func_state *callee, int insn_idx);
7100 
7101 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7102 			     int *insn_idx, int subprog,
7103 			     set_callee_state_fn set_callee_state_cb)
7104 {
7105 	struct bpf_verifier_state *state = env->cur_state;
7106 	struct bpf_func_info_aux *func_info_aux;
7107 	struct bpf_func_state *caller, *callee;
7108 	int err;
7109 	bool is_global = false;
7110 
7111 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7112 		verbose(env, "the call stack of %d frames is too deep\n",
7113 			state->curframe + 2);
7114 		return -E2BIG;
7115 	}
7116 
7117 	caller = state->frame[state->curframe];
7118 	if (state->frame[state->curframe + 1]) {
7119 		verbose(env, "verifier bug. Frame %d already allocated\n",
7120 			state->curframe + 1);
7121 		return -EFAULT;
7122 	}
7123 
7124 	func_info_aux = env->prog->aux->func_info_aux;
7125 	if (func_info_aux)
7126 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7127 	err = btf_check_subprog_call(env, subprog, caller->regs);
7128 	if (err == -EFAULT)
7129 		return err;
7130 	if (is_global) {
7131 		if (err) {
7132 			verbose(env, "Caller passes invalid args into func#%d\n",
7133 				subprog);
7134 			return err;
7135 		} else {
7136 			if (env->log.level & BPF_LOG_LEVEL)
7137 				verbose(env,
7138 					"Func#%d is global and valid. Skipping.\n",
7139 					subprog);
7140 			clear_caller_saved_regs(env, caller->regs);
7141 
7142 			/* All global functions return a 64-bit SCALAR_VALUE */
7143 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
7144 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7145 
7146 			/* continue with next insn after call */
7147 			return 0;
7148 		}
7149 	}
7150 
7151 	/* set_callee_state is used for direct subprog calls, but we are
7152 	 * interested in validating only BPF helpers that can call subprogs as
7153 	 * callbacks
7154 	 */
7155 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
7156 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
7157 			func_id_name(insn->imm), insn->imm);
7158 		return -EFAULT;
7159 	}
7160 
7161 	if (insn->code == (BPF_JMP | BPF_CALL) &&
7162 	    insn->src_reg == 0 &&
7163 	    insn->imm == BPF_FUNC_timer_set_callback) {
7164 		struct bpf_verifier_state *async_cb;
7165 
7166 		/* there is no real recursion here. timer callbacks are async */
7167 		env->subprog_info[subprog].is_async_cb = true;
7168 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7169 					 *insn_idx, subprog);
7170 		if (!async_cb)
7171 			return -EFAULT;
7172 		callee = async_cb->frame[0];
7173 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
7174 
7175 		/* Convert bpf_timer_set_callback() args into timer callback args */
7176 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
7177 		if (err)
7178 			return err;
7179 
7180 		clear_caller_saved_regs(env, caller->regs);
7181 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
7182 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7183 		/* continue with next insn after call */
7184 		return 0;
7185 	}
7186 
7187 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7188 	if (!callee)
7189 		return -ENOMEM;
7190 	state->frame[state->curframe + 1] = callee;
7191 
7192 	/* callee cannot access r0, r6 - r9 for reading and has to write
7193 	 * into its own stack before reading from it.
7194 	 * callee can read/write into caller's stack
7195 	 */
7196 	init_func_state(env, callee,
7197 			/* remember the callsite, it will be used by bpf_exit */
7198 			*insn_idx /* callsite */,
7199 			state->curframe + 1 /* frameno within this callchain */,
7200 			subprog /* subprog number within this prog */);
7201 
7202 	/* Transfer references to the callee */
7203 	err = copy_reference_state(callee, caller);
7204 	if (err)
7205 		goto err_out;
7206 
7207 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
7208 	if (err)
7209 		goto err_out;
7210 
7211 	clear_caller_saved_regs(env, caller->regs);
7212 
7213 	/* only increment it after check_reg_arg() finished */
7214 	state->curframe++;
7215 
7216 	/* and go analyze first insn of the callee */
7217 	*insn_idx = env->subprog_info[subprog].start - 1;
7218 
7219 	if (env->log.level & BPF_LOG_LEVEL) {
7220 		verbose(env, "caller:\n");
7221 		print_verifier_state(env, caller, true);
7222 		verbose(env, "callee:\n");
7223 		print_verifier_state(env, callee, true);
7224 	}
7225 	return 0;
7226 
7227 err_out:
7228 	free_func_state(callee);
7229 	state->frame[state->curframe + 1] = NULL;
7230 	return err;
7231 }
7232 
7233 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7234 				   struct bpf_func_state *caller,
7235 				   struct bpf_func_state *callee)
7236 {
7237 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7238 	 *      void *callback_ctx, u64 flags);
7239 	 * callback_fn(struct bpf_map *map, void *key, void *value,
7240 	 *      void *callback_ctx);
7241 	 */
7242 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7243 
7244 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7245 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7246 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7247 
7248 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7249 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7250 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7251 
7252 	/* pointer to stack or null */
7253 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7254 
7255 	/* unused */
7256 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7257 	return 0;
7258 }
7259 
7260 static int set_callee_state(struct bpf_verifier_env *env,
7261 			    struct bpf_func_state *caller,
7262 			    struct bpf_func_state *callee, int insn_idx)
7263 {
7264 	int i;
7265 
7266 	/* copy r1 - r5 args that callee can access.  The copy includes parent
7267 	 * pointers, which connects us up to the liveness chain
7268 	 */
7269 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7270 		callee->regs[i] = caller->regs[i];
7271 	return 0;
7272 }
7273 
7274 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7275 			   int *insn_idx)
7276 {
7277 	int subprog, target_insn;
7278 
7279 	target_insn = *insn_idx + insn->imm + 1;
7280 	subprog = find_subprog(env, target_insn);
7281 	if (subprog < 0) {
7282 		verbose(env, "verifier bug. No program starts at insn %d\n",
7283 			target_insn);
7284 		return -EFAULT;
7285 	}
7286 
7287 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7288 }
7289 
7290 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7291 				       struct bpf_func_state *caller,
7292 				       struct bpf_func_state *callee,
7293 				       int insn_idx)
7294 {
7295 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7296 	struct bpf_map *map;
7297 	int err;
7298 
7299 	if (bpf_map_ptr_poisoned(insn_aux)) {
7300 		verbose(env, "tail_call abusing map_ptr\n");
7301 		return -EINVAL;
7302 	}
7303 
7304 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7305 	if (!map->ops->map_set_for_each_callback_args ||
7306 	    !map->ops->map_for_each_callback) {
7307 		verbose(env, "callback function not allowed for map\n");
7308 		return -ENOTSUPP;
7309 	}
7310 
7311 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7312 	if (err)
7313 		return err;
7314 
7315 	callee->in_callback_fn = true;
7316 	callee->callback_ret_range = tnum_range(0, 1);
7317 	return 0;
7318 }
7319 
7320 static int set_loop_callback_state(struct bpf_verifier_env *env,
7321 				   struct bpf_func_state *caller,
7322 				   struct bpf_func_state *callee,
7323 				   int insn_idx)
7324 {
7325 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7326 	 *	    u64 flags);
7327 	 * callback_fn(u32 index, void *callback_ctx);
7328 	 */
7329 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7330 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7331 
7332 	/* unused */
7333 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7334 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7335 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7336 
7337 	callee->in_callback_fn = true;
7338 	callee->callback_ret_range = tnum_range(0, 1);
7339 	return 0;
7340 }
7341 
7342 static int set_timer_callback_state(struct bpf_verifier_env *env,
7343 				    struct bpf_func_state *caller,
7344 				    struct bpf_func_state *callee,
7345 				    int insn_idx)
7346 {
7347 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7348 
7349 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7350 	 * callback_fn(struct bpf_map *map, void *key, void *value);
7351 	 */
7352 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7353 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7354 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
7355 
7356 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7357 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7358 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
7359 
7360 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7361 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7362 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
7363 
7364 	/* unused */
7365 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7366 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7367 	callee->in_async_callback_fn = true;
7368 	callee->callback_ret_range = tnum_range(0, 1);
7369 	return 0;
7370 }
7371 
7372 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7373 				       struct bpf_func_state *caller,
7374 				       struct bpf_func_state *callee,
7375 				       int insn_idx)
7376 {
7377 	/* bpf_find_vma(struct task_struct *task, u64 addr,
7378 	 *               void *callback_fn, void *callback_ctx, u64 flags)
7379 	 * (callback_fn)(struct task_struct *task,
7380 	 *               struct vm_area_struct *vma, void *callback_ctx);
7381 	 */
7382 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7383 
7384 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7385 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7386 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7387 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7388 
7389 	/* pointer to stack or null */
7390 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7391 
7392 	/* unused */
7393 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7394 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7395 	callee->in_callback_fn = true;
7396 	callee->callback_ret_range = tnum_range(0, 1);
7397 	return 0;
7398 }
7399 
7400 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7401 					   struct bpf_func_state *caller,
7402 					   struct bpf_func_state *callee,
7403 					   int insn_idx)
7404 {
7405 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7406 	 *			  callback_ctx, u64 flags);
7407 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
7408 	 */
7409 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7410 	mark_dynptr_cb_reg(&callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
7411 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7412 
7413 	/* unused */
7414 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7415 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7416 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7417 
7418 	callee->in_callback_fn = true;
7419 	callee->callback_ret_range = tnum_range(0, 1);
7420 	return 0;
7421 }
7422 
7423 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7424 {
7425 	struct bpf_verifier_state *state = env->cur_state;
7426 	struct bpf_func_state *caller, *callee;
7427 	struct bpf_reg_state *r0;
7428 	int err;
7429 
7430 	callee = state->frame[state->curframe];
7431 	r0 = &callee->regs[BPF_REG_0];
7432 	if (r0->type == PTR_TO_STACK) {
7433 		/* technically it's ok to return caller's stack pointer
7434 		 * (or caller's caller's pointer) back to the caller,
7435 		 * since these pointers are valid. Only current stack
7436 		 * pointer will be invalid as soon as function exits,
7437 		 * but let's be conservative
7438 		 */
7439 		verbose(env, "cannot return stack pointer to the caller\n");
7440 		return -EINVAL;
7441 	}
7442 
7443 	caller = state->frame[state->curframe - 1];
7444 	if (callee->in_callback_fn) {
7445 		/* enforce R0 return value range [0, 1]. */
7446 		struct tnum range = callee->callback_ret_range;
7447 
7448 		if (r0->type != SCALAR_VALUE) {
7449 			verbose(env, "R0 not a scalar value\n");
7450 			return -EACCES;
7451 		}
7452 		if (!tnum_in(range, r0->var_off)) {
7453 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7454 			return -EINVAL;
7455 		}
7456 	} else {
7457 		/* return to the caller whatever r0 had in the callee */
7458 		caller->regs[BPF_REG_0] = *r0;
7459 	}
7460 
7461 	/* callback_fn frame should have released its own additions to parent's
7462 	 * reference state at this point, or check_reference_leak would
7463 	 * complain, hence it must be the same as the caller. There is no need
7464 	 * to copy it back.
7465 	 */
7466 	if (!callee->in_callback_fn) {
7467 		/* Transfer references to the caller */
7468 		err = copy_reference_state(caller, callee);
7469 		if (err)
7470 			return err;
7471 	}
7472 
7473 	*insn_idx = callee->callsite + 1;
7474 	if (env->log.level & BPF_LOG_LEVEL) {
7475 		verbose(env, "returning from callee:\n");
7476 		print_verifier_state(env, callee, true);
7477 		verbose(env, "to caller at %d:\n", *insn_idx);
7478 		print_verifier_state(env, caller, true);
7479 	}
7480 	/* clear everything in the callee */
7481 	free_func_state(callee);
7482 	state->frame[state->curframe--] = NULL;
7483 	return 0;
7484 }
7485 
7486 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7487 				   int func_id,
7488 				   struct bpf_call_arg_meta *meta)
7489 {
7490 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7491 
7492 	if (ret_type != RET_INTEGER ||
7493 	    (func_id != BPF_FUNC_get_stack &&
7494 	     func_id != BPF_FUNC_get_task_stack &&
7495 	     func_id != BPF_FUNC_probe_read_str &&
7496 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7497 	     func_id != BPF_FUNC_probe_read_user_str))
7498 		return;
7499 
7500 	ret_reg->smax_value = meta->msize_max_value;
7501 	ret_reg->s32_max_value = meta->msize_max_value;
7502 	ret_reg->smin_value = -MAX_ERRNO;
7503 	ret_reg->s32_min_value = -MAX_ERRNO;
7504 	reg_bounds_sync(ret_reg);
7505 }
7506 
7507 static int
7508 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7509 		int func_id, int insn_idx)
7510 {
7511 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7512 	struct bpf_map *map = meta->map_ptr;
7513 
7514 	if (func_id != BPF_FUNC_tail_call &&
7515 	    func_id != BPF_FUNC_map_lookup_elem &&
7516 	    func_id != BPF_FUNC_map_update_elem &&
7517 	    func_id != BPF_FUNC_map_delete_elem &&
7518 	    func_id != BPF_FUNC_map_push_elem &&
7519 	    func_id != BPF_FUNC_map_pop_elem &&
7520 	    func_id != BPF_FUNC_map_peek_elem &&
7521 	    func_id != BPF_FUNC_for_each_map_elem &&
7522 	    func_id != BPF_FUNC_redirect_map &&
7523 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7524 		return 0;
7525 
7526 	if (map == NULL) {
7527 		verbose(env, "kernel subsystem misconfigured verifier\n");
7528 		return -EINVAL;
7529 	}
7530 
7531 	/* In case of read-only, some additional restrictions
7532 	 * need to be applied in order to prevent altering the
7533 	 * state of the map from program side.
7534 	 */
7535 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7536 	    (func_id == BPF_FUNC_map_delete_elem ||
7537 	     func_id == BPF_FUNC_map_update_elem ||
7538 	     func_id == BPF_FUNC_map_push_elem ||
7539 	     func_id == BPF_FUNC_map_pop_elem)) {
7540 		verbose(env, "write into map forbidden\n");
7541 		return -EACCES;
7542 	}
7543 
7544 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7545 		bpf_map_ptr_store(aux, meta->map_ptr,
7546 				  !meta->map_ptr->bypass_spec_v1);
7547 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7548 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7549 				  !meta->map_ptr->bypass_spec_v1);
7550 	return 0;
7551 }
7552 
7553 static int
7554 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7555 		int func_id, int insn_idx)
7556 {
7557 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7558 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7559 	struct bpf_map *map = meta->map_ptr;
7560 	u64 val, max;
7561 	int err;
7562 
7563 	if (func_id != BPF_FUNC_tail_call)
7564 		return 0;
7565 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7566 		verbose(env, "kernel subsystem misconfigured verifier\n");
7567 		return -EINVAL;
7568 	}
7569 
7570 	reg = &regs[BPF_REG_3];
7571 	val = reg->var_off.value;
7572 	max = map->max_entries;
7573 
7574 	if (!(register_is_const(reg) && val < max)) {
7575 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7576 		return 0;
7577 	}
7578 
7579 	err = mark_chain_precision(env, BPF_REG_3);
7580 	if (err)
7581 		return err;
7582 	if (bpf_map_key_unseen(aux))
7583 		bpf_map_key_store(aux, val);
7584 	else if (!bpf_map_key_poisoned(aux) &&
7585 		  bpf_map_key_immediate(aux) != val)
7586 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7587 	return 0;
7588 }
7589 
7590 static int check_reference_leak(struct bpf_verifier_env *env)
7591 {
7592 	struct bpf_func_state *state = cur_func(env);
7593 	bool refs_lingering = false;
7594 	int i;
7595 
7596 	if (state->frameno && !state->in_callback_fn)
7597 		return 0;
7598 
7599 	for (i = 0; i < state->acquired_refs; i++) {
7600 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7601 			continue;
7602 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7603 			state->refs[i].id, state->refs[i].insn_idx);
7604 		refs_lingering = true;
7605 	}
7606 	return refs_lingering ? -EINVAL : 0;
7607 }
7608 
7609 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7610 				   struct bpf_reg_state *regs)
7611 {
7612 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7613 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7614 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7615 	int err, fmt_map_off, num_args;
7616 	u64 fmt_addr;
7617 	char *fmt;
7618 
7619 	/* data must be an array of u64 */
7620 	if (data_len_reg->var_off.value % 8)
7621 		return -EINVAL;
7622 	num_args = data_len_reg->var_off.value / 8;
7623 
7624 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7625 	 * and map_direct_value_addr is set.
7626 	 */
7627 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7628 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7629 						  fmt_map_off);
7630 	if (err) {
7631 		verbose(env, "verifier bug\n");
7632 		return -EFAULT;
7633 	}
7634 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7635 
7636 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7637 	 * can focus on validating the format specifiers.
7638 	 */
7639 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7640 	if (err < 0)
7641 		verbose(env, "Invalid format string\n");
7642 
7643 	return err;
7644 }
7645 
7646 static int check_get_func_ip(struct bpf_verifier_env *env)
7647 {
7648 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7649 	int func_id = BPF_FUNC_get_func_ip;
7650 
7651 	if (type == BPF_PROG_TYPE_TRACING) {
7652 		if (!bpf_prog_has_trampoline(env->prog)) {
7653 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7654 				func_id_name(func_id), func_id);
7655 			return -ENOTSUPP;
7656 		}
7657 		return 0;
7658 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7659 		return 0;
7660 	}
7661 
7662 	verbose(env, "func %s#%d not supported for program type %d\n",
7663 		func_id_name(func_id), func_id, type);
7664 	return -ENOTSUPP;
7665 }
7666 
7667 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7668 {
7669 	return &env->insn_aux_data[env->insn_idx];
7670 }
7671 
7672 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7673 {
7674 	struct bpf_reg_state *regs = cur_regs(env);
7675 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7676 	bool reg_is_null = register_is_null(reg);
7677 
7678 	if (reg_is_null)
7679 		mark_chain_precision(env, BPF_REG_4);
7680 
7681 	return reg_is_null;
7682 }
7683 
7684 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7685 {
7686 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7687 
7688 	if (!state->initialized) {
7689 		state->initialized = 1;
7690 		state->fit_for_inline = loop_flag_is_zero(env);
7691 		state->callback_subprogno = subprogno;
7692 		return;
7693 	}
7694 
7695 	if (!state->fit_for_inline)
7696 		return;
7697 
7698 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7699 				 state->callback_subprogno == subprogno);
7700 }
7701 
7702 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7703 			     int *insn_idx_p)
7704 {
7705 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7706 	const struct bpf_func_proto *fn = NULL;
7707 	enum bpf_return_type ret_type;
7708 	enum bpf_type_flag ret_flag;
7709 	struct bpf_reg_state *regs;
7710 	struct bpf_call_arg_meta meta;
7711 	int insn_idx = *insn_idx_p;
7712 	bool changes_data;
7713 	int i, err, func_id;
7714 
7715 	/* find function prototype */
7716 	func_id = insn->imm;
7717 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7718 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7719 			func_id);
7720 		return -EINVAL;
7721 	}
7722 
7723 	if (env->ops->get_func_proto)
7724 		fn = env->ops->get_func_proto(func_id, env->prog);
7725 	if (!fn) {
7726 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7727 			func_id);
7728 		return -EINVAL;
7729 	}
7730 
7731 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7732 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7733 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7734 		return -EINVAL;
7735 	}
7736 
7737 	if (fn->allowed && !fn->allowed(env->prog)) {
7738 		verbose(env, "helper call is not allowed in probe\n");
7739 		return -EINVAL;
7740 	}
7741 
7742 	if (!env->prog->aux->sleepable && fn->might_sleep) {
7743 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
7744 		return -EINVAL;
7745 	}
7746 
7747 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7748 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7749 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7750 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7751 			func_id_name(func_id), func_id);
7752 		return -EINVAL;
7753 	}
7754 
7755 	memset(&meta, 0, sizeof(meta));
7756 	meta.pkt_access = fn->pkt_access;
7757 
7758 	err = check_func_proto(fn, func_id);
7759 	if (err) {
7760 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7761 			func_id_name(func_id), func_id);
7762 		return err;
7763 	}
7764 
7765 	if (env->cur_state->active_rcu_lock) {
7766 		if (fn->might_sleep) {
7767 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
7768 				func_id_name(func_id), func_id);
7769 			return -EINVAL;
7770 		}
7771 
7772 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
7773 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
7774 	}
7775 
7776 	meta.func_id = func_id;
7777 	/* check args */
7778 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7779 		err = check_func_arg(env, i, &meta, fn);
7780 		if (err)
7781 			return err;
7782 	}
7783 
7784 	err = record_func_map(env, &meta, func_id, insn_idx);
7785 	if (err)
7786 		return err;
7787 
7788 	err = record_func_key(env, &meta, func_id, insn_idx);
7789 	if (err)
7790 		return err;
7791 
7792 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7793 	 * is inferred from register state.
7794 	 */
7795 	for (i = 0; i < meta.access_size; i++) {
7796 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7797 				       BPF_WRITE, -1, false);
7798 		if (err)
7799 			return err;
7800 	}
7801 
7802 	regs = cur_regs(env);
7803 
7804 	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7805 	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
7806 	 * is safe to do directly.
7807 	 */
7808 	if (meta.uninit_dynptr_regno) {
7809 		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
7810 			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
7811 			return -EFAULT;
7812 		}
7813 		/* we write BPF_DW bits (8 bytes) at a time */
7814 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7815 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7816 					       i, BPF_DW, BPF_WRITE, -1, false);
7817 			if (err)
7818 				return err;
7819 		}
7820 
7821 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7822 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7823 					      insn_idx);
7824 		if (err)
7825 			return err;
7826 	}
7827 
7828 	if (meta.release_regno) {
7829 		err = -EINVAL;
7830 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
7831 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
7832 		 * is safe to do directly.
7833 		 */
7834 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
7835 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
7836 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
7837 				return -EFAULT;
7838 			}
7839 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7840 		} else if (meta.ref_obj_id) {
7841 			err = release_reference(env, meta.ref_obj_id);
7842 		} else if (register_is_null(&regs[meta.release_regno])) {
7843 			/* meta.ref_obj_id can only be 0 if register that is meant to be
7844 			 * released is NULL, which must be > R0.
7845 			 */
7846 			err = 0;
7847 		}
7848 		if (err) {
7849 			verbose(env, "func %s#%d reference has not been acquired before\n",
7850 				func_id_name(func_id), func_id);
7851 			return err;
7852 		}
7853 	}
7854 
7855 	switch (func_id) {
7856 	case BPF_FUNC_tail_call:
7857 		err = check_reference_leak(env);
7858 		if (err) {
7859 			verbose(env, "tail_call would lead to reference leak\n");
7860 			return err;
7861 		}
7862 		break;
7863 	case BPF_FUNC_get_local_storage:
7864 		/* check that flags argument in get_local_storage(map, flags) is 0,
7865 		 * this is required because get_local_storage() can't return an error.
7866 		 */
7867 		if (!register_is_null(&regs[BPF_REG_2])) {
7868 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7869 			return -EINVAL;
7870 		}
7871 		break;
7872 	case BPF_FUNC_for_each_map_elem:
7873 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7874 					set_map_elem_callback_state);
7875 		break;
7876 	case BPF_FUNC_timer_set_callback:
7877 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7878 					set_timer_callback_state);
7879 		break;
7880 	case BPF_FUNC_find_vma:
7881 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7882 					set_find_vma_callback_state);
7883 		break;
7884 	case BPF_FUNC_snprintf:
7885 		err = check_bpf_snprintf_call(env, regs);
7886 		break;
7887 	case BPF_FUNC_loop:
7888 		update_loop_inline_state(env, meta.subprogno);
7889 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7890 					set_loop_callback_state);
7891 		break;
7892 	case BPF_FUNC_dynptr_from_mem:
7893 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7894 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7895 				reg_type_str(env, regs[BPF_REG_1].type));
7896 			return -EACCES;
7897 		}
7898 		break;
7899 	case BPF_FUNC_set_retval:
7900 		if (prog_type == BPF_PROG_TYPE_LSM &&
7901 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7902 			if (!env->prog->aux->attach_func_proto->type) {
7903 				/* Make sure programs that attach to void
7904 				 * hooks don't try to modify return value.
7905 				 */
7906 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7907 				return -EINVAL;
7908 			}
7909 		}
7910 		break;
7911 	case BPF_FUNC_dynptr_data:
7912 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7913 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7914 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7915 
7916 				if (meta.ref_obj_id) {
7917 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7918 					return -EFAULT;
7919 				}
7920 
7921 				meta.ref_obj_id = dynptr_ref_obj_id(env, reg);
7922 				break;
7923 			}
7924 		}
7925 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7926 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7927 			return -EFAULT;
7928 		}
7929 		break;
7930 	case BPF_FUNC_user_ringbuf_drain:
7931 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7932 					set_user_ringbuf_callback_state);
7933 		break;
7934 	}
7935 
7936 	if (err)
7937 		return err;
7938 
7939 	/* reset caller saved regs */
7940 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7941 		mark_reg_not_init(env, regs, caller_saved[i]);
7942 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7943 	}
7944 
7945 	/* helper call returns 64-bit value. */
7946 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7947 
7948 	/* update return register (already marked as written above) */
7949 	ret_type = fn->ret_type;
7950 	ret_flag = type_flag(ret_type);
7951 
7952 	switch (base_type(ret_type)) {
7953 	case RET_INTEGER:
7954 		/* sets type to SCALAR_VALUE */
7955 		mark_reg_unknown(env, regs, BPF_REG_0);
7956 		break;
7957 	case RET_VOID:
7958 		regs[BPF_REG_0].type = NOT_INIT;
7959 		break;
7960 	case RET_PTR_TO_MAP_VALUE:
7961 		/* There is no offset yet applied, variable or fixed */
7962 		mark_reg_known_zero(env, regs, BPF_REG_0);
7963 		/* remember map_ptr, so that check_map_access()
7964 		 * can check 'value_size' boundary of memory access
7965 		 * to map element returned from bpf_map_lookup_elem()
7966 		 */
7967 		if (meta.map_ptr == NULL) {
7968 			verbose(env,
7969 				"kernel subsystem misconfigured verifier\n");
7970 			return -EINVAL;
7971 		}
7972 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7973 		regs[BPF_REG_0].map_uid = meta.map_uid;
7974 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7975 		if (!type_may_be_null(ret_type) &&
7976 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7977 			regs[BPF_REG_0].id = ++env->id_gen;
7978 		}
7979 		break;
7980 	case RET_PTR_TO_SOCKET:
7981 		mark_reg_known_zero(env, regs, BPF_REG_0);
7982 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7983 		break;
7984 	case RET_PTR_TO_SOCK_COMMON:
7985 		mark_reg_known_zero(env, regs, BPF_REG_0);
7986 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7987 		break;
7988 	case RET_PTR_TO_TCP_SOCK:
7989 		mark_reg_known_zero(env, regs, BPF_REG_0);
7990 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7991 		break;
7992 	case RET_PTR_TO_MEM:
7993 		mark_reg_known_zero(env, regs, BPF_REG_0);
7994 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7995 		regs[BPF_REG_0].mem_size = meta.mem_size;
7996 		break;
7997 	case RET_PTR_TO_MEM_OR_BTF_ID:
7998 	{
7999 		const struct btf_type *t;
8000 
8001 		mark_reg_known_zero(env, regs, BPF_REG_0);
8002 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8003 		if (!btf_type_is_struct(t)) {
8004 			u32 tsize;
8005 			const struct btf_type *ret;
8006 			const char *tname;
8007 
8008 			/* resolve the type size of ksym. */
8009 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8010 			if (IS_ERR(ret)) {
8011 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8012 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
8013 					tname, PTR_ERR(ret));
8014 				return -EINVAL;
8015 			}
8016 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8017 			regs[BPF_REG_0].mem_size = tsize;
8018 		} else {
8019 			/* MEM_RDONLY may be carried from ret_flag, but it
8020 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8021 			 * it will confuse the check of PTR_TO_BTF_ID in
8022 			 * check_mem_access().
8023 			 */
8024 			ret_flag &= ~MEM_RDONLY;
8025 
8026 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8027 			regs[BPF_REG_0].btf = meta.ret_btf;
8028 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8029 		}
8030 		break;
8031 	}
8032 	case RET_PTR_TO_BTF_ID:
8033 	{
8034 		struct btf *ret_btf;
8035 		int ret_btf_id;
8036 
8037 		mark_reg_known_zero(env, regs, BPF_REG_0);
8038 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8039 		if (func_id == BPF_FUNC_kptr_xchg) {
8040 			ret_btf = meta.kptr_field->kptr.btf;
8041 			ret_btf_id = meta.kptr_field->kptr.btf_id;
8042 		} else {
8043 			if (fn->ret_btf_id == BPF_PTR_POISON) {
8044 				verbose(env, "verifier internal error:");
8045 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8046 					func_id_name(func_id));
8047 				return -EINVAL;
8048 			}
8049 			ret_btf = btf_vmlinux;
8050 			ret_btf_id = *fn->ret_btf_id;
8051 		}
8052 		if (ret_btf_id == 0) {
8053 			verbose(env, "invalid return type %u of func %s#%d\n",
8054 				base_type(ret_type), func_id_name(func_id),
8055 				func_id);
8056 			return -EINVAL;
8057 		}
8058 		regs[BPF_REG_0].btf = ret_btf;
8059 		regs[BPF_REG_0].btf_id = ret_btf_id;
8060 		break;
8061 	}
8062 	default:
8063 		verbose(env, "unknown return type %u of func %s#%d\n",
8064 			base_type(ret_type), func_id_name(func_id), func_id);
8065 		return -EINVAL;
8066 	}
8067 
8068 	if (type_may_be_null(regs[BPF_REG_0].type))
8069 		regs[BPF_REG_0].id = ++env->id_gen;
8070 
8071 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8072 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8073 			func_id_name(func_id), func_id);
8074 		return -EFAULT;
8075 	}
8076 
8077 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8078 		/* For release_reference() */
8079 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8080 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
8081 		int id = acquire_reference_state(env, insn_idx);
8082 
8083 		if (id < 0)
8084 			return id;
8085 		/* For mark_ptr_or_null_reg() */
8086 		regs[BPF_REG_0].id = id;
8087 		/* For release_reference() */
8088 		regs[BPF_REG_0].ref_obj_id = id;
8089 	}
8090 
8091 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8092 
8093 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8094 	if (err)
8095 		return err;
8096 
8097 	if ((func_id == BPF_FUNC_get_stack ||
8098 	     func_id == BPF_FUNC_get_task_stack) &&
8099 	    !env->prog->has_callchain_buf) {
8100 		const char *err_str;
8101 
8102 #ifdef CONFIG_PERF_EVENTS
8103 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
8104 		err_str = "cannot get callchain buffer for func %s#%d\n";
8105 #else
8106 		err = -ENOTSUPP;
8107 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8108 #endif
8109 		if (err) {
8110 			verbose(env, err_str, func_id_name(func_id), func_id);
8111 			return err;
8112 		}
8113 
8114 		env->prog->has_callchain_buf = true;
8115 	}
8116 
8117 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8118 		env->prog->call_get_stack = true;
8119 
8120 	if (func_id == BPF_FUNC_get_func_ip) {
8121 		if (check_get_func_ip(env))
8122 			return -ENOTSUPP;
8123 		env->prog->call_get_func_ip = true;
8124 	}
8125 
8126 	if (changes_data)
8127 		clear_all_pkt_pointers(env);
8128 	return 0;
8129 }
8130 
8131 /* mark_btf_func_reg_size() is used when the reg size is determined by
8132  * the BTF func_proto's return value size and argument.
8133  */
8134 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8135 				   size_t reg_size)
8136 {
8137 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
8138 
8139 	if (regno == BPF_REG_0) {
8140 		/* Function return value */
8141 		reg->live |= REG_LIVE_WRITTEN;
8142 		reg->subreg_def = reg_size == sizeof(u64) ?
8143 			DEF_NOT_SUBREG : env->insn_idx + 1;
8144 	} else {
8145 		/* Function argument */
8146 		if (reg_size == sizeof(u64)) {
8147 			mark_insn_zext(env, reg);
8148 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8149 		} else {
8150 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8151 		}
8152 	}
8153 }
8154 
8155 struct bpf_kfunc_call_arg_meta {
8156 	/* In parameters */
8157 	struct btf *btf;
8158 	u32 func_id;
8159 	u32 kfunc_flags;
8160 	const struct btf_type *func_proto;
8161 	const char *func_name;
8162 	/* Out parameters */
8163 	u32 ref_obj_id;
8164 	u8 release_regno;
8165 	bool r0_rdonly;
8166 	u32 ret_btf_id;
8167 	u64 r0_size;
8168 	struct {
8169 		u64 value;
8170 		bool found;
8171 	} arg_constant;
8172 	struct {
8173 		struct btf *btf;
8174 		u32 btf_id;
8175 	} arg_obj_drop;
8176 	struct {
8177 		struct btf_field *field;
8178 	} arg_list_head;
8179 };
8180 
8181 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8182 {
8183 	return meta->kfunc_flags & KF_ACQUIRE;
8184 }
8185 
8186 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8187 {
8188 	return meta->kfunc_flags & KF_RET_NULL;
8189 }
8190 
8191 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8192 {
8193 	return meta->kfunc_flags & KF_RELEASE;
8194 }
8195 
8196 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8197 {
8198 	return meta->kfunc_flags & KF_TRUSTED_ARGS;
8199 }
8200 
8201 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8202 {
8203 	return meta->kfunc_flags & KF_SLEEPABLE;
8204 }
8205 
8206 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8207 {
8208 	return meta->kfunc_flags & KF_DESTRUCTIVE;
8209 }
8210 
8211 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8212 {
8213 	return meta->kfunc_flags & KF_RCU;
8214 }
8215 
8216 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8217 {
8218 	return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8219 }
8220 
8221 static bool __kfunc_param_match_suffix(const struct btf *btf,
8222 				       const struct btf_param *arg,
8223 				       const char *suffix)
8224 {
8225 	int suffix_len = strlen(suffix), len;
8226 	const char *param_name;
8227 
8228 	/* In the future, this can be ported to use BTF tagging */
8229 	param_name = btf_name_by_offset(btf, arg->name_off);
8230 	if (str_is_empty(param_name))
8231 		return false;
8232 	len = strlen(param_name);
8233 	if (len < suffix_len)
8234 		return false;
8235 	param_name += len - suffix_len;
8236 	return !strncmp(param_name, suffix, suffix_len);
8237 }
8238 
8239 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8240 				  const struct btf_param *arg,
8241 				  const struct bpf_reg_state *reg)
8242 {
8243 	const struct btf_type *t;
8244 
8245 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8246 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8247 		return false;
8248 
8249 	return __kfunc_param_match_suffix(btf, arg, "__sz");
8250 }
8251 
8252 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8253 {
8254 	return __kfunc_param_match_suffix(btf, arg, "__k");
8255 }
8256 
8257 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8258 {
8259 	return __kfunc_param_match_suffix(btf, arg, "__ign");
8260 }
8261 
8262 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8263 {
8264 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
8265 }
8266 
8267 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8268 					  const struct btf_param *arg,
8269 					  const char *name)
8270 {
8271 	int len, target_len = strlen(name);
8272 	const char *param_name;
8273 
8274 	param_name = btf_name_by_offset(btf, arg->name_off);
8275 	if (str_is_empty(param_name))
8276 		return false;
8277 	len = strlen(param_name);
8278 	if (len != target_len)
8279 		return false;
8280 	if (strcmp(param_name, name))
8281 		return false;
8282 
8283 	return true;
8284 }
8285 
8286 enum {
8287 	KF_ARG_DYNPTR_ID,
8288 	KF_ARG_LIST_HEAD_ID,
8289 	KF_ARG_LIST_NODE_ID,
8290 };
8291 
8292 BTF_ID_LIST(kf_arg_btf_ids)
8293 BTF_ID(struct, bpf_dynptr_kern)
8294 BTF_ID(struct, bpf_list_head)
8295 BTF_ID(struct, bpf_list_node)
8296 
8297 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8298 				    const struct btf_param *arg, int type)
8299 {
8300 	const struct btf_type *t;
8301 	u32 res_id;
8302 
8303 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8304 	if (!t)
8305 		return false;
8306 	if (!btf_type_is_ptr(t))
8307 		return false;
8308 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
8309 	if (!t)
8310 		return false;
8311 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8312 }
8313 
8314 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8315 {
8316 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8317 }
8318 
8319 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8320 {
8321 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8322 }
8323 
8324 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8325 {
8326 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8327 }
8328 
8329 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8330 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8331 					const struct btf *btf,
8332 					const struct btf_type *t, int rec)
8333 {
8334 	const struct btf_type *member_type;
8335 	const struct btf_member *member;
8336 	u32 i;
8337 
8338 	if (!btf_type_is_struct(t))
8339 		return false;
8340 
8341 	for_each_member(i, t, member) {
8342 		const struct btf_array *array;
8343 
8344 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8345 		if (btf_type_is_struct(member_type)) {
8346 			if (rec >= 3) {
8347 				verbose(env, "max struct nesting depth exceeded\n");
8348 				return false;
8349 			}
8350 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8351 				return false;
8352 			continue;
8353 		}
8354 		if (btf_type_is_array(member_type)) {
8355 			array = btf_array(member_type);
8356 			if (!array->nelems)
8357 				return false;
8358 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8359 			if (!btf_type_is_scalar(member_type))
8360 				return false;
8361 			continue;
8362 		}
8363 		if (!btf_type_is_scalar(member_type))
8364 			return false;
8365 	}
8366 	return true;
8367 }
8368 
8369 
8370 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8371 #ifdef CONFIG_NET
8372 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8373 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8374 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8375 #endif
8376 };
8377 
8378 enum kfunc_ptr_arg_type {
8379 	KF_ARG_PTR_TO_CTX,
8380 	KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8381 	KF_ARG_PTR_TO_KPTR,	     /* PTR_TO_KPTR but type specific */
8382 	KF_ARG_PTR_TO_DYNPTR,
8383 	KF_ARG_PTR_TO_LIST_HEAD,
8384 	KF_ARG_PTR_TO_LIST_NODE,
8385 	KF_ARG_PTR_TO_BTF_ID,	     /* Also covers reg2btf_ids conversions */
8386 	KF_ARG_PTR_TO_MEM,
8387 	KF_ARG_PTR_TO_MEM_SIZE,	     /* Size derived from next argument, skip it */
8388 };
8389 
8390 enum special_kfunc_type {
8391 	KF_bpf_obj_new_impl,
8392 	KF_bpf_obj_drop_impl,
8393 	KF_bpf_list_push_front,
8394 	KF_bpf_list_push_back,
8395 	KF_bpf_list_pop_front,
8396 	KF_bpf_list_pop_back,
8397 	KF_bpf_cast_to_kern_ctx,
8398 	KF_bpf_rdonly_cast,
8399 	KF_bpf_rcu_read_lock,
8400 	KF_bpf_rcu_read_unlock,
8401 };
8402 
8403 BTF_SET_START(special_kfunc_set)
8404 BTF_ID(func, bpf_obj_new_impl)
8405 BTF_ID(func, bpf_obj_drop_impl)
8406 BTF_ID(func, bpf_list_push_front)
8407 BTF_ID(func, bpf_list_push_back)
8408 BTF_ID(func, bpf_list_pop_front)
8409 BTF_ID(func, bpf_list_pop_back)
8410 BTF_ID(func, bpf_cast_to_kern_ctx)
8411 BTF_ID(func, bpf_rdonly_cast)
8412 BTF_SET_END(special_kfunc_set)
8413 
8414 BTF_ID_LIST(special_kfunc_list)
8415 BTF_ID(func, bpf_obj_new_impl)
8416 BTF_ID(func, bpf_obj_drop_impl)
8417 BTF_ID(func, bpf_list_push_front)
8418 BTF_ID(func, bpf_list_push_back)
8419 BTF_ID(func, bpf_list_pop_front)
8420 BTF_ID(func, bpf_list_pop_back)
8421 BTF_ID(func, bpf_cast_to_kern_ctx)
8422 BTF_ID(func, bpf_rdonly_cast)
8423 BTF_ID(func, bpf_rcu_read_lock)
8424 BTF_ID(func, bpf_rcu_read_unlock)
8425 
8426 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
8427 {
8428 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
8429 }
8430 
8431 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
8432 {
8433 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
8434 }
8435 
8436 static enum kfunc_ptr_arg_type
8437 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8438 		       struct bpf_kfunc_call_arg_meta *meta,
8439 		       const struct btf_type *t, const struct btf_type *ref_t,
8440 		       const char *ref_tname, const struct btf_param *args,
8441 		       int argno, int nargs)
8442 {
8443 	u32 regno = argno + 1;
8444 	struct bpf_reg_state *regs = cur_regs(env);
8445 	struct bpf_reg_state *reg = &regs[regno];
8446 	bool arg_mem_size = false;
8447 
8448 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8449 		return KF_ARG_PTR_TO_CTX;
8450 
8451 	/* In this function, we verify the kfunc's BTF as per the argument type,
8452 	 * leaving the rest of the verification with respect to the register
8453 	 * type to our caller. When a set of conditions hold in the BTF type of
8454 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8455 	 */
8456 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8457 		return KF_ARG_PTR_TO_CTX;
8458 
8459 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8460 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8461 
8462 	if (is_kfunc_arg_kptr_get(meta, argno)) {
8463 		if (!btf_type_is_ptr(ref_t)) {
8464 			verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8465 			return -EINVAL;
8466 		}
8467 		ref_t = btf_type_by_id(meta->btf, ref_t->type);
8468 		ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8469 		if (!btf_type_is_struct(ref_t)) {
8470 			verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8471 				meta->func_name, btf_type_str(ref_t), ref_tname);
8472 			return -EINVAL;
8473 		}
8474 		return KF_ARG_PTR_TO_KPTR;
8475 	}
8476 
8477 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8478 		return KF_ARG_PTR_TO_DYNPTR;
8479 
8480 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8481 		return KF_ARG_PTR_TO_LIST_HEAD;
8482 
8483 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8484 		return KF_ARG_PTR_TO_LIST_NODE;
8485 
8486 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8487 		if (!btf_type_is_struct(ref_t)) {
8488 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8489 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8490 			return -EINVAL;
8491 		}
8492 		return KF_ARG_PTR_TO_BTF_ID;
8493 	}
8494 
8495 	if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8496 		arg_mem_size = true;
8497 
8498 	/* This is the catch all argument type of register types supported by
8499 	 * check_helper_mem_access. However, we only allow when argument type is
8500 	 * pointer to scalar, or struct composed (recursively) of scalars. When
8501 	 * arg_mem_size is true, the pointer can be void *.
8502 	 */
8503 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8504 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8505 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8506 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8507 		return -EINVAL;
8508 	}
8509 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8510 }
8511 
8512 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8513 					struct bpf_reg_state *reg,
8514 					const struct btf_type *ref_t,
8515 					const char *ref_tname, u32 ref_id,
8516 					struct bpf_kfunc_call_arg_meta *meta,
8517 					int argno)
8518 {
8519 	const struct btf_type *reg_ref_t;
8520 	bool strict_type_match = false;
8521 	const struct btf *reg_btf;
8522 	const char *reg_ref_tname;
8523 	u32 reg_ref_id;
8524 
8525 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
8526 		reg_btf = reg->btf;
8527 		reg_ref_id = reg->btf_id;
8528 	} else {
8529 		reg_btf = btf_vmlinux;
8530 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8531 	}
8532 
8533 	if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8534 		strict_type_match = true;
8535 
8536 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8537 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8538 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8539 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8540 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8541 			btf_type_str(reg_ref_t), reg_ref_tname);
8542 		return -EINVAL;
8543 	}
8544 	return 0;
8545 }
8546 
8547 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8548 				      struct bpf_reg_state *reg,
8549 				      const struct btf_type *ref_t,
8550 				      const char *ref_tname,
8551 				      struct bpf_kfunc_call_arg_meta *meta,
8552 				      int argno)
8553 {
8554 	struct btf_field *kptr_field;
8555 
8556 	/* check_func_arg_reg_off allows var_off for
8557 	 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8558 	 * off_desc.
8559 	 */
8560 	if (!tnum_is_const(reg->var_off)) {
8561 		verbose(env, "arg#0 must have constant offset\n");
8562 		return -EINVAL;
8563 	}
8564 
8565 	kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8566 	if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8567 		verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8568 			reg->off + reg->var_off.value);
8569 		return -EINVAL;
8570 	}
8571 
8572 	if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8573 				  kptr_field->kptr.btf_id, true)) {
8574 		verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8575 			meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8576 		return -EINVAL;
8577 	}
8578 	return 0;
8579 }
8580 
8581 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8582 {
8583 	struct bpf_func_state *state = cur_func(env);
8584 	struct bpf_reg_state *reg;
8585 	int i;
8586 
8587 	/* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8588 	 * subprogs, no global functions. This means that the references would
8589 	 * not be released inside the critical section but they may be added to
8590 	 * the reference state, and the acquired_refs are never copied out for a
8591 	 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8592 	 * critical sections.
8593 	 */
8594 	if (!ref_obj_id) {
8595 		verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8596 		return -EFAULT;
8597 	}
8598 	for (i = 0; i < state->acquired_refs; i++) {
8599 		if (state->refs[i].id == ref_obj_id) {
8600 			if (state->refs[i].release_on_unlock) {
8601 				verbose(env, "verifier internal error: expected false release_on_unlock");
8602 				return -EFAULT;
8603 			}
8604 			state->refs[i].release_on_unlock = true;
8605 			/* Now mark everyone sharing same ref_obj_id as untrusted */
8606 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8607 				if (reg->ref_obj_id == ref_obj_id)
8608 					reg->type |= PTR_UNTRUSTED;
8609 			}));
8610 			return 0;
8611 		}
8612 	}
8613 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8614 	return -EFAULT;
8615 }
8616 
8617 /* Implementation details:
8618  *
8619  * Each register points to some region of memory, which we define as an
8620  * allocation. Each allocation may embed a bpf_spin_lock which protects any
8621  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8622  * allocation. The lock and the data it protects are colocated in the same
8623  * memory region.
8624  *
8625  * Hence, everytime a register holds a pointer value pointing to such
8626  * allocation, the verifier preserves a unique reg->id for it.
8627  *
8628  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8629  * bpf_spin_lock is called.
8630  *
8631  * To enable this, lock state in the verifier captures two values:
8632  *	active_lock.ptr = Register's type specific pointer
8633  *	active_lock.id  = A unique ID for each register pointer value
8634  *
8635  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8636  * supported register types.
8637  *
8638  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8639  * allocated objects is the reg->btf pointer.
8640  *
8641  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8642  * can establish the provenance of the map value statically for each distinct
8643  * lookup into such maps. They always contain a single map value hence unique
8644  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8645  *
8646  * So, in case of global variables, they use array maps with max_entries = 1,
8647  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8648  * into the same map value as max_entries is 1, as described above).
8649  *
8650  * In case of inner map lookups, the inner map pointer has same map_ptr as the
8651  * outer map pointer (in verifier context), but each lookup into an inner map
8652  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8653  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8654  * will get different reg->id assigned to each lookup, hence different
8655  * active_lock.id.
8656  *
8657  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8658  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8659  * returned from bpf_obj_new. Each allocation receives a new reg->id.
8660  */
8661 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8662 {
8663 	void *ptr;
8664 	u32 id;
8665 
8666 	switch ((int)reg->type) {
8667 	case PTR_TO_MAP_VALUE:
8668 		ptr = reg->map_ptr;
8669 		break;
8670 	case PTR_TO_BTF_ID | MEM_ALLOC:
8671 	case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8672 		ptr = reg->btf;
8673 		break;
8674 	default:
8675 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
8676 		return -EFAULT;
8677 	}
8678 	id = reg->id;
8679 
8680 	if (!env->cur_state->active_lock.ptr)
8681 		return -EINVAL;
8682 	if (env->cur_state->active_lock.ptr != ptr ||
8683 	    env->cur_state->active_lock.id != id) {
8684 		verbose(env, "held lock and object are not in the same allocation\n");
8685 		return -EINVAL;
8686 	}
8687 	return 0;
8688 }
8689 
8690 static bool is_bpf_list_api_kfunc(u32 btf_id)
8691 {
8692 	return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8693 	       btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8694 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8695 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8696 }
8697 
8698 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8699 					   struct bpf_reg_state *reg, u32 regno,
8700 					   struct bpf_kfunc_call_arg_meta *meta)
8701 {
8702 	struct btf_field *field;
8703 	struct btf_record *rec;
8704 	u32 list_head_off;
8705 
8706 	if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8707 		verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8708 		return -EFAULT;
8709 	}
8710 
8711 	if (!tnum_is_const(reg->var_off)) {
8712 		verbose(env,
8713 			"R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8714 			regno);
8715 		return -EINVAL;
8716 	}
8717 
8718 	rec = reg_btf_record(reg);
8719 	list_head_off = reg->off + reg->var_off.value;
8720 	field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8721 	if (!field) {
8722 		verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8723 		return -EINVAL;
8724 	}
8725 
8726 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8727 	if (check_reg_allocation_locked(env, reg)) {
8728 		verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8729 			rec->spin_lock_off);
8730 		return -EINVAL;
8731 	}
8732 
8733 	if (meta->arg_list_head.field) {
8734 		verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8735 		return -EFAULT;
8736 	}
8737 	meta->arg_list_head.field = field;
8738 	return 0;
8739 }
8740 
8741 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8742 					   struct bpf_reg_state *reg, u32 regno,
8743 					   struct bpf_kfunc_call_arg_meta *meta)
8744 {
8745 	const struct btf_type *et, *t;
8746 	struct btf_field *field;
8747 	struct btf_record *rec;
8748 	u32 list_node_off;
8749 
8750 	if (meta->btf != btf_vmlinux ||
8751 	    (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8752 	     meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8753 		verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8754 		return -EFAULT;
8755 	}
8756 
8757 	if (!tnum_is_const(reg->var_off)) {
8758 		verbose(env,
8759 			"R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8760 			regno);
8761 		return -EINVAL;
8762 	}
8763 
8764 	rec = reg_btf_record(reg);
8765 	list_node_off = reg->off + reg->var_off.value;
8766 	field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8767 	if (!field || field->offset != list_node_off) {
8768 		verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8769 		return -EINVAL;
8770 	}
8771 
8772 	field = meta->arg_list_head.field;
8773 
8774 	et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id);
8775 	t = btf_type_by_id(reg->btf, reg->btf_id);
8776 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf,
8777 				  field->list_head.value_btf_id, true)) {
8778 		verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8779 			"in struct %s, but arg is at offset=%d in struct %s\n",
8780 			field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off),
8781 			list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8782 		return -EINVAL;
8783 	}
8784 
8785 	if (list_node_off != field->list_head.node_offset) {
8786 		verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8787 			list_node_off, field->list_head.node_offset,
8788 			btf_name_by_offset(field->list_head.btf, et->name_off));
8789 		return -EINVAL;
8790 	}
8791 	/* Set arg#1 for expiration after unlock */
8792 	return ref_set_release_on_unlock(env, reg->ref_obj_id);
8793 }
8794 
8795 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8796 {
8797 	const char *func_name = meta->func_name, *ref_tname;
8798 	const struct btf *btf = meta->btf;
8799 	const struct btf_param *args;
8800 	u32 i, nargs;
8801 	int ret;
8802 
8803 	args = (const struct btf_param *)(meta->func_proto + 1);
8804 	nargs = btf_type_vlen(meta->func_proto);
8805 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8806 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8807 			MAX_BPF_FUNC_REG_ARGS);
8808 		return -EINVAL;
8809 	}
8810 
8811 	/* Check that BTF function arguments match actual types that the
8812 	 * verifier sees.
8813 	 */
8814 	for (i = 0; i < nargs; i++) {
8815 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
8816 		const struct btf_type *t, *ref_t, *resolve_ret;
8817 		enum bpf_arg_type arg_type = ARG_DONTCARE;
8818 		u32 regno = i + 1, ref_id, type_size;
8819 		bool is_ret_buf_sz = false;
8820 		int kf_arg_type;
8821 
8822 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8823 
8824 		if (is_kfunc_arg_ignore(btf, &args[i]))
8825 			continue;
8826 
8827 		if (btf_type_is_scalar(t)) {
8828 			if (reg->type != SCALAR_VALUE) {
8829 				verbose(env, "R%d is not a scalar\n", regno);
8830 				return -EINVAL;
8831 			}
8832 
8833 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8834 				if (meta->arg_constant.found) {
8835 					verbose(env, "verifier internal error: only one constant argument permitted\n");
8836 					return -EFAULT;
8837 				}
8838 				if (!tnum_is_const(reg->var_off)) {
8839 					verbose(env, "R%d must be a known constant\n", regno);
8840 					return -EINVAL;
8841 				}
8842 				ret = mark_chain_precision(env, regno);
8843 				if (ret < 0)
8844 					return ret;
8845 				meta->arg_constant.found = true;
8846 				meta->arg_constant.value = reg->var_off.value;
8847 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8848 				meta->r0_rdonly = true;
8849 				is_ret_buf_sz = true;
8850 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8851 				is_ret_buf_sz = true;
8852 			}
8853 
8854 			if (is_ret_buf_sz) {
8855 				if (meta->r0_size) {
8856 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8857 					return -EINVAL;
8858 				}
8859 
8860 				if (!tnum_is_const(reg->var_off)) {
8861 					verbose(env, "R%d is not a const\n", regno);
8862 					return -EINVAL;
8863 				}
8864 
8865 				meta->r0_size = reg->var_off.value;
8866 				ret = mark_chain_precision(env, regno);
8867 				if (ret)
8868 					return ret;
8869 			}
8870 			continue;
8871 		}
8872 
8873 		if (!btf_type_is_ptr(t)) {
8874 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8875 			return -EINVAL;
8876 		}
8877 
8878 		if (reg->ref_obj_id) {
8879 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
8880 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8881 					regno, reg->ref_obj_id,
8882 					meta->ref_obj_id);
8883 				return -EFAULT;
8884 			}
8885 			meta->ref_obj_id = reg->ref_obj_id;
8886 			if (is_kfunc_release(meta))
8887 				meta->release_regno = regno;
8888 		}
8889 
8890 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8891 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8892 
8893 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8894 		if (kf_arg_type < 0)
8895 			return kf_arg_type;
8896 
8897 		switch (kf_arg_type) {
8898 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8899 		case KF_ARG_PTR_TO_BTF_ID:
8900 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
8901 				break;
8902 
8903 			if (!is_trusted_reg(reg)) {
8904 				if (!is_kfunc_rcu(meta)) {
8905 					verbose(env, "R%d must be referenced or trusted\n", regno);
8906 					return -EINVAL;
8907 				}
8908 				if (!is_rcu_reg(reg)) {
8909 					verbose(env, "R%d must be a rcu pointer\n", regno);
8910 					return -EINVAL;
8911 				}
8912 			}
8913 
8914 			fallthrough;
8915 		case KF_ARG_PTR_TO_CTX:
8916 			/* Trusted arguments have the same offset checks as release arguments */
8917 			arg_type |= OBJ_RELEASE;
8918 			break;
8919 		case KF_ARG_PTR_TO_KPTR:
8920 		case KF_ARG_PTR_TO_DYNPTR:
8921 		case KF_ARG_PTR_TO_LIST_HEAD:
8922 		case KF_ARG_PTR_TO_LIST_NODE:
8923 		case KF_ARG_PTR_TO_MEM:
8924 		case KF_ARG_PTR_TO_MEM_SIZE:
8925 			/* Trusted by default */
8926 			break;
8927 		default:
8928 			WARN_ON_ONCE(1);
8929 			return -EFAULT;
8930 		}
8931 
8932 		if (is_kfunc_release(meta) && reg->ref_obj_id)
8933 			arg_type |= OBJ_RELEASE;
8934 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8935 		if (ret < 0)
8936 			return ret;
8937 
8938 		switch (kf_arg_type) {
8939 		case KF_ARG_PTR_TO_CTX:
8940 			if (reg->type != PTR_TO_CTX) {
8941 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8942 				return -EINVAL;
8943 			}
8944 
8945 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8946 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8947 				if (ret < 0)
8948 					return -EINVAL;
8949 				meta->ret_btf_id  = ret;
8950 			}
8951 			break;
8952 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8953 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8954 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
8955 				return -EINVAL;
8956 			}
8957 			if (!reg->ref_obj_id) {
8958 				verbose(env, "allocated object must be referenced\n");
8959 				return -EINVAL;
8960 			}
8961 			if (meta->btf == btf_vmlinux &&
8962 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8963 				meta->arg_obj_drop.btf = reg->btf;
8964 				meta->arg_obj_drop.btf_id = reg->btf_id;
8965 			}
8966 			break;
8967 		case KF_ARG_PTR_TO_KPTR:
8968 			if (reg->type != PTR_TO_MAP_VALUE) {
8969 				verbose(env, "arg#0 expected pointer to map value\n");
8970 				return -EINVAL;
8971 			}
8972 			ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8973 			if (ret < 0)
8974 				return ret;
8975 			break;
8976 		case KF_ARG_PTR_TO_DYNPTR:
8977 			if (reg->type != PTR_TO_STACK &&
8978 			    reg->type != CONST_PTR_TO_DYNPTR) {
8979 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
8980 				return -EINVAL;
8981 			}
8982 
8983 			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
8984 			if (ret < 0)
8985 				return ret;
8986 			break;
8987 		case KF_ARG_PTR_TO_LIST_HEAD:
8988 			if (reg->type != PTR_TO_MAP_VALUE &&
8989 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8990 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8991 				return -EINVAL;
8992 			}
8993 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
8994 				verbose(env, "allocated object must be referenced\n");
8995 				return -EINVAL;
8996 			}
8997 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
8998 			if (ret < 0)
8999 				return ret;
9000 			break;
9001 		case KF_ARG_PTR_TO_LIST_NODE:
9002 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9003 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
9004 				return -EINVAL;
9005 			}
9006 			if (!reg->ref_obj_id) {
9007 				verbose(env, "allocated object must be referenced\n");
9008 				return -EINVAL;
9009 			}
9010 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9011 			if (ret < 0)
9012 				return ret;
9013 			break;
9014 		case KF_ARG_PTR_TO_BTF_ID:
9015 			/* Only base_type is checked, further checks are done here */
9016 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
9017 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
9018 			    !reg2btf_ids[base_type(reg->type)]) {
9019 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
9020 				verbose(env, "expected %s or socket\n",
9021 					reg_type_str(env, base_type(reg->type) |
9022 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
9023 				return -EINVAL;
9024 			}
9025 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
9026 			if (ret < 0)
9027 				return ret;
9028 			break;
9029 		case KF_ARG_PTR_TO_MEM:
9030 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
9031 			if (IS_ERR(resolve_ret)) {
9032 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
9033 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
9034 				return -EINVAL;
9035 			}
9036 			ret = check_mem_reg(env, reg, regno, type_size);
9037 			if (ret < 0)
9038 				return ret;
9039 			break;
9040 		case KF_ARG_PTR_TO_MEM_SIZE:
9041 			ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
9042 			if (ret < 0) {
9043 				verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
9044 				return ret;
9045 			}
9046 			/* Skip next '__sz' argument */
9047 			i++;
9048 			break;
9049 		}
9050 	}
9051 
9052 	if (is_kfunc_release(meta) && !meta->release_regno) {
9053 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
9054 			func_name);
9055 		return -EINVAL;
9056 	}
9057 
9058 	return 0;
9059 }
9060 
9061 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9062 			    int *insn_idx_p)
9063 {
9064 	const struct btf_type *t, *func, *func_proto, *ptr_type;
9065 	struct bpf_reg_state *regs = cur_regs(env);
9066 	const char *func_name, *ptr_type_name;
9067 	bool sleepable, rcu_lock, rcu_unlock;
9068 	struct bpf_kfunc_call_arg_meta meta;
9069 	u32 i, nargs, func_id, ptr_type_id;
9070 	int err, insn_idx = *insn_idx_p;
9071 	const struct btf_param *args;
9072 	const struct btf_type *ret_t;
9073 	struct btf *desc_btf;
9074 	u32 *kfunc_flags;
9075 
9076 	/* skip for now, but return error when we find this in fixup_kfunc_call */
9077 	if (!insn->imm)
9078 		return 0;
9079 
9080 	desc_btf = find_kfunc_desc_btf(env, insn->off);
9081 	if (IS_ERR(desc_btf))
9082 		return PTR_ERR(desc_btf);
9083 
9084 	func_id = insn->imm;
9085 	func = btf_type_by_id(desc_btf, func_id);
9086 	func_name = btf_name_by_offset(desc_btf, func->name_off);
9087 	func_proto = btf_type_by_id(desc_btf, func->type);
9088 
9089 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
9090 	if (!kfunc_flags) {
9091 		verbose(env, "calling kernel function %s is not allowed\n",
9092 			func_name);
9093 		return -EACCES;
9094 	}
9095 
9096 	/* Prepare kfunc call metadata */
9097 	memset(&meta, 0, sizeof(meta));
9098 	meta.btf = desc_btf;
9099 	meta.func_id = func_id;
9100 	meta.kfunc_flags = *kfunc_flags;
9101 	meta.func_proto = func_proto;
9102 	meta.func_name = func_name;
9103 
9104 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
9105 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
9106 		return -EACCES;
9107 	}
9108 
9109 	sleepable = is_kfunc_sleepable(&meta);
9110 	if (sleepable && !env->prog->aux->sleepable) {
9111 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
9112 		return -EACCES;
9113 	}
9114 
9115 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
9116 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9117 	if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) {
9118 		verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name);
9119 		return -EACCES;
9120 	}
9121 
9122 	if (env->cur_state->active_rcu_lock) {
9123 		struct bpf_func_state *state;
9124 		struct bpf_reg_state *reg;
9125 
9126 		if (rcu_lock) {
9127 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
9128 			return -EINVAL;
9129 		} else if (rcu_unlock) {
9130 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9131 				if (reg->type & MEM_RCU) {
9132 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9133 					reg->type |= PTR_UNTRUSTED;
9134 				}
9135 			}));
9136 			env->cur_state->active_rcu_lock = false;
9137 		} else if (sleepable) {
9138 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
9139 			return -EACCES;
9140 		}
9141 	} else if (rcu_lock) {
9142 		env->cur_state->active_rcu_lock = true;
9143 	} else if (rcu_unlock) {
9144 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
9145 		return -EINVAL;
9146 	}
9147 
9148 	/* Check the arguments */
9149 	err = check_kfunc_args(env, &meta);
9150 	if (err < 0)
9151 		return err;
9152 	/* In case of release function, we get register number of refcounted
9153 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
9154 	 */
9155 	if (meta.release_regno) {
9156 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
9157 		if (err) {
9158 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
9159 				func_name, func_id);
9160 			return err;
9161 		}
9162 	}
9163 
9164 	for (i = 0; i < CALLER_SAVED_REGS; i++)
9165 		mark_reg_not_init(env, regs, caller_saved[i]);
9166 
9167 	/* Check return type */
9168 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
9169 
9170 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
9171 		/* Only exception is bpf_obj_new_impl */
9172 		if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
9173 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
9174 			return -EINVAL;
9175 		}
9176 	}
9177 
9178 	if (btf_type_is_scalar(t)) {
9179 		mark_reg_unknown(env, regs, BPF_REG_0);
9180 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
9181 	} else if (btf_type_is_ptr(t)) {
9182 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
9183 
9184 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
9185 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
9186 				struct btf *ret_btf;
9187 				u32 ret_btf_id;
9188 
9189 				if (unlikely(!bpf_global_ma_set))
9190 					return -ENOMEM;
9191 
9192 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
9193 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
9194 					return -EINVAL;
9195 				}
9196 
9197 				ret_btf = env->prog->aux->btf;
9198 				ret_btf_id = meta.arg_constant.value;
9199 
9200 				/* This may be NULL due to user not supplying a BTF */
9201 				if (!ret_btf) {
9202 					verbose(env, "bpf_obj_new requires prog BTF\n");
9203 					return -EINVAL;
9204 				}
9205 
9206 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
9207 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
9208 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
9209 					return -EINVAL;
9210 				}
9211 
9212 				mark_reg_known_zero(env, regs, BPF_REG_0);
9213 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9214 				regs[BPF_REG_0].btf = ret_btf;
9215 				regs[BPF_REG_0].btf_id = ret_btf_id;
9216 
9217 				env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
9218 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9219 					btf_find_struct_meta(ret_btf, ret_btf_id);
9220 			} else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9221 				env->insn_aux_data[insn_idx].kptr_struct_meta =
9222 					btf_find_struct_meta(meta.arg_obj_drop.btf,
9223 							     meta.arg_obj_drop.btf_id);
9224 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9225 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
9226 				struct btf_field *field = meta.arg_list_head.field;
9227 
9228 				mark_reg_known_zero(env, regs, BPF_REG_0);
9229 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
9230 				regs[BPF_REG_0].btf = field->list_head.btf;
9231 				regs[BPF_REG_0].btf_id = field->list_head.value_btf_id;
9232 				regs[BPF_REG_0].off = field->list_head.node_offset;
9233 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9234 				mark_reg_known_zero(env, regs, BPF_REG_0);
9235 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
9236 				regs[BPF_REG_0].btf = desc_btf;
9237 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9238 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
9239 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
9240 				if (!ret_t || !btf_type_is_struct(ret_t)) {
9241 					verbose(env,
9242 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
9243 					return -EINVAL;
9244 				}
9245 
9246 				mark_reg_known_zero(env, regs, BPF_REG_0);
9247 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
9248 				regs[BPF_REG_0].btf = desc_btf;
9249 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
9250 			} else {
9251 				verbose(env, "kernel function %s unhandled dynamic return type\n",
9252 					meta.func_name);
9253 				return -EFAULT;
9254 			}
9255 		} else if (!__btf_type_is_struct(ptr_type)) {
9256 			if (!meta.r0_size) {
9257 				ptr_type_name = btf_name_by_offset(desc_btf,
9258 								   ptr_type->name_off);
9259 				verbose(env,
9260 					"kernel function %s returns pointer type %s %s is not supported\n",
9261 					func_name,
9262 					btf_type_str(ptr_type),
9263 					ptr_type_name);
9264 				return -EINVAL;
9265 			}
9266 
9267 			mark_reg_known_zero(env, regs, BPF_REG_0);
9268 			regs[BPF_REG_0].type = PTR_TO_MEM;
9269 			regs[BPF_REG_0].mem_size = meta.r0_size;
9270 
9271 			if (meta.r0_rdonly)
9272 				regs[BPF_REG_0].type |= MEM_RDONLY;
9273 
9274 			/* Ensures we don't access the memory after a release_reference() */
9275 			if (meta.ref_obj_id)
9276 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9277 		} else {
9278 			mark_reg_known_zero(env, regs, BPF_REG_0);
9279 			regs[BPF_REG_0].btf = desc_btf;
9280 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
9281 			regs[BPF_REG_0].btf_id = ptr_type_id;
9282 		}
9283 
9284 		if (is_kfunc_ret_null(&meta)) {
9285 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9286 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9287 			regs[BPF_REG_0].id = ++env->id_gen;
9288 		}
9289 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9290 		if (is_kfunc_acquire(&meta)) {
9291 			int id = acquire_reference_state(env, insn_idx);
9292 
9293 			if (id < 0)
9294 				return id;
9295 			if (is_kfunc_ret_null(&meta))
9296 				regs[BPF_REG_0].id = id;
9297 			regs[BPF_REG_0].ref_obj_id = id;
9298 		}
9299 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9300 			regs[BPF_REG_0].id = ++env->id_gen;
9301 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9302 
9303 	nargs = btf_type_vlen(func_proto);
9304 	args = (const struct btf_param *)(func_proto + 1);
9305 	for (i = 0; i < nargs; i++) {
9306 		u32 regno = i + 1;
9307 
9308 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9309 		if (btf_type_is_ptr(t))
9310 			mark_btf_func_reg_size(env, regno, sizeof(void *));
9311 		else
9312 			/* scalar. ensured by btf_check_kfunc_arg_match() */
9313 			mark_btf_func_reg_size(env, regno, t->size);
9314 	}
9315 
9316 	return 0;
9317 }
9318 
9319 static bool signed_add_overflows(s64 a, s64 b)
9320 {
9321 	/* Do the add in u64, where overflow is well-defined */
9322 	s64 res = (s64)((u64)a + (u64)b);
9323 
9324 	if (b < 0)
9325 		return res > a;
9326 	return res < a;
9327 }
9328 
9329 static bool signed_add32_overflows(s32 a, s32 b)
9330 {
9331 	/* Do the add in u32, where overflow is well-defined */
9332 	s32 res = (s32)((u32)a + (u32)b);
9333 
9334 	if (b < 0)
9335 		return res > a;
9336 	return res < a;
9337 }
9338 
9339 static bool signed_sub_overflows(s64 a, s64 b)
9340 {
9341 	/* Do the sub in u64, where overflow is well-defined */
9342 	s64 res = (s64)((u64)a - (u64)b);
9343 
9344 	if (b < 0)
9345 		return res < a;
9346 	return res > a;
9347 }
9348 
9349 static bool signed_sub32_overflows(s32 a, s32 b)
9350 {
9351 	/* Do the sub in u32, where overflow is well-defined */
9352 	s32 res = (s32)((u32)a - (u32)b);
9353 
9354 	if (b < 0)
9355 		return res < a;
9356 	return res > a;
9357 }
9358 
9359 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9360 				  const struct bpf_reg_state *reg,
9361 				  enum bpf_reg_type type)
9362 {
9363 	bool known = tnum_is_const(reg->var_off);
9364 	s64 val = reg->var_off.value;
9365 	s64 smin = reg->smin_value;
9366 
9367 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9368 		verbose(env, "math between %s pointer and %lld is not allowed\n",
9369 			reg_type_str(env, type), val);
9370 		return false;
9371 	}
9372 
9373 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9374 		verbose(env, "%s pointer offset %d is not allowed\n",
9375 			reg_type_str(env, type), reg->off);
9376 		return false;
9377 	}
9378 
9379 	if (smin == S64_MIN) {
9380 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9381 			reg_type_str(env, type));
9382 		return false;
9383 	}
9384 
9385 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9386 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
9387 			smin, reg_type_str(env, type));
9388 		return false;
9389 	}
9390 
9391 	return true;
9392 }
9393 
9394 enum {
9395 	REASON_BOUNDS	= -1,
9396 	REASON_TYPE	= -2,
9397 	REASON_PATHS	= -3,
9398 	REASON_LIMIT	= -4,
9399 	REASON_STACK	= -5,
9400 };
9401 
9402 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9403 			      u32 *alu_limit, bool mask_to_left)
9404 {
9405 	u32 max = 0, ptr_limit = 0;
9406 
9407 	switch (ptr_reg->type) {
9408 	case PTR_TO_STACK:
9409 		/* Offset 0 is out-of-bounds, but acceptable start for the
9410 		 * left direction, see BPF_REG_FP. Also, unknown scalar
9411 		 * offset where we would need to deal with min/max bounds is
9412 		 * currently prohibited for unprivileged.
9413 		 */
9414 		max = MAX_BPF_STACK + mask_to_left;
9415 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9416 		break;
9417 	case PTR_TO_MAP_VALUE:
9418 		max = ptr_reg->map_ptr->value_size;
9419 		ptr_limit = (mask_to_left ?
9420 			     ptr_reg->smin_value :
9421 			     ptr_reg->umax_value) + ptr_reg->off;
9422 		break;
9423 	default:
9424 		return REASON_TYPE;
9425 	}
9426 
9427 	if (ptr_limit >= max)
9428 		return REASON_LIMIT;
9429 	*alu_limit = ptr_limit;
9430 	return 0;
9431 }
9432 
9433 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9434 				    const struct bpf_insn *insn)
9435 {
9436 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9437 }
9438 
9439 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9440 				       u32 alu_state, u32 alu_limit)
9441 {
9442 	/* If we arrived here from different branches with different
9443 	 * state or limits to sanitize, then this won't work.
9444 	 */
9445 	if (aux->alu_state &&
9446 	    (aux->alu_state != alu_state ||
9447 	     aux->alu_limit != alu_limit))
9448 		return REASON_PATHS;
9449 
9450 	/* Corresponding fixup done in do_misc_fixups(). */
9451 	aux->alu_state = alu_state;
9452 	aux->alu_limit = alu_limit;
9453 	return 0;
9454 }
9455 
9456 static int sanitize_val_alu(struct bpf_verifier_env *env,
9457 			    struct bpf_insn *insn)
9458 {
9459 	struct bpf_insn_aux_data *aux = cur_aux(env);
9460 
9461 	if (can_skip_alu_sanitation(env, insn))
9462 		return 0;
9463 
9464 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9465 }
9466 
9467 static bool sanitize_needed(u8 opcode)
9468 {
9469 	return opcode == BPF_ADD || opcode == BPF_SUB;
9470 }
9471 
9472 struct bpf_sanitize_info {
9473 	struct bpf_insn_aux_data aux;
9474 	bool mask_to_left;
9475 };
9476 
9477 static struct bpf_verifier_state *
9478 sanitize_speculative_path(struct bpf_verifier_env *env,
9479 			  const struct bpf_insn *insn,
9480 			  u32 next_idx, u32 curr_idx)
9481 {
9482 	struct bpf_verifier_state *branch;
9483 	struct bpf_reg_state *regs;
9484 
9485 	branch = push_stack(env, next_idx, curr_idx, true);
9486 	if (branch && insn) {
9487 		regs = branch->frame[branch->curframe]->regs;
9488 		if (BPF_SRC(insn->code) == BPF_K) {
9489 			mark_reg_unknown(env, regs, insn->dst_reg);
9490 		} else if (BPF_SRC(insn->code) == BPF_X) {
9491 			mark_reg_unknown(env, regs, insn->dst_reg);
9492 			mark_reg_unknown(env, regs, insn->src_reg);
9493 		}
9494 	}
9495 	return branch;
9496 }
9497 
9498 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9499 			    struct bpf_insn *insn,
9500 			    const struct bpf_reg_state *ptr_reg,
9501 			    const struct bpf_reg_state *off_reg,
9502 			    struct bpf_reg_state *dst_reg,
9503 			    struct bpf_sanitize_info *info,
9504 			    const bool commit_window)
9505 {
9506 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9507 	struct bpf_verifier_state *vstate = env->cur_state;
9508 	bool off_is_imm = tnum_is_const(off_reg->var_off);
9509 	bool off_is_neg = off_reg->smin_value < 0;
9510 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
9511 	u8 opcode = BPF_OP(insn->code);
9512 	u32 alu_state, alu_limit;
9513 	struct bpf_reg_state tmp;
9514 	bool ret;
9515 	int err;
9516 
9517 	if (can_skip_alu_sanitation(env, insn))
9518 		return 0;
9519 
9520 	/* We already marked aux for masking from non-speculative
9521 	 * paths, thus we got here in the first place. We only care
9522 	 * to explore bad access from here.
9523 	 */
9524 	if (vstate->speculative)
9525 		goto do_sim;
9526 
9527 	if (!commit_window) {
9528 		if (!tnum_is_const(off_reg->var_off) &&
9529 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9530 			return REASON_BOUNDS;
9531 
9532 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
9533 				     (opcode == BPF_SUB && !off_is_neg);
9534 	}
9535 
9536 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9537 	if (err < 0)
9538 		return err;
9539 
9540 	if (commit_window) {
9541 		/* In commit phase we narrow the masking window based on
9542 		 * the observed pointer move after the simulated operation.
9543 		 */
9544 		alu_state = info->aux.alu_state;
9545 		alu_limit = abs(info->aux.alu_limit - alu_limit);
9546 	} else {
9547 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9548 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9549 		alu_state |= ptr_is_dst_reg ?
9550 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9551 
9552 		/* Limit pruning on unknown scalars to enable deep search for
9553 		 * potential masking differences from other program paths.
9554 		 */
9555 		if (!off_is_imm)
9556 			env->explore_alu_limits = true;
9557 	}
9558 
9559 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9560 	if (err < 0)
9561 		return err;
9562 do_sim:
9563 	/* If we're in commit phase, we're done here given we already
9564 	 * pushed the truncated dst_reg into the speculative verification
9565 	 * stack.
9566 	 *
9567 	 * Also, when register is a known constant, we rewrite register-based
9568 	 * operation to immediate-based, and thus do not need masking (and as
9569 	 * a consequence, do not need to simulate the zero-truncation either).
9570 	 */
9571 	if (commit_window || off_is_imm)
9572 		return 0;
9573 
9574 	/* Simulate and find potential out-of-bounds access under
9575 	 * speculative execution from truncation as a result of
9576 	 * masking when off was not within expected range. If off
9577 	 * sits in dst, then we temporarily need to move ptr there
9578 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9579 	 * for cases where we use K-based arithmetic in one direction
9580 	 * and truncated reg-based in the other in order to explore
9581 	 * bad access.
9582 	 */
9583 	if (!ptr_is_dst_reg) {
9584 		tmp = *dst_reg;
9585 		*dst_reg = *ptr_reg;
9586 	}
9587 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9588 					env->insn_idx);
9589 	if (!ptr_is_dst_reg && ret)
9590 		*dst_reg = tmp;
9591 	return !ret ? REASON_STACK : 0;
9592 }
9593 
9594 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9595 {
9596 	struct bpf_verifier_state *vstate = env->cur_state;
9597 
9598 	/* If we simulate paths under speculation, we don't update the
9599 	 * insn as 'seen' such that when we verify unreachable paths in
9600 	 * the non-speculative domain, sanitize_dead_code() can still
9601 	 * rewrite/sanitize them.
9602 	 */
9603 	if (!vstate->speculative)
9604 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9605 }
9606 
9607 static int sanitize_err(struct bpf_verifier_env *env,
9608 			const struct bpf_insn *insn, int reason,
9609 			const struct bpf_reg_state *off_reg,
9610 			const struct bpf_reg_state *dst_reg)
9611 {
9612 	static const char *err = "pointer arithmetic with it prohibited for !root";
9613 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9614 	u32 dst = insn->dst_reg, src = insn->src_reg;
9615 
9616 	switch (reason) {
9617 	case REASON_BOUNDS:
9618 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9619 			off_reg == dst_reg ? dst : src, err);
9620 		break;
9621 	case REASON_TYPE:
9622 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9623 			off_reg == dst_reg ? src : dst, err);
9624 		break;
9625 	case REASON_PATHS:
9626 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9627 			dst, op, err);
9628 		break;
9629 	case REASON_LIMIT:
9630 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9631 			dst, op, err);
9632 		break;
9633 	case REASON_STACK:
9634 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9635 			dst, err);
9636 		break;
9637 	default:
9638 		verbose(env, "verifier internal error: unknown reason (%d)\n",
9639 			reason);
9640 		break;
9641 	}
9642 
9643 	return -EACCES;
9644 }
9645 
9646 /* check that stack access falls within stack limits and that 'reg' doesn't
9647  * have a variable offset.
9648  *
9649  * Variable offset is prohibited for unprivileged mode for simplicity since it
9650  * requires corresponding support in Spectre masking for stack ALU.  See also
9651  * retrieve_ptr_limit().
9652  *
9653  *
9654  * 'off' includes 'reg->off'.
9655  */
9656 static int check_stack_access_for_ptr_arithmetic(
9657 				struct bpf_verifier_env *env,
9658 				int regno,
9659 				const struct bpf_reg_state *reg,
9660 				int off)
9661 {
9662 	if (!tnum_is_const(reg->var_off)) {
9663 		char tn_buf[48];
9664 
9665 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9666 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9667 			regno, tn_buf, off);
9668 		return -EACCES;
9669 	}
9670 
9671 	if (off >= 0 || off < -MAX_BPF_STACK) {
9672 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
9673 			"prohibited for !root; off=%d\n", regno, off);
9674 		return -EACCES;
9675 	}
9676 
9677 	return 0;
9678 }
9679 
9680 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9681 				 const struct bpf_insn *insn,
9682 				 const struct bpf_reg_state *dst_reg)
9683 {
9684 	u32 dst = insn->dst_reg;
9685 
9686 	/* For unprivileged we require that resulting offset must be in bounds
9687 	 * in order to be able to sanitize access later on.
9688 	 */
9689 	if (env->bypass_spec_v1)
9690 		return 0;
9691 
9692 	switch (dst_reg->type) {
9693 	case PTR_TO_STACK:
9694 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9695 					dst_reg->off + dst_reg->var_off.value))
9696 			return -EACCES;
9697 		break;
9698 	case PTR_TO_MAP_VALUE:
9699 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9700 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9701 				"prohibited for !root\n", dst);
9702 			return -EACCES;
9703 		}
9704 		break;
9705 	default:
9706 		break;
9707 	}
9708 
9709 	return 0;
9710 }
9711 
9712 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9713  * Caller should also handle BPF_MOV case separately.
9714  * If we return -EACCES, caller may want to try again treating pointer as a
9715  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
9716  */
9717 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9718 				   struct bpf_insn *insn,
9719 				   const struct bpf_reg_state *ptr_reg,
9720 				   const struct bpf_reg_state *off_reg)
9721 {
9722 	struct bpf_verifier_state *vstate = env->cur_state;
9723 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9724 	struct bpf_reg_state *regs = state->regs, *dst_reg;
9725 	bool known = tnum_is_const(off_reg->var_off);
9726 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9727 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9728 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9729 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9730 	struct bpf_sanitize_info info = {};
9731 	u8 opcode = BPF_OP(insn->code);
9732 	u32 dst = insn->dst_reg;
9733 	int ret;
9734 
9735 	dst_reg = &regs[dst];
9736 
9737 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9738 	    smin_val > smax_val || umin_val > umax_val) {
9739 		/* Taint dst register if offset had invalid bounds derived from
9740 		 * e.g. dead branches.
9741 		 */
9742 		__mark_reg_unknown(env, dst_reg);
9743 		return 0;
9744 	}
9745 
9746 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
9747 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
9748 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9749 			__mark_reg_unknown(env, dst_reg);
9750 			return 0;
9751 		}
9752 
9753 		verbose(env,
9754 			"R%d 32-bit pointer arithmetic prohibited\n",
9755 			dst);
9756 		return -EACCES;
9757 	}
9758 
9759 	if (ptr_reg->type & PTR_MAYBE_NULL) {
9760 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9761 			dst, reg_type_str(env, ptr_reg->type));
9762 		return -EACCES;
9763 	}
9764 
9765 	switch (base_type(ptr_reg->type)) {
9766 	case CONST_PTR_TO_MAP:
9767 		/* smin_val represents the known value */
9768 		if (known && smin_val == 0 && opcode == BPF_ADD)
9769 			break;
9770 		fallthrough;
9771 	case PTR_TO_PACKET_END:
9772 	case PTR_TO_SOCKET:
9773 	case PTR_TO_SOCK_COMMON:
9774 	case PTR_TO_TCP_SOCK:
9775 	case PTR_TO_XDP_SOCK:
9776 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9777 			dst, reg_type_str(env, ptr_reg->type));
9778 		return -EACCES;
9779 	default:
9780 		break;
9781 	}
9782 
9783 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9784 	 * The id may be overwritten later if we create a new variable offset.
9785 	 */
9786 	dst_reg->type = ptr_reg->type;
9787 	dst_reg->id = ptr_reg->id;
9788 
9789 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9790 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9791 		return -EINVAL;
9792 
9793 	/* pointer types do not carry 32-bit bounds at the moment. */
9794 	__mark_reg32_unbounded(dst_reg);
9795 
9796 	if (sanitize_needed(opcode)) {
9797 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9798 				       &info, false);
9799 		if (ret < 0)
9800 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9801 	}
9802 
9803 	switch (opcode) {
9804 	case BPF_ADD:
9805 		/* We can take a fixed offset as long as it doesn't overflow
9806 		 * the s32 'off' field
9807 		 */
9808 		if (known && (ptr_reg->off + smin_val ==
9809 			      (s64)(s32)(ptr_reg->off + smin_val))) {
9810 			/* pointer += K.  Accumulate it into fixed offset */
9811 			dst_reg->smin_value = smin_ptr;
9812 			dst_reg->smax_value = smax_ptr;
9813 			dst_reg->umin_value = umin_ptr;
9814 			dst_reg->umax_value = umax_ptr;
9815 			dst_reg->var_off = ptr_reg->var_off;
9816 			dst_reg->off = ptr_reg->off + smin_val;
9817 			dst_reg->raw = ptr_reg->raw;
9818 			break;
9819 		}
9820 		/* A new variable offset is created.  Note that off_reg->off
9821 		 * == 0, since it's a scalar.
9822 		 * dst_reg gets the pointer type and since some positive
9823 		 * integer value was added to the pointer, give it a new 'id'
9824 		 * if it's a PTR_TO_PACKET.
9825 		 * this creates a new 'base' pointer, off_reg (variable) gets
9826 		 * added into the variable offset, and we copy the fixed offset
9827 		 * from ptr_reg.
9828 		 */
9829 		if (signed_add_overflows(smin_ptr, smin_val) ||
9830 		    signed_add_overflows(smax_ptr, smax_val)) {
9831 			dst_reg->smin_value = S64_MIN;
9832 			dst_reg->smax_value = S64_MAX;
9833 		} else {
9834 			dst_reg->smin_value = smin_ptr + smin_val;
9835 			dst_reg->smax_value = smax_ptr + smax_val;
9836 		}
9837 		if (umin_ptr + umin_val < umin_ptr ||
9838 		    umax_ptr + umax_val < umax_ptr) {
9839 			dst_reg->umin_value = 0;
9840 			dst_reg->umax_value = U64_MAX;
9841 		} else {
9842 			dst_reg->umin_value = umin_ptr + umin_val;
9843 			dst_reg->umax_value = umax_ptr + umax_val;
9844 		}
9845 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9846 		dst_reg->off = ptr_reg->off;
9847 		dst_reg->raw = ptr_reg->raw;
9848 		if (reg_is_pkt_pointer(ptr_reg)) {
9849 			dst_reg->id = ++env->id_gen;
9850 			/* something was added to pkt_ptr, set range to zero */
9851 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9852 		}
9853 		break;
9854 	case BPF_SUB:
9855 		if (dst_reg == off_reg) {
9856 			/* scalar -= pointer.  Creates an unknown scalar */
9857 			verbose(env, "R%d tried to subtract pointer from scalar\n",
9858 				dst);
9859 			return -EACCES;
9860 		}
9861 		/* We don't allow subtraction from FP, because (according to
9862 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
9863 		 * be able to deal with it.
9864 		 */
9865 		if (ptr_reg->type == PTR_TO_STACK) {
9866 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
9867 				dst);
9868 			return -EACCES;
9869 		}
9870 		if (known && (ptr_reg->off - smin_val ==
9871 			      (s64)(s32)(ptr_reg->off - smin_val))) {
9872 			/* pointer -= K.  Subtract it from fixed offset */
9873 			dst_reg->smin_value = smin_ptr;
9874 			dst_reg->smax_value = smax_ptr;
9875 			dst_reg->umin_value = umin_ptr;
9876 			dst_reg->umax_value = umax_ptr;
9877 			dst_reg->var_off = ptr_reg->var_off;
9878 			dst_reg->id = ptr_reg->id;
9879 			dst_reg->off = ptr_reg->off - smin_val;
9880 			dst_reg->raw = ptr_reg->raw;
9881 			break;
9882 		}
9883 		/* A new variable offset is created.  If the subtrahend is known
9884 		 * nonnegative, then any reg->range we had before is still good.
9885 		 */
9886 		if (signed_sub_overflows(smin_ptr, smax_val) ||
9887 		    signed_sub_overflows(smax_ptr, smin_val)) {
9888 			/* Overflow possible, we know nothing */
9889 			dst_reg->smin_value = S64_MIN;
9890 			dst_reg->smax_value = S64_MAX;
9891 		} else {
9892 			dst_reg->smin_value = smin_ptr - smax_val;
9893 			dst_reg->smax_value = smax_ptr - smin_val;
9894 		}
9895 		if (umin_ptr < umax_val) {
9896 			/* Overflow possible, we know nothing */
9897 			dst_reg->umin_value = 0;
9898 			dst_reg->umax_value = U64_MAX;
9899 		} else {
9900 			/* Cannot overflow (as long as bounds are consistent) */
9901 			dst_reg->umin_value = umin_ptr - umax_val;
9902 			dst_reg->umax_value = umax_ptr - umin_val;
9903 		}
9904 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9905 		dst_reg->off = ptr_reg->off;
9906 		dst_reg->raw = ptr_reg->raw;
9907 		if (reg_is_pkt_pointer(ptr_reg)) {
9908 			dst_reg->id = ++env->id_gen;
9909 			/* something was added to pkt_ptr, set range to zero */
9910 			if (smin_val < 0)
9911 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9912 		}
9913 		break;
9914 	case BPF_AND:
9915 	case BPF_OR:
9916 	case BPF_XOR:
9917 		/* bitwise ops on pointers are troublesome, prohibit. */
9918 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9919 			dst, bpf_alu_string[opcode >> 4]);
9920 		return -EACCES;
9921 	default:
9922 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
9923 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9924 			dst, bpf_alu_string[opcode >> 4]);
9925 		return -EACCES;
9926 	}
9927 
9928 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9929 		return -EINVAL;
9930 	reg_bounds_sync(dst_reg);
9931 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9932 		return -EACCES;
9933 	if (sanitize_needed(opcode)) {
9934 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9935 				       &info, true);
9936 		if (ret < 0)
9937 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
9938 	}
9939 
9940 	return 0;
9941 }
9942 
9943 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9944 				 struct bpf_reg_state *src_reg)
9945 {
9946 	s32 smin_val = src_reg->s32_min_value;
9947 	s32 smax_val = src_reg->s32_max_value;
9948 	u32 umin_val = src_reg->u32_min_value;
9949 	u32 umax_val = src_reg->u32_max_value;
9950 
9951 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9952 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9953 		dst_reg->s32_min_value = S32_MIN;
9954 		dst_reg->s32_max_value = S32_MAX;
9955 	} else {
9956 		dst_reg->s32_min_value += smin_val;
9957 		dst_reg->s32_max_value += smax_val;
9958 	}
9959 	if (dst_reg->u32_min_value + umin_val < umin_val ||
9960 	    dst_reg->u32_max_value + umax_val < umax_val) {
9961 		dst_reg->u32_min_value = 0;
9962 		dst_reg->u32_max_value = U32_MAX;
9963 	} else {
9964 		dst_reg->u32_min_value += umin_val;
9965 		dst_reg->u32_max_value += umax_val;
9966 	}
9967 }
9968 
9969 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9970 			       struct bpf_reg_state *src_reg)
9971 {
9972 	s64 smin_val = src_reg->smin_value;
9973 	s64 smax_val = src_reg->smax_value;
9974 	u64 umin_val = src_reg->umin_value;
9975 	u64 umax_val = src_reg->umax_value;
9976 
9977 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9978 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
9979 		dst_reg->smin_value = S64_MIN;
9980 		dst_reg->smax_value = S64_MAX;
9981 	} else {
9982 		dst_reg->smin_value += smin_val;
9983 		dst_reg->smax_value += smax_val;
9984 	}
9985 	if (dst_reg->umin_value + umin_val < umin_val ||
9986 	    dst_reg->umax_value + umax_val < umax_val) {
9987 		dst_reg->umin_value = 0;
9988 		dst_reg->umax_value = U64_MAX;
9989 	} else {
9990 		dst_reg->umin_value += umin_val;
9991 		dst_reg->umax_value += umax_val;
9992 	}
9993 }
9994 
9995 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
9996 				 struct bpf_reg_state *src_reg)
9997 {
9998 	s32 smin_val = src_reg->s32_min_value;
9999 	s32 smax_val = src_reg->s32_max_value;
10000 	u32 umin_val = src_reg->u32_min_value;
10001 	u32 umax_val = src_reg->u32_max_value;
10002 
10003 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
10004 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
10005 		/* Overflow possible, we know nothing */
10006 		dst_reg->s32_min_value = S32_MIN;
10007 		dst_reg->s32_max_value = S32_MAX;
10008 	} else {
10009 		dst_reg->s32_min_value -= smax_val;
10010 		dst_reg->s32_max_value -= smin_val;
10011 	}
10012 	if (dst_reg->u32_min_value < umax_val) {
10013 		/* Overflow possible, we know nothing */
10014 		dst_reg->u32_min_value = 0;
10015 		dst_reg->u32_max_value = U32_MAX;
10016 	} else {
10017 		/* Cannot overflow (as long as bounds are consistent) */
10018 		dst_reg->u32_min_value -= umax_val;
10019 		dst_reg->u32_max_value -= umin_val;
10020 	}
10021 }
10022 
10023 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
10024 			       struct bpf_reg_state *src_reg)
10025 {
10026 	s64 smin_val = src_reg->smin_value;
10027 	s64 smax_val = src_reg->smax_value;
10028 	u64 umin_val = src_reg->umin_value;
10029 	u64 umax_val = src_reg->umax_value;
10030 
10031 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
10032 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
10033 		/* Overflow possible, we know nothing */
10034 		dst_reg->smin_value = S64_MIN;
10035 		dst_reg->smax_value = S64_MAX;
10036 	} else {
10037 		dst_reg->smin_value -= smax_val;
10038 		dst_reg->smax_value -= smin_val;
10039 	}
10040 	if (dst_reg->umin_value < umax_val) {
10041 		/* Overflow possible, we know nothing */
10042 		dst_reg->umin_value = 0;
10043 		dst_reg->umax_value = U64_MAX;
10044 	} else {
10045 		/* Cannot overflow (as long as bounds are consistent) */
10046 		dst_reg->umin_value -= umax_val;
10047 		dst_reg->umax_value -= umin_val;
10048 	}
10049 }
10050 
10051 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
10052 				 struct bpf_reg_state *src_reg)
10053 {
10054 	s32 smin_val = src_reg->s32_min_value;
10055 	u32 umin_val = src_reg->u32_min_value;
10056 	u32 umax_val = src_reg->u32_max_value;
10057 
10058 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
10059 		/* Ain't nobody got time to multiply that sign */
10060 		__mark_reg32_unbounded(dst_reg);
10061 		return;
10062 	}
10063 	/* Both values are positive, so we can work with unsigned and
10064 	 * copy the result to signed (unless it exceeds S32_MAX).
10065 	 */
10066 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
10067 		/* Potential overflow, we know nothing */
10068 		__mark_reg32_unbounded(dst_reg);
10069 		return;
10070 	}
10071 	dst_reg->u32_min_value *= umin_val;
10072 	dst_reg->u32_max_value *= umax_val;
10073 	if (dst_reg->u32_max_value > S32_MAX) {
10074 		/* Overflow possible, we know nothing */
10075 		dst_reg->s32_min_value = S32_MIN;
10076 		dst_reg->s32_max_value = S32_MAX;
10077 	} else {
10078 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10079 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10080 	}
10081 }
10082 
10083 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
10084 			       struct bpf_reg_state *src_reg)
10085 {
10086 	s64 smin_val = src_reg->smin_value;
10087 	u64 umin_val = src_reg->umin_value;
10088 	u64 umax_val = src_reg->umax_value;
10089 
10090 	if (smin_val < 0 || dst_reg->smin_value < 0) {
10091 		/* Ain't nobody got time to multiply that sign */
10092 		__mark_reg64_unbounded(dst_reg);
10093 		return;
10094 	}
10095 	/* Both values are positive, so we can work with unsigned and
10096 	 * copy the result to signed (unless it exceeds S64_MAX).
10097 	 */
10098 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
10099 		/* Potential overflow, we know nothing */
10100 		__mark_reg64_unbounded(dst_reg);
10101 		return;
10102 	}
10103 	dst_reg->umin_value *= umin_val;
10104 	dst_reg->umax_value *= umax_val;
10105 	if (dst_reg->umax_value > S64_MAX) {
10106 		/* Overflow possible, we know nothing */
10107 		dst_reg->smin_value = S64_MIN;
10108 		dst_reg->smax_value = S64_MAX;
10109 	} else {
10110 		dst_reg->smin_value = dst_reg->umin_value;
10111 		dst_reg->smax_value = dst_reg->umax_value;
10112 	}
10113 }
10114 
10115 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
10116 				 struct bpf_reg_state *src_reg)
10117 {
10118 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10119 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10120 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10121 	s32 smin_val = src_reg->s32_min_value;
10122 	u32 umax_val = src_reg->u32_max_value;
10123 
10124 	if (src_known && dst_known) {
10125 		__mark_reg32_known(dst_reg, var32_off.value);
10126 		return;
10127 	}
10128 
10129 	/* We get our minimum from the var_off, since that's inherently
10130 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10131 	 */
10132 	dst_reg->u32_min_value = var32_off.value;
10133 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
10134 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10135 		/* Lose signed bounds when ANDing negative numbers,
10136 		 * ain't nobody got time for that.
10137 		 */
10138 		dst_reg->s32_min_value = S32_MIN;
10139 		dst_reg->s32_max_value = S32_MAX;
10140 	} else {
10141 		/* ANDing two positives gives a positive, so safe to
10142 		 * cast result into s64.
10143 		 */
10144 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10145 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10146 	}
10147 }
10148 
10149 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
10150 			       struct bpf_reg_state *src_reg)
10151 {
10152 	bool src_known = tnum_is_const(src_reg->var_off);
10153 	bool dst_known = tnum_is_const(dst_reg->var_off);
10154 	s64 smin_val = src_reg->smin_value;
10155 	u64 umax_val = src_reg->umax_value;
10156 
10157 	if (src_known && dst_known) {
10158 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10159 		return;
10160 	}
10161 
10162 	/* We get our minimum from the var_off, since that's inherently
10163 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
10164 	 */
10165 	dst_reg->umin_value = dst_reg->var_off.value;
10166 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
10167 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10168 		/* Lose signed bounds when ANDing negative numbers,
10169 		 * ain't nobody got time for that.
10170 		 */
10171 		dst_reg->smin_value = S64_MIN;
10172 		dst_reg->smax_value = S64_MAX;
10173 	} else {
10174 		/* ANDing two positives gives a positive, so safe to
10175 		 * cast result into s64.
10176 		 */
10177 		dst_reg->smin_value = dst_reg->umin_value;
10178 		dst_reg->smax_value = dst_reg->umax_value;
10179 	}
10180 	/* We may learn something more from the var_off */
10181 	__update_reg_bounds(dst_reg);
10182 }
10183 
10184 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
10185 				struct bpf_reg_state *src_reg)
10186 {
10187 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10188 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10189 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10190 	s32 smin_val = src_reg->s32_min_value;
10191 	u32 umin_val = src_reg->u32_min_value;
10192 
10193 	if (src_known && dst_known) {
10194 		__mark_reg32_known(dst_reg, var32_off.value);
10195 		return;
10196 	}
10197 
10198 	/* We get our maximum from the var_off, and our minimum is the
10199 	 * maximum of the operands' minima
10200 	 */
10201 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
10202 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10203 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
10204 		/* Lose signed bounds when ORing negative numbers,
10205 		 * ain't nobody got time for that.
10206 		 */
10207 		dst_reg->s32_min_value = S32_MIN;
10208 		dst_reg->s32_max_value = S32_MAX;
10209 	} else {
10210 		/* ORing two positives gives a positive, so safe to
10211 		 * cast result into s64.
10212 		 */
10213 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10214 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10215 	}
10216 }
10217 
10218 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
10219 			      struct bpf_reg_state *src_reg)
10220 {
10221 	bool src_known = tnum_is_const(src_reg->var_off);
10222 	bool dst_known = tnum_is_const(dst_reg->var_off);
10223 	s64 smin_val = src_reg->smin_value;
10224 	u64 umin_val = src_reg->umin_value;
10225 
10226 	if (src_known && dst_known) {
10227 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10228 		return;
10229 	}
10230 
10231 	/* We get our maximum from the var_off, and our minimum is the
10232 	 * maximum of the operands' minima
10233 	 */
10234 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
10235 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10236 	if (dst_reg->smin_value < 0 || smin_val < 0) {
10237 		/* Lose signed bounds when ORing negative numbers,
10238 		 * ain't nobody got time for that.
10239 		 */
10240 		dst_reg->smin_value = S64_MIN;
10241 		dst_reg->smax_value = S64_MAX;
10242 	} else {
10243 		/* ORing two positives gives a positive, so safe to
10244 		 * cast result into s64.
10245 		 */
10246 		dst_reg->smin_value = dst_reg->umin_value;
10247 		dst_reg->smax_value = dst_reg->umax_value;
10248 	}
10249 	/* We may learn something more from the var_off */
10250 	__update_reg_bounds(dst_reg);
10251 }
10252 
10253 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
10254 				 struct bpf_reg_state *src_reg)
10255 {
10256 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
10257 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
10258 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
10259 	s32 smin_val = src_reg->s32_min_value;
10260 
10261 	if (src_known && dst_known) {
10262 		__mark_reg32_known(dst_reg, var32_off.value);
10263 		return;
10264 	}
10265 
10266 	/* We get both minimum and maximum from the var32_off. */
10267 	dst_reg->u32_min_value = var32_off.value;
10268 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
10269 
10270 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
10271 		/* XORing two positive sign numbers gives a positive,
10272 		 * so safe to cast u32 result into s32.
10273 		 */
10274 		dst_reg->s32_min_value = dst_reg->u32_min_value;
10275 		dst_reg->s32_max_value = dst_reg->u32_max_value;
10276 	} else {
10277 		dst_reg->s32_min_value = S32_MIN;
10278 		dst_reg->s32_max_value = S32_MAX;
10279 	}
10280 }
10281 
10282 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10283 			       struct bpf_reg_state *src_reg)
10284 {
10285 	bool src_known = tnum_is_const(src_reg->var_off);
10286 	bool dst_known = tnum_is_const(dst_reg->var_off);
10287 	s64 smin_val = src_reg->smin_value;
10288 
10289 	if (src_known && dst_known) {
10290 		/* dst_reg->var_off.value has been updated earlier */
10291 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
10292 		return;
10293 	}
10294 
10295 	/* We get both minimum and maximum from the var_off. */
10296 	dst_reg->umin_value = dst_reg->var_off.value;
10297 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10298 
10299 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10300 		/* XORing two positive sign numbers gives a positive,
10301 		 * so safe to cast u64 result into s64.
10302 		 */
10303 		dst_reg->smin_value = dst_reg->umin_value;
10304 		dst_reg->smax_value = dst_reg->umax_value;
10305 	} else {
10306 		dst_reg->smin_value = S64_MIN;
10307 		dst_reg->smax_value = S64_MAX;
10308 	}
10309 
10310 	__update_reg_bounds(dst_reg);
10311 }
10312 
10313 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10314 				   u64 umin_val, u64 umax_val)
10315 {
10316 	/* We lose all sign bit information (except what we can pick
10317 	 * up from var_off)
10318 	 */
10319 	dst_reg->s32_min_value = S32_MIN;
10320 	dst_reg->s32_max_value = S32_MAX;
10321 	/* If we might shift our top bit out, then we know nothing */
10322 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10323 		dst_reg->u32_min_value = 0;
10324 		dst_reg->u32_max_value = U32_MAX;
10325 	} else {
10326 		dst_reg->u32_min_value <<= umin_val;
10327 		dst_reg->u32_max_value <<= umax_val;
10328 	}
10329 }
10330 
10331 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10332 				 struct bpf_reg_state *src_reg)
10333 {
10334 	u32 umax_val = src_reg->u32_max_value;
10335 	u32 umin_val = src_reg->u32_min_value;
10336 	/* u32 alu operation will zext upper bits */
10337 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10338 
10339 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10340 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10341 	/* Not required but being careful mark reg64 bounds as unknown so
10342 	 * that we are forced to pick them up from tnum and zext later and
10343 	 * if some path skips this step we are still safe.
10344 	 */
10345 	__mark_reg64_unbounded(dst_reg);
10346 	__update_reg32_bounds(dst_reg);
10347 }
10348 
10349 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10350 				   u64 umin_val, u64 umax_val)
10351 {
10352 	/* Special case <<32 because it is a common compiler pattern to sign
10353 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10354 	 * positive we know this shift will also be positive so we can track
10355 	 * bounds correctly. Otherwise we lose all sign bit information except
10356 	 * what we can pick up from var_off. Perhaps we can generalize this
10357 	 * later to shifts of any length.
10358 	 */
10359 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10360 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10361 	else
10362 		dst_reg->smax_value = S64_MAX;
10363 
10364 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10365 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10366 	else
10367 		dst_reg->smin_value = S64_MIN;
10368 
10369 	/* If we might shift our top bit out, then we know nothing */
10370 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10371 		dst_reg->umin_value = 0;
10372 		dst_reg->umax_value = U64_MAX;
10373 	} else {
10374 		dst_reg->umin_value <<= umin_val;
10375 		dst_reg->umax_value <<= umax_val;
10376 	}
10377 }
10378 
10379 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10380 			       struct bpf_reg_state *src_reg)
10381 {
10382 	u64 umax_val = src_reg->umax_value;
10383 	u64 umin_val = src_reg->umin_value;
10384 
10385 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
10386 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10387 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10388 
10389 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10390 	/* We may learn something more from the var_off */
10391 	__update_reg_bounds(dst_reg);
10392 }
10393 
10394 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10395 				 struct bpf_reg_state *src_reg)
10396 {
10397 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
10398 	u32 umax_val = src_reg->u32_max_value;
10399 	u32 umin_val = src_reg->u32_min_value;
10400 
10401 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10402 	 * be negative, then either:
10403 	 * 1) src_reg might be zero, so the sign bit of the result is
10404 	 *    unknown, so we lose our signed bounds
10405 	 * 2) it's known negative, thus the unsigned bounds capture the
10406 	 *    signed bounds
10407 	 * 3) the signed bounds cross zero, so they tell us nothing
10408 	 *    about the result
10409 	 * If the value in dst_reg is known nonnegative, then again the
10410 	 * unsigned bounds capture the signed bounds.
10411 	 * Thus, in all cases it suffices to blow away our signed bounds
10412 	 * and rely on inferring new ones from the unsigned bounds and
10413 	 * var_off of the result.
10414 	 */
10415 	dst_reg->s32_min_value = S32_MIN;
10416 	dst_reg->s32_max_value = S32_MAX;
10417 
10418 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
10419 	dst_reg->u32_min_value >>= umax_val;
10420 	dst_reg->u32_max_value >>= umin_val;
10421 
10422 	__mark_reg64_unbounded(dst_reg);
10423 	__update_reg32_bounds(dst_reg);
10424 }
10425 
10426 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10427 			       struct bpf_reg_state *src_reg)
10428 {
10429 	u64 umax_val = src_reg->umax_value;
10430 	u64 umin_val = src_reg->umin_value;
10431 
10432 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10433 	 * be negative, then either:
10434 	 * 1) src_reg might be zero, so the sign bit of the result is
10435 	 *    unknown, so we lose our signed bounds
10436 	 * 2) it's known negative, thus the unsigned bounds capture the
10437 	 *    signed bounds
10438 	 * 3) the signed bounds cross zero, so they tell us nothing
10439 	 *    about the result
10440 	 * If the value in dst_reg is known nonnegative, then again the
10441 	 * unsigned bounds capture the signed bounds.
10442 	 * Thus, in all cases it suffices to blow away our signed bounds
10443 	 * and rely on inferring new ones from the unsigned bounds and
10444 	 * var_off of the result.
10445 	 */
10446 	dst_reg->smin_value = S64_MIN;
10447 	dst_reg->smax_value = S64_MAX;
10448 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10449 	dst_reg->umin_value >>= umax_val;
10450 	dst_reg->umax_value >>= umin_val;
10451 
10452 	/* Its not easy to operate on alu32 bounds here because it depends
10453 	 * on bits being shifted in. Take easy way out and mark unbounded
10454 	 * so we can recalculate later from tnum.
10455 	 */
10456 	__mark_reg32_unbounded(dst_reg);
10457 	__update_reg_bounds(dst_reg);
10458 }
10459 
10460 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10461 				  struct bpf_reg_state *src_reg)
10462 {
10463 	u64 umin_val = src_reg->u32_min_value;
10464 
10465 	/* Upon reaching here, src_known is true and
10466 	 * umax_val is equal to umin_val.
10467 	 */
10468 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10469 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10470 
10471 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10472 
10473 	/* blow away the dst_reg umin_value/umax_value and rely on
10474 	 * dst_reg var_off to refine the result.
10475 	 */
10476 	dst_reg->u32_min_value = 0;
10477 	dst_reg->u32_max_value = U32_MAX;
10478 
10479 	__mark_reg64_unbounded(dst_reg);
10480 	__update_reg32_bounds(dst_reg);
10481 }
10482 
10483 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10484 				struct bpf_reg_state *src_reg)
10485 {
10486 	u64 umin_val = src_reg->umin_value;
10487 
10488 	/* Upon reaching here, src_known is true and umax_val is equal
10489 	 * to umin_val.
10490 	 */
10491 	dst_reg->smin_value >>= umin_val;
10492 	dst_reg->smax_value >>= umin_val;
10493 
10494 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10495 
10496 	/* blow away the dst_reg umin_value/umax_value and rely on
10497 	 * dst_reg var_off to refine the result.
10498 	 */
10499 	dst_reg->umin_value = 0;
10500 	dst_reg->umax_value = U64_MAX;
10501 
10502 	/* Its not easy to operate on alu32 bounds here because it depends
10503 	 * on bits being shifted in from upper 32-bits. Take easy way out
10504 	 * and mark unbounded so we can recalculate later from tnum.
10505 	 */
10506 	__mark_reg32_unbounded(dst_reg);
10507 	__update_reg_bounds(dst_reg);
10508 }
10509 
10510 /* WARNING: This function does calculations on 64-bit values, but the actual
10511  * execution may occur on 32-bit values. Therefore, things like bitshifts
10512  * need extra checks in the 32-bit case.
10513  */
10514 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10515 				      struct bpf_insn *insn,
10516 				      struct bpf_reg_state *dst_reg,
10517 				      struct bpf_reg_state src_reg)
10518 {
10519 	struct bpf_reg_state *regs = cur_regs(env);
10520 	u8 opcode = BPF_OP(insn->code);
10521 	bool src_known;
10522 	s64 smin_val, smax_val;
10523 	u64 umin_val, umax_val;
10524 	s32 s32_min_val, s32_max_val;
10525 	u32 u32_min_val, u32_max_val;
10526 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10527 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10528 	int ret;
10529 
10530 	smin_val = src_reg.smin_value;
10531 	smax_val = src_reg.smax_value;
10532 	umin_val = src_reg.umin_value;
10533 	umax_val = src_reg.umax_value;
10534 
10535 	s32_min_val = src_reg.s32_min_value;
10536 	s32_max_val = src_reg.s32_max_value;
10537 	u32_min_val = src_reg.u32_min_value;
10538 	u32_max_val = src_reg.u32_max_value;
10539 
10540 	if (alu32) {
10541 		src_known = tnum_subreg_is_const(src_reg.var_off);
10542 		if ((src_known &&
10543 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10544 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10545 			/* Taint dst register if offset had invalid bounds
10546 			 * derived from e.g. dead branches.
10547 			 */
10548 			__mark_reg_unknown(env, dst_reg);
10549 			return 0;
10550 		}
10551 	} else {
10552 		src_known = tnum_is_const(src_reg.var_off);
10553 		if ((src_known &&
10554 		     (smin_val != smax_val || umin_val != umax_val)) ||
10555 		    smin_val > smax_val || umin_val > umax_val) {
10556 			/* Taint dst register if offset had invalid bounds
10557 			 * derived from e.g. dead branches.
10558 			 */
10559 			__mark_reg_unknown(env, dst_reg);
10560 			return 0;
10561 		}
10562 	}
10563 
10564 	if (!src_known &&
10565 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10566 		__mark_reg_unknown(env, dst_reg);
10567 		return 0;
10568 	}
10569 
10570 	if (sanitize_needed(opcode)) {
10571 		ret = sanitize_val_alu(env, insn);
10572 		if (ret < 0)
10573 			return sanitize_err(env, insn, ret, NULL, NULL);
10574 	}
10575 
10576 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10577 	 * There are two classes of instructions: The first class we track both
10578 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
10579 	 * greatest amount of precision when alu operations are mixed with jmp32
10580 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10581 	 * and BPF_OR. This is possible because these ops have fairly easy to
10582 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10583 	 * See alu32 verifier tests for examples. The second class of
10584 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10585 	 * with regards to tracking sign/unsigned bounds because the bits may
10586 	 * cross subreg boundaries in the alu64 case. When this happens we mark
10587 	 * the reg unbounded in the subreg bound space and use the resulting
10588 	 * tnum to calculate an approximation of the sign/unsigned bounds.
10589 	 */
10590 	switch (opcode) {
10591 	case BPF_ADD:
10592 		scalar32_min_max_add(dst_reg, &src_reg);
10593 		scalar_min_max_add(dst_reg, &src_reg);
10594 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10595 		break;
10596 	case BPF_SUB:
10597 		scalar32_min_max_sub(dst_reg, &src_reg);
10598 		scalar_min_max_sub(dst_reg, &src_reg);
10599 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10600 		break;
10601 	case BPF_MUL:
10602 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10603 		scalar32_min_max_mul(dst_reg, &src_reg);
10604 		scalar_min_max_mul(dst_reg, &src_reg);
10605 		break;
10606 	case BPF_AND:
10607 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10608 		scalar32_min_max_and(dst_reg, &src_reg);
10609 		scalar_min_max_and(dst_reg, &src_reg);
10610 		break;
10611 	case BPF_OR:
10612 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10613 		scalar32_min_max_or(dst_reg, &src_reg);
10614 		scalar_min_max_or(dst_reg, &src_reg);
10615 		break;
10616 	case BPF_XOR:
10617 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10618 		scalar32_min_max_xor(dst_reg, &src_reg);
10619 		scalar_min_max_xor(dst_reg, &src_reg);
10620 		break;
10621 	case BPF_LSH:
10622 		if (umax_val >= insn_bitness) {
10623 			/* Shifts greater than 31 or 63 are undefined.
10624 			 * This includes shifts by a negative number.
10625 			 */
10626 			mark_reg_unknown(env, regs, insn->dst_reg);
10627 			break;
10628 		}
10629 		if (alu32)
10630 			scalar32_min_max_lsh(dst_reg, &src_reg);
10631 		else
10632 			scalar_min_max_lsh(dst_reg, &src_reg);
10633 		break;
10634 	case BPF_RSH:
10635 		if (umax_val >= insn_bitness) {
10636 			/* Shifts greater than 31 or 63 are undefined.
10637 			 * This includes shifts by a negative number.
10638 			 */
10639 			mark_reg_unknown(env, regs, insn->dst_reg);
10640 			break;
10641 		}
10642 		if (alu32)
10643 			scalar32_min_max_rsh(dst_reg, &src_reg);
10644 		else
10645 			scalar_min_max_rsh(dst_reg, &src_reg);
10646 		break;
10647 	case BPF_ARSH:
10648 		if (umax_val >= insn_bitness) {
10649 			/* Shifts greater than 31 or 63 are undefined.
10650 			 * This includes shifts by a negative number.
10651 			 */
10652 			mark_reg_unknown(env, regs, insn->dst_reg);
10653 			break;
10654 		}
10655 		if (alu32)
10656 			scalar32_min_max_arsh(dst_reg, &src_reg);
10657 		else
10658 			scalar_min_max_arsh(dst_reg, &src_reg);
10659 		break;
10660 	default:
10661 		mark_reg_unknown(env, regs, insn->dst_reg);
10662 		break;
10663 	}
10664 
10665 	/* ALU32 ops are zero extended into 64bit register */
10666 	if (alu32)
10667 		zext_32_to_64(dst_reg);
10668 	reg_bounds_sync(dst_reg);
10669 	return 0;
10670 }
10671 
10672 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10673  * and var_off.
10674  */
10675 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10676 				   struct bpf_insn *insn)
10677 {
10678 	struct bpf_verifier_state *vstate = env->cur_state;
10679 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10680 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10681 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10682 	u8 opcode = BPF_OP(insn->code);
10683 	int err;
10684 
10685 	dst_reg = &regs[insn->dst_reg];
10686 	src_reg = NULL;
10687 	if (dst_reg->type != SCALAR_VALUE)
10688 		ptr_reg = dst_reg;
10689 	else
10690 		/* Make sure ID is cleared otherwise dst_reg min/max could be
10691 		 * incorrectly propagated into other registers by find_equal_scalars()
10692 		 */
10693 		dst_reg->id = 0;
10694 	if (BPF_SRC(insn->code) == BPF_X) {
10695 		src_reg = &regs[insn->src_reg];
10696 		if (src_reg->type != SCALAR_VALUE) {
10697 			if (dst_reg->type != SCALAR_VALUE) {
10698 				/* Combining two pointers by any ALU op yields
10699 				 * an arbitrary scalar. Disallow all math except
10700 				 * pointer subtraction
10701 				 */
10702 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10703 					mark_reg_unknown(env, regs, insn->dst_reg);
10704 					return 0;
10705 				}
10706 				verbose(env, "R%d pointer %s pointer prohibited\n",
10707 					insn->dst_reg,
10708 					bpf_alu_string[opcode >> 4]);
10709 				return -EACCES;
10710 			} else {
10711 				/* scalar += pointer
10712 				 * This is legal, but we have to reverse our
10713 				 * src/dest handling in computing the range
10714 				 */
10715 				err = mark_chain_precision(env, insn->dst_reg);
10716 				if (err)
10717 					return err;
10718 				return adjust_ptr_min_max_vals(env, insn,
10719 							       src_reg, dst_reg);
10720 			}
10721 		} else if (ptr_reg) {
10722 			/* pointer += scalar */
10723 			err = mark_chain_precision(env, insn->src_reg);
10724 			if (err)
10725 				return err;
10726 			return adjust_ptr_min_max_vals(env, insn,
10727 						       dst_reg, src_reg);
10728 		} else if (dst_reg->precise) {
10729 			/* if dst_reg is precise, src_reg should be precise as well */
10730 			err = mark_chain_precision(env, insn->src_reg);
10731 			if (err)
10732 				return err;
10733 		}
10734 	} else {
10735 		/* Pretend the src is a reg with a known value, since we only
10736 		 * need to be able to read from this state.
10737 		 */
10738 		off_reg.type = SCALAR_VALUE;
10739 		__mark_reg_known(&off_reg, insn->imm);
10740 		src_reg = &off_reg;
10741 		if (ptr_reg) /* pointer += K */
10742 			return adjust_ptr_min_max_vals(env, insn,
10743 						       ptr_reg, src_reg);
10744 	}
10745 
10746 	/* Got here implies adding two SCALAR_VALUEs */
10747 	if (WARN_ON_ONCE(ptr_reg)) {
10748 		print_verifier_state(env, state, true);
10749 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
10750 		return -EINVAL;
10751 	}
10752 	if (WARN_ON(!src_reg)) {
10753 		print_verifier_state(env, state, true);
10754 		verbose(env, "verifier internal error: no src_reg\n");
10755 		return -EINVAL;
10756 	}
10757 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10758 }
10759 
10760 /* check validity of 32-bit and 64-bit arithmetic operations */
10761 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10762 {
10763 	struct bpf_reg_state *regs = cur_regs(env);
10764 	u8 opcode = BPF_OP(insn->code);
10765 	int err;
10766 
10767 	if (opcode == BPF_END || opcode == BPF_NEG) {
10768 		if (opcode == BPF_NEG) {
10769 			if (BPF_SRC(insn->code) != BPF_K ||
10770 			    insn->src_reg != BPF_REG_0 ||
10771 			    insn->off != 0 || insn->imm != 0) {
10772 				verbose(env, "BPF_NEG uses reserved fields\n");
10773 				return -EINVAL;
10774 			}
10775 		} else {
10776 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10777 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10778 			    BPF_CLASS(insn->code) == BPF_ALU64) {
10779 				verbose(env, "BPF_END uses reserved fields\n");
10780 				return -EINVAL;
10781 			}
10782 		}
10783 
10784 		/* check src operand */
10785 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10786 		if (err)
10787 			return err;
10788 
10789 		if (is_pointer_value(env, insn->dst_reg)) {
10790 			verbose(env, "R%d pointer arithmetic prohibited\n",
10791 				insn->dst_reg);
10792 			return -EACCES;
10793 		}
10794 
10795 		/* check dest operand */
10796 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
10797 		if (err)
10798 			return err;
10799 
10800 	} else if (opcode == BPF_MOV) {
10801 
10802 		if (BPF_SRC(insn->code) == BPF_X) {
10803 			if (insn->imm != 0 || insn->off != 0) {
10804 				verbose(env, "BPF_MOV uses reserved fields\n");
10805 				return -EINVAL;
10806 			}
10807 
10808 			/* check src operand */
10809 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10810 			if (err)
10811 				return err;
10812 		} else {
10813 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10814 				verbose(env, "BPF_MOV uses reserved fields\n");
10815 				return -EINVAL;
10816 			}
10817 		}
10818 
10819 		/* check dest operand, mark as required later */
10820 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10821 		if (err)
10822 			return err;
10823 
10824 		if (BPF_SRC(insn->code) == BPF_X) {
10825 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
10826 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10827 
10828 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10829 				/* case: R1 = R2
10830 				 * copy register state to dest reg
10831 				 */
10832 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10833 					/* Assign src and dst registers the same ID
10834 					 * that will be used by find_equal_scalars()
10835 					 * to propagate min/max range.
10836 					 */
10837 					src_reg->id = ++env->id_gen;
10838 				*dst_reg = *src_reg;
10839 				dst_reg->live |= REG_LIVE_WRITTEN;
10840 				dst_reg->subreg_def = DEF_NOT_SUBREG;
10841 			} else {
10842 				/* R1 = (u32) R2 */
10843 				if (is_pointer_value(env, insn->src_reg)) {
10844 					verbose(env,
10845 						"R%d partial copy of pointer\n",
10846 						insn->src_reg);
10847 					return -EACCES;
10848 				} else if (src_reg->type == SCALAR_VALUE) {
10849 					*dst_reg = *src_reg;
10850 					/* Make sure ID is cleared otherwise
10851 					 * dst_reg min/max could be incorrectly
10852 					 * propagated into src_reg by find_equal_scalars()
10853 					 */
10854 					dst_reg->id = 0;
10855 					dst_reg->live |= REG_LIVE_WRITTEN;
10856 					dst_reg->subreg_def = env->insn_idx + 1;
10857 				} else {
10858 					mark_reg_unknown(env, regs,
10859 							 insn->dst_reg);
10860 				}
10861 				zext_32_to_64(dst_reg);
10862 				reg_bounds_sync(dst_reg);
10863 			}
10864 		} else {
10865 			/* case: R = imm
10866 			 * remember the value we stored into this reg
10867 			 */
10868 			/* clear any state __mark_reg_known doesn't set */
10869 			mark_reg_unknown(env, regs, insn->dst_reg);
10870 			regs[insn->dst_reg].type = SCALAR_VALUE;
10871 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
10872 				__mark_reg_known(regs + insn->dst_reg,
10873 						 insn->imm);
10874 			} else {
10875 				__mark_reg_known(regs + insn->dst_reg,
10876 						 (u32)insn->imm);
10877 			}
10878 		}
10879 
10880 	} else if (opcode > BPF_END) {
10881 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10882 		return -EINVAL;
10883 
10884 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
10885 
10886 		if (BPF_SRC(insn->code) == BPF_X) {
10887 			if (insn->imm != 0 || insn->off != 0) {
10888 				verbose(env, "BPF_ALU uses reserved fields\n");
10889 				return -EINVAL;
10890 			}
10891 			/* check src1 operand */
10892 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10893 			if (err)
10894 				return err;
10895 		} else {
10896 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10897 				verbose(env, "BPF_ALU uses reserved fields\n");
10898 				return -EINVAL;
10899 			}
10900 		}
10901 
10902 		/* check src2 operand */
10903 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10904 		if (err)
10905 			return err;
10906 
10907 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10908 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10909 			verbose(env, "div by zero\n");
10910 			return -EINVAL;
10911 		}
10912 
10913 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10914 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10915 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10916 
10917 			if (insn->imm < 0 || insn->imm >= size) {
10918 				verbose(env, "invalid shift %d\n", insn->imm);
10919 				return -EINVAL;
10920 			}
10921 		}
10922 
10923 		/* check dest operand */
10924 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10925 		if (err)
10926 			return err;
10927 
10928 		return adjust_reg_min_max_vals(env, insn);
10929 	}
10930 
10931 	return 0;
10932 }
10933 
10934 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10935 				   struct bpf_reg_state *dst_reg,
10936 				   enum bpf_reg_type type,
10937 				   bool range_right_open)
10938 {
10939 	struct bpf_func_state *state;
10940 	struct bpf_reg_state *reg;
10941 	int new_range;
10942 
10943 	if (dst_reg->off < 0 ||
10944 	    (dst_reg->off == 0 && range_right_open))
10945 		/* This doesn't give us any range */
10946 		return;
10947 
10948 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
10949 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10950 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
10951 		 * than pkt_end, but that's because it's also less than pkt.
10952 		 */
10953 		return;
10954 
10955 	new_range = dst_reg->off;
10956 	if (range_right_open)
10957 		new_range++;
10958 
10959 	/* Examples for register markings:
10960 	 *
10961 	 * pkt_data in dst register:
10962 	 *
10963 	 *   r2 = r3;
10964 	 *   r2 += 8;
10965 	 *   if (r2 > pkt_end) goto <handle exception>
10966 	 *   <access okay>
10967 	 *
10968 	 *   r2 = r3;
10969 	 *   r2 += 8;
10970 	 *   if (r2 < pkt_end) goto <access okay>
10971 	 *   <handle exception>
10972 	 *
10973 	 *   Where:
10974 	 *     r2 == dst_reg, pkt_end == src_reg
10975 	 *     r2=pkt(id=n,off=8,r=0)
10976 	 *     r3=pkt(id=n,off=0,r=0)
10977 	 *
10978 	 * pkt_data in src register:
10979 	 *
10980 	 *   r2 = r3;
10981 	 *   r2 += 8;
10982 	 *   if (pkt_end >= r2) goto <access okay>
10983 	 *   <handle exception>
10984 	 *
10985 	 *   r2 = r3;
10986 	 *   r2 += 8;
10987 	 *   if (pkt_end <= r2) goto <handle exception>
10988 	 *   <access okay>
10989 	 *
10990 	 *   Where:
10991 	 *     pkt_end == dst_reg, r2 == src_reg
10992 	 *     r2=pkt(id=n,off=8,r=0)
10993 	 *     r3=pkt(id=n,off=0,r=0)
10994 	 *
10995 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
10996 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
10997 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
10998 	 * the check.
10999 	 */
11000 
11001 	/* If our ids match, then we must have the same max_value.  And we
11002 	 * don't care about the other reg's fixed offset, since if it's too big
11003 	 * the range won't allow anything.
11004 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
11005 	 */
11006 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11007 		if (reg->type == type && reg->id == dst_reg->id)
11008 			/* keep the maximum range already checked */
11009 			reg->range = max(reg->range, new_range);
11010 	}));
11011 }
11012 
11013 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
11014 {
11015 	struct tnum subreg = tnum_subreg(reg->var_off);
11016 	s32 sval = (s32)val;
11017 
11018 	switch (opcode) {
11019 	case BPF_JEQ:
11020 		if (tnum_is_const(subreg))
11021 			return !!tnum_equals_const(subreg, val);
11022 		break;
11023 	case BPF_JNE:
11024 		if (tnum_is_const(subreg))
11025 			return !tnum_equals_const(subreg, val);
11026 		break;
11027 	case BPF_JSET:
11028 		if ((~subreg.mask & subreg.value) & val)
11029 			return 1;
11030 		if (!((subreg.mask | subreg.value) & val))
11031 			return 0;
11032 		break;
11033 	case BPF_JGT:
11034 		if (reg->u32_min_value > val)
11035 			return 1;
11036 		else if (reg->u32_max_value <= val)
11037 			return 0;
11038 		break;
11039 	case BPF_JSGT:
11040 		if (reg->s32_min_value > sval)
11041 			return 1;
11042 		else if (reg->s32_max_value <= sval)
11043 			return 0;
11044 		break;
11045 	case BPF_JLT:
11046 		if (reg->u32_max_value < val)
11047 			return 1;
11048 		else if (reg->u32_min_value >= val)
11049 			return 0;
11050 		break;
11051 	case BPF_JSLT:
11052 		if (reg->s32_max_value < sval)
11053 			return 1;
11054 		else if (reg->s32_min_value >= sval)
11055 			return 0;
11056 		break;
11057 	case BPF_JGE:
11058 		if (reg->u32_min_value >= val)
11059 			return 1;
11060 		else if (reg->u32_max_value < val)
11061 			return 0;
11062 		break;
11063 	case BPF_JSGE:
11064 		if (reg->s32_min_value >= sval)
11065 			return 1;
11066 		else if (reg->s32_max_value < sval)
11067 			return 0;
11068 		break;
11069 	case BPF_JLE:
11070 		if (reg->u32_max_value <= val)
11071 			return 1;
11072 		else if (reg->u32_min_value > val)
11073 			return 0;
11074 		break;
11075 	case BPF_JSLE:
11076 		if (reg->s32_max_value <= sval)
11077 			return 1;
11078 		else if (reg->s32_min_value > sval)
11079 			return 0;
11080 		break;
11081 	}
11082 
11083 	return -1;
11084 }
11085 
11086 
11087 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
11088 {
11089 	s64 sval = (s64)val;
11090 
11091 	switch (opcode) {
11092 	case BPF_JEQ:
11093 		if (tnum_is_const(reg->var_off))
11094 			return !!tnum_equals_const(reg->var_off, val);
11095 		break;
11096 	case BPF_JNE:
11097 		if (tnum_is_const(reg->var_off))
11098 			return !tnum_equals_const(reg->var_off, val);
11099 		break;
11100 	case BPF_JSET:
11101 		if ((~reg->var_off.mask & reg->var_off.value) & val)
11102 			return 1;
11103 		if (!((reg->var_off.mask | reg->var_off.value) & val))
11104 			return 0;
11105 		break;
11106 	case BPF_JGT:
11107 		if (reg->umin_value > val)
11108 			return 1;
11109 		else if (reg->umax_value <= val)
11110 			return 0;
11111 		break;
11112 	case BPF_JSGT:
11113 		if (reg->smin_value > sval)
11114 			return 1;
11115 		else if (reg->smax_value <= sval)
11116 			return 0;
11117 		break;
11118 	case BPF_JLT:
11119 		if (reg->umax_value < val)
11120 			return 1;
11121 		else if (reg->umin_value >= val)
11122 			return 0;
11123 		break;
11124 	case BPF_JSLT:
11125 		if (reg->smax_value < sval)
11126 			return 1;
11127 		else if (reg->smin_value >= sval)
11128 			return 0;
11129 		break;
11130 	case BPF_JGE:
11131 		if (reg->umin_value >= val)
11132 			return 1;
11133 		else if (reg->umax_value < val)
11134 			return 0;
11135 		break;
11136 	case BPF_JSGE:
11137 		if (reg->smin_value >= sval)
11138 			return 1;
11139 		else if (reg->smax_value < sval)
11140 			return 0;
11141 		break;
11142 	case BPF_JLE:
11143 		if (reg->umax_value <= val)
11144 			return 1;
11145 		else if (reg->umin_value > val)
11146 			return 0;
11147 		break;
11148 	case BPF_JSLE:
11149 		if (reg->smax_value <= sval)
11150 			return 1;
11151 		else if (reg->smin_value > sval)
11152 			return 0;
11153 		break;
11154 	}
11155 
11156 	return -1;
11157 }
11158 
11159 /* compute branch direction of the expression "if (reg opcode val) goto target;"
11160  * and return:
11161  *  1 - branch will be taken and "goto target" will be executed
11162  *  0 - branch will not be taken and fall-through to next insn
11163  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
11164  *      range [0,10]
11165  */
11166 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
11167 			   bool is_jmp32)
11168 {
11169 	if (__is_pointer_value(false, reg)) {
11170 		if (!reg_type_not_null(reg->type))
11171 			return -1;
11172 
11173 		/* If pointer is valid tests against zero will fail so we can
11174 		 * use this to direct branch taken.
11175 		 */
11176 		if (val != 0)
11177 			return -1;
11178 
11179 		switch (opcode) {
11180 		case BPF_JEQ:
11181 			return 0;
11182 		case BPF_JNE:
11183 			return 1;
11184 		default:
11185 			return -1;
11186 		}
11187 	}
11188 
11189 	if (is_jmp32)
11190 		return is_branch32_taken(reg, val, opcode);
11191 	return is_branch64_taken(reg, val, opcode);
11192 }
11193 
11194 static int flip_opcode(u32 opcode)
11195 {
11196 	/* How can we transform "a <op> b" into "b <op> a"? */
11197 	static const u8 opcode_flip[16] = {
11198 		/* these stay the same */
11199 		[BPF_JEQ  >> 4] = BPF_JEQ,
11200 		[BPF_JNE  >> 4] = BPF_JNE,
11201 		[BPF_JSET >> 4] = BPF_JSET,
11202 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
11203 		[BPF_JGE  >> 4] = BPF_JLE,
11204 		[BPF_JGT  >> 4] = BPF_JLT,
11205 		[BPF_JLE  >> 4] = BPF_JGE,
11206 		[BPF_JLT  >> 4] = BPF_JGT,
11207 		[BPF_JSGE >> 4] = BPF_JSLE,
11208 		[BPF_JSGT >> 4] = BPF_JSLT,
11209 		[BPF_JSLE >> 4] = BPF_JSGE,
11210 		[BPF_JSLT >> 4] = BPF_JSGT
11211 	};
11212 	return opcode_flip[opcode >> 4];
11213 }
11214 
11215 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
11216 				   struct bpf_reg_state *src_reg,
11217 				   u8 opcode)
11218 {
11219 	struct bpf_reg_state *pkt;
11220 
11221 	if (src_reg->type == PTR_TO_PACKET_END) {
11222 		pkt = dst_reg;
11223 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
11224 		pkt = src_reg;
11225 		opcode = flip_opcode(opcode);
11226 	} else {
11227 		return -1;
11228 	}
11229 
11230 	if (pkt->range >= 0)
11231 		return -1;
11232 
11233 	switch (opcode) {
11234 	case BPF_JLE:
11235 		/* pkt <= pkt_end */
11236 		fallthrough;
11237 	case BPF_JGT:
11238 		/* pkt > pkt_end */
11239 		if (pkt->range == BEYOND_PKT_END)
11240 			/* pkt has at last one extra byte beyond pkt_end */
11241 			return opcode == BPF_JGT;
11242 		break;
11243 	case BPF_JLT:
11244 		/* pkt < pkt_end */
11245 		fallthrough;
11246 	case BPF_JGE:
11247 		/* pkt >= pkt_end */
11248 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
11249 			return opcode == BPF_JGE;
11250 		break;
11251 	}
11252 	return -1;
11253 }
11254 
11255 /* Adjusts the register min/max values in the case that the dst_reg is the
11256  * variable register that we are working on, and src_reg is a constant or we're
11257  * simply doing a BPF_K check.
11258  * In JEQ/JNE cases we also adjust the var_off values.
11259  */
11260 static void reg_set_min_max(struct bpf_reg_state *true_reg,
11261 			    struct bpf_reg_state *false_reg,
11262 			    u64 val, u32 val32,
11263 			    u8 opcode, bool is_jmp32)
11264 {
11265 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
11266 	struct tnum false_64off = false_reg->var_off;
11267 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
11268 	struct tnum true_64off = true_reg->var_off;
11269 	s64 sval = (s64)val;
11270 	s32 sval32 = (s32)val32;
11271 
11272 	/* If the dst_reg is a pointer, we can't learn anything about its
11273 	 * variable offset from the compare (unless src_reg were a pointer into
11274 	 * the same object, but we don't bother with that.
11275 	 * Since false_reg and true_reg have the same type by construction, we
11276 	 * only need to check one of them for pointerness.
11277 	 */
11278 	if (__is_pointer_value(false, false_reg))
11279 		return;
11280 
11281 	switch (opcode) {
11282 	/* JEQ/JNE comparison doesn't change the register equivalence.
11283 	 *
11284 	 * r1 = r2;
11285 	 * if (r1 == 42) goto label;
11286 	 * ...
11287 	 * label: // here both r1 and r2 are known to be 42.
11288 	 *
11289 	 * Hence when marking register as known preserve it's ID.
11290 	 */
11291 	case BPF_JEQ:
11292 		if (is_jmp32) {
11293 			__mark_reg32_known(true_reg, val32);
11294 			true_32off = tnum_subreg(true_reg->var_off);
11295 		} else {
11296 			___mark_reg_known(true_reg, val);
11297 			true_64off = true_reg->var_off;
11298 		}
11299 		break;
11300 	case BPF_JNE:
11301 		if (is_jmp32) {
11302 			__mark_reg32_known(false_reg, val32);
11303 			false_32off = tnum_subreg(false_reg->var_off);
11304 		} else {
11305 			___mark_reg_known(false_reg, val);
11306 			false_64off = false_reg->var_off;
11307 		}
11308 		break;
11309 	case BPF_JSET:
11310 		if (is_jmp32) {
11311 			false_32off = tnum_and(false_32off, tnum_const(~val32));
11312 			if (is_power_of_2(val32))
11313 				true_32off = tnum_or(true_32off,
11314 						     tnum_const(val32));
11315 		} else {
11316 			false_64off = tnum_and(false_64off, tnum_const(~val));
11317 			if (is_power_of_2(val))
11318 				true_64off = tnum_or(true_64off,
11319 						     tnum_const(val));
11320 		}
11321 		break;
11322 	case BPF_JGE:
11323 	case BPF_JGT:
11324 	{
11325 		if (is_jmp32) {
11326 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
11327 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11328 
11329 			false_reg->u32_max_value = min(false_reg->u32_max_value,
11330 						       false_umax);
11331 			true_reg->u32_min_value = max(true_reg->u32_min_value,
11332 						      true_umin);
11333 		} else {
11334 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
11335 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11336 
11337 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
11338 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
11339 		}
11340 		break;
11341 	}
11342 	case BPF_JSGE:
11343 	case BPF_JSGT:
11344 	{
11345 		if (is_jmp32) {
11346 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
11347 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11348 
11349 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11350 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11351 		} else {
11352 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
11353 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11354 
11355 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
11356 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
11357 		}
11358 		break;
11359 	}
11360 	case BPF_JLE:
11361 	case BPF_JLT:
11362 	{
11363 		if (is_jmp32) {
11364 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
11365 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11366 
11367 			false_reg->u32_min_value = max(false_reg->u32_min_value,
11368 						       false_umin);
11369 			true_reg->u32_max_value = min(true_reg->u32_max_value,
11370 						      true_umax);
11371 		} else {
11372 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
11373 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11374 
11375 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
11376 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
11377 		}
11378 		break;
11379 	}
11380 	case BPF_JSLE:
11381 	case BPF_JSLT:
11382 	{
11383 		if (is_jmp32) {
11384 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
11385 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11386 
11387 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11388 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11389 		} else {
11390 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
11391 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11392 
11393 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
11394 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
11395 		}
11396 		break;
11397 	}
11398 	default:
11399 		return;
11400 	}
11401 
11402 	if (is_jmp32) {
11403 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11404 					     tnum_subreg(false_32off));
11405 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11406 					    tnum_subreg(true_32off));
11407 		__reg_combine_32_into_64(false_reg);
11408 		__reg_combine_32_into_64(true_reg);
11409 	} else {
11410 		false_reg->var_off = false_64off;
11411 		true_reg->var_off = true_64off;
11412 		__reg_combine_64_into_32(false_reg);
11413 		__reg_combine_64_into_32(true_reg);
11414 	}
11415 }
11416 
11417 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11418  * the variable reg.
11419  */
11420 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11421 				struct bpf_reg_state *false_reg,
11422 				u64 val, u32 val32,
11423 				u8 opcode, bool is_jmp32)
11424 {
11425 	opcode = flip_opcode(opcode);
11426 	/* This uses zero as "not present in table"; luckily the zero opcode,
11427 	 * BPF_JA, can't get here.
11428 	 */
11429 	if (opcode)
11430 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11431 }
11432 
11433 /* Regs are known to be equal, so intersect their min/max/var_off */
11434 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11435 				  struct bpf_reg_state *dst_reg)
11436 {
11437 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11438 							dst_reg->umin_value);
11439 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11440 							dst_reg->umax_value);
11441 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11442 							dst_reg->smin_value);
11443 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11444 							dst_reg->smax_value);
11445 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11446 							     dst_reg->var_off);
11447 	reg_bounds_sync(src_reg);
11448 	reg_bounds_sync(dst_reg);
11449 }
11450 
11451 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11452 				struct bpf_reg_state *true_dst,
11453 				struct bpf_reg_state *false_src,
11454 				struct bpf_reg_state *false_dst,
11455 				u8 opcode)
11456 {
11457 	switch (opcode) {
11458 	case BPF_JEQ:
11459 		__reg_combine_min_max(true_src, true_dst);
11460 		break;
11461 	case BPF_JNE:
11462 		__reg_combine_min_max(false_src, false_dst);
11463 		break;
11464 	}
11465 }
11466 
11467 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11468 				 struct bpf_reg_state *reg, u32 id,
11469 				 bool is_null)
11470 {
11471 	if (type_may_be_null(reg->type) && reg->id == id &&
11472 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
11473 		/* Old offset (both fixed and variable parts) should have been
11474 		 * known-zero, because we don't allow pointer arithmetic on
11475 		 * pointers that might be NULL. If we see this happening, don't
11476 		 * convert the register.
11477 		 *
11478 		 * But in some cases, some helpers that return local kptrs
11479 		 * advance offset for the returned pointer. In those cases, it
11480 		 * is fine to expect to see reg->off.
11481 		 */
11482 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11483 			return;
11484 		if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11485 			return;
11486 		if (is_null) {
11487 			reg->type = SCALAR_VALUE;
11488 			/* We don't need id and ref_obj_id from this point
11489 			 * onwards anymore, thus we should better reset it,
11490 			 * so that state pruning has chances to take effect.
11491 			 */
11492 			reg->id = 0;
11493 			reg->ref_obj_id = 0;
11494 
11495 			return;
11496 		}
11497 
11498 		mark_ptr_not_null_reg(reg);
11499 
11500 		if (!reg_may_point_to_spin_lock(reg)) {
11501 			/* For not-NULL ptr, reg->ref_obj_id will be reset
11502 			 * in release_reference().
11503 			 *
11504 			 * reg->id is still used by spin_lock ptr. Other
11505 			 * than spin_lock ptr type, reg->id can be reset.
11506 			 */
11507 			reg->id = 0;
11508 		}
11509 	}
11510 }
11511 
11512 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11513  * be folded together at some point.
11514  */
11515 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11516 				  bool is_null)
11517 {
11518 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11519 	struct bpf_reg_state *regs = state->regs, *reg;
11520 	u32 ref_obj_id = regs[regno].ref_obj_id;
11521 	u32 id = regs[regno].id;
11522 
11523 	if (ref_obj_id && ref_obj_id == id && is_null)
11524 		/* regs[regno] is in the " == NULL" branch.
11525 		 * No one could have freed the reference state before
11526 		 * doing the NULL check.
11527 		 */
11528 		WARN_ON_ONCE(release_reference_state(state, id));
11529 
11530 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11531 		mark_ptr_or_null_reg(state, reg, id, is_null);
11532 	}));
11533 }
11534 
11535 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11536 				   struct bpf_reg_state *dst_reg,
11537 				   struct bpf_reg_state *src_reg,
11538 				   struct bpf_verifier_state *this_branch,
11539 				   struct bpf_verifier_state *other_branch)
11540 {
11541 	if (BPF_SRC(insn->code) != BPF_X)
11542 		return false;
11543 
11544 	/* Pointers are always 64-bit. */
11545 	if (BPF_CLASS(insn->code) == BPF_JMP32)
11546 		return false;
11547 
11548 	switch (BPF_OP(insn->code)) {
11549 	case BPF_JGT:
11550 		if ((dst_reg->type == PTR_TO_PACKET &&
11551 		     src_reg->type == PTR_TO_PACKET_END) ||
11552 		    (dst_reg->type == PTR_TO_PACKET_META &&
11553 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11554 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11555 			find_good_pkt_pointers(this_branch, dst_reg,
11556 					       dst_reg->type, false);
11557 			mark_pkt_end(other_branch, insn->dst_reg, true);
11558 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11559 			    src_reg->type == PTR_TO_PACKET) ||
11560 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11561 			    src_reg->type == PTR_TO_PACKET_META)) {
11562 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
11563 			find_good_pkt_pointers(other_branch, src_reg,
11564 					       src_reg->type, true);
11565 			mark_pkt_end(this_branch, insn->src_reg, false);
11566 		} else {
11567 			return false;
11568 		}
11569 		break;
11570 	case BPF_JLT:
11571 		if ((dst_reg->type == PTR_TO_PACKET &&
11572 		     src_reg->type == PTR_TO_PACKET_END) ||
11573 		    (dst_reg->type == PTR_TO_PACKET_META &&
11574 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11575 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11576 			find_good_pkt_pointers(other_branch, dst_reg,
11577 					       dst_reg->type, true);
11578 			mark_pkt_end(this_branch, insn->dst_reg, false);
11579 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11580 			    src_reg->type == PTR_TO_PACKET) ||
11581 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11582 			    src_reg->type == PTR_TO_PACKET_META)) {
11583 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
11584 			find_good_pkt_pointers(this_branch, src_reg,
11585 					       src_reg->type, false);
11586 			mark_pkt_end(other_branch, insn->src_reg, true);
11587 		} else {
11588 			return false;
11589 		}
11590 		break;
11591 	case BPF_JGE:
11592 		if ((dst_reg->type == PTR_TO_PACKET &&
11593 		     src_reg->type == PTR_TO_PACKET_END) ||
11594 		    (dst_reg->type == PTR_TO_PACKET_META &&
11595 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11596 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11597 			find_good_pkt_pointers(this_branch, dst_reg,
11598 					       dst_reg->type, true);
11599 			mark_pkt_end(other_branch, insn->dst_reg, false);
11600 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11601 			    src_reg->type == PTR_TO_PACKET) ||
11602 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11603 			    src_reg->type == PTR_TO_PACKET_META)) {
11604 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11605 			find_good_pkt_pointers(other_branch, src_reg,
11606 					       src_reg->type, false);
11607 			mark_pkt_end(this_branch, insn->src_reg, true);
11608 		} else {
11609 			return false;
11610 		}
11611 		break;
11612 	case BPF_JLE:
11613 		if ((dst_reg->type == PTR_TO_PACKET &&
11614 		     src_reg->type == PTR_TO_PACKET_END) ||
11615 		    (dst_reg->type == PTR_TO_PACKET_META &&
11616 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11617 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11618 			find_good_pkt_pointers(other_branch, dst_reg,
11619 					       dst_reg->type, false);
11620 			mark_pkt_end(this_branch, insn->dst_reg, true);
11621 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
11622 			    src_reg->type == PTR_TO_PACKET) ||
11623 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11624 			    src_reg->type == PTR_TO_PACKET_META)) {
11625 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11626 			find_good_pkt_pointers(this_branch, src_reg,
11627 					       src_reg->type, true);
11628 			mark_pkt_end(other_branch, insn->src_reg, false);
11629 		} else {
11630 			return false;
11631 		}
11632 		break;
11633 	default:
11634 		return false;
11635 	}
11636 
11637 	return true;
11638 }
11639 
11640 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11641 			       struct bpf_reg_state *known_reg)
11642 {
11643 	struct bpf_func_state *state;
11644 	struct bpf_reg_state *reg;
11645 
11646 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11647 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11648 			*reg = *known_reg;
11649 	}));
11650 }
11651 
11652 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11653 			     struct bpf_insn *insn, int *insn_idx)
11654 {
11655 	struct bpf_verifier_state *this_branch = env->cur_state;
11656 	struct bpf_verifier_state *other_branch;
11657 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11658 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11659 	struct bpf_reg_state *eq_branch_regs;
11660 	u8 opcode = BPF_OP(insn->code);
11661 	bool is_jmp32;
11662 	int pred = -1;
11663 	int err;
11664 
11665 	/* Only conditional jumps are expected to reach here. */
11666 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
11667 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11668 		return -EINVAL;
11669 	}
11670 
11671 	if (BPF_SRC(insn->code) == BPF_X) {
11672 		if (insn->imm != 0) {
11673 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11674 			return -EINVAL;
11675 		}
11676 
11677 		/* check src1 operand */
11678 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
11679 		if (err)
11680 			return err;
11681 
11682 		if (is_pointer_value(env, insn->src_reg)) {
11683 			verbose(env, "R%d pointer comparison prohibited\n",
11684 				insn->src_reg);
11685 			return -EACCES;
11686 		}
11687 		src_reg = &regs[insn->src_reg];
11688 	} else {
11689 		if (insn->src_reg != BPF_REG_0) {
11690 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11691 			return -EINVAL;
11692 		}
11693 	}
11694 
11695 	/* check src2 operand */
11696 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11697 	if (err)
11698 		return err;
11699 
11700 	dst_reg = &regs[insn->dst_reg];
11701 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11702 
11703 	if (BPF_SRC(insn->code) == BPF_K) {
11704 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11705 	} else if (src_reg->type == SCALAR_VALUE &&
11706 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11707 		pred = is_branch_taken(dst_reg,
11708 				       tnum_subreg(src_reg->var_off).value,
11709 				       opcode,
11710 				       is_jmp32);
11711 	} else if (src_reg->type == SCALAR_VALUE &&
11712 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11713 		pred = is_branch_taken(dst_reg,
11714 				       src_reg->var_off.value,
11715 				       opcode,
11716 				       is_jmp32);
11717 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
11718 		   reg_is_pkt_pointer_any(src_reg) &&
11719 		   !is_jmp32) {
11720 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11721 	}
11722 
11723 	if (pred >= 0) {
11724 		/* If we get here with a dst_reg pointer type it is because
11725 		 * above is_branch_taken() special cased the 0 comparison.
11726 		 */
11727 		if (!__is_pointer_value(false, dst_reg))
11728 			err = mark_chain_precision(env, insn->dst_reg);
11729 		if (BPF_SRC(insn->code) == BPF_X && !err &&
11730 		    !__is_pointer_value(false, src_reg))
11731 			err = mark_chain_precision(env, insn->src_reg);
11732 		if (err)
11733 			return err;
11734 	}
11735 
11736 	if (pred == 1) {
11737 		/* Only follow the goto, ignore fall-through. If needed, push
11738 		 * the fall-through branch for simulation under speculative
11739 		 * execution.
11740 		 */
11741 		if (!env->bypass_spec_v1 &&
11742 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
11743 					       *insn_idx))
11744 			return -EFAULT;
11745 		*insn_idx += insn->off;
11746 		return 0;
11747 	} else if (pred == 0) {
11748 		/* Only follow the fall-through branch, since that's where the
11749 		 * program will go. If needed, push the goto branch for
11750 		 * simulation under speculative execution.
11751 		 */
11752 		if (!env->bypass_spec_v1 &&
11753 		    !sanitize_speculative_path(env, insn,
11754 					       *insn_idx + insn->off + 1,
11755 					       *insn_idx))
11756 			return -EFAULT;
11757 		return 0;
11758 	}
11759 
11760 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11761 				  false);
11762 	if (!other_branch)
11763 		return -EFAULT;
11764 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11765 
11766 	/* detect if we are comparing against a constant value so we can adjust
11767 	 * our min/max values for our dst register.
11768 	 * this is only legit if both are scalars (or pointers to the same
11769 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11770 	 * because otherwise the different base pointers mean the offsets aren't
11771 	 * comparable.
11772 	 */
11773 	if (BPF_SRC(insn->code) == BPF_X) {
11774 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
11775 
11776 		if (dst_reg->type == SCALAR_VALUE &&
11777 		    src_reg->type == SCALAR_VALUE) {
11778 			if (tnum_is_const(src_reg->var_off) ||
11779 			    (is_jmp32 &&
11780 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
11781 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
11782 						dst_reg,
11783 						src_reg->var_off.value,
11784 						tnum_subreg(src_reg->var_off).value,
11785 						opcode, is_jmp32);
11786 			else if (tnum_is_const(dst_reg->var_off) ||
11787 				 (is_jmp32 &&
11788 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
11789 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11790 						    src_reg,
11791 						    dst_reg->var_off.value,
11792 						    tnum_subreg(dst_reg->var_off).value,
11793 						    opcode, is_jmp32);
11794 			else if (!is_jmp32 &&
11795 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
11796 				/* Comparing for equality, we can combine knowledge */
11797 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
11798 						    &other_branch_regs[insn->dst_reg],
11799 						    src_reg, dst_reg, opcode);
11800 			if (src_reg->id &&
11801 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11802 				find_equal_scalars(this_branch, src_reg);
11803 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11804 			}
11805 
11806 		}
11807 	} else if (dst_reg->type == SCALAR_VALUE) {
11808 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
11809 					dst_reg, insn->imm, (u32)insn->imm,
11810 					opcode, is_jmp32);
11811 	}
11812 
11813 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11814 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11815 		find_equal_scalars(this_branch, dst_reg);
11816 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11817 	}
11818 
11819 	/* if one pointer register is compared to another pointer
11820 	 * register check if PTR_MAYBE_NULL could be lifted.
11821 	 * E.g. register A - maybe null
11822 	 *      register B - not null
11823 	 * for JNE A, B, ... - A is not null in the false branch;
11824 	 * for JEQ A, B, ... - A is not null in the true branch.
11825 	 */
11826 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11827 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11828 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type)) {
11829 		eq_branch_regs = NULL;
11830 		switch (opcode) {
11831 		case BPF_JEQ:
11832 			eq_branch_regs = other_branch_regs;
11833 			break;
11834 		case BPF_JNE:
11835 			eq_branch_regs = regs;
11836 			break;
11837 		default:
11838 			/* do nothing */
11839 			break;
11840 		}
11841 		if (eq_branch_regs) {
11842 			if (type_may_be_null(src_reg->type))
11843 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11844 			else
11845 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11846 		}
11847 	}
11848 
11849 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11850 	 * NOTE: these optimizations below are related with pointer comparison
11851 	 *       which will never be JMP32.
11852 	 */
11853 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11854 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11855 	    type_may_be_null(dst_reg->type)) {
11856 		/* Mark all identical registers in each branch as either
11857 		 * safe or unknown depending R == 0 or R != 0 conditional.
11858 		 */
11859 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11860 				      opcode == BPF_JNE);
11861 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11862 				      opcode == BPF_JEQ);
11863 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
11864 					   this_branch, other_branch) &&
11865 		   is_pointer_value(env, insn->dst_reg)) {
11866 		verbose(env, "R%d pointer comparison prohibited\n",
11867 			insn->dst_reg);
11868 		return -EACCES;
11869 	}
11870 	if (env->log.level & BPF_LOG_LEVEL)
11871 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
11872 	return 0;
11873 }
11874 
11875 /* verify BPF_LD_IMM64 instruction */
11876 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11877 {
11878 	struct bpf_insn_aux_data *aux = cur_aux(env);
11879 	struct bpf_reg_state *regs = cur_regs(env);
11880 	struct bpf_reg_state *dst_reg;
11881 	struct bpf_map *map;
11882 	int err;
11883 
11884 	if (BPF_SIZE(insn->code) != BPF_DW) {
11885 		verbose(env, "invalid BPF_LD_IMM insn\n");
11886 		return -EINVAL;
11887 	}
11888 	if (insn->off != 0) {
11889 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11890 		return -EINVAL;
11891 	}
11892 
11893 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
11894 	if (err)
11895 		return err;
11896 
11897 	dst_reg = &regs[insn->dst_reg];
11898 	if (insn->src_reg == 0) {
11899 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11900 
11901 		dst_reg->type = SCALAR_VALUE;
11902 		__mark_reg_known(&regs[insn->dst_reg], imm);
11903 		return 0;
11904 	}
11905 
11906 	/* All special src_reg cases are listed below. From this point onwards
11907 	 * we either succeed and assign a corresponding dst_reg->type after
11908 	 * zeroing the offset, or fail and reject the program.
11909 	 */
11910 	mark_reg_known_zero(env, regs, insn->dst_reg);
11911 
11912 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11913 		dst_reg->type = aux->btf_var.reg_type;
11914 		switch (base_type(dst_reg->type)) {
11915 		case PTR_TO_MEM:
11916 			dst_reg->mem_size = aux->btf_var.mem_size;
11917 			break;
11918 		case PTR_TO_BTF_ID:
11919 			dst_reg->btf = aux->btf_var.btf;
11920 			dst_reg->btf_id = aux->btf_var.btf_id;
11921 			break;
11922 		default:
11923 			verbose(env, "bpf verifier is misconfigured\n");
11924 			return -EFAULT;
11925 		}
11926 		return 0;
11927 	}
11928 
11929 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
11930 		struct bpf_prog_aux *aux = env->prog->aux;
11931 		u32 subprogno = find_subprog(env,
11932 					     env->insn_idx + insn->imm + 1);
11933 
11934 		if (!aux->func_info) {
11935 			verbose(env, "missing btf func_info\n");
11936 			return -EINVAL;
11937 		}
11938 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11939 			verbose(env, "callback function not static\n");
11940 			return -EINVAL;
11941 		}
11942 
11943 		dst_reg->type = PTR_TO_FUNC;
11944 		dst_reg->subprogno = subprogno;
11945 		return 0;
11946 	}
11947 
11948 	map = env->used_maps[aux->map_index];
11949 	dst_reg->map_ptr = map;
11950 
11951 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11952 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11953 		dst_reg->type = PTR_TO_MAP_VALUE;
11954 		dst_reg->off = aux->map_off;
11955 		WARN_ON_ONCE(map->max_entries != 1);
11956 		/* We want reg->id to be same (0) as map_value is not distinct */
11957 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11958 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11959 		dst_reg->type = CONST_PTR_TO_MAP;
11960 	} else {
11961 		verbose(env, "bpf verifier is misconfigured\n");
11962 		return -EINVAL;
11963 	}
11964 
11965 	return 0;
11966 }
11967 
11968 static bool may_access_skb(enum bpf_prog_type type)
11969 {
11970 	switch (type) {
11971 	case BPF_PROG_TYPE_SOCKET_FILTER:
11972 	case BPF_PROG_TYPE_SCHED_CLS:
11973 	case BPF_PROG_TYPE_SCHED_ACT:
11974 		return true;
11975 	default:
11976 		return false;
11977 	}
11978 }
11979 
11980 /* verify safety of LD_ABS|LD_IND instructions:
11981  * - they can only appear in the programs where ctx == skb
11982  * - since they are wrappers of function calls, they scratch R1-R5 registers,
11983  *   preserve R6-R9, and store return value into R0
11984  *
11985  * Implicit input:
11986  *   ctx == skb == R6 == CTX
11987  *
11988  * Explicit input:
11989  *   SRC == any register
11990  *   IMM == 32-bit immediate
11991  *
11992  * Output:
11993  *   R0 - 8/16/32-bit skb data converted to cpu endianness
11994  */
11995 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
11996 {
11997 	struct bpf_reg_state *regs = cur_regs(env);
11998 	static const int ctx_reg = BPF_REG_6;
11999 	u8 mode = BPF_MODE(insn->code);
12000 	int i, err;
12001 
12002 	if (!may_access_skb(resolve_prog_type(env->prog))) {
12003 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
12004 		return -EINVAL;
12005 	}
12006 
12007 	if (!env->ops->gen_ld_abs) {
12008 		verbose(env, "bpf verifier is misconfigured\n");
12009 		return -EINVAL;
12010 	}
12011 
12012 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
12013 	    BPF_SIZE(insn->code) == BPF_DW ||
12014 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
12015 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
12016 		return -EINVAL;
12017 	}
12018 
12019 	/* check whether implicit source operand (register R6) is readable */
12020 	err = check_reg_arg(env, ctx_reg, SRC_OP);
12021 	if (err)
12022 		return err;
12023 
12024 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
12025 	 * gen_ld_abs() may terminate the program at runtime, leading to
12026 	 * reference leak.
12027 	 */
12028 	err = check_reference_leak(env);
12029 	if (err) {
12030 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
12031 		return err;
12032 	}
12033 
12034 	if (env->cur_state->active_lock.ptr) {
12035 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
12036 		return -EINVAL;
12037 	}
12038 
12039 	if (env->cur_state->active_rcu_lock) {
12040 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
12041 		return -EINVAL;
12042 	}
12043 
12044 	if (regs[ctx_reg].type != PTR_TO_CTX) {
12045 		verbose(env,
12046 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
12047 		return -EINVAL;
12048 	}
12049 
12050 	if (mode == BPF_IND) {
12051 		/* check explicit source operand */
12052 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
12053 		if (err)
12054 			return err;
12055 	}
12056 
12057 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
12058 	if (err < 0)
12059 		return err;
12060 
12061 	/* reset caller saved regs to unreadable */
12062 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12063 		mark_reg_not_init(env, regs, caller_saved[i]);
12064 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12065 	}
12066 
12067 	/* mark destination R0 register as readable, since it contains
12068 	 * the value fetched from the packet.
12069 	 * Already marked as written above.
12070 	 */
12071 	mark_reg_unknown(env, regs, BPF_REG_0);
12072 	/* ld_abs load up to 32-bit skb data. */
12073 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
12074 	return 0;
12075 }
12076 
12077 static int check_return_code(struct bpf_verifier_env *env)
12078 {
12079 	struct tnum enforce_attach_type_range = tnum_unknown;
12080 	const struct bpf_prog *prog = env->prog;
12081 	struct bpf_reg_state *reg;
12082 	struct tnum range = tnum_range(0, 1);
12083 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12084 	int err;
12085 	struct bpf_func_state *frame = env->cur_state->frame[0];
12086 	const bool is_subprog = frame->subprogno;
12087 
12088 	/* LSM and struct_ops func-ptr's return type could be "void" */
12089 	if (!is_subprog) {
12090 		switch (prog_type) {
12091 		case BPF_PROG_TYPE_LSM:
12092 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
12093 				/* See below, can be 0 or 0-1 depending on hook. */
12094 				break;
12095 			fallthrough;
12096 		case BPF_PROG_TYPE_STRUCT_OPS:
12097 			if (!prog->aux->attach_func_proto->type)
12098 				return 0;
12099 			break;
12100 		default:
12101 			break;
12102 		}
12103 	}
12104 
12105 	/* eBPF calling convention is such that R0 is used
12106 	 * to return the value from eBPF program.
12107 	 * Make sure that it's readable at this time
12108 	 * of bpf_exit, which means that program wrote
12109 	 * something into it earlier
12110 	 */
12111 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
12112 	if (err)
12113 		return err;
12114 
12115 	if (is_pointer_value(env, BPF_REG_0)) {
12116 		verbose(env, "R0 leaks addr as return value\n");
12117 		return -EACCES;
12118 	}
12119 
12120 	reg = cur_regs(env) + BPF_REG_0;
12121 
12122 	if (frame->in_async_callback_fn) {
12123 		/* enforce return zero from async callbacks like timer */
12124 		if (reg->type != SCALAR_VALUE) {
12125 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
12126 				reg_type_str(env, reg->type));
12127 			return -EINVAL;
12128 		}
12129 
12130 		if (!tnum_in(tnum_const(0), reg->var_off)) {
12131 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
12132 			return -EINVAL;
12133 		}
12134 		return 0;
12135 	}
12136 
12137 	if (is_subprog) {
12138 		if (reg->type != SCALAR_VALUE) {
12139 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
12140 				reg_type_str(env, reg->type));
12141 			return -EINVAL;
12142 		}
12143 		return 0;
12144 	}
12145 
12146 	switch (prog_type) {
12147 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
12148 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
12149 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
12150 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
12151 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
12152 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
12153 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
12154 			range = tnum_range(1, 1);
12155 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
12156 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
12157 			range = tnum_range(0, 3);
12158 		break;
12159 	case BPF_PROG_TYPE_CGROUP_SKB:
12160 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
12161 			range = tnum_range(0, 3);
12162 			enforce_attach_type_range = tnum_range(2, 3);
12163 		}
12164 		break;
12165 	case BPF_PROG_TYPE_CGROUP_SOCK:
12166 	case BPF_PROG_TYPE_SOCK_OPS:
12167 	case BPF_PROG_TYPE_CGROUP_DEVICE:
12168 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
12169 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
12170 		break;
12171 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12172 		if (!env->prog->aux->attach_btf_id)
12173 			return 0;
12174 		range = tnum_const(0);
12175 		break;
12176 	case BPF_PROG_TYPE_TRACING:
12177 		switch (env->prog->expected_attach_type) {
12178 		case BPF_TRACE_FENTRY:
12179 		case BPF_TRACE_FEXIT:
12180 			range = tnum_const(0);
12181 			break;
12182 		case BPF_TRACE_RAW_TP:
12183 		case BPF_MODIFY_RETURN:
12184 			return 0;
12185 		case BPF_TRACE_ITER:
12186 			break;
12187 		default:
12188 			return -ENOTSUPP;
12189 		}
12190 		break;
12191 	case BPF_PROG_TYPE_SK_LOOKUP:
12192 		range = tnum_range(SK_DROP, SK_PASS);
12193 		break;
12194 
12195 	case BPF_PROG_TYPE_LSM:
12196 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
12197 			/* Regular BPF_PROG_TYPE_LSM programs can return
12198 			 * any value.
12199 			 */
12200 			return 0;
12201 		}
12202 		if (!env->prog->aux->attach_func_proto->type) {
12203 			/* Make sure programs that attach to void
12204 			 * hooks don't try to modify return value.
12205 			 */
12206 			range = tnum_range(1, 1);
12207 		}
12208 		break;
12209 
12210 	case BPF_PROG_TYPE_EXT:
12211 		/* freplace program can return anything as its return value
12212 		 * depends on the to-be-replaced kernel func or bpf program.
12213 		 */
12214 	default:
12215 		return 0;
12216 	}
12217 
12218 	if (reg->type != SCALAR_VALUE) {
12219 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
12220 			reg_type_str(env, reg->type));
12221 		return -EINVAL;
12222 	}
12223 
12224 	if (!tnum_in(range, reg->var_off)) {
12225 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
12226 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
12227 		    prog_type == BPF_PROG_TYPE_LSM &&
12228 		    !prog->aux->attach_func_proto->type)
12229 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12230 		return -EINVAL;
12231 	}
12232 
12233 	if (!tnum_is_unknown(enforce_attach_type_range) &&
12234 	    tnum_in(enforce_attach_type_range, reg->var_off))
12235 		env->prog->enforce_expected_attach_type = 1;
12236 	return 0;
12237 }
12238 
12239 /* non-recursive DFS pseudo code
12240  * 1  procedure DFS-iterative(G,v):
12241  * 2      label v as discovered
12242  * 3      let S be a stack
12243  * 4      S.push(v)
12244  * 5      while S is not empty
12245  * 6            t <- S.peek()
12246  * 7            if t is what we're looking for:
12247  * 8                return t
12248  * 9            for all edges e in G.adjacentEdges(t) do
12249  * 10               if edge e is already labelled
12250  * 11                   continue with the next edge
12251  * 12               w <- G.adjacentVertex(t,e)
12252  * 13               if vertex w is not discovered and not explored
12253  * 14                   label e as tree-edge
12254  * 15                   label w as discovered
12255  * 16                   S.push(w)
12256  * 17                   continue at 5
12257  * 18               else if vertex w is discovered
12258  * 19                   label e as back-edge
12259  * 20               else
12260  * 21                   // vertex w is explored
12261  * 22                   label e as forward- or cross-edge
12262  * 23           label t as explored
12263  * 24           S.pop()
12264  *
12265  * convention:
12266  * 0x10 - discovered
12267  * 0x11 - discovered and fall-through edge labelled
12268  * 0x12 - discovered and fall-through and branch edges labelled
12269  * 0x20 - explored
12270  */
12271 
12272 enum {
12273 	DISCOVERED = 0x10,
12274 	EXPLORED = 0x20,
12275 	FALLTHROUGH = 1,
12276 	BRANCH = 2,
12277 };
12278 
12279 static u32 state_htab_size(struct bpf_verifier_env *env)
12280 {
12281 	return env->prog->len;
12282 }
12283 
12284 static struct bpf_verifier_state_list **explored_state(
12285 					struct bpf_verifier_env *env,
12286 					int idx)
12287 {
12288 	struct bpf_verifier_state *cur = env->cur_state;
12289 	struct bpf_func_state *state = cur->frame[cur->curframe];
12290 
12291 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12292 }
12293 
12294 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
12295 {
12296 	env->insn_aux_data[idx].prune_point = true;
12297 }
12298 
12299 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
12300 {
12301 	return env->insn_aux_data[insn_idx].prune_point;
12302 }
12303 
12304 enum {
12305 	DONE_EXPLORING = 0,
12306 	KEEP_EXPLORING = 1,
12307 };
12308 
12309 /* t, w, e - match pseudo-code above:
12310  * t - index of current instruction
12311  * w - next instruction
12312  * e - edge
12313  */
12314 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12315 		     bool loop_ok)
12316 {
12317 	int *insn_stack = env->cfg.insn_stack;
12318 	int *insn_state = env->cfg.insn_state;
12319 
12320 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12321 		return DONE_EXPLORING;
12322 
12323 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12324 		return DONE_EXPLORING;
12325 
12326 	if (w < 0 || w >= env->prog->len) {
12327 		verbose_linfo(env, t, "%d: ", t);
12328 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
12329 		return -EINVAL;
12330 	}
12331 
12332 	if (e == BRANCH) {
12333 		/* mark branch target for state pruning */
12334 		mark_prune_point(env, w);
12335 		mark_jmp_point(env, w);
12336 	}
12337 
12338 	if (insn_state[w] == 0) {
12339 		/* tree-edge */
12340 		insn_state[t] = DISCOVERED | e;
12341 		insn_state[w] = DISCOVERED;
12342 		if (env->cfg.cur_stack >= env->prog->len)
12343 			return -E2BIG;
12344 		insn_stack[env->cfg.cur_stack++] = w;
12345 		return KEEP_EXPLORING;
12346 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12347 		if (loop_ok && env->bpf_capable)
12348 			return DONE_EXPLORING;
12349 		verbose_linfo(env, t, "%d: ", t);
12350 		verbose_linfo(env, w, "%d: ", w);
12351 		verbose(env, "back-edge from insn %d to %d\n", t, w);
12352 		return -EINVAL;
12353 	} else if (insn_state[w] == EXPLORED) {
12354 		/* forward- or cross-edge */
12355 		insn_state[t] = DISCOVERED | e;
12356 	} else {
12357 		verbose(env, "insn state internal bug\n");
12358 		return -EFAULT;
12359 	}
12360 	return DONE_EXPLORING;
12361 }
12362 
12363 static int visit_func_call_insn(int t, struct bpf_insn *insns,
12364 				struct bpf_verifier_env *env,
12365 				bool visit_callee)
12366 {
12367 	int ret;
12368 
12369 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12370 	if (ret)
12371 		return ret;
12372 
12373 	mark_prune_point(env, t + 1);
12374 	/* when we exit from subprog, we need to record non-linear history */
12375 	mark_jmp_point(env, t + 1);
12376 
12377 	if (visit_callee) {
12378 		mark_prune_point(env, t);
12379 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12380 				/* It's ok to allow recursion from CFG point of
12381 				 * view. __check_func_call() will do the actual
12382 				 * check.
12383 				 */
12384 				bpf_pseudo_func(insns + t));
12385 	}
12386 	return ret;
12387 }
12388 
12389 /* Visits the instruction at index t and returns one of the following:
12390  *  < 0 - an error occurred
12391  *  DONE_EXPLORING - the instruction was fully explored
12392  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
12393  */
12394 static int visit_insn(int t, struct bpf_verifier_env *env)
12395 {
12396 	struct bpf_insn *insns = env->prog->insnsi;
12397 	int ret;
12398 
12399 	if (bpf_pseudo_func(insns + t))
12400 		return visit_func_call_insn(t, insns, env, true);
12401 
12402 	/* All non-branch instructions have a single fall-through edge. */
12403 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12404 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
12405 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
12406 
12407 	switch (BPF_OP(insns[t].code)) {
12408 	case BPF_EXIT:
12409 		return DONE_EXPLORING;
12410 
12411 	case BPF_CALL:
12412 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
12413 			/* Mark this call insn as a prune point to trigger
12414 			 * is_state_visited() check before call itself is
12415 			 * processed by __check_func_call(). Otherwise new
12416 			 * async state will be pushed for further exploration.
12417 			 */
12418 			mark_prune_point(env, t);
12419 		return visit_func_call_insn(t, insns, env,
12420 					    insns[t].src_reg == BPF_PSEUDO_CALL);
12421 
12422 	case BPF_JA:
12423 		if (BPF_SRC(insns[t].code) != BPF_K)
12424 			return -EINVAL;
12425 
12426 		/* unconditional jump with single edge */
12427 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12428 				true);
12429 		if (ret)
12430 			return ret;
12431 
12432 		mark_prune_point(env, t + insns[t].off + 1);
12433 		mark_jmp_point(env, t + insns[t].off + 1);
12434 
12435 		return ret;
12436 
12437 	default:
12438 		/* conditional jump with two edges */
12439 		mark_prune_point(env, t);
12440 
12441 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12442 		if (ret)
12443 			return ret;
12444 
12445 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12446 	}
12447 }
12448 
12449 /* non-recursive depth-first-search to detect loops in BPF program
12450  * loop == back-edge in directed graph
12451  */
12452 static int check_cfg(struct bpf_verifier_env *env)
12453 {
12454 	int insn_cnt = env->prog->len;
12455 	int *insn_stack, *insn_state;
12456 	int ret = 0;
12457 	int i;
12458 
12459 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12460 	if (!insn_state)
12461 		return -ENOMEM;
12462 
12463 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12464 	if (!insn_stack) {
12465 		kvfree(insn_state);
12466 		return -ENOMEM;
12467 	}
12468 
12469 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12470 	insn_stack[0] = 0; /* 0 is the first instruction */
12471 	env->cfg.cur_stack = 1;
12472 
12473 	while (env->cfg.cur_stack > 0) {
12474 		int t = insn_stack[env->cfg.cur_stack - 1];
12475 
12476 		ret = visit_insn(t, env);
12477 		switch (ret) {
12478 		case DONE_EXPLORING:
12479 			insn_state[t] = EXPLORED;
12480 			env->cfg.cur_stack--;
12481 			break;
12482 		case KEEP_EXPLORING:
12483 			break;
12484 		default:
12485 			if (ret > 0) {
12486 				verbose(env, "visit_insn internal bug\n");
12487 				ret = -EFAULT;
12488 			}
12489 			goto err_free;
12490 		}
12491 	}
12492 
12493 	if (env->cfg.cur_stack < 0) {
12494 		verbose(env, "pop stack internal bug\n");
12495 		ret = -EFAULT;
12496 		goto err_free;
12497 	}
12498 
12499 	for (i = 0; i < insn_cnt; i++) {
12500 		if (insn_state[i] != EXPLORED) {
12501 			verbose(env, "unreachable insn %d\n", i);
12502 			ret = -EINVAL;
12503 			goto err_free;
12504 		}
12505 	}
12506 	ret = 0; /* cfg looks good */
12507 
12508 err_free:
12509 	kvfree(insn_state);
12510 	kvfree(insn_stack);
12511 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
12512 	return ret;
12513 }
12514 
12515 static int check_abnormal_return(struct bpf_verifier_env *env)
12516 {
12517 	int i;
12518 
12519 	for (i = 1; i < env->subprog_cnt; i++) {
12520 		if (env->subprog_info[i].has_ld_abs) {
12521 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12522 			return -EINVAL;
12523 		}
12524 		if (env->subprog_info[i].has_tail_call) {
12525 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12526 			return -EINVAL;
12527 		}
12528 	}
12529 	return 0;
12530 }
12531 
12532 /* The minimum supported BTF func info size */
12533 #define MIN_BPF_FUNCINFO_SIZE	8
12534 #define MAX_FUNCINFO_REC_SIZE	252
12535 
12536 static int check_btf_func(struct bpf_verifier_env *env,
12537 			  const union bpf_attr *attr,
12538 			  bpfptr_t uattr)
12539 {
12540 	const struct btf_type *type, *func_proto, *ret_type;
12541 	u32 i, nfuncs, urec_size, min_size;
12542 	u32 krec_size = sizeof(struct bpf_func_info);
12543 	struct bpf_func_info *krecord;
12544 	struct bpf_func_info_aux *info_aux = NULL;
12545 	struct bpf_prog *prog;
12546 	const struct btf *btf;
12547 	bpfptr_t urecord;
12548 	u32 prev_offset = 0;
12549 	bool scalar_return;
12550 	int ret = -ENOMEM;
12551 
12552 	nfuncs = attr->func_info_cnt;
12553 	if (!nfuncs) {
12554 		if (check_abnormal_return(env))
12555 			return -EINVAL;
12556 		return 0;
12557 	}
12558 
12559 	if (nfuncs != env->subprog_cnt) {
12560 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12561 		return -EINVAL;
12562 	}
12563 
12564 	urec_size = attr->func_info_rec_size;
12565 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12566 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
12567 	    urec_size % sizeof(u32)) {
12568 		verbose(env, "invalid func info rec size %u\n", urec_size);
12569 		return -EINVAL;
12570 	}
12571 
12572 	prog = env->prog;
12573 	btf = prog->aux->btf;
12574 
12575 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12576 	min_size = min_t(u32, krec_size, urec_size);
12577 
12578 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12579 	if (!krecord)
12580 		return -ENOMEM;
12581 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12582 	if (!info_aux)
12583 		goto err_free;
12584 
12585 	for (i = 0; i < nfuncs; i++) {
12586 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12587 		if (ret) {
12588 			if (ret == -E2BIG) {
12589 				verbose(env, "nonzero tailing record in func info");
12590 				/* set the size kernel expects so loader can zero
12591 				 * out the rest of the record.
12592 				 */
12593 				if (copy_to_bpfptr_offset(uattr,
12594 							  offsetof(union bpf_attr, func_info_rec_size),
12595 							  &min_size, sizeof(min_size)))
12596 					ret = -EFAULT;
12597 			}
12598 			goto err_free;
12599 		}
12600 
12601 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12602 			ret = -EFAULT;
12603 			goto err_free;
12604 		}
12605 
12606 		/* check insn_off */
12607 		ret = -EINVAL;
12608 		if (i == 0) {
12609 			if (krecord[i].insn_off) {
12610 				verbose(env,
12611 					"nonzero insn_off %u for the first func info record",
12612 					krecord[i].insn_off);
12613 				goto err_free;
12614 			}
12615 		} else if (krecord[i].insn_off <= prev_offset) {
12616 			verbose(env,
12617 				"same or smaller insn offset (%u) than previous func info record (%u)",
12618 				krecord[i].insn_off, prev_offset);
12619 			goto err_free;
12620 		}
12621 
12622 		if (env->subprog_info[i].start != krecord[i].insn_off) {
12623 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12624 			goto err_free;
12625 		}
12626 
12627 		/* check type_id */
12628 		type = btf_type_by_id(btf, krecord[i].type_id);
12629 		if (!type || !btf_type_is_func(type)) {
12630 			verbose(env, "invalid type id %d in func info",
12631 				krecord[i].type_id);
12632 			goto err_free;
12633 		}
12634 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12635 
12636 		func_proto = btf_type_by_id(btf, type->type);
12637 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12638 			/* btf_func_check() already verified it during BTF load */
12639 			goto err_free;
12640 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12641 		scalar_return =
12642 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12643 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12644 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12645 			goto err_free;
12646 		}
12647 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12648 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12649 			goto err_free;
12650 		}
12651 
12652 		prev_offset = krecord[i].insn_off;
12653 		bpfptr_add(&urecord, urec_size);
12654 	}
12655 
12656 	prog->aux->func_info = krecord;
12657 	prog->aux->func_info_cnt = nfuncs;
12658 	prog->aux->func_info_aux = info_aux;
12659 	return 0;
12660 
12661 err_free:
12662 	kvfree(krecord);
12663 	kfree(info_aux);
12664 	return ret;
12665 }
12666 
12667 static void adjust_btf_func(struct bpf_verifier_env *env)
12668 {
12669 	struct bpf_prog_aux *aux = env->prog->aux;
12670 	int i;
12671 
12672 	if (!aux->func_info)
12673 		return;
12674 
12675 	for (i = 0; i < env->subprog_cnt; i++)
12676 		aux->func_info[i].insn_off = env->subprog_info[i].start;
12677 }
12678 
12679 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
12680 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
12681 
12682 static int check_btf_line(struct bpf_verifier_env *env,
12683 			  const union bpf_attr *attr,
12684 			  bpfptr_t uattr)
12685 {
12686 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12687 	struct bpf_subprog_info *sub;
12688 	struct bpf_line_info *linfo;
12689 	struct bpf_prog *prog;
12690 	const struct btf *btf;
12691 	bpfptr_t ulinfo;
12692 	int err;
12693 
12694 	nr_linfo = attr->line_info_cnt;
12695 	if (!nr_linfo)
12696 		return 0;
12697 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12698 		return -EINVAL;
12699 
12700 	rec_size = attr->line_info_rec_size;
12701 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12702 	    rec_size > MAX_LINEINFO_REC_SIZE ||
12703 	    rec_size & (sizeof(u32) - 1))
12704 		return -EINVAL;
12705 
12706 	/* Need to zero it in case the userspace may
12707 	 * pass in a smaller bpf_line_info object.
12708 	 */
12709 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12710 			 GFP_KERNEL | __GFP_NOWARN);
12711 	if (!linfo)
12712 		return -ENOMEM;
12713 
12714 	prog = env->prog;
12715 	btf = prog->aux->btf;
12716 
12717 	s = 0;
12718 	sub = env->subprog_info;
12719 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12720 	expected_size = sizeof(struct bpf_line_info);
12721 	ncopy = min_t(u32, expected_size, rec_size);
12722 	for (i = 0; i < nr_linfo; i++) {
12723 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12724 		if (err) {
12725 			if (err == -E2BIG) {
12726 				verbose(env, "nonzero tailing record in line_info");
12727 				if (copy_to_bpfptr_offset(uattr,
12728 							  offsetof(union bpf_attr, line_info_rec_size),
12729 							  &expected_size, sizeof(expected_size)))
12730 					err = -EFAULT;
12731 			}
12732 			goto err_free;
12733 		}
12734 
12735 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12736 			err = -EFAULT;
12737 			goto err_free;
12738 		}
12739 
12740 		/*
12741 		 * Check insn_off to ensure
12742 		 * 1) strictly increasing AND
12743 		 * 2) bounded by prog->len
12744 		 *
12745 		 * The linfo[0].insn_off == 0 check logically falls into
12746 		 * the later "missing bpf_line_info for func..." case
12747 		 * because the first linfo[0].insn_off must be the
12748 		 * first sub also and the first sub must have
12749 		 * subprog_info[0].start == 0.
12750 		 */
12751 		if ((i && linfo[i].insn_off <= prev_offset) ||
12752 		    linfo[i].insn_off >= prog->len) {
12753 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12754 				i, linfo[i].insn_off, prev_offset,
12755 				prog->len);
12756 			err = -EINVAL;
12757 			goto err_free;
12758 		}
12759 
12760 		if (!prog->insnsi[linfo[i].insn_off].code) {
12761 			verbose(env,
12762 				"Invalid insn code at line_info[%u].insn_off\n",
12763 				i);
12764 			err = -EINVAL;
12765 			goto err_free;
12766 		}
12767 
12768 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12769 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12770 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12771 			err = -EINVAL;
12772 			goto err_free;
12773 		}
12774 
12775 		if (s != env->subprog_cnt) {
12776 			if (linfo[i].insn_off == sub[s].start) {
12777 				sub[s].linfo_idx = i;
12778 				s++;
12779 			} else if (sub[s].start < linfo[i].insn_off) {
12780 				verbose(env, "missing bpf_line_info for func#%u\n", s);
12781 				err = -EINVAL;
12782 				goto err_free;
12783 			}
12784 		}
12785 
12786 		prev_offset = linfo[i].insn_off;
12787 		bpfptr_add(&ulinfo, rec_size);
12788 	}
12789 
12790 	if (s != env->subprog_cnt) {
12791 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12792 			env->subprog_cnt - s, s);
12793 		err = -EINVAL;
12794 		goto err_free;
12795 	}
12796 
12797 	prog->aux->linfo = linfo;
12798 	prog->aux->nr_linfo = nr_linfo;
12799 
12800 	return 0;
12801 
12802 err_free:
12803 	kvfree(linfo);
12804 	return err;
12805 }
12806 
12807 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
12808 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
12809 
12810 static int check_core_relo(struct bpf_verifier_env *env,
12811 			   const union bpf_attr *attr,
12812 			   bpfptr_t uattr)
12813 {
12814 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12815 	struct bpf_core_relo core_relo = {};
12816 	struct bpf_prog *prog = env->prog;
12817 	const struct btf *btf = prog->aux->btf;
12818 	struct bpf_core_ctx ctx = {
12819 		.log = &env->log,
12820 		.btf = btf,
12821 	};
12822 	bpfptr_t u_core_relo;
12823 	int err;
12824 
12825 	nr_core_relo = attr->core_relo_cnt;
12826 	if (!nr_core_relo)
12827 		return 0;
12828 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12829 		return -EINVAL;
12830 
12831 	rec_size = attr->core_relo_rec_size;
12832 	if (rec_size < MIN_CORE_RELO_SIZE ||
12833 	    rec_size > MAX_CORE_RELO_SIZE ||
12834 	    rec_size % sizeof(u32))
12835 		return -EINVAL;
12836 
12837 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12838 	expected_size = sizeof(struct bpf_core_relo);
12839 	ncopy = min_t(u32, expected_size, rec_size);
12840 
12841 	/* Unlike func_info and line_info, copy and apply each CO-RE
12842 	 * relocation record one at a time.
12843 	 */
12844 	for (i = 0; i < nr_core_relo; i++) {
12845 		/* future proofing when sizeof(bpf_core_relo) changes */
12846 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12847 		if (err) {
12848 			if (err == -E2BIG) {
12849 				verbose(env, "nonzero tailing record in core_relo");
12850 				if (copy_to_bpfptr_offset(uattr,
12851 							  offsetof(union bpf_attr, core_relo_rec_size),
12852 							  &expected_size, sizeof(expected_size)))
12853 					err = -EFAULT;
12854 			}
12855 			break;
12856 		}
12857 
12858 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12859 			err = -EFAULT;
12860 			break;
12861 		}
12862 
12863 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12864 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12865 				i, core_relo.insn_off, prog->len);
12866 			err = -EINVAL;
12867 			break;
12868 		}
12869 
12870 		err = bpf_core_apply(&ctx, &core_relo, i,
12871 				     &prog->insnsi[core_relo.insn_off / 8]);
12872 		if (err)
12873 			break;
12874 		bpfptr_add(&u_core_relo, rec_size);
12875 	}
12876 	return err;
12877 }
12878 
12879 static int check_btf_info(struct bpf_verifier_env *env,
12880 			  const union bpf_attr *attr,
12881 			  bpfptr_t uattr)
12882 {
12883 	struct btf *btf;
12884 	int err;
12885 
12886 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
12887 		if (check_abnormal_return(env))
12888 			return -EINVAL;
12889 		return 0;
12890 	}
12891 
12892 	btf = btf_get_by_fd(attr->prog_btf_fd);
12893 	if (IS_ERR(btf))
12894 		return PTR_ERR(btf);
12895 	if (btf_is_kernel(btf)) {
12896 		btf_put(btf);
12897 		return -EACCES;
12898 	}
12899 	env->prog->aux->btf = btf;
12900 
12901 	err = check_btf_func(env, attr, uattr);
12902 	if (err)
12903 		return err;
12904 
12905 	err = check_btf_line(env, attr, uattr);
12906 	if (err)
12907 		return err;
12908 
12909 	err = check_core_relo(env, attr, uattr);
12910 	if (err)
12911 		return err;
12912 
12913 	return 0;
12914 }
12915 
12916 /* check %cur's range satisfies %old's */
12917 static bool range_within(struct bpf_reg_state *old,
12918 			 struct bpf_reg_state *cur)
12919 {
12920 	return old->umin_value <= cur->umin_value &&
12921 	       old->umax_value >= cur->umax_value &&
12922 	       old->smin_value <= cur->smin_value &&
12923 	       old->smax_value >= cur->smax_value &&
12924 	       old->u32_min_value <= cur->u32_min_value &&
12925 	       old->u32_max_value >= cur->u32_max_value &&
12926 	       old->s32_min_value <= cur->s32_min_value &&
12927 	       old->s32_max_value >= cur->s32_max_value;
12928 }
12929 
12930 /* If in the old state two registers had the same id, then they need to have
12931  * the same id in the new state as well.  But that id could be different from
12932  * the old state, so we need to track the mapping from old to new ids.
12933  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12934  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
12935  * regs with a different old id could still have new id 9, we don't care about
12936  * that.
12937  * So we look through our idmap to see if this old id has been seen before.  If
12938  * so, we require the new id to match; otherwise, we add the id pair to the map.
12939  */
12940 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12941 {
12942 	unsigned int i;
12943 
12944 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12945 		if (!idmap[i].old) {
12946 			/* Reached an empty slot; haven't seen this id before */
12947 			idmap[i].old = old_id;
12948 			idmap[i].cur = cur_id;
12949 			return true;
12950 		}
12951 		if (idmap[i].old == old_id)
12952 			return idmap[i].cur == cur_id;
12953 	}
12954 	/* We ran out of idmap slots, which should be impossible */
12955 	WARN_ON_ONCE(1);
12956 	return false;
12957 }
12958 
12959 static void clean_func_state(struct bpf_verifier_env *env,
12960 			     struct bpf_func_state *st)
12961 {
12962 	enum bpf_reg_liveness live;
12963 	int i, j;
12964 
12965 	for (i = 0; i < BPF_REG_FP; i++) {
12966 		live = st->regs[i].live;
12967 		/* liveness must not touch this register anymore */
12968 		st->regs[i].live |= REG_LIVE_DONE;
12969 		if (!(live & REG_LIVE_READ))
12970 			/* since the register is unused, clear its state
12971 			 * to make further comparison simpler
12972 			 */
12973 			__mark_reg_not_init(env, &st->regs[i]);
12974 	}
12975 
12976 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12977 		live = st->stack[i].spilled_ptr.live;
12978 		/* liveness must not touch this stack slot anymore */
12979 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
12980 		if (!(live & REG_LIVE_READ)) {
12981 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
12982 			for (j = 0; j < BPF_REG_SIZE; j++)
12983 				st->stack[i].slot_type[j] = STACK_INVALID;
12984 		}
12985 	}
12986 }
12987 
12988 static void clean_verifier_state(struct bpf_verifier_env *env,
12989 				 struct bpf_verifier_state *st)
12990 {
12991 	int i;
12992 
12993 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
12994 		/* all regs in this state in all frames were already marked */
12995 		return;
12996 
12997 	for (i = 0; i <= st->curframe; i++)
12998 		clean_func_state(env, st->frame[i]);
12999 }
13000 
13001 /* the parentage chains form a tree.
13002  * the verifier states are added to state lists at given insn and
13003  * pushed into state stack for future exploration.
13004  * when the verifier reaches bpf_exit insn some of the verifer states
13005  * stored in the state lists have their final liveness state already,
13006  * but a lot of states will get revised from liveness point of view when
13007  * the verifier explores other branches.
13008  * Example:
13009  * 1: r0 = 1
13010  * 2: if r1 == 100 goto pc+1
13011  * 3: r0 = 2
13012  * 4: exit
13013  * when the verifier reaches exit insn the register r0 in the state list of
13014  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
13015  * of insn 2 and goes exploring further. At the insn 4 it will walk the
13016  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
13017  *
13018  * Since the verifier pushes the branch states as it sees them while exploring
13019  * the program the condition of walking the branch instruction for the second
13020  * time means that all states below this branch were already explored and
13021  * their final liveness marks are already propagated.
13022  * Hence when the verifier completes the search of state list in is_state_visited()
13023  * we can call this clean_live_states() function to mark all liveness states
13024  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
13025  * will not be used.
13026  * This function also clears the registers and stack for states that !READ
13027  * to simplify state merging.
13028  *
13029  * Important note here that walking the same branch instruction in the callee
13030  * doesn't meant that the states are DONE. The verifier has to compare
13031  * the callsites
13032  */
13033 static void clean_live_states(struct bpf_verifier_env *env, int insn,
13034 			      struct bpf_verifier_state *cur)
13035 {
13036 	struct bpf_verifier_state_list *sl;
13037 	int i;
13038 
13039 	sl = *explored_state(env, insn);
13040 	while (sl) {
13041 		if (sl->state.branches)
13042 			goto next;
13043 		if (sl->state.insn_idx != insn ||
13044 		    sl->state.curframe != cur->curframe)
13045 			goto next;
13046 		for (i = 0; i <= cur->curframe; i++)
13047 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
13048 				goto next;
13049 		clean_verifier_state(env, &sl->state);
13050 next:
13051 		sl = sl->next;
13052 	}
13053 }
13054 
13055 /* Returns true if (rold safe implies rcur safe) */
13056 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
13057 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
13058 {
13059 	bool equal;
13060 
13061 	if (!(rold->live & REG_LIVE_READ))
13062 		/* explored state didn't use this */
13063 		return true;
13064 
13065 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
13066 
13067 	if (rold->type == NOT_INIT)
13068 		/* explored state can't have used this */
13069 		return true;
13070 	if (rcur->type == NOT_INIT)
13071 		return false;
13072 	switch (base_type(rold->type)) {
13073 	case SCALAR_VALUE:
13074 		if (equal)
13075 			return true;
13076 		if (env->explore_alu_limits)
13077 			return false;
13078 		if (rcur->type == SCALAR_VALUE) {
13079 			if (!rold->precise)
13080 				return true;
13081 			/* new val must satisfy old val knowledge */
13082 			return range_within(rold, rcur) &&
13083 			       tnum_in(rold->var_off, rcur->var_off);
13084 		} else {
13085 			/* We're trying to use a pointer in place of a scalar.
13086 			 * Even if the scalar was unbounded, this could lead to
13087 			 * pointer leaks because scalars are allowed to leak
13088 			 * while pointers are not. We could make this safe in
13089 			 * special cases if root is calling us, but it's
13090 			 * probably not worth the hassle.
13091 			 */
13092 			return false;
13093 		}
13094 	case PTR_TO_MAP_KEY:
13095 	case PTR_TO_MAP_VALUE:
13096 		/* a PTR_TO_MAP_VALUE could be safe to use as a
13097 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
13098 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
13099 		 * checked, doing so could have affected others with the same
13100 		 * id, and we can't check for that because we lost the id when
13101 		 * we converted to a PTR_TO_MAP_VALUE.
13102 		 */
13103 		if (type_may_be_null(rold->type)) {
13104 			if (!type_may_be_null(rcur->type))
13105 				return false;
13106 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
13107 				return false;
13108 			/* Check our ids match any regs they're supposed to */
13109 			return check_ids(rold->id, rcur->id, idmap);
13110 		}
13111 
13112 		/* If the new min/max/var_off satisfy the old ones and
13113 		 * everything else matches, we are OK.
13114 		 * 'id' is not compared, since it's only used for maps with
13115 		 * bpf_spin_lock inside map element and in such cases if
13116 		 * the rest of the prog is valid for one map element then
13117 		 * it's valid for all map elements regardless of the key
13118 		 * used in bpf_map_lookup()
13119 		 */
13120 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
13121 		       range_within(rold, rcur) &&
13122 		       tnum_in(rold->var_off, rcur->var_off) &&
13123 		       check_ids(rold->id, rcur->id, idmap);
13124 	case PTR_TO_PACKET_META:
13125 	case PTR_TO_PACKET:
13126 		if (rcur->type != rold->type)
13127 			return false;
13128 		/* We must have at least as much range as the old ptr
13129 		 * did, so that any accesses which were safe before are
13130 		 * still safe.  This is true even if old range < old off,
13131 		 * since someone could have accessed through (ptr - k), or
13132 		 * even done ptr -= k in a register, to get a safe access.
13133 		 */
13134 		if (rold->range > rcur->range)
13135 			return false;
13136 		/* If the offsets don't match, we can't trust our alignment;
13137 		 * nor can we be sure that we won't fall out of range.
13138 		 */
13139 		if (rold->off != rcur->off)
13140 			return false;
13141 		/* id relations must be preserved */
13142 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
13143 			return false;
13144 		/* new val must satisfy old val knowledge */
13145 		return range_within(rold, rcur) &&
13146 		       tnum_in(rold->var_off, rcur->var_off);
13147 	case PTR_TO_STACK:
13148 		/* two stack pointers are equal only if they're pointing to
13149 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
13150 		 */
13151 		return equal && rold->frameno == rcur->frameno;
13152 	default:
13153 		/* Only valid matches are exact, which memcmp() */
13154 		return equal;
13155 	}
13156 
13157 	/* Shouldn't get here; if we do, say it's not safe */
13158 	WARN_ON_ONCE(1);
13159 	return false;
13160 }
13161 
13162 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
13163 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
13164 {
13165 	int i, spi;
13166 
13167 	/* walk slots of the explored stack and ignore any additional
13168 	 * slots in the current stack, since explored(safe) state
13169 	 * didn't use them
13170 	 */
13171 	for (i = 0; i < old->allocated_stack; i++) {
13172 		spi = i / BPF_REG_SIZE;
13173 
13174 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
13175 			i += BPF_REG_SIZE - 1;
13176 			/* explored state didn't use this */
13177 			continue;
13178 		}
13179 
13180 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
13181 			continue;
13182 
13183 		/* explored stack has more populated slots than current stack
13184 		 * and these slots were used
13185 		 */
13186 		if (i >= cur->allocated_stack)
13187 			return false;
13188 
13189 		/* if old state was safe with misc data in the stack
13190 		 * it will be safe with zero-initialized stack.
13191 		 * The opposite is not true
13192 		 */
13193 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
13194 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
13195 			continue;
13196 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
13197 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
13198 			/* Ex: old explored (safe) state has STACK_SPILL in
13199 			 * this stack slot, but current has STACK_MISC ->
13200 			 * this verifier states are not equivalent,
13201 			 * return false to continue verification of this path
13202 			 */
13203 			return false;
13204 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
13205 			continue;
13206 		if (!is_spilled_reg(&old->stack[spi]))
13207 			continue;
13208 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
13209 			     &cur->stack[spi].spilled_ptr, idmap))
13210 			/* when explored and current stack slot are both storing
13211 			 * spilled registers, check that stored pointers types
13212 			 * are the same as well.
13213 			 * Ex: explored safe path could have stored
13214 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
13215 			 * but current path has stored:
13216 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
13217 			 * such verifier states are not equivalent.
13218 			 * return false to continue verification of this path
13219 			 */
13220 			return false;
13221 	}
13222 	return true;
13223 }
13224 
13225 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
13226 {
13227 	if (old->acquired_refs != cur->acquired_refs)
13228 		return false;
13229 	return !memcmp(old->refs, cur->refs,
13230 		       sizeof(*old->refs) * old->acquired_refs);
13231 }
13232 
13233 /* compare two verifier states
13234  *
13235  * all states stored in state_list are known to be valid, since
13236  * verifier reached 'bpf_exit' instruction through them
13237  *
13238  * this function is called when verifier exploring different branches of
13239  * execution popped from the state stack. If it sees an old state that has
13240  * more strict register state and more strict stack state then this execution
13241  * branch doesn't need to be explored further, since verifier already
13242  * concluded that more strict state leads to valid finish.
13243  *
13244  * Therefore two states are equivalent if register state is more conservative
13245  * and explored stack state is more conservative than the current one.
13246  * Example:
13247  *       explored                   current
13248  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
13249  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
13250  *
13251  * In other words if current stack state (one being explored) has more
13252  * valid slots than old one that already passed validation, it means
13253  * the verifier can stop exploring and conclude that current state is valid too
13254  *
13255  * Similarly with registers. If explored state has register type as invalid
13256  * whereas register type in current state is meaningful, it means that
13257  * the current state will reach 'bpf_exit' instruction safely
13258  */
13259 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
13260 			      struct bpf_func_state *cur)
13261 {
13262 	int i;
13263 
13264 	for (i = 0; i < MAX_BPF_REG; i++)
13265 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
13266 			     env->idmap_scratch))
13267 			return false;
13268 
13269 	if (!stacksafe(env, old, cur, env->idmap_scratch))
13270 		return false;
13271 
13272 	if (!refsafe(old, cur))
13273 		return false;
13274 
13275 	return true;
13276 }
13277 
13278 static bool states_equal(struct bpf_verifier_env *env,
13279 			 struct bpf_verifier_state *old,
13280 			 struct bpf_verifier_state *cur)
13281 {
13282 	int i;
13283 
13284 	if (old->curframe != cur->curframe)
13285 		return false;
13286 
13287 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
13288 
13289 	/* Verification state from speculative execution simulation
13290 	 * must never prune a non-speculative execution one.
13291 	 */
13292 	if (old->speculative && !cur->speculative)
13293 		return false;
13294 
13295 	if (old->active_lock.ptr != cur->active_lock.ptr)
13296 		return false;
13297 
13298 	/* Old and cur active_lock's have to be either both present
13299 	 * or both absent.
13300 	 */
13301 	if (!!old->active_lock.id != !!cur->active_lock.id)
13302 		return false;
13303 
13304 	if (old->active_lock.id &&
13305 	    !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
13306 		return false;
13307 
13308 	if (old->active_rcu_lock != cur->active_rcu_lock)
13309 		return false;
13310 
13311 	/* for states to be equal callsites have to be the same
13312 	 * and all frame states need to be equivalent
13313 	 */
13314 	for (i = 0; i <= old->curframe; i++) {
13315 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
13316 			return false;
13317 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13318 			return false;
13319 	}
13320 	return true;
13321 }
13322 
13323 /* Return 0 if no propagation happened. Return negative error code if error
13324  * happened. Otherwise, return the propagated bit.
13325  */
13326 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13327 				  struct bpf_reg_state *reg,
13328 				  struct bpf_reg_state *parent_reg)
13329 {
13330 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13331 	u8 flag = reg->live & REG_LIVE_READ;
13332 	int err;
13333 
13334 	/* When comes here, read flags of PARENT_REG or REG could be any of
13335 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13336 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13337 	 */
13338 	if (parent_flag == REG_LIVE_READ64 ||
13339 	    /* Or if there is no read flag from REG. */
13340 	    !flag ||
13341 	    /* Or if the read flag from REG is the same as PARENT_REG. */
13342 	    parent_flag == flag)
13343 		return 0;
13344 
13345 	err = mark_reg_read(env, reg, parent_reg, flag);
13346 	if (err)
13347 		return err;
13348 
13349 	return flag;
13350 }
13351 
13352 /* A write screens off any subsequent reads; but write marks come from the
13353  * straight-line code between a state and its parent.  When we arrive at an
13354  * equivalent state (jump target or such) we didn't arrive by the straight-line
13355  * code, so read marks in the state must propagate to the parent regardless
13356  * of the state's write marks. That's what 'parent == state->parent' comparison
13357  * in mark_reg_read() is for.
13358  */
13359 static int propagate_liveness(struct bpf_verifier_env *env,
13360 			      const struct bpf_verifier_state *vstate,
13361 			      struct bpf_verifier_state *vparent)
13362 {
13363 	struct bpf_reg_state *state_reg, *parent_reg;
13364 	struct bpf_func_state *state, *parent;
13365 	int i, frame, err = 0;
13366 
13367 	if (vparent->curframe != vstate->curframe) {
13368 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
13369 		     vparent->curframe, vstate->curframe);
13370 		return -EFAULT;
13371 	}
13372 	/* Propagate read liveness of registers... */
13373 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13374 	for (frame = 0; frame <= vstate->curframe; frame++) {
13375 		parent = vparent->frame[frame];
13376 		state = vstate->frame[frame];
13377 		parent_reg = parent->regs;
13378 		state_reg = state->regs;
13379 		/* We don't need to worry about FP liveness, it's read-only */
13380 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13381 			err = propagate_liveness_reg(env, &state_reg[i],
13382 						     &parent_reg[i]);
13383 			if (err < 0)
13384 				return err;
13385 			if (err == REG_LIVE_READ64)
13386 				mark_insn_zext(env, &parent_reg[i]);
13387 		}
13388 
13389 		/* Propagate stack slots. */
13390 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13391 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13392 			parent_reg = &parent->stack[i].spilled_ptr;
13393 			state_reg = &state->stack[i].spilled_ptr;
13394 			err = propagate_liveness_reg(env, state_reg,
13395 						     parent_reg);
13396 			if (err < 0)
13397 				return err;
13398 		}
13399 	}
13400 	return 0;
13401 }
13402 
13403 /* find precise scalars in the previous equivalent state and
13404  * propagate them into the current state
13405  */
13406 static int propagate_precision(struct bpf_verifier_env *env,
13407 			       const struct bpf_verifier_state *old)
13408 {
13409 	struct bpf_reg_state *state_reg;
13410 	struct bpf_func_state *state;
13411 	int i, err = 0, fr;
13412 
13413 	for (fr = old->curframe; fr >= 0; fr--) {
13414 		state = old->frame[fr];
13415 		state_reg = state->regs;
13416 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13417 			if (state_reg->type != SCALAR_VALUE ||
13418 			    !state_reg->precise)
13419 				continue;
13420 			if (env->log.level & BPF_LOG_LEVEL2)
13421 				verbose(env, "frame %d: propagating r%d\n", i, fr);
13422 			err = mark_chain_precision_frame(env, fr, i);
13423 			if (err < 0)
13424 				return err;
13425 		}
13426 
13427 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13428 			if (!is_spilled_reg(&state->stack[i]))
13429 				continue;
13430 			state_reg = &state->stack[i].spilled_ptr;
13431 			if (state_reg->type != SCALAR_VALUE ||
13432 			    !state_reg->precise)
13433 				continue;
13434 			if (env->log.level & BPF_LOG_LEVEL2)
13435 				verbose(env, "frame %d: propagating fp%d\n",
13436 					(-i - 1) * BPF_REG_SIZE, fr);
13437 			err = mark_chain_precision_stack_frame(env, fr, i);
13438 			if (err < 0)
13439 				return err;
13440 		}
13441 	}
13442 	return 0;
13443 }
13444 
13445 static bool states_maybe_looping(struct bpf_verifier_state *old,
13446 				 struct bpf_verifier_state *cur)
13447 {
13448 	struct bpf_func_state *fold, *fcur;
13449 	int i, fr = cur->curframe;
13450 
13451 	if (old->curframe != fr)
13452 		return false;
13453 
13454 	fold = old->frame[fr];
13455 	fcur = cur->frame[fr];
13456 	for (i = 0; i < MAX_BPF_REG; i++)
13457 		if (memcmp(&fold->regs[i], &fcur->regs[i],
13458 			   offsetof(struct bpf_reg_state, parent)))
13459 			return false;
13460 	return true;
13461 }
13462 
13463 
13464 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13465 {
13466 	struct bpf_verifier_state_list *new_sl;
13467 	struct bpf_verifier_state_list *sl, **pprev;
13468 	struct bpf_verifier_state *cur = env->cur_state, *new;
13469 	int i, j, err, states_cnt = 0;
13470 	bool add_new_state = env->test_state_freq ? true : false;
13471 
13472 	/* bpf progs typically have pruning point every 4 instructions
13473 	 * http://vger.kernel.org/bpfconf2019.html#session-1
13474 	 * Do not add new state for future pruning if the verifier hasn't seen
13475 	 * at least 2 jumps and at least 8 instructions.
13476 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13477 	 * In tests that amounts to up to 50% reduction into total verifier
13478 	 * memory consumption and 20% verifier time speedup.
13479 	 */
13480 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13481 	    env->insn_processed - env->prev_insn_processed >= 8)
13482 		add_new_state = true;
13483 
13484 	pprev = explored_state(env, insn_idx);
13485 	sl = *pprev;
13486 
13487 	clean_live_states(env, insn_idx, cur);
13488 
13489 	while (sl) {
13490 		states_cnt++;
13491 		if (sl->state.insn_idx != insn_idx)
13492 			goto next;
13493 
13494 		if (sl->state.branches) {
13495 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13496 
13497 			if (frame->in_async_callback_fn &&
13498 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13499 				/* Different async_entry_cnt means that the verifier is
13500 				 * processing another entry into async callback.
13501 				 * Seeing the same state is not an indication of infinite
13502 				 * loop or infinite recursion.
13503 				 * But finding the same state doesn't mean that it's safe
13504 				 * to stop processing the current state. The previous state
13505 				 * hasn't yet reached bpf_exit, since state.branches > 0.
13506 				 * Checking in_async_callback_fn alone is not enough either.
13507 				 * Since the verifier still needs to catch infinite loops
13508 				 * inside async callbacks.
13509 				 */
13510 			} else if (states_maybe_looping(&sl->state, cur) &&
13511 				   states_equal(env, &sl->state, cur)) {
13512 				verbose_linfo(env, insn_idx, "; ");
13513 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13514 				return -EINVAL;
13515 			}
13516 			/* if the verifier is processing a loop, avoid adding new state
13517 			 * too often, since different loop iterations have distinct
13518 			 * states and may not help future pruning.
13519 			 * This threshold shouldn't be too low to make sure that
13520 			 * a loop with large bound will be rejected quickly.
13521 			 * The most abusive loop will be:
13522 			 * r1 += 1
13523 			 * if r1 < 1000000 goto pc-2
13524 			 * 1M insn_procssed limit / 100 == 10k peak states.
13525 			 * This threshold shouldn't be too high either, since states
13526 			 * at the end of the loop are likely to be useful in pruning.
13527 			 */
13528 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13529 			    env->insn_processed - env->prev_insn_processed < 100)
13530 				add_new_state = false;
13531 			goto miss;
13532 		}
13533 		if (states_equal(env, &sl->state, cur)) {
13534 			sl->hit_cnt++;
13535 			/* reached equivalent register/stack state,
13536 			 * prune the search.
13537 			 * Registers read by the continuation are read by us.
13538 			 * If we have any write marks in env->cur_state, they
13539 			 * will prevent corresponding reads in the continuation
13540 			 * from reaching our parent (an explored_state).  Our
13541 			 * own state will get the read marks recorded, but
13542 			 * they'll be immediately forgotten as we're pruning
13543 			 * this state and will pop a new one.
13544 			 */
13545 			err = propagate_liveness(env, &sl->state, cur);
13546 
13547 			/* if previous state reached the exit with precision and
13548 			 * current state is equivalent to it (except precsion marks)
13549 			 * the precision needs to be propagated back in
13550 			 * the current state.
13551 			 */
13552 			err = err ? : push_jmp_history(env, cur);
13553 			err = err ? : propagate_precision(env, &sl->state);
13554 			if (err)
13555 				return err;
13556 			return 1;
13557 		}
13558 miss:
13559 		/* when new state is not going to be added do not increase miss count.
13560 		 * Otherwise several loop iterations will remove the state
13561 		 * recorded earlier. The goal of these heuristics is to have
13562 		 * states from some iterations of the loop (some in the beginning
13563 		 * and some at the end) to help pruning.
13564 		 */
13565 		if (add_new_state)
13566 			sl->miss_cnt++;
13567 		/* heuristic to determine whether this state is beneficial
13568 		 * to keep checking from state equivalence point of view.
13569 		 * Higher numbers increase max_states_per_insn and verification time,
13570 		 * but do not meaningfully decrease insn_processed.
13571 		 */
13572 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13573 			/* the state is unlikely to be useful. Remove it to
13574 			 * speed up verification
13575 			 */
13576 			*pprev = sl->next;
13577 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13578 				u32 br = sl->state.branches;
13579 
13580 				WARN_ONCE(br,
13581 					  "BUG live_done but branches_to_explore %d\n",
13582 					  br);
13583 				free_verifier_state(&sl->state, false);
13584 				kfree(sl);
13585 				env->peak_states--;
13586 			} else {
13587 				/* cannot free this state, since parentage chain may
13588 				 * walk it later. Add it for free_list instead to
13589 				 * be freed at the end of verification
13590 				 */
13591 				sl->next = env->free_list;
13592 				env->free_list = sl;
13593 			}
13594 			sl = *pprev;
13595 			continue;
13596 		}
13597 next:
13598 		pprev = &sl->next;
13599 		sl = *pprev;
13600 	}
13601 
13602 	if (env->max_states_per_insn < states_cnt)
13603 		env->max_states_per_insn = states_cnt;
13604 
13605 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13606 		return 0;
13607 
13608 	if (!add_new_state)
13609 		return 0;
13610 
13611 	/* There were no equivalent states, remember the current one.
13612 	 * Technically the current state is not proven to be safe yet,
13613 	 * but it will either reach outer most bpf_exit (which means it's safe)
13614 	 * or it will be rejected. When there are no loops the verifier won't be
13615 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13616 	 * again on the way to bpf_exit.
13617 	 * When looping the sl->state.branches will be > 0 and this state
13618 	 * will not be considered for equivalence until branches == 0.
13619 	 */
13620 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13621 	if (!new_sl)
13622 		return -ENOMEM;
13623 	env->total_states++;
13624 	env->peak_states++;
13625 	env->prev_jmps_processed = env->jmps_processed;
13626 	env->prev_insn_processed = env->insn_processed;
13627 
13628 	/* forget precise markings we inherited, see __mark_chain_precision */
13629 	if (env->bpf_capable)
13630 		mark_all_scalars_imprecise(env, cur);
13631 
13632 	/* add new state to the head of linked list */
13633 	new = &new_sl->state;
13634 	err = copy_verifier_state(new, cur);
13635 	if (err) {
13636 		free_verifier_state(new, false);
13637 		kfree(new_sl);
13638 		return err;
13639 	}
13640 	new->insn_idx = insn_idx;
13641 	WARN_ONCE(new->branches != 1,
13642 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13643 
13644 	cur->parent = new;
13645 	cur->first_insn_idx = insn_idx;
13646 	clear_jmp_history(cur);
13647 	new_sl->next = *explored_state(env, insn_idx);
13648 	*explored_state(env, insn_idx) = new_sl;
13649 	/* connect new state to parentage chain. Current frame needs all
13650 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
13651 	 * to the stack implicitly by JITs) so in callers' frames connect just
13652 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13653 	 * the state of the call instruction (with WRITTEN set), and r0 comes
13654 	 * from callee with its full parentage chain, anyway.
13655 	 */
13656 	/* clear write marks in current state: the writes we did are not writes
13657 	 * our child did, so they don't screen off its reads from us.
13658 	 * (There are no read marks in current state, because reads always mark
13659 	 * their parent and current state never has children yet.  Only
13660 	 * explored_states can get read marks.)
13661 	 */
13662 	for (j = 0; j <= cur->curframe; j++) {
13663 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13664 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13665 		for (i = 0; i < BPF_REG_FP; i++)
13666 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13667 	}
13668 
13669 	/* all stack frames are accessible from callee, clear them all */
13670 	for (j = 0; j <= cur->curframe; j++) {
13671 		struct bpf_func_state *frame = cur->frame[j];
13672 		struct bpf_func_state *newframe = new->frame[j];
13673 
13674 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13675 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13676 			frame->stack[i].spilled_ptr.parent =
13677 						&newframe->stack[i].spilled_ptr;
13678 		}
13679 	}
13680 	return 0;
13681 }
13682 
13683 /* Return true if it's OK to have the same insn return a different type. */
13684 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13685 {
13686 	switch (base_type(type)) {
13687 	case PTR_TO_CTX:
13688 	case PTR_TO_SOCKET:
13689 	case PTR_TO_SOCK_COMMON:
13690 	case PTR_TO_TCP_SOCK:
13691 	case PTR_TO_XDP_SOCK:
13692 	case PTR_TO_BTF_ID:
13693 		return false;
13694 	default:
13695 		return true;
13696 	}
13697 }
13698 
13699 /* If an instruction was previously used with particular pointer types, then we
13700  * need to be careful to avoid cases such as the below, where it may be ok
13701  * for one branch accessing the pointer, but not ok for the other branch:
13702  *
13703  * R1 = sock_ptr
13704  * goto X;
13705  * ...
13706  * R1 = some_other_valid_ptr;
13707  * goto X;
13708  * ...
13709  * R2 = *(u32 *)(R1 + 0);
13710  */
13711 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13712 {
13713 	return src != prev && (!reg_type_mismatch_ok(src) ||
13714 			       !reg_type_mismatch_ok(prev));
13715 }
13716 
13717 static int do_check(struct bpf_verifier_env *env)
13718 {
13719 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13720 	struct bpf_verifier_state *state = env->cur_state;
13721 	struct bpf_insn *insns = env->prog->insnsi;
13722 	struct bpf_reg_state *regs;
13723 	int insn_cnt = env->prog->len;
13724 	bool do_print_state = false;
13725 	int prev_insn_idx = -1;
13726 
13727 	for (;;) {
13728 		struct bpf_insn *insn;
13729 		u8 class;
13730 		int err;
13731 
13732 		env->prev_insn_idx = prev_insn_idx;
13733 		if (env->insn_idx >= insn_cnt) {
13734 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
13735 				env->insn_idx, insn_cnt);
13736 			return -EFAULT;
13737 		}
13738 
13739 		insn = &insns[env->insn_idx];
13740 		class = BPF_CLASS(insn->code);
13741 
13742 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13743 			verbose(env,
13744 				"BPF program is too large. Processed %d insn\n",
13745 				env->insn_processed);
13746 			return -E2BIG;
13747 		}
13748 
13749 		state->last_insn_idx = env->prev_insn_idx;
13750 
13751 		if (is_prune_point(env, env->insn_idx)) {
13752 			err = is_state_visited(env, env->insn_idx);
13753 			if (err < 0)
13754 				return err;
13755 			if (err == 1) {
13756 				/* found equivalent state, can prune the search */
13757 				if (env->log.level & BPF_LOG_LEVEL) {
13758 					if (do_print_state)
13759 						verbose(env, "\nfrom %d to %d%s: safe\n",
13760 							env->prev_insn_idx, env->insn_idx,
13761 							env->cur_state->speculative ?
13762 							" (speculative execution)" : "");
13763 					else
13764 						verbose(env, "%d: safe\n", env->insn_idx);
13765 				}
13766 				goto process_bpf_exit;
13767 			}
13768 		}
13769 
13770 		if (is_jmp_point(env, env->insn_idx)) {
13771 			err = push_jmp_history(env, state);
13772 			if (err)
13773 				return err;
13774 		}
13775 
13776 		if (signal_pending(current))
13777 			return -EAGAIN;
13778 
13779 		if (need_resched())
13780 			cond_resched();
13781 
13782 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13783 			verbose(env, "\nfrom %d to %d%s:",
13784 				env->prev_insn_idx, env->insn_idx,
13785 				env->cur_state->speculative ?
13786 				" (speculative execution)" : "");
13787 			print_verifier_state(env, state->frame[state->curframe], true);
13788 			do_print_state = false;
13789 		}
13790 
13791 		if (env->log.level & BPF_LOG_LEVEL) {
13792 			const struct bpf_insn_cbs cbs = {
13793 				.cb_call	= disasm_kfunc_name,
13794 				.cb_print	= verbose,
13795 				.private_data	= env,
13796 			};
13797 
13798 			if (verifier_state_scratched(env))
13799 				print_insn_state(env, state->frame[state->curframe]);
13800 
13801 			verbose_linfo(env, env->insn_idx, "; ");
13802 			env->prev_log_len = env->log.len_used;
13803 			verbose(env, "%d: ", env->insn_idx);
13804 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13805 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13806 			env->prev_log_len = env->log.len_used;
13807 		}
13808 
13809 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
13810 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13811 							   env->prev_insn_idx);
13812 			if (err)
13813 				return err;
13814 		}
13815 
13816 		regs = cur_regs(env);
13817 		sanitize_mark_insn_seen(env);
13818 		prev_insn_idx = env->insn_idx;
13819 
13820 		if (class == BPF_ALU || class == BPF_ALU64) {
13821 			err = check_alu_op(env, insn);
13822 			if (err)
13823 				return err;
13824 
13825 		} else if (class == BPF_LDX) {
13826 			enum bpf_reg_type *prev_src_type, src_reg_type;
13827 
13828 			/* check for reserved fields is already done */
13829 
13830 			/* check src operand */
13831 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13832 			if (err)
13833 				return err;
13834 
13835 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13836 			if (err)
13837 				return err;
13838 
13839 			src_reg_type = regs[insn->src_reg].type;
13840 
13841 			/* check that memory (src_reg + off) is readable,
13842 			 * the state of dst_reg will be updated by this func
13843 			 */
13844 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
13845 					       insn->off, BPF_SIZE(insn->code),
13846 					       BPF_READ, insn->dst_reg, false);
13847 			if (err)
13848 				return err;
13849 
13850 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13851 
13852 			if (*prev_src_type == NOT_INIT) {
13853 				/* saw a valid insn
13854 				 * dst_reg = *(u32 *)(src_reg + off)
13855 				 * save type to validate intersecting paths
13856 				 */
13857 				*prev_src_type = src_reg_type;
13858 
13859 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13860 				/* ABuser program is trying to use the same insn
13861 				 * dst_reg = *(u32*) (src_reg + off)
13862 				 * with different pointer types:
13863 				 * src_reg == ctx in one branch and
13864 				 * src_reg == stack|map in some other branch.
13865 				 * Reject it.
13866 				 */
13867 				verbose(env, "same insn cannot be used with different pointers\n");
13868 				return -EINVAL;
13869 			}
13870 
13871 		} else if (class == BPF_STX) {
13872 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
13873 
13874 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13875 				err = check_atomic(env, env->insn_idx, insn);
13876 				if (err)
13877 					return err;
13878 				env->insn_idx++;
13879 				continue;
13880 			}
13881 
13882 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13883 				verbose(env, "BPF_STX uses reserved fields\n");
13884 				return -EINVAL;
13885 			}
13886 
13887 			/* check src1 operand */
13888 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13889 			if (err)
13890 				return err;
13891 			/* check src2 operand */
13892 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13893 			if (err)
13894 				return err;
13895 
13896 			dst_reg_type = regs[insn->dst_reg].type;
13897 
13898 			/* check that memory (dst_reg + off) is writeable */
13899 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13900 					       insn->off, BPF_SIZE(insn->code),
13901 					       BPF_WRITE, insn->src_reg, false);
13902 			if (err)
13903 				return err;
13904 
13905 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13906 
13907 			if (*prev_dst_type == NOT_INIT) {
13908 				*prev_dst_type = dst_reg_type;
13909 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13910 				verbose(env, "same insn cannot be used with different pointers\n");
13911 				return -EINVAL;
13912 			}
13913 
13914 		} else if (class == BPF_ST) {
13915 			if (BPF_MODE(insn->code) != BPF_MEM ||
13916 			    insn->src_reg != BPF_REG_0) {
13917 				verbose(env, "BPF_ST uses reserved fields\n");
13918 				return -EINVAL;
13919 			}
13920 			/* check src operand */
13921 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13922 			if (err)
13923 				return err;
13924 
13925 			if (is_ctx_reg(env, insn->dst_reg)) {
13926 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13927 					insn->dst_reg,
13928 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13929 				return -EACCES;
13930 			}
13931 
13932 			/* check that memory (dst_reg + off) is writeable */
13933 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13934 					       insn->off, BPF_SIZE(insn->code),
13935 					       BPF_WRITE, -1, false);
13936 			if (err)
13937 				return err;
13938 
13939 		} else if (class == BPF_JMP || class == BPF_JMP32) {
13940 			u8 opcode = BPF_OP(insn->code);
13941 
13942 			env->jmps_processed++;
13943 			if (opcode == BPF_CALL) {
13944 				if (BPF_SRC(insn->code) != BPF_K ||
13945 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13946 				     && insn->off != 0) ||
13947 				    (insn->src_reg != BPF_REG_0 &&
13948 				     insn->src_reg != BPF_PSEUDO_CALL &&
13949 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13950 				    insn->dst_reg != BPF_REG_0 ||
13951 				    class == BPF_JMP32) {
13952 					verbose(env, "BPF_CALL uses reserved fields\n");
13953 					return -EINVAL;
13954 				}
13955 
13956 				if (env->cur_state->active_lock.ptr) {
13957 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13958 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
13959 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13960 					     (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13961 						verbose(env, "function calls are not allowed while holding a lock\n");
13962 						return -EINVAL;
13963 					}
13964 				}
13965 				if (insn->src_reg == BPF_PSEUDO_CALL)
13966 					err = check_func_call(env, insn, &env->insn_idx);
13967 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13968 					err = check_kfunc_call(env, insn, &env->insn_idx);
13969 				else
13970 					err = check_helper_call(env, insn, &env->insn_idx);
13971 				if (err)
13972 					return err;
13973 			} else if (opcode == BPF_JA) {
13974 				if (BPF_SRC(insn->code) != BPF_K ||
13975 				    insn->imm != 0 ||
13976 				    insn->src_reg != BPF_REG_0 ||
13977 				    insn->dst_reg != BPF_REG_0 ||
13978 				    class == BPF_JMP32) {
13979 					verbose(env, "BPF_JA uses reserved fields\n");
13980 					return -EINVAL;
13981 				}
13982 
13983 				env->insn_idx += insn->off + 1;
13984 				continue;
13985 
13986 			} else if (opcode == BPF_EXIT) {
13987 				if (BPF_SRC(insn->code) != BPF_K ||
13988 				    insn->imm != 0 ||
13989 				    insn->src_reg != BPF_REG_0 ||
13990 				    insn->dst_reg != BPF_REG_0 ||
13991 				    class == BPF_JMP32) {
13992 					verbose(env, "BPF_EXIT uses reserved fields\n");
13993 					return -EINVAL;
13994 				}
13995 
13996 				if (env->cur_state->active_lock.ptr) {
13997 					verbose(env, "bpf_spin_unlock is missing\n");
13998 					return -EINVAL;
13999 				}
14000 
14001 				if (env->cur_state->active_rcu_lock) {
14002 					verbose(env, "bpf_rcu_read_unlock is missing\n");
14003 					return -EINVAL;
14004 				}
14005 
14006 				/* We must do check_reference_leak here before
14007 				 * prepare_func_exit to handle the case when
14008 				 * state->curframe > 0, it may be a callback
14009 				 * function, for which reference_state must
14010 				 * match caller reference state when it exits.
14011 				 */
14012 				err = check_reference_leak(env);
14013 				if (err)
14014 					return err;
14015 
14016 				if (state->curframe) {
14017 					/* exit from nested function */
14018 					err = prepare_func_exit(env, &env->insn_idx);
14019 					if (err)
14020 						return err;
14021 					do_print_state = true;
14022 					continue;
14023 				}
14024 
14025 				err = check_return_code(env);
14026 				if (err)
14027 					return err;
14028 process_bpf_exit:
14029 				mark_verifier_state_scratched(env);
14030 				update_branch_counts(env, env->cur_state);
14031 				err = pop_stack(env, &prev_insn_idx,
14032 						&env->insn_idx, pop_log);
14033 				if (err < 0) {
14034 					if (err != -ENOENT)
14035 						return err;
14036 					break;
14037 				} else {
14038 					do_print_state = true;
14039 					continue;
14040 				}
14041 			} else {
14042 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
14043 				if (err)
14044 					return err;
14045 			}
14046 		} else if (class == BPF_LD) {
14047 			u8 mode = BPF_MODE(insn->code);
14048 
14049 			if (mode == BPF_ABS || mode == BPF_IND) {
14050 				err = check_ld_abs(env, insn);
14051 				if (err)
14052 					return err;
14053 
14054 			} else if (mode == BPF_IMM) {
14055 				err = check_ld_imm(env, insn);
14056 				if (err)
14057 					return err;
14058 
14059 				env->insn_idx++;
14060 				sanitize_mark_insn_seen(env);
14061 			} else {
14062 				verbose(env, "invalid BPF_LD mode\n");
14063 				return -EINVAL;
14064 			}
14065 		} else {
14066 			verbose(env, "unknown insn class %d\n", class);
14067 			return -EINVAL;
14068 		}
14069 
14070 		env->insn_idx++;
14071 	}
14072 
14073 	return 0;
14074 }
14075 
14076 static int find_btf_percpu_datasec(struct btf *btf)
14077 {
14078 	const struct btf_type *t;
14079 	const char *tname;
14080 	int i, n;
14081 
14082 	/*
14083 	 * Both vmlinux and module each have their own ".data..percpu"
14084 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
14085 	 * types to look at only module's own BTF types.
14086 	 */
14087 	n = btf_nr_types(btf);
14088 	if (btf_is_module(btf))
14089 		i = btf_nr_types(btf_vmlinux);
14090 	else
14091 		i = 1;
14092 
14093 	for(; i < n; i++) {
14094 		t = btf_type_by_id(btf, i);
14095 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
14096 			continue;
14097 
14098 		tname = btf_name_by_offset(btf, t->name_off);
14099 		if (!strcmp(tname, ".data..percpu"))
14100 			return i;
14101 	}
14102 
14103 	return -ENOENT;
14104 }
14105 
14106 /* replace pseudo btf_id with kernel symbol address */
14107 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
14108 			       struct bpf_insn *insn,
14109 			       struct bpf_insn_aux_data *aux)
14110 {
14111 	const struct btf_var_secinfo *vsi;
14112 	const struct btf_type *datasec;
14113 	struct btf_mod_pair *btf_mod;
14114 	const struct btf_type *t;
14115 	const char *sym_name;
14116 	bool percpu = false;
14117 	u32 type, id = insn->imm;
14118 	struct btf *btf;
14119 	s32 datasec_id;
14120 	u64 addr;
14121 	int i, btf_fd, err;
14122 
14123 	btf_fd = insn[1].imm;
14124 	if (btf_fd) {
14125 		btf = btf_get_by_fd(btf_fd);
14126 		if (IS_ERR(btf)) {
14127 			verbose(env, "invalid module BTF object FD specified.\n");
14128 			return -EINVAL;
14129 		}
14130 	} else {
14131 		if (!btf_vmlinux) {
14132 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
14133 			return -EINVAL;
14134 		}
14135 		btf = btf_vmlinux;
14136 		btf_get(btf);
14137 	}
14138 
14139 	t = btf_type_by_id(btf, id);
14140 	if (!t) {
14141 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
14142 		err = -ENOENT;
14143 		goto err_put;
14144 	}
14145 
14146 	if (!btf_type_is_var(t)) {
14147 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
14148 		err = -EINVAL;
14149 		goto err_put;
14150 	}
14151 
14152 	sym_name = btf_name_by_offset(btf, t->name_off);
14153 	addr = kallsyms_lookup_name(sym_name);
14154 	if (!addr) {
14155 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
14156 			sym_name);
14157 		err = -ENOENT;
14158 		goto err_put;
14159 	}
14160 
14161 	datasec_id = find_btf_percpu_datasec(btf);
14162 	if (datasec_id > 0) {
14163 		datasec = btf_type_by_id(btf, datasec_id);
14164 		for_each_vsi(i, datasec, vsi) {
14165 			if (vsi->type == id) {
14166 				percpu = true;
14167 				break;
14168 			}
14169 		}
14170 	}
14171 
14172 	insn[0].imm = (u32)addr;
14173 	insn[1].imm = addr >> 32;
14174 
14175 	type = t->type;
14176 	t = btf_type_skip_modifiers(btf, type, NULL);
14177 	if (percpu) {
14178 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
14179 		aux->btf_var.btf = btf;
14180 		aux->btf_var.btf_id = type;
14181 	} else if (!btf_type_is_struct(t)) {
14182 		const struct btf_type *ret;
14183 		const char *tname;
14184 		u32 tsize;
14185 
14186 		/* resolve the type size of ksym. */
14187 		ret = btf_resolve_size(btf, t, &tsize);
14188 		if (IS_ERR(ret)) {
14189 			tname = btf_name_by_offset(btf, t->name_off);
14190 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
14191 				tname, PTR_ERR(ret));
14192 			err = -EINVAL;
14193 			goto err_put;
14194 		}
14195 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
14196 		aux->btf_var.mem_size = tsize;
14197 	} else {
14198 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
14199 		aux->btf_var.btf = btf;
14200 		aux->btf_var.btf_id = type;
14201 	}
14202 
14203 	/* check whether we recorded this BTF (and maybe module) already */
14204 	for (i = 0; i < env->used_btf_cnt; i++) {
14205 		if (env->used_btfs[i].btf == btf) {
14206 			btf_put(btf);
14207 			return 0;
14208 		}
14209 	}
14210 
14211 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
14212 		err = -E2BIG;
14213 		goto err_put;
14214 	}
14215 
14216 	btf_mod = &env->used_btfs[env->used_btf_cnt];
14217 	btf_mod->btf = btf;
14218 	btf_mod->module = NULL;
14219 
14220 	/* if we reference variables from kernel module, bump its refcount */
14221 	if (btf_is_module(btf)) {
14222 		btf_mod->module = btf_try_get_module(btf);
14223 		if (!btf_mod->module) {
14224 			err = -ENXIO;
14225 			goto err_put;
14226 		}
14227 	}
14228 
14229 	env->used_btf_cnt++;
14230 
14231 	return 0;
14232 err_put:
14233 	btf_put(btf);
14234 	return err;
14235 }
14236 
14237 static bool is_tracing_prog_type(enum bpf_prog_type type)
14238 {
14239 	switch (type) {
14240 	case BPF_PROG_TYPE_KPROBE:
14241 	case BPF_PROG_TYPE_TRACEPOINT:
14242 	case BPF_PROG_TYPE_PERF_EVENT:
14243 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
14244 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
14245 		return true;
14246 	default:
14247 		return false;
14248 	}
14249 }
14250 
14251 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
14252 					struct bpf_map *map,
14253 					struct bpf_prog *prog)
14254 
14255 {
14256 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
14257 
14258 	if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
14259 		if (is_tracing_prog_type(prog_type)) {
14260 			verbose(env, "tracing progs cannot use bpf_list_head yet\n");
14261 			return -EINVAL;
14262 		}
14263 	}
14264 
14265 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
14266 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
14267 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
14268 			return -EINVAL;
14269 		}
14270 
14271 		if (is_tracing_prog_type(prog_type)) {
14272 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
14273 			return -EINVAL;
14274 		}
14275 
14276 		if (prog->aux->sleepable) {
14277 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
14278 			return -EINVAL;
14279 		}
14280 	}
14281 
14282 	if (btf_record_has_field(map->record, BPF_TIMER)) {
14283 		if (is_tracing_prog_type(prog_type)) {
14284 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
14285 			return -EINVAL;
14286 		}
14287 	}
14288 
14289 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
14290 	    !bpf_offload_prog_map_match(prog, map)) {
14291 		verbose(env, "offload device mismatch between prog and map\n");
14292 		return -EINVAL;
14293 	}
14294 
14295 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
14296 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14297 		return -EINVAL;
14298 	}
14299 
14300 	if (prog->aux->sleepable)
14301 		switch (map->map_type) {
14302 		case BPF_MAP_TYPE_HASH:
14303 		case BPF_MAP_TYPE_LRU_HASH:
14304 		case BPF_MAP_TYPE_ARRAY:
14305 		case BPF_MAP_TYPE_PERCPU_HASH:
14306 		case BPF_MAP_TYPE_PERCPU_ARRAY:
14307 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14308 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14309 		case BPF_MAP_TYPE_HASH_OF_MAPS:
14310 		case BPF_MAP_TYPE_RINGBUF:
14311 		case BPF_MAP_TYPE_USER_RINGBUF:
14312 		case BPF_MAP_TYPE_INODE_STORAGE:
14313 		case BPF_MAP_TYPE_SK_STORAGE:
14314 		case BPF_MAP_TYPE_TASK_STORAGE:
14315 		case BPF_MAP_TYPE_CGRP_STORAGE:
14316 			break;
14317 		default:
14318 			verbose(env,
14319 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
14320 			return -EINVAL;
14321 		}
14322 
14323 	return 0;
14324 }
14325 
14326 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14327 {
14328 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14329 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14330 }
14331 
14332 /* find and rewrite pseudo imm in ld_imm64 instructions:
14333  *
14334  * 1. if it accesses map FD, replace it with actual map pointer.
14335  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14336  *
14337  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14338  */
14339 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14340 {
14341 	struct bpf_insn *insn = env->prog->insnsi;
14342 	int insn_cnt = env->prog->len;
14343 	int i, j, err;
14344 
14345 	err = bpf_prog_calc_tag(env->prog);
14346 	if (err)
14347 		return err;
14348 
14349 	for (i = 0; i < insn_cnt; i++, insn++) {
14350 		if (BPF_CLASS(insn->code) == BPF_LDX &&
14351 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14352 			verbose(env, "BPF_LDX uses reserved fields\n");
14353 			return -EINVAL;
14354 		}
14355 
14356 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14357 			struct bpf_insn_aux_data *aux;
14358 			struct bpf_map *map;
14359 			struct fd f;
14360 			u64 addr;
14361 			u32 fd;
14362 
14363 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
14364 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14365 			    insn[1].off != 0) {
14366 				verbose(env, "invalid bpf_ld_imm64 insn\n");
14367 				return -EINVAL;
14368 			}
14369 
14370 			if (insn[0].src_reg == 0)
14371 				/* valid generic load 64-bit imm */
14372 				goto next_insn;
14373 
14374 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14375 				aux = &env->insn_aux_data[i];
14376 				err = check_pseudo_btf_id(env, insn, aux);
14377 				if (err)
14378 					return err;
14379 				goto next_insn;
14380 			}
14381 
14382 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14383 				aux = &env->insn_aux_data[i];
14384 				aux->ptr_type = PTR_TO_FUNC;
14385 				goto next_insn;
14386 			}
14387 
14388 			/* In final convert_pseudo_ld_imm64() step, this is
14389 			 * converted into regular 64-bit imm load insn.
14390 			 */
14391 			switch (insn[0].src_reg) {
14392 			case BPF_PSEUDO_MAP_VALUE:
14393 			case BPF_PSEUDO_MAP_IDX_VALUE:
14394 				break;
14395 			case BPF_PSEUDO_MAP_FD:
14396 			case BPF_PSEUDO_MAP_IDX:
14397 				if (insn[1].imm == 0)
14398 					break;
14399 				fallthrough;
14400 			default:
14401 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14402 				return -EINVAL;
14403 			}
14404 
14405 			switch (insn[0].src_reg) {
14406 			case BPF_PSEUDO_MAP_IDX_VALUE:
14407 			case BPF_PSEUDO_MAP_IDX:
14408 				if (bpfptr_is_null(env->fd_array)) {
14409 					verbose(env, "fd_idx without fd_array is invalid\n");
14410 					return -EPROTO;
14411 				}
14412 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
14413 							    insn[0].imm * sizeof(fd),
14414 							    sizeof(fd)))
14415 					return -EFAULT;
14416 				break;
14417 			default:
14418 				fd = insn[0].imm;
14419 				break;
14420 			}
14421 
14422 			f = fdget(fd);
14423 			map = __bpf_map_get(f);
14424 			if (IS_ERR(map)) {
14425 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
14426 					insn[0].imm);
14427 				return PTR_ERR(map);
14428 			}
14429 
14430 			err = check_map_prog_compatibility(env, map, env->prog);
14431 			if (err) {
14432 				fdput(f);
14433 				return err;
14434 			}
14435 
14436 			aux = &env->insn_aux_data[i];
14437 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14438 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14439 				addr = (unsigned long)map;
14440 			} else {
14441 				u32 off = insn[1].imm;
14442 
14443 				if (off >= BPF_MAX_VAR_OFF) {
14444 					verbose(env, "direct value offset of %u is not allowed\n", off);
14445 					fdput(f);
14446 					return -EINVAL;
14447 				}
14448 
14449 				if (!map->ops->map_direct_value_addr) {
14450 					verbose(env, "no direct value access support for this map type\n");
14451 					fdput(f);
14452 					return -EINVAL;
14453 				}
14454 
14455 				err = map->ops->map_direct_value_addr(map, &addr, off);
14456 				if (err) {
14457 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14458 						map->value_size, off);
14459 					fdput(f);
14460 					return err;
14461 				}
14462 
14463 				aux->map_off = off;
14464 				addr += off;
14465 			}
14466 
14467 			insn[0].imm = (u32)addr;
14468 			insn[1].imm = addr >> 32;
14469 
14470 			/* check whether we recorded this map already */
14471 			for (j = 0; j < env->used_map_cnt; j++) {
14472 				if (env->used_maps[j] == map) {
14473 					aux->map_index = j;
14474 					fdput(f);
14475 					goto next_insn;
14476 				}
14477 			}
14478 
14479 			if (env->used_map_cnt >= MAX_USED_MAPS) {
14480 				fdput(f);
14481 				return -E2BIG;
14482 			}
14483 
14484 			/* hold the map. If the program is rejected by verifier,
14485 			 * the map will be released by release_maps() or it
14486 			 * will be used by the valid program until it's unloaded
14487 			 * and all maps are released in free_used_maps()
14488 			 */
14489 			bpf_map_inc(map);
14490 
14491 			aux->map_index = env->used_map_cnt;
14492 			env->used_maps[env->used_map_cnt++] = map;
14493 
14494 			if (bpf_map_is_cgroup_storage(map) &&
14495 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
14496 				verbose(env, "only one cgroup storage of each type is allowed\n");
14497 				fdput(f);
14498 				return -EBUSY;
14499 			}
14500 
14501 			fdput(f);
14502 next_insn:
14503 			insn++;
14504 			i++;
14505 			continue;
14506 		}
14507 
14508 		/* Basic sanity check before we invest more work here. */
14509 		if (!bpf_opcode_in_insntable(insn->code)) {
14510 			verbose(env, "unknown opcode %02x\n", insn->code);
14511 			return -EINVAL;
14512 		}
14513 	}
14514 
14515 	/* now all pseudo BPF_LD_IMM64 instructions load valid
14516 	 * 'struct bpf_map *' into a register instead of user map_fd.
14517 	 * These pointers will be used later by verifier to validate map access.
14518 	 */
14519 	return 0;
14520 }
14521 
14522 /* drop refcnt of maps used by the rejected program */
14523 static void release_maps(struct bpf_verifier_env *env)
14524 {
14525 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
14526 			     env->used_map_cnt);
14527 }
14528 
14529 /* drop refcnt of maps used by the rejected program */
14530 static void release_btfs(struct bpf_verifier_env *env)
14531 {
14532 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14533 			     env->used_btf_cnt);
14534 }
14535 
14536 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14537 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14538 {
14539 	struct bpf_insn *insn = env->prog->insnsi;
14540 	int insn_cnt = env->prog->len;
14541 	int i;
14542 
14543 	for (i = 0; i < insn_cnt; i++, insn++) {
14544 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14545 			continue;
14546 		if (insn->src_reg == BPF_PSEUDO_FUNC)
14547 			continue;
14548 		insn->src_reg = 0;
14549 	}
14550 }
14551 
14552 /* single env->prog->insni[off] instruction was replaced with the range
14553  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
14554  * [0, off) and [off, end) to new locations, so the patched range stays zero
14555  */
14556 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14557 				 struct bpf_insn_aux_data *new_data,
14558 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
14559 {
14560 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14561 	struct bpf_insn *insn = new_prog->insnsi;
14562 	u32 old_seen = old_data[off].seen;
14563 	u32 prog_len;
14564 	int i;
14565 
14566 	/* aux info at OFF always needs adjustment, no matter fast path
14567 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14568 	 * original insn at old prog.
14569 	 */
14570 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14571 
14572 	if (cnt == 1)
14573 		return;
14574 	prog_len = new_prog->len;
14575 
14576 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14577 	memcpy(new_data + off + cnt - 1, old_data + off,
14578 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14579 	for (i = off; i < off + cnt - 1; i++) {
14580 		/* Expand insni[off]'s seen count to the patched range. */
14581 		new_data[i].seen = old_seen;
14582 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
14583 	}
14584 	env->insn_aux_data = new_data;
14585 	vfree(old_data);
14586 }
14587 
14588 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14589 {
14590 	int i;
14591 
14592 	if (len == 1)
14593 		return;
14594 	/* NOTE: fake 'exit' subprog should be updated as well. */
14595 	for (i = 0; i <= env->subprog_cnt; i++) {
14596 		if (env->subprog_info[i].start <= off)
14597 			continue;
14598 		env->subprog_info[i].start += len - 1;
14599 	}
14600 }
14601 
14602 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14603 {
14604 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14605 	int i, sz = prog->aux->size_poke_tab;
14606 	struct bpf_jit_poke_descriptor *desc;
14607 
14608 	for (i = 0; i < sz; i++) {
14609 		desc = &tab[i];
14610 		if (desc->insn_idx <= off)
14611 			continue;
14612 		desc->insn_idx += len - 1;
14613 	}
14614 }
14615 
14616 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14617 					    const struct bpf_insn *patch, u32 len)
14618 {
14619 	struct bpf_prog *new_prog;
14620 	struct bpf_insn_aux_data *new_data = NULL;
14621 
14622 	if (len > 1) {
14623 		new_data = vzalloc(array_size(env->prog->len + len - 1,
14624 					      sizeof(struct bpf_insn_aux_data)));
14625 		if (!new_data)
14626 			return NULL;
14627 	}
14628 
14629 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14630 	if (IS_ERR(new_prog)) {
14631 		if (PTR_ERR(new_prog) == -ERANGE)
14632 			verbose(env,
14633 				"insn %d cannot be patched due to 16-bit range\n",
14634 				env->insn_aux_data[off].orig_idx);
14635 		vfree(new_data);
14636 		return NULL;
14637 	}
14638 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
14639 	adjust_subprog_starts(env, off, len);
14640 	adjust_poke_descs(new_prog, off, len);
14641 	return new_prog;
14642 }
14643 
14644 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14645 					      u32 off, u32 cnt)
14646 {
14647 	int i, j;
14648 
14649 	/* find first prog starting at or after off (first to remove) */
14650 	for (i = 0; i < env->subprog_cnt; i++)
14651 		if (env->subprog_info[i].start >= off)
14652 			break;
14653 	/* find first prog starting at or after off + cnt (first to stay) */
14654 	for (j = i; j < env->subprog_cnt; j++)
14655 		if (env->subprog_info[j].start >= off + cnt)
14656 			break;
14657 	/* if j doesn't start exactly at off + cnt, we are just removing
14658 	 * the front of previous prog
14659 	 */
14660 	if (env->subprog_info[j].start != off + cnt)
14661 		j--;
14662 
14663 	if (j > i) {
14664 		struct bpf_prog_aux *aux = env->prog->aux;
14665 		int move;
14666 
14667 		/* move fake 'exit' subprog as well */
14668 		move = env->subprog_cnt + 1 - j;
14669 
14670 		memmove(env->subprog_info + i,
14671 			env->subprog_info + j,
14672 			sizeof(*env->subprog_info) * move);
14673 		env->subprog_cnt -= j - i;
14674 
14675 		/* remove func_info */
14676 		if (aux->func_info) {
14677 			move = aux->func_info_cnt - j;
14678 
14679 			memmove(aux->func_info + i,
14680 				aux->func_info + j,
14681 				sizeof(*aux->func_info) * move);
14682 			aux->func_info_cnt -= j - i;
14683 			/* func_info->insn_off is set after all code rewrites,
14684 			 * in adjust_btf_func() - no need to adjust
14685 			 */
14686 		}
14687 	} else {
14688 		/* convert i from "first prog to remove" to "first to adjust" */
14689 		if (env->subprog_info[i].start == off)
14690 			i++;
14691 	}
14692 
14693 	/* update fake 'exit' subprog as well */
14694 	for (; i <= env->subprog_cnt; i++)
14695 		env->subprog_info[i].start -= cnt;
14696 
14697 	return 0;
14698 }
14699 
14700 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14701 				      u32 cnt)
14702 {
14703 	struct bpf_prog *prog = env->prog;
14704 	u32 i, l_off, l_cnt, nr_linfo;
14705 	struct bpf_line_info *linfo;
14706 
14707 	nr_linfo = prog->aux->nr_linfo;
14708 	if (!nr_linfo)
14709 		return 0;
14710 
14711 	linfo = prog->aux->linfo;
14712 
14713 	/* find first line info to remove, count lines to be removed */
14714 	for (i = 0; i < nr_linfo; i++)
14715 		if (linfo[i].insn_off >= off)
14716 			break;
14717 
14718 	l_off = i;
14719 	l_cnt = 0;
14720 	for (; i < nr_linfo; i++)
14721 		if (linfo[i].insn_off < off + cnt)
14722 			l_cnt++;
14723 		else
14724 			break;
14725 
14726 	/* First live insn doesn't match first live linfo, it needs to "inherit"
14727 	 * last removed linfo.  prog is already modified, so prog->len == off
14728 	 * means no live instructions after (tail of the program was removed).
14729 	 */
14730 	if (prog->len != off && l_cnt &&
14731 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14732 		l_cnt--;
14733 		linfo[--i].insn_off = off + cnt;
14734 	}
14735 
14736 	/* remove the line info which refer to the removed instructions */
14737 	if (l_cnt) {
14738 		memmove(linfo + l_off, linfo + i,
14739 			sizeof(*linfo) * (nr_linfo - i));
14740 
14741 		prog->aux->nr_linfo -= l_cnt;
14742 		nr_linfo = prog->aux->nr_linfo;
14743 	}
14744 
14745 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
14746 	for (i = l_off; i < nr_linfo; i++)
14747 		linfo[i].insn_off -= cnt;
14748 
14749 	/* fix up all subprogs (incl. 'exit') which start >= off */
14750 	for (i = 0; i <= env->subprog_cnt; i++)
14751 		if (env->subprog_info[i].linfo_idx > l_off) {
14752 			/* program may have started in the removed region but
14753 			 * may not be fully removed
14754 			 */
14755 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14756 				env->subprog_info[i].linfo_idx -= l_cnt;
14757 			else
14758 				env->subprog_info[i].linfo_idx = l_off;
14759 		}
14760 
14761 	return 0;
14762 }
14763 
14764 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14765 {
14766 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14767 	unsigned int orig_prog_len = env->prog->len;
14768 	int err;
14769 
14770 	if (bpf_prog_is_dev_bound(env->prog->aux))
14771 		bpf_prog_offload_remove_insns(env, off, cnt);
14772 
14773 	err = bpf_remove_insns(env->prog, off, cnt);
14774 	if (err)
14775 		return err;
14776 
14777 	err = adjust_subprog_starts_after_remove(env, off, cnt);
14778 	if (err)
14779 		return err;
14780 
14781 	err = bpf_adj_linfo_after_remove(env, off, cnt);
14782 	if (err)
14783 		return err;
14784 
14785 	memmove(aux_data + off,	aux_data + off + cnt,
14786 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
14787 
14788 	return 0;
14789 }
14790 
14791 /* The verifier does more data flow analysis than llvm and will not
14792  * explore branches that are dead at run time. Malicious programs can
14793  * have dead code too. Therefore replace all dead at-run-time code
14794  * with 'ja -1'.
14795  *
14796  * Just nops are not optimal, e.g. if they would sit at the end of the
14797  * program and through another bug we would manage to jump there, then
14798  * we'd execute beyond program memory otherwise. Returning exception
14799  * code also wouldn't work since we can have subprogs where the dead
14800  * code could be located.
14801  */
14802 static void sanitize_dead_code(struct bpf_verifier_env *env)
14803 {
14804 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14805 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14806 	struct bpf_insn *insn = env->prog->insnsi;
14807 	const int insn_cnt = env->prog->len;
14808 	int i;
14809 
14810 	for (i = 0; i < insn_cnt; i++) {
14811 		if (aux_data[i].seen)
14812 			continue;
14813 		memcpy(insn + i, &trap, sizeof(trap));
14814 		aux_data[i].zext_dst = false;
14815 	}
14816 }
14817 
14818 static bool insn_is_cond_jump(u8 code)
14819 {
14820 	u8 op;
14821 
14822 	if (BPF_CLASS(code) == BPF_JMP32)
14823 		return true;
14824 
14825 	if (BPF_CLASS(code) != BPF_JMP)
14826 		return false;
14827 
14828 	op = BPF_OP(code);
14829 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14830 }
14831 
14832 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14833 {
14834 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14835 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14836 	struct bpf_insn *insn = env->prog->insnsi;
14837 	const int insn_cnt = env->prog->len;
14838 	int i;
14839 
14840 	for (i = 0; i < insn_cnt; i++, insn++) {
14841 		if (!insn_is_cond_jump(insn->code))
14842 			continue;
14843 
14844 		if (!aux_data[i + 1].seen)
14845 			ja.off = insn->off;
14846 		else if (!aux_data[i + 1 + insn->off].seen)
14847 			ja.off = 0;
14848 		else
14849 			continue;
14850 
14851 		if (bpf_prog_is_dev_bound(env->prog->aux))
14852 			bpf_prog_offload_replace_insn(env, i, &ja);
14853 
14854 		memcpy(insn, &ja, sizeof(ja));
14855 	}
14856 }
14857 
14858 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14859 {
14860 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14861 	int insn_cnt = env->prog->len;
14862 	int i, err;
14863 
14864 	for (i = 0; i < insn_cnt; i++) {
14865 		int j;
14866 
14867 		j = 0;
14868 		while (i + j < insn_cnt && !aux_data[i + j].seen)
14869 			j++;
14870 		if (!j)
14871 			continue;
14872 
14873 		err = verifier_remove_insns(env, i, j);
14874 		if (err)
14875 			return err;
14876 		insn_cnt = env->prog->len;
14877 	}
14878 
14879 	return 0;
14880 }
14881 
14882 static int opt_remove_nops(struct bpf_verifier_env *env)
14883 {
14884 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14885 	struct bpf_insn *insn = env->prog->insnsi;
14886 	int insn_cnt = env->prog->len;
14887 	int i, err;
14888 
14889 	for (i = 0; i < insn_cnt; i++) {
14890 		if (memcmp(&insn[i], &ja, sizeof(ja)))
14891 			continue;
14892 
14893 		err = verifier_remove_insns(env, i, 1);
14894 		if (err)
14895 			return err;
14896 		insn_cnt--;
14897 		i--;
14898 	}
14899 
14900 	return 0;
14901 }
14902 
14903 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14904 					 const union bpf_attr *attr)
14905 {
14906 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14907 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
14908 	int i, patch_len, delta = 0, len = env->prog->len;
14909 	struct bpf_insn *insns = env->prog->insnsi;
14910 	struct bpf_prog *new_prog;
14911 	bool rnd_hi32;
14912 
14913 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14914 	zext_patch[1] = BPF_ZEXT_REG(0);
14915 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14916 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14917 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14918 	for (i = 0; i < len; i++) {
14919 		int adj_idx = i + delta;
14920 		struct bpf_insn insn;
14921 		int load_reg;
14922 
14923 		insn = insns[adj_idx];
14924 		load_reg = insn_def_regno(&insn);
14925 		if (!aux[adj_idx].zext_dst) {
14926 			u8 code, class;
14927 			u32 imm_rnd;
14928 
14929 			if (!rnd_hi32)
14930 				continue;
14931 
14932 			code = insn.code;
14933 			class = BPF_CLASS(code);
14934 			if (load_reg == -1)
14935 				continue;
14936 
14937 			/* NOTE: arg "reg" (the fourth one) is only used for
14938 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
14939 			 *       here.
14940 			 */
14941 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14942 				if (class == BPF_LD &&
14943 				    BPF_MODE(code) == BPF_IMM)
14944 					i++;
14945 				continue;
14946 			}
14947 
14948 			/* ctx load could be transformed into wider load. */
14949 			if (class == BPF_LDX &&
14950 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
14951 				continue;
14952 
14953 			imm_rnd = get_random_u32();
14954 			rnd_hi32_patch[0] = insn;
14955 			rnd_hi32_patch[1].imm = imm_rnd;
14956 			rnd_hi32_patch[3].dst_reg = load_reg;
14957 			patch = rnd_hi32_patch;
14958 			patch_len = 4;
14959 			goto apply_patch_buffer;
14960 		}
14961 
14962 		/* Add in an zero-extend instruction if a) the JIT has requested
14963 		 * it or b) it's a CMPXCHG.
14964 		 *
14965 		 * The latter is because: BPF_CMPXCHG always loads a value into
14966 		 * R0, therefore always zero-extends. However some archs'
14967 		 * equivalent instruction only does this load when the
14968 		 * comparison is successful. This detail of CMPXCHG is
14969 		 * orthogonal to the general zero-extension behaviour of the
14970 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
14971 		 */
14972 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
14973 			continue;
14974 
14975 		/* Zero-extension is done by the caller. */
14976 		if (bpf_pseudo_kfunc_call(&insn))
14977 			continue;
14978 
14979 		if (WARN_ON(load_reg == -1)) {
14980 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
14981 			return -EFAULT;
14982 		}
14983 
14984 		zext_patch[0] = insn;
14985 		zext_patch[1].dst_reg = load_reg;
14986 		zext_patch[1].src_reg = load_reg;
14987 		patch = zext_patch;
14988 		patch_len = 2;
14989 apply_patch_buffer:
14990 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
14991 		if (!new_prog)
14992 			return -ENOMEM;
14993 		env->prog = new_prog;
14994 		insns = new_prog->insnsi;
14995 		aux = env->insn_aux_data;
14996 		delta += patch_len - 1;
14997 	}
14998 
14999 	return 0;
15000 }
15001 
15002 /* convert load instructions that access fields of a context type into a
15003  * sequence of instructions that access fields of the underlying structure:
15004  *     struct __sk_buff    -> struct sk_buff
15005  *     struct bpf_sock_ops -> struct sock
15006  */
15007 static int convert_ctx_accesses(struct bpf_verifier_env *env)
15008 {
15009 	const struct bpf_verifier_ops *ops = env->ops;
15010 	int i, cnt, size, ctx_field_size, delta = 0;
15011 	const int insn_cnt = env->prog->len;
15012 	struct bpf_insn insn_buf[16], *insn;
15013 	u32 target_size, size_default, off;
15014 	struct bpf_prog *new_prog;
15015 	enum bpf_access_type type;
15016 	bool is_narrower_load;
15017 
15018 	if (ops->gen_prologue || env->seen_direct_write) {
15019 		if (!ops->gen_prologue) {
15020 			verbose(env, "bpf verifier is misconfigured\n");
15021 			return -EINVAL;
15022 		}
15023 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
15024 					env->prog);
15025 		if (cnt >= ARRAY_SIZE(insn_buf)) {
15026 			verbose(env, "bpf verifier is misconfigured\n");
15027 			return -EINVAL;
15028 		} else if (cnt) {
15029 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
15030 			if (!new_prog)
15031 				return -ENOMEM;
15032 
15033 			env->prog = new_prog;
15034 			delta += cnt - 1;
15035 		}
15036 	}
15037 
15038 	if (bpf_prog_is_dev_bound(env->prog->aux))
15039 		return 0;
15040 
15041 	insn = env->prog->insnsi + delta;
15042 
15043 	for (i = 0; i < insn_cnt; i++, insn++) {
15044 		bpf_convert_ctx_access_t convert_ctx_access;
15045 		bool ctx_access;
15046 
15047 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
15048 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
15049 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
15050 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
15051 			type = BPF_READ;
15052 			ctx_access = true;
15053 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
15054 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
15055 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
15056 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
15057 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
15058 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
15059 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
15060 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
15061 			type = BPF_WRITE;
15062 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
15063 		} else {
15064 			continue;
15065 		}
15066 
15067 		if (type == BPF_WRITE &&
15068 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
15069 			struct bpf_insn patch[] = {
15070 				*insn,
15071 				BPF_ST_NOSPEC(),
15072 			};
15073 
15074 			cnt = ARRAY_SIZE(patch);
15075 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
15076 			if (!new_prog)
15077 				return -ENOMEM;
15078 
15079 			delta    += cnt - 1;
15080 			env->prog = new_prog;
15081 			insn      = new_prog->insnsi + i + delta;
15082 			continue;
15083 		}
15084 
15085 		if (!ctx_access)
15086 			continue;
15087 
15088 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
15089 		case PTR_TO_CTX:
15090 			if (!ops->convert_ctx_access)
15091 				continue;
15092 			convert_ctx_access = ops->convert_ctx_access;
15093 			break;
15094 		case PTR_TO_SOCKET:
15095 		case PTR_TO_SOCK_COMMON:
15096 			convert_ctx_access = bpf_sock_convert_ctx_access;
15097 			break;
15098 		case PTR_TO_TCP_SOCK:
15099 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
15100 			break;
15101 		case PTR_TO_XDP_SOCK:
15102 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
15103 			break;
15104 		case PTR_TO_BTF_ID:
15105 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
15106 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
15107 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
15108 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
15109 		 * any faults for loads into such types. BPF_WRITE is disallowed
15110 		 * for this case.
15111 		 */
15112 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
15113 			if (type == BPF_READ) {
15114 				insn->code = BPF_LDX | BPF_PROBE_MEM |
15115 					BPF_SIZE((insn)->code);
15116 				env->prog->aux->num_exentries++;
15117 			}
15118 			continue;
15119 		default:
15120 			continue;
15121 		}
15122 
15123 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
15124 		size = BPF_LDST_BYTES(insn);
15125 
15126 		/* If the read access is a narrower load of the field,
15127 		 * convert to a 4/8-byte load, to minimum program type specific
15128 		 * convert_ctx_access changes. If conversion is successful,
15129 		 * we will apply proper mask to the result.
15130 		 */
15131 		is_narrower_load = size < ctx_field_size;
15132 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
15133 		off = insn->off;
15134 		if (is_narrower_load) {
15135 			u8 size_code;
15136 
15137 			if (type == BPF_WRITE) {
15138 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
15139 				return -EINVAL;
15140 			}
15141 
15142 			size_code = BPF_H;
15143 			if (ctx_field_size == 4)
15144 				size_code = BPF_W;
15145 			else if (ctx_field_size == 8)
15146 				size_code = BPF_DW;
15147 
15148 			insn->off = off & ~(size_default - 1);
15149 			insn->code = BPF_LDX | BPF_MEM | size_code;
15150 		}
15151 
15152 		target_size = 0;
15153 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
15154 					 &target_size);
15155 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
15156 		    (ctx_field_size && !target_size)) {
15157 			verbose(env, "bpf verifier is misconfigured\n");
15158 			return -EINVAL;
15159 		}
15160 
15161 		if (is_narrower_load && size < target_size) {
15162 			u8 shift = bpf_ctx_narrow_access_offset(
15163 				off, size, size_default) * 8;
15164 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
15165 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
15166 				return -EINVAL;
15167 			}
15168 			if (ctx_field_size <= 4) {
15169 				if (shift)
15170 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
15171 									insn->dst_reg,
15172 									shift);
15173 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
15174 								(1 << size * 8) - 1);
15175 			} else {
15176 				if (shift)
15177 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
15178 									insn->dst_reg,
15179 									shift);
15180 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
15181 								(1ULL << size * 8) - 1);
15182 			}
15183 		}
15184 
15185 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15186 		if (!new_prog)
15187 			return -ENOMEM;
15188 
15189 		delta += cnt - 1;
15190 
15191 		/* keep walking new program and skip insns we just inserted */
15192 		env->prog = new_prog;
15193 		insn      = new_prog->insnsi + i + delta;
15194 	}
15195 
15196 	return 0;
15197 }
15198 
15199 static int jit_subprogs(struct bpf_verifier_env *env)
15200 {
15201 	struct bpf_prog *prog = env->prog, **func, *tmp;
15202 	int i, j, subprog_start, subprog_end = 0, len, subprog;
15203 	struct bpf_map *map_ptr;
15204 	struct bpf_insn *insn;
15205 	void *old_bpf_func;
15206 	int err, num_exentries;
15207 
15208 	if (env->subprog_cnt <= 1)
15209 		return 0;
15210 
15211 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15212 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
15213 			continue;
15214 
15215 		/* Upon error here we cannot fall back to interpreter but
15216 		 * need a hard reject of the program. Thus -EFAULT is
15217 		 * propagated in any case.
15218 		 */
15219 		subprog = find_subprog(env, i + insn->imm + 1);
15220 		if (subprog < 0) {
15221 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
15222 				  i + insn->imm + 1);
15223 			return -EFAULT;
15224 		}
15225 		/* temporarily remember subprog id inside insn instead of
15226 		 * aux_data, since next loop will split up all insns into funcs
15227 		 */
15228 		insn->off = subprog;
15229 		/* remember original imm in case JIT fails and fallback
15230 		 * to interpreter will be needed
15231 		 */
15232 		env->insn_aux_data[i].call_imm = insn->imm;
15233 		/* point imm to __bpf_call_base+1 from JITs point of view */
15234 		insn->imm = 1;
15235 		if (bpf_pseudo_func(insn))
15236 			/* jit (e.g. x86_64) may emit fewer instructions
15237 			 * if it learns a u32 imm is the same as a u64 imm.
15238 			 * Force a non zero here.
15239 			 */
15240 			insn[1].imm = 1;
15241 	}
15242 
15243 	err = bpf_prog_alloc_jited_linfo(prog);
15244 	if (err)
15245 		goto out_undo_insn;
15246 
15247 	err = -ENOMEM;
15248 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
15249 	if (!func)
15250 		goto out_undo_insn;
15251 
15252 	for (i = 0; i < env->subprog_cnt; i++) {
15253 		subprog_start = subprog_end;
15254 		subprog_end = env->subprog_info[i + 1].start;
15255 
15256 		len = subprog_end - subprog_start;
15257 		/* bpf_prog_run() doesn't call subprogs directly,
15258 		 * hence main prog stats include the runtime of subprogs.
15259 		 * subprogs don't have IDs and not reachable via prog_get_next_id
15260 		 * func[i]->stats will never be accessed and stays NULL
15261 		 */
15262 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
15263 		if (!func[i])
15264 			goto out_free;
15265 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
15266 		       len * sizeof(struct bpf_insn));
15267 		func[i]->type = prog->type;
15268 		func[i]->len = len;
15269 		if (bpf_prog_calc_tag(func[i]))
15270 			goto out_free;
15271 		func[i]->is_func = 1;
15272 		func[i]->aux->func_idx = i;
15273 		/* Below members will be freed only at prog->aux */
15274 		func[i]->aux->btf = prog->aux->btf;
15275 		func[i]->aux->func_info = prog->aux->func_info;
15276 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
15277 		func[i]->aux->poke_tab = prog->aux->poke_tab;
15278 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
15279 
15280 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
15281 			struct bpf_jit_poke_descriptor *poke;
15282 
15283 			poke = &prog->aux->poke_tab[j];
15284 			if (poke->insn_idx < subprog_end &&
15285 			    poke->insn_idx >= subprog_start)
15286 				poke->aux = func[i]->aux;
15287 		}
15288 
15289 		func[i]->aux->name[0] = 'F';
15290 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
15291 		func[i]->jit_requested = 1;
15292 		func[i]->blinding_requested = prog->blinding_requested;
15293 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
15294 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
15295 		func[i]->aux->linfo = prog->aux->linfo;
15296 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
15297 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
15298 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15299 		num_exentries = 0;
15300 		insn = func[i]->insnsi;
15301 		for (j = 0; j < func[i]->len; j++, insn++) {
15302 			if (BPF_CLASS(insn->code) == BPF_LDX &&
15303 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
15304 				num_exentries++;
15305 		}
15306 		func[i]->aux->num_exentries = num_exentries;
15307 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15308 		func[i] = bpf_int_jit_compile(func[i]);
15309 		if (!func[i]->jited) {
15310 			err = -ENOTSUPP;
15311 			goto out_free;
15312 		}
15313 		cond_resched();
15314 	}
15315 
15316 	/* at this point all bpf functions were successfully JITed
15317 	 * now populate all bpf_calls with correct addresses and
15318 	 * run last pass of JIT
15319 	 */
15320 	for (i = 0; i < env->subprog_cnt; i++) {
15321 		insn = func[i]->insnsi;
15322 		for (j = 0; j < func[i]->len; j++, insn++) {
15323 			if (bpf_pseudo_func(insn)) {
15324 				subprog = insn->off;
15325 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15326 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15327 				continue;
15328 			}
15329 			if (!bpf_pseudo_call(insn))
15330 				continue;
15331 			subprog = insn->off;
15332 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15333 		}
15334 
15335 		/* we use the aux data to keep a list of the start addresses
15336 		 * of the JITed images for each function in the program
15337 		 *
15338 		 * for some architectures, such as powerpc64, the imm field
15339 		 * might not be large enough to hold the offset of the start
15340 		 * address of the callee's JITed image from __bpf_call_base
15341 		 *
15342 		 * in such cases, we can lookup the start address of a callee
15343 		 * by using its subprog id, available from the off field of
15344 		 * the call instruction, as an index for this list
15345 		 */
15346 		func[i]->aux->func = func;
15347 		func[i]->aux->func_cnt = env->subprog_cnt;
15348 	}
15349 	for (i = 0; i < env->subprog_cnt; i++) {
15350 		old_bpf_func = func[i]->bpf_func;
15351 		tmp = bpf_int_jit_compile(func[i]);
15352 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15353 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15354 			err = -ENOTSUPP;
15355 			goto out_free;
15356 		}
15357 		cond_resched();
15358 	}
15359 
15360 	/* finally lock prog and jit images for all functions and
15361 	 * populate kallsysm
15362 	 */
15363 	for (i = 0; i < env->subprog_cnt; i++) {
15364 		bpf_prog_lock_ro(func[i]);
15365 		bpf_prog_kallsyms_add(func[i]);
15366 	}
15367 
15368 	/* Last step: make now unused interpreter insns from main
15369 	 * prog consistent for later dump requests, so they can
15370 	 * later look the same as if they were interpreted only.
15371 	 */
15372 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15373 		if (bpf_pseudo_func(insn)) {
15374 			insn[0].imm = env->insn_aux_data[i].call_imm;
15375 			insn[1].imm = insn->off;
15376 			insn->off = 0;
15377 			continue;
15378 		}
15379 		if (!bpf_pseudo_call(insn))
15380 			continue;
15381 		insn->off = env->insn_aux_data[i].call_imm;
15382 		subprog = find_subprog(env, i + insn->off + 1);
15383 		insn->imm = subprog;
15384 	}
15385 
15386 	prog->jited = 1;
15387 	prog->bpf_func = func[0]->bpf_func;
15388 	prog->jited_len = func[0]->jited_len;
15389 	prog->aux->func = func;
15390 	prog->aux->func_cnt = env->subprog_cnt;
15391 	bpf_prog_jit_attempt_done(prog);
15392 	return 0;
15393 out_free:
15394 	/* We failed JIT'ing, so at this point we need to unregister poke
15395 	 * descriptors from subprogs, so that kernel is not attempting to
15396 	 * patch it anymore as we're freeing the subprog JIT memory.
15397 	 */
15398 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
15399 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
15400 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15401 	}
15402 	/* At this point we're guaranteed that poke descriptors are not
15403 	 * live anymore. We can just unlink its descriptor table as it's
15404 	 * released with the main prog.
15405 	 */
15406 	for (i = 0; i < env->subprog_cnt; i++) {
15407 		if (!func[i])
15408 			continue;
15409 		func[i]->aux->poke_tab = NULL;
15410 		bpf_jit_free(func[i]);
15411 	}
15412 	kfree(func);
15413 out_undo_insn:
15414 	/* cleanup main prog to be interpreted */
15415 	prog->jit_requested = 0;
15416 	prog->blinding_requested = 0;
15417 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15418 		if (!bpf_pseudo_call(insn))
15419 			continue;
15420 		insn->off = 0;
15421 		insn->imm = env->insn_aux_data[i].call_imm;
15422 	}
15423 	bpf_prog_jit_attempt_done(prog);
15424 	return err;
15425 }
15426 
15427 static int fixup_call_args(struct bpf_verifier_env *env)
15428 {
15429 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15430 	struct bpf_prog *prog = env->prog;
15431 	struct bpf_insn *insn = prog->insnsi;
15432 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15433 	int i, depth;
15434 #endif
15435 	int err = 0;
15436 
15437 	if (env->prog->jit_requested &&
15438 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
15439 		err = jit_subprogs(env);
15440 		if (err == 0)
15441 			return 0;
15442 		if (err == -EFAULT)
15443 			return err;
15444 	}
15445 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15446 	if (has_kfunc_call) {
15447 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15448 		return -EINVAL;
15449 	}
15450 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15451 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
15452 		 * have to be rejected, since interpreter doesn't support them yet.
15453 		 */
15454 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15455 		return -EINVAL;
15456 	}
15457 	for (i = 0; i < prog->len; i++, insn++) {
15458 		if (bpf_pseudo_func(insn)) {
15459 			/* When JIT fails the progs with callback calls
15460 			 * have to be rejected, since interpreter doesn't support them yet.
15461 			 */
15462 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
15463 			return -EINVAL;
15464 		}
15465 
15466 		if (!bpf_pseudo_call(insn))
15467 			continue;
15468 		depth = get_callee_stack_depth(env, insn, i);
15469 		if (depth < 0)
15470 			return depth;
15471 		bpf_patch_call_args(insn, depth);
15472 	}
15473 	err = 0;
15474 #endif
15475 	return err;
15476 }
15477 
15478 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15479 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15480 {
15481 	const struct bpf_kfunc_desc *desc;
15482 
15483 	if (!insn->imm) {
15484 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15485 		return -EINVAL;
15486 	}
15487 
15488 	/* insn->imm has the btf func_id. Replace it with
15489 	 * an address (relative to __bpf_call_base).
15490 	 */
15491 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15492 	if (!desc) {
15493 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15494 			insn->imm);
15495 		return -EFAULT;
15496 	}
15497 
15498 	*cnt = 0;
15499 	insn->imm = desc->imm;
15500 	if (insn->off)
15501 		return 0;
15502 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15503 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15504 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15505 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15506 
15507 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15508 		insn_buf[1] = addr[0];
15509 		insn_buf[2] = addr[1];
15510 		insn_buf[3] = *insn;
15511 		*cnt = 4;
15512 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15513 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15514 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15515 
15516 		insn_buf[0] = addr[0];
15517 		insn_buf[1] = addr[1];
15518 		insn_buf[2] = *insn;
15519 		*cnt = 3;
15520 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15521 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15522 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15523 		*cnt = 1;
15524 	}
15525 	return 0;
15526 }
15527 
15528 /* Do various post-verification rewrites in a single program pass.
15529  * These rewrites simplify JIT and interpreter implementations.
15530  */
15531 static int do_misc_fixups(struct bpf_verifier_env *env)
15532 {
15533 	struct bpf_prog *prog = env->prog;
15534 	enum bpf_attach_type eatype = prog->expected_attach_type;
15535 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
15536 	struct bpf_insn *insn = prog->insnsi;
15537 	const struct bpf_func_proto *fn;
15538 	const int insn_cnt = prog->len;
15539 	const struct bpf_map_ops *ops;
15540 	struct bpf_insn_aux_data *aux;
15541 	struct bpf_insn insn_buf[16];
15542 	struct bpf_prog *new_prog;
15543 	struct bpf_map *map_ptr;
15544 	int i, ret, cnt, delta = 0;
15545 
15546 	for (i = 0; i < insn_cnt; i++, insn++) {
15547 		/* Make divide-by-zero exceptions impossible. */
15548 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15549 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15550 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15551 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15552 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15553 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15554 			struct bpf_insn *patchlet;
15555 			struct bpf_insn chk_and_div[] = {
15556 				/* [R,W]x div 0 -> 0 */
15557 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15558 					     BPF_JNE | BPF_K, insn->src_reg,
15559 					     0, 2, 0),
15560 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15561 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15562 				*insn,
15563 			};
15564 			struct bpf_insn chk_and_mod[] = {
15565 				/* [R,W]x mod 0 -> [R,W]x */
15566 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15567 					     BPF_JEQ | BPF_K, insn->src_reg,
15568 					     0, 1 + (is64 ? 0 : 1), 0),
15569 				*insn,
15570 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15571 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15572 			};
15573 
15574 			patchlet = isdiv ? chk_and_div : chk_and_mod;
15575 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15576 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15577 
15578 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15579 			if (!new_prog)
15580 				return -ENOMEM;
15581 
15582 			delta    += cnt - 1;
15583 			env->prog = prog = new_prog;
15584 			insn      = new_prog->insnsi + i + delta;
15585 			continue;
15586 		}
15587 
15588 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15589 		if (BPF_CLASS(insn->code) == BPF_LD &&
15590 		    (BPF_MODE(insn->code) == BPF_ABS ||
15591 		     BPF_MODE(insn->code) == BPF_IND)) {
15592 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
15593 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15594 				verbose(env, "bpf verifier is misconfigured\n");
15595 				return -EINVAL;
15596 			}
15597 
15598 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15599 			if (!new_prog)
15600 				return -ENOMEM;
15601 
15602 			delta    += cnt - 1;
15603 			env->prog = prog = new_prog;
15604 			insn      = new_prog->insnsi + i + delta;
15605 			continue;
15606 		}
15607 
15608 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
15609 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15610 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15611 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15612 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15613 			struct bpf_insn *patch = &insn_buf[0];
15614 			bool issrc, isneg, isimm;
15615 			u32 off_reg;
15616 
15617 			aux = &env->insn_aux_data[i + delta];
15618 			if (!aux->alu_state ||
15619 			    aux->alu_state == BPF_ALU_NON_POINTER)
15620 				continue;
15621 
15622 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15623 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15624 				BPF_ALU_SANITIZE_SRC;
15625 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15626 
15627 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
15628 			if (isimm) {
15629 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15630 			} else {
15631 				if (isneg)
15632 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15633 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15634 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15635 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15636 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15637 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15638 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15639 			}
15640 			if (!issrc)
15641 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15642 			insn->src_reg = BPF_REG_AX;
15643 			if (isneg)
15644 				insn->code = insn->code == code_add ?
15645 					     code_sub : code_add;
15646 			*patch++ = *insn;
15647 			if (issrc && isneg && !isimm)
15648 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15649 			cnt = patch - insn_buf;
15650 
15651 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15652 			if (!new_prog)
15653 				return -ENOMEM;
15654 
15655 			delta    += cnt - 1;
15656 			env->prog = prog = new_prog;
15657 			insn      = new_prog->insnsi + i + delta;
15658 			continue;
15659 		}
15660 
15661 		if (insn->code != (BPF_JMP | BPF_CALL))
15662 			continue;
15663 		if (insn->src_reg == BPF_PSEUDO_CALL)
15664 			continue;
15665 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15666 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15667 			if (ret)
15668 				return ret;
15669 			if (cnt == 0)
15670 				continue;
15671 
15672 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15673 			if (!new_prog)
15674 				return -ENOMEM;
15675 
15676 			delta	 += cnt - 1;
15677 			env->prog = prog = new_prog;
15678 			insn	  = new_prog->insnsi + i + delta;
15679 			continue;
15680 		}
15681 
15682 		if (insn->imm == BPF_FUNC_get_route_realm)
15683 			prog->dst_needed = 1;
15684 		if (insn->imm == BPF_FUNC_get_prandom_u32)
15685 			bpf_user_rnd_init_once();
15686 		if (insn->imm == BPF_FUNC_override_return)
15687 			prog->kprobe_override = 1;
15688 		if (insn->imm == BPF_FUNC_tail_call) {
15689 			/* If we tail call into other programs, we
15690 			 * cannot make any assumptions since they can
15691 			 * be replaced dynamically during runtime in
15692 			 * the program array.
15693 			 */
15694 			prog->cb_access = 1;
15695 			if (!allow_tail_call_in_subprogs(env))
15696 				prog->aux->stack_depth = MAX_BPF_STACK;
15697 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15698 
15699 			/* mark bpf_tail_call as different opcode to avoid
15700 			 * conditional branch in the interpreter for every normal
15701 			 * call and to prevent accidental JITing by JIT compiler
15702 			 * that doesn't support bpf_tail_call yet
15703 			 */
15704 			insn->imm = 0;
15705 			insn->code = BPF_JMP | BPF_TAIL_CALL;
15706 
15707 			aux = &env->insn_aux_data[i + delta];
15708 			if (env->bpf_capable && !prog->blinding_requested &&
15709 			    prog->jit_requested &&
15710 			    !bpf_map_key_poisoned(aux) &&
15711 			    !bpf_map_ptr_poisoned(aux) &&
15712 			    !bpf_map_ptr_unpriv(aux)) {
15713 				struct bpf_jit_poke_descriptor desc = {
15714 					.reason = BPF_POKE_REASON_TAIL_CALL,
15715 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15716 					.tail_call.key = bpf_map_key_immediate(aux),
15717 					.insn_idx = i + delta,
15718 				};
15719 
15720 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
15721 				if (ret < 0) {
15722 					verbose(env, "adding tail call poke descriptor failed\n");
15723 					return ret;
15724 				}
15725 
15726 				insn->imm = ret + 1;
15727 				continue;
15728 			}
15729 
15730 			if (!bpf_map_ptr_unpriv(aux))
15731 				continue;
15732 
15733 			/* instead of changing every JIT dealing with tail_call
15734 			 * emit two extra insns:
15735 			 * if (index >= max_entries) goto out;
15736 			 * index &= array->index_mask;
15737 			 * to avoid out-of-bounds cpu speculation
15738 			 */
15739 			if (bpf_map_ptr_poisoned(aux)) {
15740 				verbose(env, "tail_call abusing map_ptr\n");
15741 				return -EINVAL;
15742 			}
15743 
15744 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15745 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15746 						  map_ptr->max_entries, 2);
15747 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15748 						    container_of(map_ptr,
15749 								 struct bpf_array,
15750 								 map)->index_mask);
15751 			insn_buf[2] = *insn;
15752 			cnt = 3;
15753 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15754 			if (!new_prog)
15755 				return -ENOMEM;
15756 
15757 			delta    += cnt - 1;
15758 			env->prog = prog = new_prog;
15759 			insn      = new_prog->insnsi + i + delta;
15760 			continue;
15761 		}
15762 
15763 		if (insn->imm == BPF_FUNC_timer_set_callback) {
15764 			/* The verifier will process callback_fn as many times as necessary
15765 			 * with different maps and the register states prepared by
15766 			 * set_timer_callback_state will be accurate.
15767 			 *
15768 			 * The following use case is valid:
15769 			 *   map1 is shared by prog1, prog2, prog3.
15770 			 *   prog1 calls bpf_timer_init for some map1 elements
15771 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
15772 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
15773 			 *   prog3 calls bpf_timer_start for some map1 elements.
15774 			 *     Those that were not both bpf_timer_init-ed and
15775 			 *     bpf_timer_set_callback-ed will return -EINVAL.
15776 			 */
15777 			struct bpf_insn ld_addrs[2] = {
15778 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15779 			};
15780 
15781 			insn_buf[0] = ld_addrs[0];
15782 			insn_buf[1] = ld_addrs[1];
15783 			insn_buf[2] = *insn;
15784 			cnt = 3;
15785 
15786 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15787 			if (!new_prog)
15788 				return -ENOMEM;
15789 
15790 			delta    += cnt - 1;
15791 			env->prog = prog = new_prog;
15792 			insn      = new_prog->insnsi + i + delta;
15793 			goto patch_call_imm;
15794 		}
15795 
15796 		if (is_storage_get_function(insn->imm)) {
15797 			if (!env->prog->aux->sleepable ||
15798 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
15799 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15800 			else
15801 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15802 			insn_buf[1] = *insn;
15803 			cnt = 2;
15804 
15805 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15806 			if (!new_prog)
15807 				return -ENOMEM;
15808 
15809 			delta += cnt - 1;
15810 			env->prog = prog = new_prog;
15811 			insn = new_prog->insnsi + i + delta;
15812 			goto patch_call_imm;
15813 		}
15814 
15815 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15816 		 * and other inlining handlers are currently limited to 64 bit
15817 		 * only.
15818 		 */
15819 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15820 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
15821 		     insn->imm == BPF_FUNC_map_update_elem ||
15822 		     insn->imm == BPF_FUNC_map_delete_elem ||
15823 		     insn->imm == BPF_FUNC_map_push_elem   ||
15824 		     insn->imm == BPF_FUNC_map_pop_elem    ||
15825 		     insn->imm == BPF_FUNC_map_peek_elem   ||
15826 		     insn->imm == BPF_FUNC_redirect_map    ||
15827 		     insn->imm == BPF_FUNC_for_each_map_elem ||
15828 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15829 			aux = &env->insn_aux_data[i + delta];
15830 			if (bpf_map_ptr_poisoned(aux))
15831 				goto patch_call_imm;
15832 
15833 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15834 			ops = map_ptr->ops;
15835 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
15836 			    ops->map_gen_lookup) {
15837 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15838 				if (cnt == -EOPNOTSUPP)
15839 					goto patch_map_ops_generic;
15840 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15841 					verbose(env, "bpf verifier is misconfigured\n");
15842 					return -EINVAL;
15843 				}
15844 
15845 				new_prog = bpf_patch_insn_data(env, i + delta,
15846 							       insn_buf, cnt);
15847 				if (!new_prog)
15848 					return -ENOMEM;
15849 
15850 				delta    += cnt - 1;
15851 				env->prog = prog = new_prog;
15852 				insn      = new_prog->insnsi + i + delta;
15853 				continue;
15854 			}
15855 
15856 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15857 				     (void *(*)(struct bpf_map *map, void *key))NULL));
15858 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15859 				     (int (*)(struct bpf_map *map, void *key))NULL));
15860 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15861 				     (int (*)(struct bpf_map *map, void *key, void *value,
15862 					      u64 flags))NULL));
15863 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15864 				     (int (*)(struct bpf_map *map, void *value,
15865 					      u64 flags))NULL));
15866 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15867 				     (int (*)(struct bpf_map *map, void *value))NULL));
15868 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15869 				     (int (*)(struct bpf_map *map, void *value))NULL));
15870 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
15871 				     (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15872 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15873 				     (int (*)(struct bpf_map *map,
15874 					      bpf_callback_t callback_fn,
15875 					      void *callback_ctx,
15876 					      u64 flags))NULL));
15877 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15878 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15879 
15880 patch_map_ops_generic:
15881 			switch (insn->imm) {
15882 			case BPF_FUNC_map_lookup_elem:
15883 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15884 				continue;
15885 			case BPF_FUNC_map_update_elem:
15886 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15887 				continue;
15888 			case BPF_FUNC_map_delete_elem:
15889 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15890 				continue;
15891 			case BPF_FUNC_map_push_elem:
15892 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15893 				continue;
15894 			case BPF_FUNC_map_pop_elem:
15895 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15896 				continue;
15897 			case BPF_FUNC_map_peek_elem:
15898 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15899 				continue;
15900 			case BPF_FUNC_redirect_map:
15901 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
15902 				continue;
15903 			case BPF_FUNC_for_each_map_elem:
15904 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15905 				continue;
15906 			case BPF_FUNC_map_lookup_percpu_elem:
15907 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15908 				continue;
15909 			}
15910 
15911 			goto patch_call_imm;
15912 		}
15913 
15914 		/* Implement bpf_jiffies64 inline. */
15915 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
15916 		    insn->imm == BPF_FUNC_jiffies64) {
15917 			struct bpf_insn ld_jiffies_addr[2] = {
15918 				BPF_LD_IMM64(BPF_REG_0,
15919 					     (unsigned long)&jiffies),
15920 			};
15921 
15922 			insn_buf[0] = ld_jiffies_addr[0];
15923 			insn_buf[1] = ld_jiffies_addr[1];
15924 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15925 						  BPF_REG_0, 0);
15926 			cnt = 3;
15927 
15928 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15929 						       cnt);
15930 			if (!new_prog)
15931 				return -ENOMEM;
15932 
15933 			delta    += cnt - 1;
15934 			env->prog = prog = new_prog;
15935 			insn      = new_prog->insnsi + i + delta;
15936 			continue;
15937 		}
15938 
15939 		/* Implement bpf_get_func_arg inline. */
15940 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15941 		    insn->imm == BPF_FUNC_get_func_arg) {
15942 			/* Load nr_args from ctx - 8 */
15943 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15944 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15945 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15946 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15947 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15948 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15949 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15950 			insn_buf[7] = BPF_JMP_A(1);
15951 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15952 			cnt = 9;
15953 
15954 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15955 			if (!new_prog)
15956 				return -ENOMEM;
15957 
15958 			delta    += cnt - 1;
15959 			env->prog = prog = new_prog;
15960 			insn      = new_prog->insnsi + i + delta;
15961 			continue;
15962 		}
15963 
15964 		/* Implement bpf_get_func_ret inline. */
15965 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15966 		    insn->imm == BPF_FUNC_get_func_ret) {
15967 			if (eatype == BPF_TRACE_FEXIT ||
15968 			    eatype == BPF_MODIFY_RETURN) {
15969 				/* Load nr_args from ctx - 8 */
15970 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15971 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15972 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15973 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15974 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15975 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15976 				cnt = 6;
15977 			} else {
15978 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15979 				cnt = 1;
15980 			}
15981 
15982 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15983 			if (!new_prog)
15984 				return -ENOMEM;
15985 
15986 			delta    += cnt - 1;
15987 			env->prog = prog = new_prog;
15988 			insn      = new_prog->insnsi + i + delta;
15989 			continue;
15990 		}
15991 
15992 		/* Implement get_func_arg_cnt inline. */
15993 		if (prog_type == BPF_PROG_TYPE_TRACING &&
15994 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
15995 			/* Load nr_args from ctx - 8 */
15996 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15997 
15998 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15999 			if (!new_prog)
16000 				return -ENOMEM;
16001 
16002 			env->prog = prog = new_prog;
16003 			insn      = new_prog->insnsi + i + delta;
16004 			continue;
16005 		}
16006 
16007 		/* Implement bpf_get_func_ip inline. */
16008 		if (prog_type == BPF_PROG_TYPE_TRACING &&
16009 		    insn->imm == BPF_FUNC_get_func_ip) {
16010 			/* Load IP address from ctx - 16 */
16011 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
16012 
16013 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
16014 			if (!new_prog)
16015 				return -ENOMEM;
16016 
16017 			env->prog = prog = new_prog;
16018 			insn      = new_prog->insnsi + i + delta;
16019 			continue;
16020 		}
16021 
16022 patch_call_imm:
16023 		fn = env->ops->get_func_proto(insn->imm, env->prog);
16024 		/* all functions that have prototype and verifier allowed
16025 		 * programs to call them, must be real in-kernel functions
16026 		 */
16027 		if (!fn->func) {
16028 			verbose(env,
16029 				"kernel subsystem misconfigured func %s#%d\n",
16030 				func_id_name(insn->imm), insn->imm);
16031 			return -EFAULT;
16032 		}
16033 		insn->imm = fn->func - __bpf_call_base;
16034 	}
16035 
16036 	/* Since poke tab is now finalized, publish aux to tracker. */
16037 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
16038 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
16039 		if (!map_ptr->ops->map_poke_track ||
16040 		    !map_ptr->ops->map_poke_untrack ||
16041 		    !map_ptr->ops->map_poke_run) {
16042 			verbose(env, "bpf verifier is misconfigured\n");
16043 			return -EINVAL;
16044 		}
16045 
16046 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
16047 		if (ret < 0) {
16048 			verbose(env, "tracking tail call prog failed\n");
16049 			return ret;
16050 		}
16051 	}
16052 
16053 	sort_kfunc_descs_by_imm(env->prog);
16054 
16055 	return 0;
16056 }
16057 
16058 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
16059 					int position,
16060 					s32 stack_base,
16061 					u32 callback_subprogno,
16062 					u32 *cnt)
16063 {
16064 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
16065 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
16066 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
16067 	int reg_loop_max = BPF_REG_6;
16068 	int reg_loop_cnt = BPF_REG_7;
16069 	int reg_loop_ctx = BPF_REG_8;
16070 
16071 	struct bpf_prog *new_prog;
16072 	u32 callback_start;
16073 	u32 call_insn_offset;
16074 	s32 callback_offset;
16075 
16076 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
16077 	 * be careful to modify this code in sync.
16078 	 */
16079 	struct bpf_insn insn_buf[] = {
16080 		/* Return error and jump to the end of the patch if
16081 		 * expected number of iterations is too big.
16082 		 */
16083 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
16084 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
16085 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
16086 		/* spill R6, R7, R8 to use these as loop vars */
16087 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
16088 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
16089 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
16090 		/* initialize loop vars */
16091 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
16092 		BPF_MOV32_IMM(reg_loop_cnt, 0),
16093 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
16094 		/* loop header,
16095 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
16096 		 */
16097 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
16098 		/* callback call,
16099 		 * correct callback offset would be set after patching
16100 		 */
16101 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
16102 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
16103 		BPF_CALL_REL(0),
16104 		/* increment loop counter */
16105 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
16106 		/* jump to loop header if callback returned 0 */
16107 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
16108 		/* return value of bpf_loop,
16109 		 * set R0 to the number of iterations
16110 		 */
16111 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
16112 		/* restore original values of R6, R7, R8 */
16113 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
16114 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
16115 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
16116 	};
16117 
16118 	*cnt = ARRAY_SIZE(insn_buf);
16119 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
16120 	if (!new_prog)
16121 		return new_prog;
16122 
16123 	/* callback start is known only after patching */
16124 	callback_start = env->subprog_info[callback_subprogno].start;
16125 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
16126 	call_insn_offset = position + 12;
16127 	callback_offset = callback_start - call_insn_offset - 1;
16128 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
16129 
16130 	return new_prog;
16131 }
16132 
16133 static bool is_bpf_loop_call(struct bpf_insn *insn)
16134 {
16135 	return insn->code == (BPF_JMP | BPF_CALL) &&
16136 		insn->src_reg == 0 &&
16137 		insn->imm == BPF_FUNC_loop;
16138 }
16139 
16140 /* For all sub-programs in the program (including main) check
16141  * insn_aux_data to see if there are bpf_loop calls that require
16142  * inlining. If such calls are found the calls are replaced with a
16143  * sequence of instructions produced by `inline_bpf_loop` function and
16144  * subprog stack_depth is increased by the size of 3 registers.
16145  * This stack space is used to spill values of the R6, R7, R8.  These
16146  * registers are used to store the loop bound, counter and context
16147  * variables.
16148  */
16149 static int optimize_bpf_loop(struct bpf_verifier_env *env)
16150 {
16151 	struct bpf_subprog_info *subprogs = env->subprog_info;
16152 	int i, cur_subprog = 0, cnt, delta = 0;
16153 	struct bpf_insn *insn = env->prog->insnsi;
16154 	int insn_cnt = env->prog->len;
16155 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
16156 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16157 	u16 stack_depth_extra = 0;
16158 
16159 	for (i = 0; i < insn_cnt; i++, insn++) {
16160 		struct bpf_loop_inline_state *inline_state =
16161 			&env->insn_aux_data[i + delta].loop_inline_state;
16162 
16163 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
16164 			struct bpf_prog *new_prog;
16165 
16166 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
16167 			new_prog = inline_bpf_loop(env,
16168 						   i + delta,
16169 						   -(stack_depth + stack_depth_extra),
16170 						   inline_state->callback_subprogno,
16171 						   &cnt);
16172 			if (!new_prog)
16173 				return -ENOMEM;
16174 
16175 			delta     += cnt - 1;
16176 			env->prog  = new_prog;
16177 			insn       = new_prog->insnsi + i + delta;
16178 		}
16179 
16180 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
16181 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
16182 			cur_subprog++;
16183 			stack_depth = subprogs[cur_subprog].stack_depth;
16184 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
16185 			stack_depth_extra = 0;
16186 		}
16187 	}
16188 
16189 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16190 
16191 	return 0;
16192 }
16193 
16194 static void free_states(struct bpf_verifier_env *env)
16195 {
16196 	struct bpf_verifier_state_list *sl, *sln;
16197 	int i;
16198 
16199 	sl = env->free_list;
16200 	while (sl) {
16201 		sln = sl->next;
16202 		free_verifier_state(&sl->state, false);
16203 		kfree(sl);
16204 		sl = sln;
16205 	}
16206 	env->free_list = NULL;
16207 
16208 	if (!env->explored_states)
16209 		return;
16210 
16211 	for (i = 0; i < state_htab_size(env); i++) {
16212 		sl = env->explored_states[i];
16213 
16214 		while (sl) {
16215 			sln = sl->next;
16216 			free_verifier_state(&sl->state, false);
16217 			kfree(sl);
16218 			sl = sln;
16219 		}
16220 		env->explored_states[i] = NULL;
16221 	}
16222 }
16223 
16224 static int do_check_common(struct bpf_verifier_env *env, int subprog)
16225 {
16226 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16227 	struct bpf_verifier_state *state;
16228 	struct bpf_reg_state *regs;
16229 	int ret, i;
16230 
16231 	env->prev_linfo = NULL;
16232 	env->pass_cnt++;
16233 
16234 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
16235 	if (!state)
16236 		return -ENOMEM;
16237 	state->curframe = 0;
16238 	state->speculative = false;
16239 	state->branches = 1;
16240 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
16241 	if (!state->frame[0]) {
16242 		kfree(state);
16243 		return -ENOMEM;
16244 	}
16245 	env->cur_state = state;
16246 	init_func_state(env, state->frame[0],
16247 			BPF_MAIN_FUNC /* callsite */,
16248 			0 /* frameno */,
16249 			subprog);
16250 	state->first_insn_idx = env->subprog_info[subprog].start;
16251 	state->last_insn_idx = -1;
16252 
16253 	regs = state->frame[state->curframe]->regs;
16254 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
16255 		ret = btf_prepare_func_args(env, subprog, regs);
16256 		if (ret)
16257 			goto out;
16258 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
16259 			if (regs[i].type == PTR_TO_CTX)
16260 				mark_reg_known_zero(env, regs, i);
16261 			else if (regs[i].type == SCALAR_VALUE)
16262 				mark_reg_unknown(env, regs, i);
16263 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
16264 				const u32 mem_size = regs[i].mem_size;
16265 
16266 				mark_reg_known_zero(env, regs, i);
16267 				regs[i].mem_size = mem_size;
16268 				regs[i].id = ++env->id_gen;
16269 			}
16270 		}
16271 	} else {
16272 		/* 1st arg to a function */
16273 		regs[BPF_REG_1].type = PTR_TO_CTX;
16274 		mark_reg_known_zero(env, regs, BPF_REG_1);
16275 		ret = btf_check_subprog_arg_match(env, subprog, regs);
16276 		if (ret == -EFAULT)
16277 			/* unlikely verifier bug. abort.
16278 			 * ret == 0 and ret < 0 are sadly acceptable for
16279 			 * main() function due to backward compatibility.
16280 			 * Like socket filter program may be written as:
16281 			 * int bpf_prog(struct pt_regs *ctx)
16282 			 * and never dereference that ctx in the program.
16283 			 * 'struct pt_regs' is a type mismatch for socket
16284 			 * filter that should be using 'struct __sk_buff'.
16285 			 */
16286 			goto out;
16287 	}
16288 
16289 	ret = do_check(env);
16290 out:
16291 	/* check for NULL is necessary, since cur_state can be freed inside
16292 	 * do_check() under memory pressure.
16293 	 */
16294 	if (env->cur_state) {
16295 		free_verifier_state(env->cur_state, true);
16296 		env->cur_state = NULL;
16297 	}
16298 	while (!pop_stack(env, NULL, NULL, false));
16299 	if (!ret && pop_log)
16300 		bpf_vlog_reset(&env->log, 0);
16301 	free_states(env);
16302 	return ret;
16303 }
16304 
16305 /* Verify all global functions in a BPF program one by one based on their BTF.
16306  * All global functions must pass verification. Otherwise the whole program is rejected.
16307  * Consider:
16308  * int bar(int);
16309  * int foo(int f)
16310  * {
16311  *    return bar(f);
16312  * }
16313  * int bar(int b)
16314  * {
16315  *    ...
16316  * }
16317  * foo() will be verified first for R1=any_scalar_value. During verification it
16318  * will be assumed that bar() already verified successfully and call to bar()
16319  * from foo() will be checked for type match only. Later bar() will be verified
16320  * independently to check that it's safe for R1=any_scalar_value.
16321  */
16322 static int do_check_subprogs(struct bpf_verifier_env *env)
16323 {
16324 	struct bpf_prog_aux *aux = env->prog->aux;
16325 	int i, ret;
16326 
16327 	if (!aux->func_info)
16328 		return 0;
16329 
16330 	for (i = 1; i < env->subprog_cnt; i++) {
16331 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16332 			continue;
16333 		env->insn_idx = env->subprog_info[i].start;
16334 		WARN_ON_ONCE(env->insn_idx == 0);
16335 		ret = do_check_common(env, i);
16336 		if (ret) {
16337 			return ret;
16338 		} else if (env->log.level & BPF_LOG_LEVEL) {
16339 			verbose(env,
16340 				"Func#%d is safe for any args that match its prototype\n",
16341 				i);
16342 		}
16343 	}
16344 	return 0;
16345 }
16346 
16347 static int do_check_main(struct bpf_verifier_env *env)
16348 {
16349 	int ret;
16350 
16351 	env->insn_idx = 0;
16352 	ret = do_check_common(env, 0);
16353 	if (!ret)
16354 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16355 	return ret;
16356 }
16357 
16358 
16359 static void print_verification_stats(struct bpf_verifier_env *env)
16360 {
16361 	int i;
16362 
16363 	if (env->log.level & BPF_LOG_STATS) {
16364 		verbose(env, "verification time %lld usec\n",
16365 			div_u64(env->verification_time, 1000));
16366 		verbose(env, "stack depth ");
16367 		for (i = 0; i < env->subprog_cnt; i++) {
16368 			u32 depth = env->subprog_info[i].stack_depth;
16369 
16370 			verbose(env, "%d", depth);
16371 			if (i + 1 < env->subprog_cnt)
16372 				verbose(env, "+");
16373 		}
16374 		verbose(env, "\n");
16375 	}
16376 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16377 		"total_states %d peak_states %d mark_read %d\n",
16378 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16379 		env->max_states_per_insn, env->total_states,
16380 		env->peak_states, env->longest_mark_read_walk);
16381 }
16382 
16383 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16384 {
16385 	const struct btf_type *t, *func_proto;
16386 	const struct bpf_struct_ops *st_ops;
16387 	const struct btf_member *member;
16388 	struct bpf_prog *prog = env->prog;
16389 	u32 btf_id, member_idx;
16390 	const char *mname;
16391 
16392 	if (!prog->gpl_compatible) {
16393 		verbose(env, "struct ops programs must have a GPL compatible license\n");
16394 		return -EINVAL;
16395 	}
16396 
16397 	btf_id = prog->aux->attach_btf_id;
16398 	st_ops = bpf_struct_ops_find(btf_id);
16399 	if (!st_ops) {
16400 		verbose(env, "attach_btf_id %u is not a supported struct\n",
16401 			btf_id);
16402 		return -ENOTSUPP;
16403 	}
16404 
16405 	t = st_ops->type;
16406 	member_idx = prog->expected_attach_type;
16407 	if (member_idx >= btf_type_vlen(t)) {
16408 		verbose(env, "attach to invalid member idx %u of struct %s\n",
16409 			member_idx, st_ops->name);
16410 		return -EINVAL;
16411 	}
16412 
16413 	member = &btf_type_member(t)[member_idx];
16414 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16415 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16416 					       NULL);
16417 	if (!func_proto) {
16418 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16419 			mname, member_idx, st_ops->name);
16420 		return -EINVAL;
16421 	}
16422 
16423 	if (st_ops->check_member) {
16424 		int err = st_ops->check_member(t, member);
16425 
16426 		if (err) {
16427 			verbose(env, "attach to unsupported member %s of struct %s\n",
16428 				mname, st_ops->name);
16429 			return err;
16430 		}
16431 	}
16432 
16433 	prog->aux->attach_func_proto = func_proto;
16434 	prog->aux->attach_func_name = mname;
16435 	env->ops = st_ops->verifier_ops;
16436 
16437 	return 0;
16438 }
16439 #define SECURITY_PREFIX "security_"
16440 
16441 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16442 {
16443 	if (within_error_injection_list(addr) ||
16444 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16445 		return 0;
16446 
16447 	return -EINVAL;
16448 }
16449 
16450 /* list of non-sleepable functions that are otherwise on
16451  * ALLOW_ERROR_INJECTION list
16452  */
16453 BTF_SET_START(btf_non_sleepable_error_inject)
16454 /* Three functions below can be called from sleepable and non-sleepable context.
16455  * Assume non-sleepable from bpf safety point of view.
16456  */
16457 BTF_ID(func, __filemap_add_folio)
16458 BTF_ID(func, should_fail_alloc_page)
16459 BTF_ID(func, should_failslab)
16460 BTF_SET_END(btf_non_sleepable_error_inject)
16461 
16462 static int check_non_sleepable_error_inject(u32 btf_id)
16463 {
16464 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16465 }
16466 
16467 int bpf_check_attach_target(struct bpf_verifier_log *log,
16468 			    const struct bpf_prog *prog,
16469 			    const struct bpf_prog *tgt_prog,
16470 			    u32 btf_id,
16471 			    struct bpf_attach_target_info *tgt_info)
16472 {
16473 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16474 	const char prefix[] = "btf_trace_";
16475 	int ret = 0, subprog = -1, i;
16476 	const struct btf_type *t;
16477 	bool conservative = true;
16478 	const char *tname;
16479 	struct btf *btf;
16480 	long addr = 0;
16481 
16482 	if (!btf_id) {
16483 		bpf_log(log, "Tracing programs must provide btf_id\n");
16484 		return -EINVAL;
16485 	}
16486 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16487 	if (!btf) {
16488 		bpf_log(log,
16489 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16490 		return -EINVAL;
16491 	}
16492 	t = btf_type_by_id(btf, btf_id);
16493 	if (!t) {
16494 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16495 		return -EINVAL;
16496 	}
16497 	tname = btf_name_by_offset(btf, t->name_off);
16498 	if (!tname) {
16499 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16500 		return -EINVAL;
16501 	}
16502 	if (tgt_prog) {
16503 		struct bpf_prog_aux *aux = tgt_prog->aux;
16504 
16505 		for (i = 0; i < aux->func_info_cnt; i++)
16506 			if (aux->func_info[i].type_id == btf_id) {
16507 				subprog = i;
16508 				break;
16509 			}
16510 		if (subprog == -1) {
16511 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
16512 			return -EINVAL;
16513 		}
16514 		conservative = aux->func_info_aux[subprog].unreliable;
16515 		if (prog_extension) {
16516 			if (conservative) {
16517 				bpf_log(log,
16518 					"Cannot replace static functions\n");
16519 				return -EINVAL;
16520 			}
16521 			if (!prog->jit_requested) {
16522 				bpf_log(log,
16523 					"Extension programs should be JITed\n");
16524 				return -EINVAL;
16525 			}
16526 		}
16527 		if (!tgt_prog->jited) {
16528 			bpf_log(log, "Can attach to only JITed progs\n");
16529 			return -EINVAL;
16530 		}
16531 		if (tgt_prog->type == prog->type) {
16532 			/* Cannot fentry/fexit another fentry/fexit program.
16533 			 * Cannot attach program extension to another extension.
16534 			 * It's ok to attach fentry/fexit to extension program.
16535 			 */
16536 			bpf_log(log, "Cannot recursively attach\n");
16537 			return -EINVAL;
16538 		}
16539 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16540 		    prog_extension &&
16541 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16542 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16543 			/* Program extensions can extend all program types
16544 			 * except fentry/fexit. The reason is the following.
16545 			 * The fentry/fexit programs are used for performance
16546 			 * analysis, stats and can be attached to any program
16547 			 * type except themselves. When extension program is
16548 			 * replacing XDP function it is necessary to allow
16549 			 * performance analysis of all functions. Both original
16550 			 * XDP program and its program extension. Hence
16551 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16552 			 * allowed. If extending of fentry/fexit was allowed it
16553 			 * would be possible to create long call chain
16554 			 * fentry->extension->fentry->extension beyond
16555 			 * reasonable stack size. Hence extending fentry is not
16556 			 * allowed.
16557 			 */
16558 			bpf_log(log, "Cannot extend fentry/fexit\n");
16559 			return -EINVAL;
16560 		}
16561 	} else {
16562 		if (prog_extension) {
16563 			bpf_log(log, "Cannot replace kernel functions\n");
16564 			return -EINVAL;
16565 		}
16566 	}
16567 
16568 	switch (prog->expected_attach_type) {
16569 	case BPF_TRACE_RAW_TP:
16570 		if (tgt_prog) {
16571 			bpf_log(log,
16572 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16573 			return -EINVAL;
16574 		}
16575 		if (!btf_type_is_typedef(t)) {
16576 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
16577 				btf_id);
16578 			return -EINVAL;
16579 		}
16580 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16581 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16582 				btf_id, tname);
16583 			return -EINVAL;
16584 		}
16585 		tname += sizeof(prefix) - 1;
16586 		t = btf_type_by_id(btf, t->type);
16587 		if (!btf_type_is_ptr(t))
16588 			/* should never happen in valid vmlinux build */
16589 			return -EINVAL;
16590 		t = btf_type_by_id(btf, t->type);
16591 		if (!btf_type_is_func_proto(t))
16592 			/* should never happen in valid vmlinux build */
16593 			return -EINVAL;
16594 
16595 		break;
16596 	case BPF_TRACE_ITER:
16597 		if (!btf_type_is_func(t)) {
16598 			bpf_log(log, "attach_btf_id %u is not a function\n",
16599 				btf_id);
16600 			return -EINVAL;
16601 		}
16602 		t = btf_type_by_id(btf, t->type);
16603 		if (!btf_type_is_func_proto(t))
16604 			return -EINVAL;
16605 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16606 		if (ret)
16607 			return ret;
16608 		break;
16609 	default:
16610 		if (!prog_extension)
16611 			return -EINVAL;
16612 		fallthrough;
16613 	case BPF_MODIFY_RETURN:
16614 	case BPF_LSM_MAC:
16615 	case BPF_LSM_CGROUP:
16616 	case BPF_TRACE_FENTRY:
16617 	case BPF_TRACE_FEXIT:
16618 		if (!btf_type_is_func(t)) {
16619 			bpf_log(log, "attach_btf_id %u is not a function\n",
16620 				btf_id);
16621 			return -EINVAL;
16622 		}
16623 		if (prog_extension &&
16624 		    btf_check_type_match(log, prog, btf, t))
16625 			return -EINVAL;
16626 		t = btf_type_by_id(btf, t->type);
16627 		if (!btf_type_is_func_proto(t))
16628 			return -EINVAL;
16629 
16630 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16631 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16632 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16633 			return -EINVAL;
16634 
16635 		if (tgt_prog && conservative)
16636 			t = NULL;
16637 
16638 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16639 		if (ret < 0)
16640 			return ret;
16641 
16642 		if (tgt_prog) {
16643 			if (subprog == 0)
16644 				addr = (long) tgt_prog->bpf_func;
16645 			else
16646 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16647 		} else {
16648 			addr = kallsyms_lookup_name(tname);
16649 			if (!addr) {
16650 				bpf_log(log,
16651 					"The address of function %s cannot be found\n",
16652 					tname);
16653 				return -ENOENT;
16654 			}
16655 		}
16656 
16657 		if (prog->aux->sleepable) {
16658 			ret = -EINVAL;
16659 			switch (prog->type) {
16660 			case BPF_PROG_TYPE_TRACING:
16661 
16662 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
16663 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16664 				 */
16665 				if (!check_non_sleepable_error_inject(btf_id) &&
16666 				    within_error_injection_list(addr))
16667 					ret = 0;
16668 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
16669 				 * in the fmodret id set with the KF_SLEEPABLE flag.
16670 				 */
16671 				else {
16672 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
16673 
16674 					if (flags && (*flags & KF_SLEEPABLE))
16675 						ret = 0;
16676 				}
16677 				break;
16678 			case BPF_PROG_TYPE_LSM:
16679 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
16680 				 * Only some of them are sleepable.
16681 				 */
16682 				if (bpf_lsm_is_sleepable_hook(btf_id))
16683 					ret = 0;
16684 				break;
16685 			default:
16686 				break;
16687 			}
16688 			if (ret) {
16689 				bpf_log(log, "%s is not sleepable\n", tname);
16690 				return ret;
16691 			}
16692 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16693 			if (tgt_prog) {
16694 				bpf_log(log, "can't modify return codes of BPF programs\n");
16695 				return -EINVAL;
16696 			}
16697 			ret = -EINVAL;
16698 			if (btf_kfunc_is_modify_return(btf, btf_id) ||
16699 			    !check_attach_modify_return(addr, tname))
16700 				ret = 0;
16701 			if (ret) {
16702 				bpf_log(log, "%s() is not modifiable\n", tname);
16703 				return ret;
16704 			}
16705 		}
16706 
16707 		break;
16708 	}
16709 	tgt_info->tgt_addr = addr;
16710 	tgt_info->tgt_name = tname;
16711 	tgt_info->tgt_type = t;
16712 	return 0;
16713 }
16714 
16715 BTF_SET_START(btf_id_deny)
16716 BTF_ID_UNUSED
16717 #ifdef CONFIG_SMP
16718 BTF_ID(func, migrate_disable)
16719 BTF_ID(func, migrate_enable)
16720 #endif
16721 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16722 BTF_ID(func, rcu_read_unlock_strict)
16723 #endif
16724 BTF_SET_END(btf_id_deny)
16725 
16726 static int check_attach_btf_id(struct bpf_verifier_env *env)
16727 {
16728 	struct bpf_prog *prog = env->prog;
16729 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16730 	struct bpf_attach_target_info tgt_info = {};
16731 	u32 btf_id = prog->aux->attach_btf_id;
16732 	struct bpf_trampoline *tr;
16733 	int ret;
16734 	u64 key;
16735 
16736 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16737 		if (prog->aux->sleepable)
16738 			/* attach_btf_id checked to be zero already */
16739 			return 0;
16740 		verbose(env, "Syscall programs can only be sleepable\n");
16741 		return -EINVAL;
16742 	}
16743 
16744 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16745 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16746 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16747 		return -EINVAL;
16748 	}
16749 
16750 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16751 		return check_struct_ops_btf_id(env);
16752 
16753 	if (prog->type != BPF_PROG_TYPE_TRACING &&
16754 	    prog->type != BPF_PROG_TYPE_LSM &&
16755 	    prog->type != BPF_PROG_TYPE_EXT)
16756 		return 0;
16757 
16758 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16759 	if (ret)
16760 		return ret;
16761 
16762 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16763 		/* to make freplace equivalent to their targets, they need to
16764 		 * inherit env->ops and expected_attach_type for the rest of the
16765 		 * verification
16766 		 */
16767 		env->ops = bpf_verifier_ops[tgt_prog->type];
16768 		prog->expected_attach_type = tgt_prog->expected_attach_type;
16769 	}
16770 
16771 	/* store info about the attachment target that will be used later */
16772 	prog->aux->attach_func_proto = tgt_info.tgt_type;
16773 	prog->aux->attach_func_name = tgt_info.tgt_name;
16774 
16775 	if (tgt_prog) {
16776 		prog->aux->saved_dst_prog_type = tgt_prog->type;
16777 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16778 	}
16779 
16780 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16781 		prog->aux->attach_btf_trace = true;
16782 		return 0;
16783 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16784 		if (!bpf_iter_prog_supported(prog))
16785 			return -EINVAL;
16786 		return 0;
16787 	}
16788 
16789 	if (prog->type == BPF_PROG_TYPE_LSM) {
16790 		ret = bpf_lsm_verify_prog(&env->log, prog);
16791 		if (ret < 0)
16792 			return ret;
16793 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
16794 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
16795 		return -EINVAL;
16796 	}
16797 
16798 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16799 	tr = bpf_trampoline_get(key, &tgt_info);
16800 	if (!tr)
16801 		return -ENOMEM;
16802 
16803 	prog->aux->dst_trampoline = tr;
16804 	return 0;
16805 }
16806 
16807 struct btf *bpf_get_btf_vmlinux(void)
16808 {
16809 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16810 		mutex_lock(&bpf_verifier_lock);
16811 		if (!btf_vmlinux)
16812 			btf_vmlinux = btf_parse_vmlinux();
16813 		mutex_unlock(&bpf_verifier_lock);
16814 	}
16815 	return btf_vmlinux;
16816 }
16817 
16818 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16819 {
16820 	u64 start_time = ktime_get_ns();
16821 	struct bpf_verifier_env *env;
16822 	struct bpf_verifier_log *log;
16823 	int i, len, ret = -EINVAL;
16824 	bool is_priv;
16825 
16826 	/* no program is valid */
16827 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16828 		return -EINVAL;
16829 
16830 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
16831 	 * allocate/free it every time bpf_check() is called
16832 	 */
16833 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16834 	if (!env)
16835 		return -ENOMEM;
16836 	log = &env->log;
16837 
16838 	len = (*prog)->len;
16839 	env->insn_aux_data =
16840 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16841 	ret = -ENOMEM;
16842 	if (!env->insn_aux_data)
16843 		goto err_free_env;
16844 	for (i = 0; i < len; i++)
16845 		env->insn_aux_data[i].orig_idx = i;
16846 	env->prog = *prog;
16847 	env->ops = bpf_verifier_ops[env->prog->type];
16848 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16849 	is_priv = bpf_capable();
16850 
16851 	bpf_get_btf_vmlinux();
16852 
16853 	/* grab the mutex to protect few globals used by verifier */
16854 	if (!is_priv)
16855 		mutex_lock(&bpf_verifier_lock);
16856 
16857 	if (attr->log_level || attr->log_buf || attr->log_size) {
16858 		/* user requested verbose verifier output
16859 		 * and supplied buffer to store the verification trace
16860 		 */
16861 		log->level = attr->log_level;
16862 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16863 		log->len_total = attr->log_size;
16864 
16865 		/* log attributes have to be sane */
16866 		if (!bpf_verifier_log_attr_valid(log)) {
16867 			ret = -EINVAL;
16868 			goto err_unlock;
16869 		}
16870 	}
16871 
16872 	mark_verifier_state_clean(env);
16873 
16874 	if (IS_ERR(btf_vmlinux)) {
16875 		/* Either gcc or pahole or kernel are broken. */
16876 		verbose(env, "in-kernel BTF is malformed\n");
16877 		ret = PTR_ERR(btf_vmlinux);
16878 		goto skip_full_check;
16879 	}
16880 
16881 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16882 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16883 		env->strict_alignment = true;
16884 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16885 		env->strict_alignment = false;
16886 
16887 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16888 	env->allow_uninit_stack = bpf_allow_uninit_stack();
16889 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
16890 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
16891 	env->bpf_capable = bpf_capable();
16892 	env->rcu_tag_supported = btf_vmlinux &&
16893 		btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0;
16894 
16895 	if (is_priv)
16896 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16897 
16898 	env->explored_states = kvcalloc(state_htab_size(env),
16899 				       sizeof(struct bpf_verifier_state_list *),
16900 				       GFP_USER);
16901 	ret = -ENOMEM;
16902 	if (!env->explored_states)
16903 		goto skip_full_check;
16904 
16905 	ret = add_subprog_and_kfunc(env);
16906 	if (ret < 0)
16907 		goto skip_full_check;
16908 
16909 	ret = check_subprogs(env);
16910 	if (ret < 0)
16911 		goto skip_full_check;
16912 
16913 	ret = check_btf_info(env, attr, uattr);
16914 	if (ret < 0)
16915 		goto skip_full_check;
16916 
16917 	ret = check_attach_btf_id(env);
16918 	if (ret)
16919 		goto skip_full_check;
16920 
16921 	ret = resolve_pseudo_ldimm64(env);
16922 	if (ret < 0)
16923 		goto skip_full_check;
16924 
16925 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
16926 		ret = bpf_prog_offload_verifier_prep(env->prog);
16927 		if (ret)
16928 			goto skip_full_check;
16929 	}
16930 
16931 	ret = check_cfg(env);
16932 	if (ret < 0)
16933 		goto skip_full_check;
16934 
16935 	ret = do_check_subprogs(env);
16936 	ret = ret ?: do_check_main(env);
16937 
16938 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16939 		ret = bpf_prog_offload_finalize(env);
16940 
16941 skip_full_check:
16942 	kvfree(env->explored_states);
16943 
16944 	if (ret == 0)
16945 		ret = check_max_stack_depth(env);
16946 
16947 	/* instruction rewrites happen after this point */
16948 	if (ret == 0)
16949 		ret = optimize_bpf_loop(env);
16950 
16951 	if (is_priv) {
16952 		if (ret == 0)
16953 			opt_hard_wire_dead_code_branches(env);
16954 		if (ret == 0)
16955 			ret = opt_remove_dead_code(env);
16956 		if (ret == 0)
16957 			ret = opt_remove_nops(env);
16958 	} else {
16959 		if (ret == 0)
16960 			sanitize_dead_code(env);
16961 	}
16962 
16963 	if (ret == 0)
16964 		/* program is valid, convert *(u32*)(ctx + off) accesses */
16965 		ret = convert_ctx_accesses(env);
16966 
16967 	if (ret == 0)
16968 		ret = do_misc_fixups(env);
16969 
16970 	/* do 32-bit optimization after insn patching has done so those patched
16971 	 * insns could be handled correctly.
16972 	 */
16973 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16974 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16975 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16976 								     : false;
16977 	}
16978 
16979 	if (ret == 0)
16980 		ret = fixup_call_args(env);
16981 
16982 	env->verification_time = ktime_get_ns() - start_time;
16983 	print_verification_stats(env);
16984 	env->prog->aux->verified_insns = env->insn_processed;
16985 
16986 	if (log->level && bpf_verifier_log_full(log))
16987 		ret = -ENOSPC;
16988 	if (log->level && !log->ubuf) {
16989 		ret = -EFAULT;
16990 		goto err_release_maps;
16991 	}
16992 
16993 	if (ret)
16994 		goto err_release_maps;
16995 
16996 	if (env->used_map_cnt) {
16997 		/* if program passed verifier, update used_maps in bpf_prog_info */
16998 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
16999 							  sizeof(env->used_maps[0]),
17000 							  GFP_KERNEL);
17001 
17002 		if (!env->prog->aux->used_maps) {
17003 			ret = -ENOMEM;
17004 			goto err_release_maps;
17005 		}
17006 
17007 		memcpy(env->prog->aux->used_maps, env->used_maps,
17008 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
17009 		env->prog->aux->used_map_cnt = env->used_map_cnt;
17010 	}
17011 	if (env->used_btf_cnt) {
17012 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
17013 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
17014 							  sizeof(env->used_btfs[0]),
17015 							  GFP_KERNEL);
17016 		if (!env->prog->aux->used_btfs) {
17017 			ret = -ENOMEM;
17018 			goto err_release_maps;
17019 		}
17020 
17021 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
17022 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
17023 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
17024 	}
17025 	if (env->used_map_cnt || env->used_btf_cnt) {
17026 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
17027 		 * bpf_ld_imm64 instructions
17028 		 */
17029 		convert_pseudo_ld_imm64(env);
17030 	}
17031 
17032 	adjust_btf_func(env);
17033 
17034 err_release_maps:
17035 	if (!env->prog->aux->used_maps)
17036 		/* if we didn't copy map pointers into bpf_prog_info, release
17037 		 * them now. Otherwise free_used_maps() will release them.
17038 		 */
17039 		release_maps(env);
17040 	if (!env->prog->aux->used_btfs)
17041 		release_btfs(env);
17042 
17043 	/* extension progs temporarily inherit the attach_type of their targets
17044 	   for verification purposes, so set it back to zero before returning
17045 	 */
17046 	if (env->prog->type == BPF_PROG_TYPE_EXT)
17047 		env->prog->expected_attach_type = 0;
17048 
17049 	*prog = env->prog;
17050 err_unlock:
17051 	if (!is_priv)
17052 		mutex_unlock(&bpf_verifier_lock);
17053 	vfree(env->insn_aux_data);
17054 err_free_env:
17055 	kfree(env);
17056 	return ret;
17057 }
17058