bpf: allow more maps in sleepable bpf programs
[linux-block.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31
32 #include "disasm.h"
33
34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
36         [_id] = & _name ## _verifier_ops,
37 #define BPF_MAP_TYPE(_id, _ops)
38 #define BPF_LINK_TYPE(_id, _name)
39 #include <linux/bpf_types.h>
40 #undef BPF_PROG_TYPE
41 #undef BPF_MAP_TYPE
42 #undef BPF_LINK_TYPE
43 };
44
45 struct bpf_mem_alloc bpf_global_percpu_ma;
46 static bool bpf_global_percpu_ma_set;
47
48 /* bpf_check() is a static code analyzer that walks eBPF program
49  * instruction by instruction and updates register/stack state.
50  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
51  *
52  * The first pass is depth-first-search to check that the program is a DAG.
53  * It rejects the following programs:
54  * - larger than BPF_MAXINSNS insns
55  * - if loop is present (detected via back-edge)
56  * - unreachable insns exist (shouldn't be a forest. program = one function)
57  * - out of bounds or malformed jumps
58  * The second pass is all possible path descent from the 1st insn.
59  * Since it's analyzing all paths through the program, the length of the
60  * analysis is limited to 64k insn, which may be hit even if total number of
61  * insn is less then 4K, but there are too many branches that change stack/regs.
62  * Number of 'branches to be analyzed' is limited to 1k
63  *
64  * On entry to each instruction, each register has a type, and the instruction
65  * changes the types of the registers depending on instruction semantics.
66  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
67  * copied to R1.
68  *
69  * All registers are 64-bit.
70  * R0 - return register
71  * R1-R5 argument passing registers
72  * R6-R9 callee saved registers
73  * R10 - frame pointer read-only
74  *
75  * At the start of BPF program the register R1 contains a pointer to bpf_context
76  * and has type PTR_TO_CTX.
77  *
78  * Verifier tracks arithmetic operations on pointers in case:
79  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81  * 1st insn copies R10 (which has FRAME_PTR) type into R1
82  * and 2nd arithmetic instruction is pattern matched to recognize
83  * that it wants to construct a pointer to some element within stack.
84  * So after 2nd insn, the register R1 has type PTR_TO_STACK
85  * (and -20 constant is saved for further stack bounds checking).
86  * Meaning that this reg is a pointer to stack plus known immediate constant.
87  *
88  * Most of the time the registers have SCALAR_VALUE type, which
89  * means the register has some value, but it's not a valid pointer.
90  * (like pointer plus pointer becomes SCALAR_VALUE type)
91  *
92  * When verifier sees load or store instructions the type of base register
93  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94  * four pointer types recognized by check_mem_access() function.
95  *
96  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97  * and the range of [ptr, ptr + map's value_size) is accessible.
98  *
99  * registers used to pass values to function calls are checked against
100  * function argument constraints.
101  *
102  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103  * It means that the register type passed to this function must be
104  * PTR_TO_STACK and it will be used inside the function as
105  * 'pointer to map element key'
106  *
107  * For example the argument constraints for bpf_map_lookup_elem():
108  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109  *   .arg1_type = ARG_CONST_MAP_PTR,
110  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
111  *
112  * ret_type says that this function returns 'pointer to map elem value or null'
113  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114  * 2nd argument should be a pointer to stack, which will be used inside
115  * the helper function as a pointer to map element key.
116  *
117  * On the kernel side the helper function looks like:
118  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
119  * {
120  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121  *    void *key = (void *) (unsigned long) r2;
122  *    void *value;
123  *
124  *    here kernel can access 'key' and 'map' pointers safely, knowing that
125  *    [key, key + map->key_size) bytes are valid and were initialized on
126  *    the stack of eBPF program.
127  * }
128  *
129  * Corresponding eBPF program may look like:
130  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
131  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
133  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134  * here verifier looks at prototype of map_lookup_elem() and sees:
135  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
137  *
138  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140  * and were initialized prior to this call.
141  * If it's ok, then verifier allows this BPF_CALL insn and looks at
142  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
144  * returns either pointer to map value or NULL.
145  *
146  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147  * insn, the register holding that pointer in the true branch changes state to
148  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149  * branch. See check_cond_jmp_op().
150  *
151  * After the call R0 is set to return type of the function and registers R1-R5
152  * are set to NOT_INIT to indicate that they are no longer readable.
153  *
154  * The following reference types represent a potential reference to a kernel
155  * resource which, after first being allocated, must be checked and freed by
156  * the BPF program:
157  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
158  *
159  * When the verifier sees a helper call return a reference type, it allocates a
160  * pointer id for the reference and stores it in the current function state.
161  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163  * passes through a NULL-check conditional. For the branch wherein the state is
164  * changed to CONST_IMM, the verifier releases the reference.
165  *
166  * For each helper function that allocates a reference, such as
167  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168  * bpf_sk_release(). When a reference type passes into the release function,
169  * the verifier also releases the reference. If any unchecked or unreleased
170  * reference remains at the end of the program, the verifier rejects it.
171  */
172
173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
174 struct bpf_verifier_stack_elem {
175         /* verifer state is 'st'
176          * before processing instruction 'insn_idx'
177          * and after processing instruction 'prev_insn_idx'
178          */
179         struct bpf_verifier_state st;
180         int insn_idx;
181         int prev_insn_idx;
182         struct bpf_verifier_stack_elem *next;
183         /* length of verifier log at the time this state was pushed on stack */
184         u32 log_pos;
185 };
186
187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
188 #define BPF_COMPLEXITY_LIMIT_STATES     64
189
190 #define BPF_MAP_KEY_POISON      (1ULL << 63)
191 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
192
193 #define BPF_MAP_PTR_UNPRIV      1UL
194 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
195                                           POISON_POINTER_DELTA))
196 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
197
198 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
199
200 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
204 static int ref_set_non_owning(struct bpf_verifier_env *env,
205                               struct bpf_reg_state *reg);
206 static void specialize_kfunc(struct bpf_verifier_env *env,
207                              u32 func_id, u16 offset, unsigned long *addr);
208 static bool is_trusted_reg(const struct bpf_reg_state *reg);
209
210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
211 {
212         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
213 }
214
215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
216 {
217         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
218 }
219
220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
221                               const struct bpf_map *map, bool unpriv)
222 {
223         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
224         unpriv |= bpf_map_ptr_unpriv(aux);
225         aux->map_ptr_state = (unsigned long)map |
226                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
227 }
228
229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
230 {
231         return aux->map_key_state & BPF_MAP_KEY_POISON;
232 }
233
234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
235 {
236         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
237 }
238
239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
240 {
241         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
242 }
243
244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
245 {
246         bool poisoned = bpf_map_key_poisoned(aux);
247
248         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
249                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
250 }
251
252 static bool bpf_helper_call(const struct bpf_insn *insn)
253 {
254         return insn->code == (BPF_JMP | BPF_CALL) &&
255                insn->src_reg == 0;
256 }
257
258 static bool bpf_pseudo_call(const struct bpf_insn *insn)
259 {
260         return insn->code == (BPF_JMP | BPF_CALL) &&
261                insn->src_reg == BPF_PSEUDO_CALL;
262 }
263
264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
265 {
266         return insn->code == (BPF_JMP | BPF_CALL) &&
267                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
268 }
269
270 struct bpf_call_arg_meta {
271         struct bpf_map *map_ptr;
272         bool raw_mode;
273         bool pkt_access;
274         u8 release_regno;
275         int regno;
276         int access_size;
277         int mem_size;
278         u64 msize_max_value;
279         int ref_obj_id;
280         int dynptr_id;
281         int map_uid;
282         int func_id;
283         struct btf *btf;
284         u32 btf_id;
285         struct btf *ret_btf;
286         u32 ret_btf_id;
287         u32 subprogno;
288         struct btf_field *kptr_field;
289 };
290
291 struct bpf_kfunc_call_arg_meta {
292         /* In parameters */
293         struct btf *btf;
294         u32 func_id;
295         u32 kfunc_flags;
296         const struct btf_type *func_proto;
297         const char *func_name;
298         /* Out parameters */
299         u32 ref_obj_id;
300         u8 release_regno;
301         bool r0_rdonly;
302         u32 ret_btf_id;
303         u64 r0_size;
304         u32 subprogno;
305         struct {
306                 u64 value;
307                 bool found;
308         } arg_constant;
309
310         /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
311          * generally to pass info about user-defined local kptr types to later
312          * verification logic
313          *   bpf_obj_drop/bpf_percpu_obj_drop
314          *     Record the local kptr type to be drop'd
315          *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
316          *     Record the local kptr type to be refcount_incr'd and use
317          *     arg_owning_ref to determine whether refcount_acquire should be
318          *     fallible
319          */
320         struct btf *arg_btf;
321         u32 arg_btf_id;
322         bool arg_owning_ref;
323
324         struct {
325                 struct btf_field *field;
326         } arg_list_head;
327         struct {
328                 struct btf_field *field;
329         } arg_rbtree_root;
330         struct {
331                 enum bpf_dynptr_type type;
332                 u32 id;
333                 u32 ref_obj_id;
334         } initialized_dynptr;
335         struct {
336                 u8 spi;
337                 u8 frameno;
338         } iter;
339         u64 mem_size;
340 };
341
342 struct btf *btf_vmlinux;
343
344 static const char *btf_type_name(const struct btf *btf, u32 id)
345 {
346         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
347 }
348
349 static DEFINE_MUTEX(bpf_verifier_lock);
350 static DEFINE_MUTEX(bpf_percpu_ma_lock);
351
352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
353 {
354         struct bpf_verifier_env *env = private_data;
355         va_list args;
356
357         if (!bpf_verifier_log_needed(&env->log))
358                 return;
359
360         va_start(args, fmt);
361         bpf_verifier_vlog(&env->log, fmt, args);
362         va_end(args);
363 }
364
365 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
366                                    struct bpf_reg_state *reg,
367                                    struct bpf_retval_range range, const char *ctx,
368                                    const char *reg_name)
369 {
370         bool unknown = true;
371
372         verbose(env, "%s the register %s has", ctx, reg_name);
373         if (reg->smin_value > S64_MIN) {
374                 verbose(env, " smin=%lld", reg->smin_value);
375                 unknown = false;
376         }
377         if (reg->smax_value < S64_MAX) {
378                 verbose(env, " smax=%lld", reg->smax_value);
379                 unknown = false;
380         }
381         if (unknown)
382                 verbose(env, " unknown scalar value");
383         verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
384 }
385
386 static bool type_may_be_null(u32 type)
387 {
388         return type & PTR_MAYBE_NULL;
389 }
390
391 static bool reg_not_null(const struct bpf_reg_state *reg)
392 {
393         enum bpf_reg_type type;
394
395         type = reg->type;
396         if (type_may_be_null(type))
397                 return false;
398
399         type = base_type(type);
400         return type == PTR_TO_SOCKET ||
401                 type == PTR_TO_TCP_SOCK ||
402                 type == PTR_TO_MAP_VALUE ||
403                 type == PTR_TO_MAP_KEY ||
404                 type == PTR_TO_SOCK_COMMON ||
405                 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
406                 type == PTR_TO_MEM;
407 }
408
409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
410 {
411         struct btf_record *rec = NULL;
412         struct btf_struct_meta *meta;
413
414         if (reg->type == PTR_TO_MAP_VALUE) {
415                 rec = reg->map_ptr->record;
416         } else if (type_is_ptr_alloc_obj(reg->type)) {
417                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
418                 if (meta)
419                         rec = meta->record;
420         }
421         return rec;
422 }
423
424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
425 {
426         struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
427
428         return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
429 }
430
431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
432 {
433         struct bpf_func_info *info;
434
435         if (!env->prog->aux->func_info)
436                 return "";
437
438         info = &env->prog->aux->func_info[subprog];
439         return btf_type_name(env->prog->aux->btf, info->type_id);
440 }
441
442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
443 {
444         struct bpf_subprog_info *info = subprog_info(env, subprog);
445
446         info->is_cb = true;
447         info->is_async_cb = true;
448         info->is_exception_cb = true;
449 }
450
451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453         return subprog_info(env, subprog)->is_exception_cb;
454 }
455
456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
457 {
458         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
459 }
460
461 static bool type_is_rdonly_mem(u32 type)
462 {
463         return type & MEM_RDONLY;
464 }
465
466 static bool is_acquire_function(enum bpf_func_id func_id,
467                                 const struct bpf_map *map)
468 {
469         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
470
471         if (func_id == BPF_FUNC_sk_lookup_tcp ||
472             func_id == BPF_FUNC_sk_lookup_udp ||
473             func_id == BPF_FUNC_skc_lookup_tcp ||
474             func_id == BPF_FUNC_ringbuf_reserve ||
475             func_id == BPF_FUNC_kptr_xchg)
476                 return true;
477
478         if (func_id == BPF_FUNC_map_lookup_elem &&
479             (map_type == BPF_MAP_TYPE_SOCKMAP ||
480              map_type == BPF_MAP_TYPE_SOCKHASH))
481                 return true;
482
483         return false;
484 }
485
486 static bool is_ptr_cast_function(enum bpf_func_id func_id)
487 {
488         return func_id == BPF_FUNC_tcp_sock ||
489                 func_id == BPF_FUNC_sk_fullsock ||
490                 func_id == BPF_FUNC_skc_to_tcp_sock ||
491                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
492                 func_id == BPF_FUNC_skc_to_udp6_sock ||
493                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
494                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
495                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
496 }
497
498 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
499 {
500         return func_id == BPF_FUNC_dynptr_data;
501 }
502
503 static bool is_sync_callback_calling_kfunc(u32 btf_id);
504 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
505
506 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
507 {
508         return func_id == BPF_FUNC_for_each_map_elem ||
509                func_id == BPF_FUNC_find_vma ||
510                func_id == BPF_FUNC_loop ||
511                func_id == BPF_FUNC_user_ringbuf_drain;
512 }
513
514 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
515 {
516         return func_id == BPF_FUNC_timer_set_callback;
517 }
518
519 static bool is_callback_calling_function(enum bpf_func_id func_id)
520 {
521         return is_sync_callback_calling_function(func_id) ||
522                is_async_callback_calling_function(func_id);
523 }
524
525 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
526 {
527         return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
528                (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
529 }
530
531 static bool is_storage_get_function(enum bpf_func_id func_id)
532 {
533         return func_id == BPF_FUNC_sk_storage_get ||
534                func_id == BPF_FUNC_inode_storage_get ||
535                func_id == BPF_FUNC_task_storage_get ||
536                func_id == BPF_FUNC_cgrp_storage_get;
537 }
538
539 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
540                                         const struct bpf_map *map)
541 {
542         int ref_obj_uses = 0;
543
544         if (is_ptr_cast_function(func_id))
545                 ref_obj_uses++;
546         if (is_acquire_function(func_id, map))
547                 ref_obj_uses++;
548         if (is_dynptr_ref_function(func_id))
549                 ref_obj_uses++;
550
551         return ref_obj_uses > 1;
552 }
553
554 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
555 {
556         return BPF_CLASS(insn->code) == BPF_STX &&
557                BPF_MODE(insn->code) == BPF_ATOMIC &&
558                insn->imm == BPF_CMPXCHG;
559 }
560
561 static int __get_spi(s32 off)
562 {
563         return (-off - 1) / BPF_REG_SIZE;
564 }
565
566 static struct bpf_func_state *func(struct bpf_verifier_env *env,
567                                    const struct bpf_reg_state *reg)
568 {
569         struct bpf_verifier_state *cur = env->cur_state;
570
571         return cur->frame[reg->frameno];
572 }
573
574 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
575 {
576        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
577
578        /* We need to check that slots between [spi - nr_slots + 1, spi] are
579         * within [0, allocated_stack).
580         *
581         * Please note that the spi grows downwards. For example, a dynptr
582         * takes the size of two stack slots; the first slot will be at
583         * spi and the second slot will be at spi - 1.
584         */
585        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
586 }
587
588 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
589                                   const char *obj_kind, int nr_slots)
590 {
591         int off, spi;
592
593         if (!tnum_is_const(reg->var_off)) {
594                 verbose(env, "%s has to be at a constant offset\n", obj_kind);
595                 return -EINVAL;
596         }
597
598         off = reg->off + reg->var_off.value;
599         if (off % BPF_REG_SIZE) {
600                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
601                 return -EINVAL;
602         }
603
604         spi = __get_spi(off);
605         if (spi + 1 < nr_slots) {
606                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
607                 return -EINVAL;
608         }
609
610         if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
611                 return -ERANGE;
612         return spi;
613 }
614
615 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
616 {
617         return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
618 }
619
620 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
621 {
622         return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
623 }
624
625 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
626 {
627         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
628         case DYNPTR_TYPE_LOCAL:
629                 return BPF_DYNPTR_TYPE_LOCAL;
630         case DYNPTR_TYPE_RINGBUF:
631                 return BPF_DYNPTR_TYPE_RINGBUF;
632         case DYNPTR_TYPE_SKB:
633                 return BPF_DYNPTR_TYPE_SKB;
634         case DYNPTR_TYPE_XDP:
635                 return BPF_DYNPTR_TYPE_XDP;
636         default:
637                 return BPF_DYNPTR_TYPE_INVALID;
638         }
639 }
640
641 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
642 {
643         switch (type) {
644         case BPF_DYNPTR_TYPE_LOCAL:
645                 return DYNPTR_TYPE_LOCAL;
646         case BPF_DYNPTR_TYPE_RINGBUF:
647                 return DYNPTR_TYPE_RINGBUF;
648         case BPF_DYNPTR_TYPE_SKB:
649                 return DYNPTR_TYPE_SKB;
650         case BPF_DYNPTR_TYPE_XDP:
651                 return DYNPTR_TYPE_XDP;
652         default:
653                 return 0;
654         }
655 }
656
657 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
658 {
659         return type == BPF_DYNPTR_TYPE_RINGBUF;
660 }
661
662 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
663                               enum bpf_dynptr_type type,
664                               bool first_slot, int dynptr_id);
665
666 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
667                                 struct bpf_reg_state *reg);
668
669 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
670                                    struct bpf_reg_state *sreg1,
671                                    struct bpf_reg_state *sreg2,
672                                    enum bpf_dynptr_type type)
673 {
674         int id = ++env->id_gen;
675
676         __mark_dynptr_reg(sreg1, type, true, id);
677         __mark_dynptr_reg(sreg2, type, false, id);
678 }
679
680 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
681                                struct bpf_reg_state *reg,
682                                enum bpf_dynptr_type type)
683 {
684         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
685 }
686
687 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
688                                         struct bpf_func_state *state, int spi);
689
690 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
691                                    enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
692 {
693         struct bpf_func_state *state = func(env, reg);
694         enum bpf_dynptr_type type;
695         int spi, i, err;
696
697         spi = dynptr_get_spi(env, reg);
698         if (spi < 0)
699                 return spi;
700
701         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
702          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
703          * to ensure that for the following example:
704          *      [d1][d1][d2][d2]
705          * spi    3   2   1   0
706          * So marking spi = 2 should lead to destruction of both d1 and d2. In
707          * case they do belong to same dynptr, second call won't see slot_type
708          * as STACK_DYNPTR and will simply skip destruction.
709          */
710         err = destroy_if_dynptr_stack_slot(env, state, spi);
711         if (err)
712                 return err;
713         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
714         if (err)
715                 return err;
716
717         for (i = 0; i < BPF_REG_SIZE; i++) {
718                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
719                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
720         }
721
722         type = arg_to_dynptr_type(arg_type);
723         if (type == BPF_DYNPTR_TYPE_INVALID)
724                 return -EINVAL;
725
726         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
727                                &state->stack[spi - 1].spilled_ptr, type);
728
729         if (dynptr_type_refcounted(type)) {
730                 /* The id is used to track proper releasing */
731                 int id;
732
733                 if (clone_ref_obj_id)
734                         id = clone_ref_obj_id;
735                 else
736                         id = acquire_reference_state(env, insn_idx);
737
738                 if (id < 0)
739                         return id;
740
741                 state->stack[spi].spilled_ptr.ref_obj_id = id;
742                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
743         }
744
745         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
746         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
747
748         return 0;
749 }
750
751 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
752 {
753         int i;
754
755         for (i = 0; i < BPF_REG_SIZE; i++) {
756                 state->stack[spi].slot_type[i] = STACK_INVALID;
757                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
758         }
759
760         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
761         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
762
763         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
764          *
765          * While we don't allow reading STACK_INVALID, it is still possible to
766          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
767          * helpers or insns can do partial read of that part without failing,
768          * but check_stack_range_initialized, check_stack_read_var_off, and
769          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
770          * the slot conservatively. Hence we need to prevent those liveness
771          * marking walks.
772          *
773          * This was not a problem before because STACK_INVALID is only set by
774          * default (where the default reg state has its reg->parent as NULL), or
775          * in clean_live_states after REG_LIVE_DONE (at which point
776          * mark_reg_read won't walk reg->parent chain), but not randomly during
777          * verifier state exploration (like we did above). Hence, for our case
778          * parentage chain will still be live (i.e. reg->parent may be
779          * non-NULL), while earlier reg->parent was NULL, so we need
780          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
781          * done later on reads or by mark_dynptr_read as well to unnecessary
782          * mark registers in verifier state.
783          */
784         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
785         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
786 }
787
788 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
789 {
790         struct bpf_func_state *state = func(env, reg);
791         int spi, ref_obj_id, i;
792
793         spi = dynptr_get_spi(env, reg);
794         if (spi < 0)
795                 return spi;
796
797         if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
798                 invalidate_dynptr(env, state, spi);
799                 return 0;
800         }
801
802         ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
803
804         /* If the dynptr has a ref_obj_id, then we need to invalidate
805          * two things:
806          *
807          * 1) Any dynptrs with a matching ref_obj_id (clones)
808          * 2) Any slices derived from this dynptr.
809          */
810
811         /* Invalidate any slices associated with this dynptr */
812         WARN_ON_ONCE(release_reference(env, ref_obj_id));
813
814         /* Invalidate any dynptr clones */
815         for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
816                 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
817                         continue;
818
819                 /* it should always be the case that if the ref obj id
820                  * matches then the stack slot also belongs to a
821                  * dynptr
822                  */
823                 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
824                         verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
825                         return -EFAULT;
826                 }
827                 if (state->stack[i].spilled_ptr.dynptr.first_slot)
828                         invalidate_dynptr(env, state, i);
829         }
830
831         return 0;
832 }
833
834 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
835                                struct bpf_reg_state *reg);
836
837 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
838 {
839         if (!env->allow_ptr_leaks)
840                 __mark_reg_not_init(env, reg);
841         else
842                 __mark_reg_unknown(env, reg);
843 }
844
845 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
846                                         struct bpf_func_state *state, int spi)
847 {
848         struct bpf_func_state *fstate;
849         struct bpf_reg_state *dreg;
850         int i, dynptr_id;
851
852         /* We always ensure that STACK_DYNPTR is never set partially,
853          * hence just checking for slot_type[0] is enough. This is
854          * different for STACK_SPILL, where it may be only set for
855          * 1 byte, so code has to use is_spilled_reg.
856          */
857         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
858                 return 0;
859
860         /* Reposition spi to first slot */
861         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
862                 spi = spi + 1;
863
864         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
865                 verbose(env, "cannot overwrite referenced dynptr\n");
866                 return -EINVAL;
867         }
868
869         mark_stack_slot_scratched(env, spi);
870         mark_stack_slot_scratched(env, spi - 1);
871
872         /* Writing partially to one dynptr stack slot destroys both. */
873         for (i = 0; i < BPF_REG_SIZE; i++) {
874                 state->stack[spi].slot_type[i] = STACK_INVALID;
875                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
876         }
877
878         dynptr_id = state->stack[spi].spilled_ptr.id;
879         /* Invalidate any slices associated with this dynptr */
880         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
881                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
882                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
883                         continue;
884                 if (dreg->dynptr_id == dynptr_id)
885                         mark_reg_invalid(env, dreg);
886         }));
887
888         /* Do not release reference state, we are destroying dynptr on stack,
889          * not using some helper to release it. Just reset register.
890          */
891         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
892         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
893
894         /* Same reason as unmark_stack_slots_dynptr above */
895         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
896         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
897
898         return 0;
899 }
900
901 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
902 {
903         int spi;
904
905         if (reg->type == CONST_PTR_TO_DYNPTR)
906                 return false;
907
908         spi = dynptr_get_spi(env, reg);
909
910         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
911          * error because this just means the stack state hasn't been updated yet.
912          * We will do check_mem_access to check and update stack bounds later.
913          */
914         if (spi < 0 && spi != -ERANGE)
915                 return false;
916
917         /* We don't need to check if the stack slots are marked by previous
918          * dynptr initializations because we allow overwriting existing unreferenced
919          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
920          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
921          * touching are completely destructed before we reinitialize them for a new
922          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
923          * instead of delaying it until the end where the user will get "Unreleased
924          * reference" error.
925          */
926         return true;
927 }
928
929 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
930 {
931         struct bpf_func_state *state = func(env, reg);
932         int i, spi;
933
934         /* This already represents first slot of initialized bpf_dynptr.
935          *
936          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
937          * check_func_arg_reg_off's logic, so we don't need to check its
938          * offset and alignment.
939          */
940         if (reg->type == CONST_PTR_TO_DYNPTR)
941                 return true;
942
943         spi = dynptr_get_spi(env, reg);
944         if (spi < 0)
945                 return false;
946         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
947                 return false;
948
949         for (i = 0; i < BPF_REG_SIZE; i++) {
950                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
951                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
952                         return false;
953         }
954
955         return true;
956 }
957
958 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
959                                     enum bpf_arg_type arg_type)
960 {
961         struct bpf_func_state *state = func(env, reg);
962         enum bpf_dynptr_type dynptr_type;
963         int spi;
964
965         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
966         if (arg_type == ARG_PTR_TO_DYNPTR)
967                 return true;
968
969         dynptr_type = arg_to_dynptr_type(arg_type);
970         if (reg->type == CONST_PTR_TO_DYNPTR) {
971                 return reg->dynptr.type == dynptr_type;
972         } else {
973                 spi = dynptr_get_spi(env, reg);
974                 if (spi < 0)
975                         return false;
976                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
977         }
978 }
979
980 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
981
982 static bool in_rcu_cs(struct bpf_verifier_env *env);
983
984 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
985
986 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
987                                  struct bpf_kfunc_call_arg_meta *meta,
988                                  struct bpf_reg_state *reg, int insn_idx,
989                                  struct btf *btf, u32 btf_id, int nr_slots)
990 {
991         struct bpf_func_state *state = func(env, reg);
992         int spi, i, j, id;
993
994         spi = iter_get_spi(env, reg, nr_slots);
995         if (spi < 0)
996                 return spi;
997
998         id = acquire_reference_state(env, insn_idx);
999         if (id < 0)
1000                 return id;
1001
1002         for (i = 0; i < nr_slots; i++) {
1003                 struct bpf_stack_state *slot = &state->stack[spi - i];
1004                 struct bpf_reg_state *st = &slot->spilled_ptr;
1005
1006                 __mark_reg_known_zero(st);
1007                 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1008                 if (is_kfunc_rcu_protected(meta)) {
1009                         if (in_rcu_cs(env))
1010                                 st->type |= MEM_RCU;
1011                         else
1012                                 st->type |= PTR_UNTRUSTED;
1013                 }
1014                 st->live |= REG_LIVE_WRITTEN;
1015                 st->ref_obj_id = i == 0 ? id : 0;
1016                 st->iter.btf = btf;
1017                 st->iter.btf_id = btf_id;
1018                 st->iter.state = BPF_ITER_STATE_ACTIVE;
1019                 st->iter.depth = 0;
1020
1021                 for (j = 0; j < BPF_REG_SIZE; j++)
1022                         slot->slot_type[j] = STACK_ITER;
1023
1024                 mark_stack_slot_scratched(env, spi - i);
1025         }
1026
1027         return 0;
1028 }
1029
1030 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1031                                    struct bpf_reg_state *reg, int nr_slots)
1032 {
1033         struct bpf_func_state *state = func(env, reg);
1034         int spi, i, j;
1035
1036         spi = iter_get_spi(env, reg, nr_slots);
1037         if (spi < 0)
1038                 return spi;
1039
1040         for (i = 0; i < nr_slots; i++) {
1041                 struct bpf_stack_state *slot = &state->stack[spi - i];
1042                 struct bpf_reg_state *st = &slot->spilled_ptr;
1043
1044                 if (i == 0)
1045                         WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1046
1047                 __mark_reg_not_init(env, st);
1048
1049                 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1050                 st->live |= REG_LIVE_WRITTEN;
1051
1052                 for (j = 0; j < BPF_REG_SIZE; j++)
1053                         slot->slot_type[j] = STACK_INVALID;
1054
1055                 mark_stack_slot_scratched(env, spi - i);
1056         }
1057
1058         return 0;
1059 }
1060
1061 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1062                                      struct bpf_reg_state *reg, int nr_slots)
1063 {
1064         struct bpf_func_state *state = func(env, reg);
1065         int spi, i, j;
1066
1067         /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1068          * will do check_mem_access to check and update stack bounds later, so
1069          * return true for that case.
1070          */
1071         spi = iter_get_spi(env, reg, nr_slots);
1072         if (spi == -ERANGE)
1073                 return true;
1074         if (spi < 0)
1075                 return false;
1076
1077         for (i = 0; i < nr_slots; i++) {
1078                 struct bpf_stack_state *slot = &state->stack[spi - i];
1079
1080                 for (j = 0; j < BPF_REG_SIZE; j++)
1081                         if (slot->slot_type[j] == STACK_ITER)
1082                                 return false;
1083         }
1084
1085         return true;
1086 }
1087
1088 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1089                                    struct btf *btf, u32 btf_id, int nr_slots)
1090 {
1091         struct bpf_func_state *state = func(env, reg);
1092         int spi, i, j;
1093
1094         spi = iter_get_spi(env, reg, nr_slots);
1095         if (spi < 0)
1096                 return -EINVAL;
1097
1098         for (i = 0; i < nr_slots; i++) {
1099                 struct bpf_stack_state *slot = &state->stack[spi - i];
1100                 struct bpf_reg_state *st = &slot->spilled_ptr;
1101
1102                 if (st->type & PTR_UNTRUSTED)
1103                         return -EPROTO;
1104                 /* only main (first) slot has ref_obj_id set */
1105                 if (i == 0 && !st->ref_obj_id)
1106                         return -EINVAL;
1107                 if (i != 0 && st->ref_obj_id)
1108                         return -EINVAL;
1109                 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1110                         return -EINVAL;
1111
1112                 for (j = 0; j < BPF_REG_SIZE; j++)
1113                         if (slot->slot_type[j] != STACK_ITER)
1114                                 return -EINVAL;
1115         }
1116
1117         return 0;
1118 }
1119
1120 /* Check if given stack slot is "special":
1121  *   - spilled register state (STACK_SPILL);
1122  *   - dynptr state (STACK_DYNPTR);
1123  *   - iter state (STACK_ITER).
1124  */
1125 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1126 {
1127         enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1128
1129         switch (type) {
1130         case STACK_SPILL:
1131         case STACK_DYNPTR:
1132         case STACK_ITER:
1133                 return true;
1134         case STACK_INVALID:
1135         case STACK_MISC:
1136         case STACK_ZERO:
1137                 return false;
1138         default:
1139                 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1140                 return true;
1141         }
1142 }
1143
1144 /* The reg state of a pointer or a bounded scalar was saved when
1145  * it was spilled to the stack.
1146  */
1147 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1148 {
1149         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1150 }
1151
1152 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1153 {
1154         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1155                stack->spilled_ptr.type == SCALAR_VALUE;
1156 }
1157
1158 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1159 {
1160         return stack->slot_type[0] == STACK_SPILL &&
1161                stack->spilled_ptr.type == SCALAR_VALUE;
1162 }
1163
1164 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1165  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1166  * more precise STACK_ZERO.
1167  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1168  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1169  */
1170 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1171 {
1172         if (*stype == STACK_ZERO)
1173                 return;
1174         if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1175                 return;
1176         *stype = STACK_MISC;
1177 }
1178
1179 static void scrub_spilled_slot(u8 *stype)
1180 {
1181         if (*stype != STACK_INVALID)
1182                 *stype = STACK_MISC;
1183 }
1184
1185 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1186  * small to hold src. This is different from krealloc since we don't want to preserve
1187  * the contents of dst.
1188  *
1189  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1190  * not be allocated.
1191  */
1192 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1193 {
1194         size_t alloc_bytes;
1195         void *orig = dst;
1196         size_t bytes;
1197
1198         if (ZERO_OR_NULL_PTR(src))
1199                 goto out;
1200
1201         if (unlikely(check_mul_overflow(n, size, &bytes)))
1202                 return NULL;
1203
1204         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1205         dst = krealloc(orig, alloc_bytes, flags);
1206         if (!dst) {
1207                 kfree(orig);
1208                 return NULL;
1209         }
1210
1211         memcpy(dst, src, bytes);
1212 out:
1213         return dst ? dst : ZERO_SIZE_PTR;
1214 }
1215
1216 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1217  * small to hold new_n items. new items are zeroed out if the array grows.
1218  *
1219  * Contrary to krealloc_array, does not free arr if new_n is zero.
1220  */
1221 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1222 {
1223         size_t alloc_size;
1224         void *new_arr;
1225
1226         if (!new_n || old_n == new_n)
1227                 goto out;
1228
1229         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1230         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1231         if (!new_arr) {
1232                 kfree(arr);
1233                 return NULL;
1234         }
1235         arr = new_arr;
1236
1237         if (new_n > old_n)
1238                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1239
1240 out:
1241         return arr ? arr : ZERO_SIZE_PTR;
1242 }
1243
1244 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1245 {
1246         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1247                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1248         if (!dst->refs)
1249                 return -ENOMEM;
1250
1251         dst->acquired_refs = src->acquired_refs;
1252         return 0;
1253 }
1254
1255 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1256 {
1257         size_t n = src->allocated_stack / BPF_REG_SIZE;
1258
1259         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1260                                 GFP_KERNEL);
1261         if (!dst->stack)
1262                 return -ENOMEM;
1263
1264         dst->allocated_stack = src->allocated_stack;
1265         return 0;
1266 }
1267
1268 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1269 {
1270         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1271                                     sizeof(struct bpf_reference_state));
1272         if (!state->refs)
1273                 return -ENOMEM;
1274
1275         state->acquired_refs = n;
1276         return 0;
1277 }
1278
1279 /* Possibly update state->allocated_stack to be at least size bytes. Also
1280  * possibly update the function's high-water mark in its bpf_subprog_info.
1281  */
1282 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1283 {
1284         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1285
1286         /* The stack size is always a multiple of BPF_REG_SIZE. */
1287         size = round_up(size, BPF_REG_SIZE);
1288         n = size / BPF_REG_SIZE;
1289
1290         if (old_n >= n)
1291                 return 0;
1292
1293         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1294         if (!state->stack)
1295                 return -ENOMEM;
1296
1297         state->allocated_stack = size;
1298
1299         /* update known max for given subprogram */
1300         if (env->subprog_info[state->subprogno].stack_depth < size)
1301                 env->subprog_info[state->subprogno].stack_depth = size;
1302
1303         return 0;
1304 }
1305
1306 /* Acquire a pointer id from the env and update the state->refs to include
1307  * this new pointer reference.
1308  * On success, returns a valid pointer id to associate with the register
1309  * On failure, returns a negative errno.
1310  */
1311 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1312 {
1313         struct bpf_func_state *state = cur_func(env);
1314         int new_ofs = state->acquired_refs;
1315         int id, err;
1316
1317         err = resize_reference_state(state, state->acquired_refs + 1);
1318         if (err)
1319                 return err;
1320         id = ++env->id_gen;
1321         state->refs[new_ofs].id = id;
1322         state->refs[new_ofs].insn_idx = insn_idx;
1323         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1324
1325         return id;
1326 }
1327
1328 /* release function corresponding to acquire_reference_state(). Idempotent. */
1329 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1330 {
1331         int i, last_idx;
1332
1333         last_idx = state->acquired_refs - 1;
1334         for (i = 0; i < state->acquired_refs; i++) {
1335                 if (state->refs[i].id == ptr_id) {
1336                         /* Cannot release caller references in callbacks */
1337                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1338                                 return -EINVAL;
1339                         if (last_idx && i != last_idx)
1340                                 memcpy(&state->refs[i], &state->refs[last_idx],
1341                                        sizeof(*state->refs));
1342                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1343                         state->acquired_refs--;
1344                         return 0;
1345                 }
1346         }
1347         return -EINVAL;
1348 }
1349
1350 static void free_func_state(struct bpf_func_state *state)
1351 {
1352         if (!state)
1353                 return;
1354         kfree(state->refs);
1355         kfree(state->stack);
1356         kfree(state);
1357 }
1358
1359 static void clear_jmp_history(struct bpf_verifier_state *state)
1360 {
1361         kfree(state->jmp_history);
1362         state->jmp_history = NULL;
1363         state->jmp_history_cnt = 0;
1364 }
1365
1366 static void free_verifier_state(struct bpf_verifier_state *state,
1367                                 bool free_self)
1368 {
1369         int i;
1370
1371         for (i = 0; i <= state->curframe; i++) {
1372                 free_func_state(state->frame[i]);
1373                 state->frame[i] = NULL;
1374         }
1375         clear_jmp_history(state);
1376         if (free_self)
1377                 kfree(state);
1378 }
1379
1380 /* copy verifier state from src to dst growing dst stack space
1381  * when necessary to accommodate larger src stack
1382  */
1383 static int copy_func_state(struct bpf_func_state *dst,
1384                            const struct bpf_func_state *src)
1385 {
1386         int err;
1387
1388         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1389         err = copy_reference_state(dst, src);
1390         if (err)
1391                 return err;
1392         return copy_stack_state(dst, src);
1393 }
1394
1395 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1396                                const struct bpf_verifier_state *src)
1397 {
1398         struct bpf_func_state *dst;
1399         int i, err;
1400
1401         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1402                                           src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1403                                           GFP_USER);
1404         if (!dst_state->jmp_history)
1405                 return -ENOMEM;
1406         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1407
1408         /* if dst has more stack frames then src frame, free them, this is also
1409          * necessary in case of exceptional exits using bpf_throw.
1410          */
1411         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1412                 free_func_state(dst_state->frame[i]);
1413                 dst_state->frame[i] = NULL;
1414         }
1415         dst_state->speculative = src->speculative;
1416         dst_state->active_rcu_lock = src->active_rcu_lock;
1417         dst_state->curframe = src->curframe;
1418         dst_state->active_lock.ptr = src->active_lock.ptr;
1419         dst_state->active_lock.id = src->active_lock.id;
1420         dst_state->branches = src->branches;
1421         dst_state->parent = src->parent;
1422         dst_state->first_insn_idx = src->first_insn_idx;
1423         dst_state->last_insn_idx = src->last_insn_idx;
1424         dst_state->dfs_depth = src->dfs_depth;
1425         dst_state->callback_unroll_depth = src->callback_unroll_depth;
1426         dst_state->used_as_loop_entry = src->used_as_loop_entry;
1427         for (i = 0; i <= src->curframe; i++) {
1428                 dst = dst_state->frame[i];
1429                 if (!dst) {
1430                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1431                         if (!dst)
1432                                 return -ENOMEM;
1433                         dst_state->frame[i] = dst;
1434                 }
1435                 err = copy_func_state(dst, src->frame[i]);
1436                 if (err)
1437                         return err;
1438         }
1439         return 0;
1440 }
1441
1442 static u32 state_htab_size(struct bpf_verifier_env *env)
1443 {
1444         return env->prog->len;
1445 }
1446
1447 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1448 {
1449         struct bpf_verifier_state *cur = env->cur_state;
1450         struct bpf_func_state *state = cur->frame[cur->curframe];
1451
1452         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1453 }
1454
1455 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1456 {
1457         int fr;
1458
1459         if (a->curframe != b->curframe)
1460                 return false;
1461
1462         for (fr = a->curframe; fr >= 0; fr--)
1463                 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1464                         return false;
1465
1466         return true;
1467 }
1468
1469 /* Open coded iterators allow back-edges in the state graph in order to
1470  * check unbounded loops that iterators.
1471  *
1472  * In is_state_visited() it is necessary to know if explored states are
1473  * part of some loops in order to decide whether non-exact states
1474  * comparison could be used:
1475  * - non-exact states comparison establishes sub-state relation and uses
1476  *   read and precision marks to do so, these marks are propagated from
1477  *   children states and thus are not guaranteed to be final in a loop;
1478  * - exact states comparison just checks if current and explored states
1479  *   are identical (and thus form a back-edge).
1480  *
1481  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1482  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1483  * algorithm for loop structure detection and gives an overview of
1484  * relevant terminology. It also has helpful illustrations.
1485  *
1486  * [1] https://api.semanticscholar.org/CorpusID:15784067
1487  *
1488  * We use a similar algorithm but because loop nested structure is
1489  * irrelevant for verifier ours is significantly simpler and resembles
1490  * strongly connected components algorithm from Sedgewick's textbook.
1491  *
1492  * Define topmost loop entry as a first node of the loop traversed in a
1493  * depth first search starting from initial state. The goal of the loop
1494  * tracking algorithm is to associate topmost loop entries with states
1495  * derived from these entries.
1496  *
1497  * For each step in the DFS states traversal algorithm needs to identify
1498  * the following situations:
1499  *
1500  *          initial                     initial                   initial
1501  *            |                           |                         |
1502  *            V                           V                         V
1503  *           ...                         ...           .---------> hdr
1504  *            |                           |            |            |
1505  *            V                           V            |            V
1506  *           cur                     .-> succ          |    .------...
1507  *            |                      |    |            |    |       |
1508  *            V                      |    V            |    V       V
1509  *           succ                    '-- cur           |   ...     ...
1510  *                                                     |    |       |
1511  *                                                     |    V       V
1512  *                                                     |   succ <- cur
1513  *                                                     |    |
1514  *                                                     |    V
1515  *                                                     |   ...
1516  *                                                     |    |
1517  *                                                     '----'
1518  *
1519  *  (A) successor state of cur   (B) successor state of cur or it's entry
1520  *      not yet traversed            are in current DFS path, thus cur and succ
1521  *                                   are members of the same outermost loop
1522  *
1523  *                      initial                  initial
1524  *                        |                        |
1525  *                        V                        V
1526  *                       ...                      ...
1527  *                        |                        |
1528  *                        V                        V
1529  *                .------...               .------...
1530  *                |       |                |       |
1531  *                V       V                V       V
1532  *           .-> hdr     ...              ...     ...
1533  *           |    |       |                |       |
1534  *           |    V       V                V       V
1535  *           |   succ <- cur              succ <- cur
1536  *           |    |                        |
1537  *           |    V                        V
1538  *           |   ...                      ...
1539  *           |    |                        |
1540  *           '----'                       exit
1541  *
1542  * (C) successor state of cur is a part of some loop but this loop
1543  *     does not include cur or successor state is not in a loop at all.
1544  *
1545  * Algorithm could be described as the following python code:
1546  *
1547  *     traversed = set()   # Set of traversed nodes
1548  *     entries = {}        # Mapping from node to loop entry
1549  *     depths = {}         # Depth level assigned to graph node
1550  *     path = set()        # Current DFS path
1551  *
1552  *     # Find outermost loop entry known for n
1553  *     def get_loop_entry(n):
1554  *         h = entries.get(n, None)
1555  *         while h in entries and entries[h] != h:
1556  *             h = entries[h]
1557  *         return h
1558  *
1559  *     # Update n's loop entry if h's outermost entry comes
1560  *     # before n's outermost entry in current DFS path.
1561  *     def update_loop_entry(n, h):
1562  *         n1 = get_loop_entry(n) or n
1563  *         h1 = get_loop_entry(h) or h
1564  *         if h1 in path and depths[h1] <= depths[n1]:
1565  *             entries[n] = h1
1566  *
1567  *     def dfs(n, depth):
1568  *         traversed.add(n)
1569  *         path.add(n)
1570  *         depths[n] = depth
1571  *         for succ in G.successors(n):
1572  *             if succ not in traversed:
1573  *                 # Case A: explore succ and update cur's loop entry
1574  *                 #         only if succ's entry is in current DFS path.
1575  *                 dfs(succ, depth + 1)
1576  *                 h = get_loop_entry(succ)
1577  *                 update_loop_entry(n, h)
1578  *             else:
1579  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1580  *                 update_loop_entry(n, succ)
1581  *         path.remove(n)
1582  *
1583  * To adapt this algorithm for use with verifier:
1584  * - use st->branch == 0 as a signal that DFS of succ had been finished
1585  *   and cur's loop entry has to be updated (case A), handle this in
1586  *   update_branch_counts();
1587  * - use st->branch > 0 as a signal that st is in the current DFS path;
1588  * - handle cases B and C in is_state_visited();
1589  * - update topmost loop entry for intermediate states in get_loop_entry().
1590  */
1591 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1592 {
1593         struct bpf_verifier_state *topmost = st->loop_entry, *old;
1594
1595         while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1596                 topmost = topmost->loop_entry;
1597         /* Update loop entries for intermediate states to avoid this
1598          * traversal in future get_loop_entry() calls.
1599          */
1600         while (st && st->loop_entry != topmost) {
1601                 old = st->loop_entry;
1602                 st->loop_entry = topmost;
1603                 st = old;
1604         }
1605         return topmost;
1606 }
1607
1608 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1609 {
1610         struct bpf_verifier_state *cur1, *hdr1;
1611
1612         cur1 = get_loop_entry(cur) ?: cur;
1613         hdr1 = get_loop_entry(hdr) ?: hdr;
1614         /* The head1->branches check decides between cases B and C in
1615          * comment for get_loop_entry(). If hdr1->branches == 0 then
1616          * head's topmost loop entry is not in current DFS path,
1617          * hence 'cur' and 'hdr' are not in the same loop and there is
1618          * no need to update cur->loop_entry.
1619          */
1620         if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1621                 cur->loop_entry = hdr;
1622                 hdr->used_as_loop_entry = true;
1623         }
1624 }
1625
1626 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1627 {
1628         while (st) {
1629                 u32 br = --st->branches;
1630
1631                 /* br == 0 signals that DFS exploration for 'st' is finished,
1632                  * thus it is necessary to update parent's loop entry if it
1633                  * turned out that st is a part of some loop.
1634                  * This is a part of 'case A' in get_loop_entry() comment.
1635                  */
1636                 if (br == 0 && st->parent && st->loop_entry)
1637                         update_loop_entry(st->parent, st->loop_entry);
1638
1639                 /* WARN_ON(br > 1) technically makes sense here,
1640                  * but see comment in push_stack(), hence:
1641                  */
1642                 WARN_ONCE((int)br < 0,
1643                           "BUG update_branch_counts:branches_to_explore=%d\n",
1644                           br);
1645                 if (br)
1646                         break;
1647                 st = st->parent;
1648         }
1649 }
1650
1651 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1652                      int *insn_idx, bool pop_log)
1653 {
1654         struct bpf_verifier_state *cur = env->cur_state;
1655         struct bpf_verifier_stack_elem *elem, *head = env->head;
1656         int err;
1657
1658         if (env->head == NULL)
1659                 return -ENOENT;
1660
1661         if (cur) {
1662                 err = copy_verifier_state(cur, &head->st);
1663                 if (err)
1664                         return err;
1665         }
1666         if (pop_log)
1667                 bpf_vlog_reset(&env->log, head->log_pos);
1668         if (insn_idx)
1669                 *insn_idx = head->insn_idx;
1670         if (prev_insn_idx)
1671                 *prev_insn_idx = head->prev_insn_idx;
1672         elem = head->next;
1673         free_verifier_state(&head->st, false);
1674         kfree(head);
1675         env->head = elem;
1676         env->stack_size--;
1677         return 0;
1678 }
1679
1680 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1681                                              int insn_idx, int prev_insn_idx,
1682                                              bool speculative)
1683 {
1684         struct bpf_verifier_state *cur = env->cur_state;
1685         struct bpf_verifier_stack_elem *elem;
1686         int err;
1687
1688         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1689         if (!elem)
1690                 goto err;
1691
1692         elem->insn_idx = insn_idx;
1693         elem->prev_insn_idx = prev_insn_idx;
1694         elem->next = env->head;
1695         elem->log_pos = env->log.end_pos;
1696         env->head = elem;
1697         env->stack_size++;
1698         err = copy_verifier_state(&elem->st, cur);
1699         if (err)
1700                 goto err;
1701         elem->st.speculative |= speculative;
1702         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1703                 verbose(env, "The sequence of %d jumps is too complex.\n",
1704                         env->stack_size);
1705                 goto err;
1706         }
1707         if (elem->st.parent) {
1708                 ++elem->st.parent->branches;
1709                 /* WARN_ON(branches > 2) technically makes sense here,
1710                  * but
1711                  * 1. speculative states will bump 'branches' for non-branch
1712                  * instructions
1713                  * 2. is_state_visited() heuristics may decide not to create
1714                  * a new state for a sequence of branches and all such current
1715                  * and cloned states will be pointing to a single parent state
1716                  * which might have large 'branches' count.
1717                  */
1718         }
1719         return &elem->st;
1720 err:
1721         free_verifier_state(env->cur_state, true);
1722         env->cur_state = NULL;
1723         /* pop all elements and return */
1724         while (!pop_stack(env, NULL, NULL, false));
1725         return NULL;
1726 }
1727
1728 #define CALLER_SAVED_REGS 6
1729 static const int caller_saved[CALLER_SAVED_REGS] = {
1730         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1731 };
1732
1733 /* This helper doesn't clear reg->id */
1734 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1735 {
1736         reg->var_off = tnum_const(imm);
1737         reg->smin_value = (s64)imm;
1738         reg->smax_value = (s64)imm;
1739         reg->umin_value = imm;
1740         reg->umax_value = imm;
1741
1742         reg->s32_min_value = (s32)imm;
1743         reg->s32_max_value = (s32)imm;
1744         reg->u32_min_value = (u32)imm;
1745         reg->u32_max_value = (u32)imm;
1746 }
1747
1748 /* Mark the unknown part of a register (variable offset or scalar value) as
1749  * known to have the value @imm.
1750  */
1751 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1752 {
1753         /* Clear off and union(map_ptr, range) */
1754         memset(((u8 *)reg) + sizeof(reg->type), 0,
1755                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1756         reg->id = 0;
1757         reg->ref_obj_id = 0;
1758         ___mark_reg_known(reg, imm);
1759 }
1760
1761 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1762 {
1763         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1764         reg->s32_min_value = (s32)imm;
1765         reg->s32_max_value = (s32)imm;
1766         reg->u32_min_value = (u32)imm;
1767         reg->u32_max_value = (u32)imm;
1768 }
1769
1770 /* Mark the 'variable offset' part of a register as zero.  This should be
1771  * used only on registers holding a pointer type.
1772  */
1773 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1774 {
1775         __mark_reg_known(reg, 0);
1776 }
1777
1778 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1779 {
1780         __mark_reg_known(reg, 0);
1781         reg->type = SCALAR_VALUE;
1782         /* all scalars are assumed imprecise initially (unless unprivileged,
1783          * in which case everything is forced to be precise)
1784          */
1785         reg->precise = !env->bpf_capable;
1786 }
1787
1788 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1789                                 struct bpf_reg_state *regs, u32 regno)
1790 {
1791         if (WARN_ON(regno >= MAX_BPF_REG)) {
1792                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1793                 /* Something bad happened, let's kill all regs */
1794                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1795                         __mark_reg_not_init(env, regs + regno);
1796                 return;
1797         }
1798         __mark_reg_known_zero(regs + regno);
1799 }
1800
1801 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1802                               bool first_slot, int dynptr_id)
1803 {
1804         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1805          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1806          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1807          */
1808         __mark_reg_known_zero(reg);
1809         reg->type = CONST_PTR_TO_DYNPTR;
1810         /* Give each dynptr a unique id to uniquely associate slices to it. */
1811         reg->id = dynptr_id;
1812         reg->dynptr.type = type;
1813         reg->dynptr.first_slot = first_slot;
1814 }
1815
1816 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1817 {
1818         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1819                 const struct bpf_map *map = reg->map_ptr;
1820
1821                 if (map->inner_map_meta) {
1822                         reg->type = CONST_PTR_TO_MAP;
1823                         reg->map_ptr = map->inner_map_meta;
1824                         /* transfer reg's id which is unique for every map_lookup_elem
1825                          * as UID of the inner map.
1826                          */
1827                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1828                                 reg->map_uid = reg->id;
1829                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1830                         reg->type = PTR_TO_XDP_SOCK;
1831                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1832                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1833                         reg->type = PTR_TO_SOCKET;
1834                 } else {
1835                         reg->type = PTR_TO_MAP_VALUE;
1836                 }
1837                 return;
1838         }
1839
1840         reg->type &= ~PTR_MAYBE_NULL;
1841 }
1842
1843 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1844                                 struct btf_field_graph_root *ds_head)
1845 {
1846         __mark_reg_known_zero(&regs[regno]);
1847         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1848         regs[regno].btf = ds_head->btf;
1849         regs[regno].btf_id = ds_head->value_btf_id;
1850         regs[regno].off = ds_head->node_offset;
1851 }
1852
1853 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1854 {
1855         return type_is_pkt_pointer(reg->type);
1856 }
1857
1858 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1859 {
1860         return reg_is_pkt_pointer(reg) ||
1861                reg->type == PTR_TO_PACKET_END;
1862 }
1863
1864 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1865 {
1866         return base_type(reg->type) == PTR_TO_MEM &&
1867                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1868 }
1869
1870 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1871 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1872                                     enum bpf_reg_type which)
1873 {
1874         /* The register can already have a range from prior markings.
1875          * This is fine as long as it hasn't been advanced from its
1876          * origin.
1877          */
1878         return reg->type == which &&
1879                reg->id == 0 &&
1880                reg->off == 0 &&
1881                tnum_equals_const(reg->var_off, 0);
1882 }
1883
1884 /* Reset the min/max bounds of a register */
1885 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1886 {
1887         reg->smin_value = S64_MIN;
1888         reg->smax_value = S64_MAX;
1889         reg->umin_value = 0;
1890         reg->umax_value = U64_MAX;
1891
1892         reg->s32_min_value = S32_MIN;
1893         reg->s32_max_value = S32_MAX;
1894         reg->u32_min_value = 0;
1895         reg->u32_max_value = U32_MAX;
1896 }
1897
1898 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1899 {
1900         reg->smin_value = S64_MIN;
1901         reg->smax_value = S64_MAX;
1902         reg->umin_value = 0;
1903         reg->umax_value = U64_MAX;
1904 }
1905
1906 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1907 {
1908         reg->s32_min_value = S32_MIN;
1909         reg->s32_max_value = S32_MAX;
1910         reg->u32_min_value = 0;
1911         reg->u32_max_value = U32_MAX;
1912 }
1913
1914 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1915 {
1916         struct tnum var32_off = tnum_subreg(reg->var_off);
1917
1918         /* min signed is max(sign bit) | min(other bits) */
1919         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1920                         var32_off.value | (var32_off.mask & S32_MIN));
1921         /* max signed is min(sign bit) | max(other bits) */
1922         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1923                         var32_off.value | (var32_off.mask & S32_MAX));
1924         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1925         reg->u32_max_value = min(reg->u32_max_value,
1926                                  (u32)(var32_off.value | var32_off.mask));
1927 }
1928
1929 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1930 {
1931         /* min signed is max(sign bit) | min(other bits) */
1932         reg->smin_value = max_t(s64, reg->smin_value,
1933                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1934         /* max signed is min(sign bit) | max(other bits) */
1935         reg->smax_value = min_t(s64, reg->smax_value,
1936                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1937         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1938         reg->umax_value = min(reg->umax_value,
1939                               reg->var_off.value | reg->var_off.mask);
1940 }
1941
1942 static void __update_reg_bounds(struct bpf_reg_state *reg)
1943 {
1944         __update_reg32_bounds(reg);
1945         __update_reg64_bounds(reg);
1946 }
1947
1948 /* Uses signed min/max values to inform unsigned, and vice-versa */
1949 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1950 {
1951         /* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1952          * bits to improve our u32/s32 boundaries.
1953          *
1954          * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1955          * u64) is pretty trivial, it's obvious that in u32 we'll also have
1956          * [10, 20] range. But this property holds for any 64-bit range as
1957          * long as upper 32 bits in that entire range of values stay the same.
1958          *
1959          * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1960          * in decimal) has the same upper 32 bits throughout all the values in
1961          * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1962          * range.
1963          *
1964          * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1965          * following the rules outlined below about u64/s64 correspondence
1966          * (which equally applies to u32 vs s32 correspondence). In general it
1967          * depends on actual hexadecimal values of 32-bit range. They can form
1968          * only valid u32, or only valid s32 ranges in some cases.
1969          *
1970          * So we use all these insights to derive bounds for subregisters here.
1971          */
1972         if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1973                 /* u64 to u32 casting preserves validity of low 32 bits as
1974                  * a range, if upper 32 bits are the same
1975                  */
1976                 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1977                 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1978
1979                 if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1980                         reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1981                         reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1982                 }
1983         }
1984         if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
1985                 /* low 32 bits should form a proper u32 range */
1986                 if ((u32)reg->smin_value <= (u32)reg->smax_value) {
1987                         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
1988                         reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
1989                 }
1990                 /* low 32 bits should form a proper s32 range */
1991                 if ((s32)reg->smin_value <= (s32)reg->smax_value) {
1992                         reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1993                         reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1994                 }
1995         }
1996         /* Special case where upper bits form a small sequence of two
1997          * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
1998          * 0x00000000 is also valid), while lower bits form a proper s32 range
1999          * going from negative numbers to positive numbers. E.g., let's say we
2000          * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2001          * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2002          * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2003          * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2004          * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2005          * upper 32 bits. As a random example, s64 range
2006          * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2007          * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2008          */
2009         if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2010             (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2011                 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2012                 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2013         }
2014         if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2015             (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2016                 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2017                 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2018         }
2019         /* if u32 range forms a valid s32 range (due to matching sign bit),
2020          * try to learn from that
2021          */
2022         if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2023                 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2024                 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2025         }
2026         /* If we cannot cross the sign boundary, then signed and unsigned bounds
2027          * are the same, so combine.  This works even in the negative case, e.g.
2028          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2029          */
2030         if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2031                 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2032                 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2033         }
2034 }
2035
2036 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2037 {
2038         /* If u64 range forms a valid s64 range (due to matching sign bit),
2039          * try to learn from that. Let's do a bit of ASCII art to see when
2040          * this is happening. Let's take u64 range first:
2041          *
2042          * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2043          * |-------------------------------|--------------------------------|
2044          *
2045          * Valid u64 range is formed when umin and umax are anywhere in the
2046          * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2047          * straightforward. Let's see how s64 range maps onto the same range
2048          * of values, annotated below the line for comparison:
2049          *
2050          * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2051          * |-------------------------------|--------------------------------|
2052          * 0                        S64_MAX S64_MIN                        -1
2053          *
2054          * So s64 values basically start in the middle and they are logically
2055          * contiguous to the right of it, wrapping around from -1 to 0, and
2056          * then finishing as S64_MAX (0x7fffffffffffffff) right before
2057          * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2058          * more visually as mapped to sign-agnostic range of hex values.
2059          *
2060          *  u64 start                                               u64 end
2061          *  _______________________________________________________________
2062          * /                                                               \
2063          * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2064          * |-------------------------------|--------------------------------|
2065          * 0                        S64_MAX S64_MIN                        -1
2066          *                                / \
2067          * >------------------------------   ------------------------------->
2068          * s64 continues...        s64 end   s64 start          s64 "midpoint"
2069          *
2070          * What this means is that, in general, we can't always derive
2071          * something new about u64 from any random s64 range, and vice versa.
2072          *
2073          * But we can do that in two particular cases. One is when entire
2074          * u64/s64 range is *entirely* contained within left half of the above
2075          * diagram or when it is *entirely* contained in the right half. I.e.:
2076          *
2077          * |-------------------------------|--------------------------------|
2078          *     ^                   ^            ^                 ^
2079          *     A                   B            C                 D
2080          *
2081          * [A, B] and [C, D] are contained entirely in their respective halves
2082          * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2083          * will be non-negative both as u64 and s64 (and in fact it will be
2084          * identical ranges no matter the signedness). [C, D] treated as s64
2085          * will be a range of negative values, while in u64 it will be
2086          * non-negative range of values larger than 0x8000000000000000.
2087          *
2088          * Now, any other range here can't be represented in both u64 and s64
2089          * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2090          * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2091          * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2092          * for example. Similarly, valid s64 range [D, A] (going from negative
2093          * to positive values), would be two separate [D, U64_MAX] and [0, A]
2094          * ranges as u64. Currently reg_state can't represent two segments per
2095          * numeric domain, so in such situations we can only derive maximal
2096          * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2097          *
2098          * So we use these facts to derive umin/umax from smin/smax and vice
2099          * versa only if they stay within the same "half". This is equivalent
2100          * to checking sign bit: lower half will have sign bit as zero, upper
2101          * half have sign bit 1. Below in code we simplify this by just
2102          * casting umin/umax as smin/smax and checking if they form valid
2103          * range, and vice versa. Those are equivalent checks.
2104          */
2105         if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2106                 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2107                 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2108         }
2109         /* If we cannot cross the sign boundary, then signed and unsigned bounds
2110          * are the same, so combine.  This works even in the negative case, e.g.
2111          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2112          */
2113         if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2114                 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2115                 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2116         }
2117 }
2118
2119 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2120 {
2121         /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2122          * values on both sides of 64-bit range in hope to have tigher range.
2123          * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2124          * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2125          * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2126          * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2127          * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2128          * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2129          * We just need to make sure that derived bounds we are intersecting
2130          * with are well-formed ranges in respecitve s64 or u64 domain, just
2131          * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2132          */
2133         __u64 new_umin, new_umax;
2134         __s64 new_smin, new_smax;
2135
2136         /* u32 -> u64 tightening, it's always well-formed */
2137         new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2138         new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2139         reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2140         reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2141         /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2142         new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2143         new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2144         reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2145         reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2146
2147         /* if s32 can be treated as valid u32 range, we can use it as well */
2148         if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2149                 /* s32 -> u64 tightening */
2150                 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2151                 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2152                 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2153                 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2154                 /* s32 -> s64 tightening */
2155                 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2156                 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2157                 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2158                 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2159         }
2160 }
2161
2162 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2163 {
2164         __reg32_deduce_bounds(reg);
2165         __reg64_deduce_bounds(reg);
2166         __reg_deduce_mixed_bounds(reg);
2167 }
2168
2169 /* Attempts to improve var_off based on unsigned min/max information */
2170 static void __reg_bound_offset(struct bpf_reg_state *reg)
2171 {
2172         struct tnum var64_off = tnum_intersect(reg->var_off,
2173                                                tnum_range(reg->umin_value,
2174                                                           reg->umax_value));
2175         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2176                                                tnum_range(reg->u32_min_value,
2177                                                           reg->u32_max_value));
2178
2179         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2180 }
2181
2182 static void reg_bounds_sync(struct bpf_reg_state *reg)
2183 {
2184         /* We might have learned new bounds from the var_off. */
2185         __update_reg_bounds(reg);
2186         /* We might have learned something about the sign bit. */
2187         __reg_deduce_bounds(reg);
2188         __reg_deduce_bounds(reg);
2189         /* We might have learned some bits from the bounds. */
2190         __reg_bound_offset(reg);
2191         /* Intersecting with the old var_off might have improved our bounds
2192          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2193          * then new var_off is (0; 0x7f...fc) which improves our umax.
2194          */
2195         __update_reg_bounds(reg);
2196 }
2197
2198 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2199                                    struct bpf_reg_state *reg, const char *ctx)
2200 {
2201         const char *msg;
2202
2203         if (reg->umin_value > reg->umax_value ||
2204             reg->smin_value > reg->smax_value ||
2205             reg->u32_min_value > reg->u32_max_value ||
2206             reg->s32_min_value > reg->s32_max_value) {
2207                     msg = "range bounds violation";
2208                     goto out;
2209         }
2210
2211         if (tnum_is_const(reg->var_off)) {
2212                 u64 uval = reg->var_off.value;
2213                 s64 sval = (s64)uval;
2214
2215                 if (reg->umin_value != uval || reg->umax_value != uval ||
2216                     reg->smin_value != sval || reg->smax_value != sval) {
2217                         msg = "const tnum out of sync with range bounds";
2218                         goto out;
2219                 }
2220         }
2221
2222         if (tnum_subreg_is_const(reg->var_off)) {
2223                 u32 uval32 = tnum_subreg(reg->var_off).value;
2224                 s32 sval32 = (s32)uval32;
2225
2226                 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2227                     reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2228                         msg = "const subreg tnum out of sync with range bounds";
2229                         goto out;
2230                 }
2231         }
2232
2233         return 0;
2234 out:
2235         verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2236                 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2237                 ctx, msg, reg->umin_value, reg->umax_value,
2238                 reg->smin_value, reg->smax_value,
2239                 reg->u32_min_value, reg->u32_max_value,
2240                 reg->s32_min_value, reg->s32_max_value,
2241                 reg->var_off.value, reg->var_off.mask);
2242         if (env->test_reg_invariants)
2243                 return -EFAULT;
2244         __mark_reg_unbounded(reg);
2245         return 0;
2246 }
2247
2248 static bool __reg32_bound_s64(s32 a)
2249 {
2250         return a >= 0 && a <= S32_MAX;
2251 }
2252
2253 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2254 {
2255         reg->umin_value = reg->u32_min_value;
2256         reg->umax_value = reg->u32_max_value;
2257
2258         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2259          * be positive otherwise set to worse case bounds and refine later
2260          * from tnum.
2261          */
2262         if (__reg32_bound_s64(reg->s32_min_value) &&
2263             __reg32_bound_s64(reg->s32_max_value)) {
2264                 reg->smin_value = reg->s32_min_value;
2265                 reg->smax_value = reg->s32_max_value;
2266         } else {
2267                 reg->smin_value = 0;
2268                 reg->smax_value = U32_MAX;
2269         }
2270 }
2271
2272 /* Mark a register as having a completely unknown (scalar) value. */
2273 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2274 {
2275         /*
2276          * Clear type, off, and union(map_ptr, range) and
2277          * padding between 'type' and union
2278          */
2279         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2280         reg->type = SCALAR_VALUE;
2281         reg->id = 0;
2282         reg->ref_obj_id = 0;
2283         reg->var_off = tnum_unknown;
2284         reg->frameno = 0;
2285         reg->precise = false;
2286         __mark_reg_unbounded(reg);
2287 }
2288
2289 /* Mark a register as having a completely unknown (scalar) value,
2290  * initialize .precise as true when not bpf capable.
2291  */
2292 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2293                                struct bpf_reg_state *reg)
2294 {
2295         __mark_reg_unknown_imprecise(reg);
2296         reg->precise = !env->bpf_capable;
2297 }
2298
2299 static void mark_reg_unknown(struct bpf_verifier_env *env,
2300                              struct bpf_reg_state *regs, u32 regno)
2301 {
2302         if (WARN_ON(regno >= MAX_BPF_REG)) {
2303                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2304                 /* Something bad happened, let's kill all regs except FP */
2305                 for (regno = 0; regno < BPF_REG_FP; regno++)
2306                         __mark_reg_not_init(env, regs + regno);
2307                 return;
2308         }
2309         __mark_reg_unknown(env, regs + regno);
2310 }
2311
2312 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2313                                 struct bpf_reg_state *reg)
2314 {
2315         __mark_reg_unknown(env, reg);
2316         reg->type = NOT_INIT;
2317 }
2318
2319 static void mark_reg_not_init(struct bpf_verifier_env *env,
2320                               struct bpf_reg_state *regs, u32 regno)
2321 {
2322         if (WARN_ON(regno >= MAX_BPF_REG)) {
2323                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2324                 /* Something bad happened, let's kill all regs except FP */
2325                 for (regno = 0; regno < BPF_REG_FP; regno++)
2326                         __mark_reg_not_init(env, regs + regno);
2327                 return;
2328         }
2329         __mark_reg_not_init(env, regs + regno);
2330 }
2331
2332 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2333                             struct bpf_reg_state *regs, u32 regno,
2334                             enum bpf_reg_type reg_type,
2335                             struct btf *btf, u32 btf_id,
2336                             enum bpf_type_flag flag)
2337 {
2338         if (reg_type == SCALAR_VALUE) {
2339                 mark_reg_unknown(env, regs, regno);
2340                 return;
2341         }
2342         mark_reg_known_zero(env, regs, regno);
2343         regs[regno].type = PTR_TO_BTF_ID | flag;
2344         regs[regno].btf = btf;
2345         regs[regno].btf_id = btf_id;
2346 }
2347
2348 #define DEF_NOT_SUBREG  (0)
2349 static void init_reg_state(struct bpf_verifier_env *env,
2350                            struct bpf_func_state *state)
2351 {
2352         struct bpf_reg_state *regs = state->regs;
2353         int i;
2354
2355         for (i = 0; i < MAX_BPF_REG; i++) {
2356                 mark_reg_not_init(env, regs, i);
2357                 regs[i].live = REG_LIVE_NONE;
2358                 regs[i].parent = NULL;
2359                 regs[i].subreg_def = DEF_NOT_SUBREG;
2360         }
2361
2362         /* frame pointer */
2363         regs[BPF_REG_FP].type = PTR_TO_STACK;
2364         mark_reg_known_zero(env, regs, BPF_REG_FP);
2365         regs[BPF_REG_FP].frameno = state->frameno;
2366 }
2367
2368 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2369 {
2370         return (struct bpf_retval_range){ minval, maxval };
2371 }
2372
2373 #define BPF_MAIN_FUNC (-1)
2374 static void init_func_state(struct bpf_verifier_env *env,
2375                             struct bpf_func_state *state,
2376                             int callsite, int frameno, int subprogno)
2377 {
2378         state->callsite = callsite;
2379         state->frameno = frameno;
2380         state->subprogno = subprogno;
2381         state->callback_ret_range = retval_range(0, 0);
2382         init_reg_state(env, state);
2383         mark_verifier_state_scratched(env);
2384 }
2385
2386 /* Similar to push_stack(), but for async callbacks */
2387 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2388                                                 int insn_idx, int prev_insn_idx,
2389                                                 int subprog)
2390 {
2391         struct bpf_verifier_stack_elem *elem;
2392         struct bpf_func_state *frame;
2393
2394         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2395         if (!elem)
2396                 goto err;
2397
2398         elem->insn_idx = insn_idx;
2399         elem->prev_insn_idx = prev_insn_idx;
2400         elem->next = env->head;
2401         elem->log_pos = env->log.end_pos;
2402         env->head = elem;
2403         env->stack_size++;
2404         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2405                 verbose(env,
2406                         "The sequence of %d jumps is too complex for async cb.\n",
2407                         env->stack_size);
2408                 goto err;
2409         }
2410         /* Unlike push_stack() do not copy_verifier_state().
2411          * The caller state doesn't matter.
2412          * This is async callback. It starts in a fresh stack.
2413          * Initialize it similar to do_check_common().
2414          */
2415         elem->st.branches = 1;
2416         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2417         if (!frame)
2418                 goto err;
2419         init_func_state(env, frame,
2420                         BPF_MAIN_FUNC /* callsite */,
2421                         0 /* frameno within this callchain */,
2422                         subprog /* subprog number within this prog */);
2423         elem->st.frame[0] = frame;
2424         return &elem->st;
2425 err:
2426         free_verifier_state(env->cur_state, true);
2427         env->cur_state = NULL;
2428         /* pop all elements and return */
2429         while (!pop_stack(env, NULL, NULL, false));
2430         return NULL;
2431 }
2432
2433
2434 enum reg_arg_type {
2435         SRC_OP,         /* register is used as source operand */
2436         DST_OP,         /* register is used as destination operand */
2437         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2438 };
2439
2440 static int cmp_subprogs(const void *a, const void *b)
2441 {
2442         return ((struct bpf_subprog_info *)a)->start -
2443                ((struct bpf_subprog_info *)b)->start;
2444 }
2445
2446 static int find_subprog(struct bpf_verifier_env *env, int off)
2447 {
2448         struct bpf_subprog_info *p;
2449
2450         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2451                     sizeof(env->subprog_info[0]), cmp_subprogs);
2452         if (!p)
2453                 return -ENOENT;
2454         return p - env->subprog_info;
2455
2456 }
2457
2458 static int add_subprog(struct bpf_verifier_env *env, int off)
2459 {
2460         int insn_cnt = env->prog->len;
2461         int ret;
2462
2463         if (off >= insn_cnt || off < 0) {
2464                 verbose(env, "call to invalid destination\n");
2465                 return -EINVAL;
2466         }
2467         ret = find_subprog(env, off);
2468         if (ret >= 0)
2469                 return ret;
2470         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2471                 verbose(env, "too many subprograms\n");
2472                 return -E2BIG;
2473         }
2474         /* determine subprog starts. The end is one before the next starts */
2475         env->subprog_info[env->subprog_cnt++].start = off;
2476         sort(env->subprog_info, env->subprog_cnt,
2477              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2478         return env->subprog_cnt - 1;
2479 }
2480
2481 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2482 {
2483         struct bpf_prog_aux *aux = env->prog->aux;
2484         struct btf *btf = aux->btf;
2485         const struct btf_type *t;
2486         u32 main_btf_id, id;
2487         const char *name;
2488         int ret, i;
2489
2490         /* Non-zero func_info_cnt implies valid btf */
2491         if (!aux->func_info_cnt)
2492                 return 0;
2493         main_btf_id = aux->func_info[0].type_id;
2494
2495         t = btf_type_by_id(btf, main_btf_id);
2496         if (!t) {
2497                 verbose(env, "invalid btf id for main subprog in func_info\n");
2498                 return -EINVAL;
2499         }
2500
2501         name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2502         if (IS_ERR(name)) {
2503                 ret = PTR_ERR(name);
2504                 /* If there is no tag present, there is no exception callback */
2505                 if (ret == -ENOENT)
2506                         ret = 0;
2507                 else if (ret == -EEXIST)
2508                         verbose(env, "multiple exception callback tags for main subprog\n");
2509                 return ret;
2510         }
2511
2512         ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2513         if (ret < 0) {
2514                 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2515                 return ret;
2516         }
2517         id = ret;
2518         t = btf_type_by_id(btf, id);
2519         if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2520                 verbose(env, "exception callback '%s' must have global linkage\n", name);
2521                 return -EINVAL;
2522         }
2523         ret = 0;
2524         for (i = 0; i < aux->func_info_cnt; i++) {
2525                 if (aux->func_info[i].type_id != id)
2526                         continue;
2527                 ret = aux->func_info[i].insn_off;
2528                 /* Further func_info and subprog checks will also happen
2529                  * later, so assume this is the right insn_off for now.
2530                  */
2531                 if (!ret) {
2532                         verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2533                         ret = -EINVAL;
2534                 }
2535         }
2536         if (!ret) {
2537                 verbose(env, "exception callback type id not found in func_info\n");
2538                 ret = -EINVAL;
2539         }
2540         return ret;
2541 }
2542
2543 #define MAX_KFUNC_DESCS 256
2544 #define MAX_KFUNC_BTFS  256
2545
2546 struct bpf_kfunc_desc {
2547         struct btf_func_model func_model;
2548         u32 func_id;
2549         s32 imm;
2550         u16 offset;
2551         unsigned long addr;
2552 };
2553
2554 struct bpf_kfunc_btf {
2555         struct btf *btf;
2556         struct module *module;
2557         u16 offset;
2558 };
2559
2560 struct bpf_kfunc_desc_tab {
2561         /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2562          * verification. JITs do lookups by bpf_insn, where func_id may not be
2563          * available, therefore at the end of verification do_misc_fixups()
2564          * sorts this by imm and offset.
2565          */
2566         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2567         u32 nr_descs;
2568 };
2569
2570 struct bpf_kfunc_btf_tab {
2571         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2572         u32 nr_descs;
2573 };
2574
2575 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2576 {
2577         const struct bpf_kfunc_desc *d0 = a;
2578         const struct bpf_kfunc_desc *d1 = b;
2579
2580         /* func_id is not greater than BTF_MAX_TYPE */
2581         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2582 }
2583
2584 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2585 {
2586         const struct bpf_kfunc_btf *d0 = a;
2587         const struct bpf_kfunc_btf *d1 = b;
2588
2589         return d0->offset - d1->offset;
2590 }
2591
2592 static const struct bpf_kfunc_desc *
2593 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2594 {
2595         struct bpf_kfunc_desc desc = {
2596                 .func_id = func_id,
2597                 .offset = offset,
2598         };
2599         struct bpf_kfunc_desc_tab *tab;
2600
2601         tab = prog->aux->kfunc_tab;
2602         return bsearch(&desc, tab->descs, tab->nr_descs,
2603                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2604 }
2605
2606 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2607                        u16 btf_fd_idx, u8 **func_addr)
2608 {
2609         const struct bpf_kfunc_desc *desc;
2610
2611         desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2612         if (!desc)
2613                 return -EFAULT;
2614
2615         *func_addr = (u8 *)desc->addr;
2616         return 0;
2617 }
2618
2619 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2620                                          s16 offset)
2621 {
2622         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2623         struct bpf_kfunc_btf_tab *tab;
2624         struct bpf_kfunc_btf *b;
2625         struct module *mod;
2626         struct btf *btf;
2627         int btf_fd;
2628
2629         tab = env->prog->aux->kfunc_btf_tab;
2630         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2631                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2632         if (!b) {
2633                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2634                         verbose(env, "too many different module BTFs\n");
2635                         return ERR_PTR(-E2BIG);
2636                 }
2637
2638                 if (bpfptr_is_null(env->fd_array)) {
2639                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2640                         return ERR_PTR(-EPROTO);
2641                 }
2642
2643                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2644                                             offset * sizeof(btf_fd),
2645                                             sizeof(btf_fd)))
2646                         return ERR_PTR(-EFAULT);
2647
2648                 btf = btf_get_by_fd(btf_fd);
2649                 if (IS_ERR(btf)) {
2650                         verbose(env, "invalid module BTF fd specified\n");
2651                         return btf;
2652                 }
2653
2654                 if (!btf_is_module(btf)) {
2655                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2656                         btf_put(btf);
2657                         return ERR_PTR(-EINVAL);
2658                 }
2659
2660                 mod = btf_try_get_module(btf);
2661                 if (!mod) {
2662                         btf_put(btf);
2663                         return ERR_PTR(-ENXIO);
2664                 }
2665
2666                 b = &tab->descs[tab->nr_descs++];
2667                 b->btf = btf;
2668                 b->module = mod;
2669                 b->offset = offset;
2670
2671                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2672                      kfunc_btf_cmp_by_off, NULL);
2673         }
2674         return b->btf;
2675 }
2676
2677 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2678 {
2679         if (!tab)
2680                 return;
2681
2682         while (tab->nr_descs--) {
2683                 module_put(tab->descs[tab->nr_descs].module);
2684                 btf_put(tab->descs[tab->nr_descs].btf);
2685         }
2686         kfree(tab);
2687 }
2688
2689 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2690 {
2691         if (offset) {
2692                 if (offset < 0) {
2693                         /* In the future, this can be allowed to increase limit
2694                          * of fd index into fd_array, interpreted as u16.
2695                          */
2696                         verbose(env, "negative offset disallowed for kernel module function call\n");
2697                         return ERR_PTR(-EINVAL);
2698                 }
2699
2700                 return __find_kfunc_desc_btf(env, offset);
2701         }
2702         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2703 }
2704
2705 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2706 {
2707         const struct btf_type *func, *func_proto;
2708         struct bpf_kfunc_btf_tab *btf_tab;
2709         struct bpf_kfunc_desc_tab *tab;
2710         struct bpf_prog_aux *prog_aux;
2711         struct bpf_kfunc_desc *desc;
2712         const char *func_name;
2713         struct btf *desc_btf;
2714         unsigned long call_imm;
2715         unsigned long addr;
2716         int err;
2717
2718         prog_aux = env->prog->aux;
2719         tab = prog_aux->kfunc_tab;
2720         btf_tab = prog_aux->kfunc_btf_tab;
2721         if (!tab) {
2722                 if (!btf_vmlinux) {
2723                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2724                         return -ENOTSUPP;
2725                 }
2726
2727                 if (!env->prog->jit_requested) {
2728                         verbose(env, "JIT is required for calling kernel function\n");
2729                         return -ENOTSUPP;
2730                 }
2731
2732                 if (!bpf_jit_supports_kfunc_call()) {
2733                         verbose(env, "JIT does not support calling kernel function\n");
2734                         return -ENOTSUPP;
2735                 }
2736
2737                 if (!env->prog->gpl_compatible) {
2738                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2739                         return -EINVAL;
2740                 }
2741
2742                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2743                 if (!tab)
2744                         return -ENOMEM;
2745                 prog_aux->kfunc_tab = tab;
2746         }
2747
2748         /* func_id == 0 is always invalid, but instead of returning an error, be
2749          * conservative and wait until the code elimination pass before returning
2750          * error, so that invalid calls that get pruned out can be in BPF programs
2751          * loaded from userspace.  It is also required that offset be untouched
2752          * for such calls.
2753          */
2754         if (!func_id && !offset)
2755                 return 0;
2756
2757         if (!btf_tab && offset) {
2758                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2759                 if (!btf_tab)
2760                         return -ENOMEM;
2761                 prog_aux->kfunc_btf_tab = btf_tab;
2762         }
2763
2764         desc_btf = find_kfunc_desc_btf(env, offset);
2765         if (IS_ERR(desc_btf)) {
2766                 verbose(env, "failed to find BTF for kernel function\n");
2767                 return PTR_ERR(desc_btf);
2768         }
2769
2770         if (find_kfunc_desc(env->prog, func_id, offset))
2771                 return 0;
2772
2773         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2774                 verbose(env, "too many different kernel function calls\n");
2775                 return -E2BIG;
2776         }
2777
2778         func = btf_type_by_id(desc_btf, func_id);
2779         if (!func || !btf_type_is_func(func)) {
2780                 verbose(env, "kernel btf_id %u is not a function\n",
2781                         func_id);
2782                 return -EINVAL;
2783         }
2784         func_proto = btf_type_by_id(desc_btf, func->type);
2785         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2786                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2787                         func_id);
2788                 return -EINVAL;
2789         }
2790
2791         func_name = btf_name_by_offset(desc_btf, func->name_off);
2792         addr = kallsyms_lookup_name(func_name);
2793         if (!addr) {
2794                 verbose(env, "cannot find address for kernel function %s\n",
2795                         func_name);
2796                 return -EINVAL;
2797         }
2798         specialize_kfunc(env, func_id, offset, &addr);
2799
2800         if (bpf_jit_supports_far_kfunc_call()) {
2801                 call_imm = func_id;
2802         } else {
2803                 call_imm = BPF_CALL_IMM(addr);
2804                 /* Check whether the relative offset overflows desc->imm */
2805                 if ((unsigned long)(s32)call_imm != call_imm) {
2806                         verbose(env, "address of kernel function %s is out of range\n",
2807                                 func_name);
2808                         return -EINVAL;
2809                 }
2810         }
2811
2812         if (bpf_dev_bound_kfunc_id(func_id)) {
2813                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2814                 if (err)
2815                         return err;
2816         }
2817
2818         desc = &tab->descs[tab->nr_descs++];
2819         desc->func_id = func_id;
2820         desc->imm = call_imm;
2821         desc->offset = offset;
2822         desc->addr = addr;
2823         err = btf_distill_func_proto(&env->log, desc_btf,
2824                                      func_proto, func_name,
2825                                      &desc->func_model);
2826         if (!err)
2827                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2828                      kfunc_desc_cmp_by_id_off, NULL);
2829         return err;
2830 }
2831
2832 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2833 {
2834         const struct bpf_kfunc_desc *d0 = a;
2835         const struct bpf_kfunc_desc *d1 = b;
2836
2837         if (d0->imm != d1->imm)
2838                 return d0->imm < d1->imm ? -1 : 1;
2839         if (d0->offset != d1->offset)
2840                 return d0->offset < d1->offset ? -1 : 1;
2841         return 0;
2842 }
2843
2844 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2845 {
2846         struct bpf_kfunc_desc_tab *tab;
2847
2848         tab = prog->aux->kfunc_tab;
2849         if (!tab)
2850                 return;
2851
2852         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2853              kfunc_desc_cmp_by_imm_off, NULL);
2854 }
2855
2856 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2857 {
2858         return !!prog->aux->kfunc_tab;
2859 }
2860
2861 const struct btf_func_model *
2862 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2863                          const struct bpf_insn *insn)
2864 {
2865         const struct bpf_kfunc_desc desc = {
2866                 .imm = insn->imm,
2867                 .offset = insn->off,
2868         };
2869         const struct bpf_kfunc_desc *res;
2870         struct bpf_kfunc_desc_tab *tab;
2871
2872         tab = prog->aux->kfunc_tab;
2873         res = bsearch(&desc, tab->descs, tab->nr_descs,
2874                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2875
2876         return res ? &res->func_model : NULL;
2877 }
2878
2879 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2880 {
2881         struct bpf_subprog_info *subprog = env->subprog_info;
2882         int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2883         struct bpf_insn *insn = env->prog->insnsi;
2884
2885         /* Add entry function. */
2886         ret = add_subprog(env, 0);
2887         if (ret)
2888                 return ret;
2889
2890         for (i = 0; i < insn_cnt; i++, insn++) {
2891                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2892                     !bpf_pseudo_kfunc_call(insn))
2893                         continue;
2894
2895                 if (!env->bpf_capable) {
2896                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2897                         return -EPERM;
2898                 }
2899
2900                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2901                         ret = add_subprog(env, i + insn->imm + 1);
2902                 else
2903                         ret = add_kfunc_call(env, insn->imm, insn->off);
2904
2905                 if (ret < 0)
2906                         return ret;
2907         }
2908
2909         ret = bpf_find_exception_callback_insn_off(env);
2910         if (ret < 0)
2911                 return ret;
2912         ex_cb_insn = ret;
2913
2914         /* If ex_cb_insn > 0, this means that the main program has a subprog
2915          * marked using BTF decl tag to serve as the exception callback.
2916          */
2917         if (ex_cb_insn) {
2918                 ret = add_subprog(env, ex_cb_insn);
2919                 if (ret < 0)
2920                         return ret;
2921                 for (i = 1; i < env->subprog_cnt; i++) {
2922                         if (env->subprog_info[i].start != ex_cb_insn)
2923                                 continue;
2924                         env->exception_callback_subprog = i;
2925                         mark_subprog_exc_cb(env, i);
2926                         break;
2927                 }
2928         }
2929
2930         /* Add a fake 'exit' subprog which could simplify subprog iteration
2931          * logic. 'subprog_cnt' should not be increased.
2932          */
2933         subprog[env->subprog_cnt].start = insn_cnt;
2934
2935         if (env->log.level & BPF_LOG_LEVEL2)
2936                 for (i = 0; i < env->subprog_cnt; i++)
2937                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2938
2939         return 0;
2940 }
2941
2942 static int check_subprogs(struct bpf_verifier_env *env)
2943 {
2944         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2945         struct bpf_subprog_info *subprog = env->subprog_info;
2946         struct bpf_insn *insn = env->prog->insnsi;
2947         int insn_cnt = env->prog->len;
2948
2949         /* now check that all jumps are within the same subprog */
2950         subprog_start = subprog[cur_subprog].start;
2951         subprog_end = subprog[cur_subprog + 1].start;
2952         for (i = 0; i < insn_cnt; i++) {
2953                 u8 code = insn[i].code;
2954
2955                 if (code == (BPF_JMP | BPF_CALL) &&
2956                     insn[i].src_reg == 0 &&
2957                     insn[i].imm == BPF_FUNC_tail_call)
2958                         subprog[cur_subprog].has_tail_call = true;
2959                 if (BPF_CLASS(code) == BPF_LD &&
2960                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2961                         subprog[cur_subprog].has_ld_abs = true;
2962                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2963                         goto next;
2964                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2965                         goto next;
2966                 if (code == (BPF_JMP32 | BPF_JA))
2967                         off = i + insn[i].imm + 1;
2968                 else
2969                         off = i + insn[i].off + 1;
2970                 if (off < subprog_start || off >= subprog_end) {
2971                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2972                         return -EINVAL;
2973                 }
2974 next:
2975                 if (i == subprog_end - 1) {
2976                         /* to avoid fall-through from one subprog into another
2977                          * the last insn of the subprog should be either exit
2978                          * or unconditional jump back or bpf_throw call
2979                          */
2980                         if (code != (BPF_JMP | BPF_EXIT) &&
2981                             code != (BPF_JMP32 | BPF_JA) &&
2982                             code != (BPF_JMP | BPF_JA)) {
2983                                 verbose(env, "last insn is not an exit or jmp\n");
2984                                 return -EINVAL;
2985                         }
2986                         subprog_start = subprog_end;
2987                         cur_subprog++;
2988                         if (cur_subprog < env->subprog_cnt)
2989                                 subprog_end = subprog[cur_subprog + 1].start;
2990                 }
2991         }
2992         return 0;
2993 }
2994
2995 /* Parentage chain of this register (or stack slot) should take care of all
2996  * issues like callee-saved registers, stack slot allocation time, etc.
2997  */
2998 static int mark_reg_read(struct bpf_verifier_env *env,
2999                          const struct bpf_reg_state *state,
3000                          struct bpf_reg_state *parent, u8 flag)
3001 {
3002         bool writes = parent == state->parent; /* Observe write marks */
3003         int cnt = 0;
3004
3005         while (parent) {
3006                 /* if read wasn't screened by an earlier write ... */
3007                 if (writes && state->live & REG_LIVE_WRITTEN)
3008                         break;
3009                 if (parent->live & REG_LIVE_DONE) {
3010                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3011                                 reg_type_str(env, parent->type),
3012                                 parent->var_off.value, parent->off);
3013                         return -EFAULT;
3014                 }
3015                 /* The first condition is more likely to be true than the
3016                  * second, checked it first.
3017                  */
3018                 if ((parent->live & REG_LIVE_READ) == flag ||
3019                     parent->live & REG_LIVE_READ64)
3020                         /* The parentage chain never changes and
3021                          * this parent was already marked as LIVE_READ.
3022                          * There is no need to keep walking the chain again and
3023                          * keep re-marking all parents as LIVE_READ.
3024                          * This case happens when the same register is read
3025                          * multiple times without writes into it in-between.
3026                          * Also, if parent has the stronger REG_LIVE_READ64 set,
3027                          * then no need to set the weak REG_LIVE_READ32.
3028                          */
3029                         break;
3030                 /* ... then we depend on parent's value */
3031                 parent->live |= flag;
3032                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3033                 if (flag == REG_LIVE_READ64)
3034                         parent->live &= ~REG_LIVE_READ32;
3035                 state = parent;
3036                 parent = state->parent;
3037                 writes = true;
3038                 cnt++;
3039         }
3040
3041         if (env->longest_mark_read_walk < cnt)
3042                 env->longest_mark_read_walk = cnt;
3043         return 0;
3044 }
3045
3046 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3047 {
3048         struct bpf_func_state *state = func(env, reg);
3049         int spi, ret;
3050
3051         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3052          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3053          * check_kfunc_call.
3054          */
3055         if (reg->type == CONST_PTR_TO_DYNPTR)
3056                 return 0;
3057         spi = dynptr_get_spi(env, reg);
3058         if (spi < 0)
3059                 return spi;
3060         /* Caller ensures dynptr is valid and initialized, which means spi is in
3061          * bounds and spi is the first dynptr slot. Simply mark stack slot as
3062          * read.
3063          */
3064         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3065                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3066         if (ret)
3067                 return ret;
3068         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3069                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3070 }
3071
3072 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3073                           int spi, int nr_slots)
3074 {
3075         struct bpf_func_state *state = func(env, reg);
3076         int err, i;
3077
3078         for (i = 0; i < nr_slots; i++) {
3079                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3080
3081                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3082                 if (err)
3083                         return err;
3084
3085                 mark_stack_slot_scratched(env, spi - i);
3086         }
3087
3088         return 0;
3089 }
3090
3091 /* This function is supposed to be used by the following 32-bit optimization
3092  * code only. It returns TRUE if the source or destination register operates
3093  * on 64-bit, otherwise return FALSE.
3094  */
3095 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3096                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3097 {
3098         u8 code, class, op;
3099
3100         code = insn->code;
3101         class = BPF_CLASS(code);
3102         op = BPF_OP(code);
3103         if (class == BPF_JMP) {
3104                 /* BPF_EXIT for "main" will reach here. Return TRUE
3105                  * conservatively.
3106                  */
3107                 if (op == BPF_EXIT)
3108                         return true;
3109                 if (op == BPF_CALL) {
3110                         /* BPF to BPF call will reach here because of marking
3111                          * caller saved clobber with DST_OP_NO_MARK for which we
3112                          * don't care the register def because they are anyway
3113                          * marked as NOT_INIT already.
3114                          */
3115                         if (insn->src_reg == BPF_PSEUDO_CALL)
3116                                 return false;
3117                         /* Helper call will reach here because of arg type
3118                          * check, conservatively return TRUE.
3119                          */
3120                         if (t == SRC_OP)
3121                                 return true;
3122
3123                         return false;
3124                 }
3125         }
3126
3127         if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3128                 return false;
3129
3130         if (class == BPF_ALU64 || class == BPF_JMP ||
3131             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3132                 return true;
3133
3134         if (class == BPF_ALU || class == BPF_JMP32)
3135                 return false;
3136
3137         if (class == BPF_LDX) {
3138                 if (t != SRC_OP)
3139                         return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3140                 /* LDX source must be ptr. */
3141                 return true;
3142         }
3143
3144         if (class == BPF_STX) {
3145                 /* BPF_STX (including atomic variants) has multiple source
3146                  * operands, one of which is a ptr. Check whether the caller is
3147                  * asking about it.
3148                  */
3149                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3150                         return true;
3151                 return BPF_SIZE(code) == BPF_DW;
3152         }
3153
3154         if (class == BPF_LD) {
3155                 u8 mode = BPF_MODE(code);
3156
3157                 /* LD_IMM64 */
3158                 if (mode == BPF_IMM)
3159                         return true;
3160
3161                 /* Both LD_IND and LD_ABS return 32-bit data. */
3162                 if (t != SRC_OP)
3163                         return  false;
3164
3165                 /* Implicit ctx ptr. */
3166                 if (regno == BPF_REG_6)
3167                         return true;
3168
3169                 /* Explicit source could be any width. */
3170                 return true;
3171         }
3172
3173         if (class == BPF_ST)
3174                 /* The only source register for BPF_ST is a ptr. */
3175                 return true;
3176
3177         /* Conservatively return true at default. */
3178         return true;
3179 }
3180
3181 /* Return the regno defined by the insn, or -1. */
3182 static int insn_def_regno(const struct bpf_insn *insn)
3183 {
3184         switch (BPF_CLASS(insn->code)) {
3185         case BPF_JMP:
3186         case BPF_JMP32:
3187         case BPF_ST:
3188                 return -1;
3189         case BPF_STX:
3190                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3191                     (insn->imm & BPF_FETCH)) {
3192                         if (insn->imm == BPF_CMPXCHG)
3193                                 return BPF_REG_0;
3194                         else
3195                                 return insn->src_reg;
3196                 } else {
3197                         return -1;
3198                 }
3199         default:
3200                 return insn->dst_reg;
3201         }
3202 }
3203
3204 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3205 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3206 {
3207         int dst_reg = insn_def_regno(insn);
3208
3209         if (dst_reg == -1)
3210                 return false;
3211
3212         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3213 }
3214
3215 static void mark_insn_zext(struct bpf_verifier_env *env,
3216                            struct bpf_reg_state *reg)
3217 {
3218         s32 def_idx = reg->subreg_def;
3219
3220         if (def_idx == DEF_NOT_SUBREG)
3221                 return;
3222
3223         env->insn_aux_data[def_idx - 1].zext_dst = true;
3224         /* The dst will be zero extended, so won't be sub-register anymore. */
3225         reg->subreg_def = DEF_NOT_SUBREG;
3226 }
3227
3228 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3229                            enum reg_arg_type t)
3230 {
3231         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3232         struct bpf_reg_state *reg;
3233         bool rw64;
3234
3235         if (regno >= MAX_BPF_REG) {
3236                 verbose(env, "R%d is invalid\n", regno);
3237                 return -EINVAL;
3238         }
3239
3240         mark_reg_scratched(env, regno);
3241
3242         reg = &regs[regno];
3243         rw64 = is_reg64(env, insn, regno, reg, t);
3244         if (t == SRC_OP) {
3245                 /* check whether register used as source operand can be read */
3246                 if (reg->type == NOT_INIT) {
3247                         verbose(env, "R%d !read_ok\n", regno);
3248                         return -EACCES;
3249                 }
3250                 /* We don't need to worry about FP liveness because it's read-only */
3251                 if (regno == BPF_REG_FP)
3252                         return 0;
3253
3254                 if (rw64)
3255                         mark_insn_zext(env, reg);
3256
3257                 return mark_reg_read(env, reg, reg->parent,
3258                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3259         } else {
3260                 /* check whether register used as dest operand can be written to */
3261                 if (regno == BPF_REG_FP) {
3262                         verbose(env, "frame pointer is read only\n");
3263                         return -EACCES;
3264                 }
3265                 reg->live |= REG_LIVE_WRITTEN;
3266                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3267                 if (t == DST_OP)
3268                         mark_reg_unknown(env, regs, regno);
3269         }
3270         return 0;
3271 }
3272
3273 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3274                          enum reg_arg_type t)
3275 {
3276         struct bpf_verifier_state *vstate = env->cur_state;
3277         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3278
3279         return __check_reg_arg(env, state->regs, regno, t);
3280 }
3281
3282 static int insn_stack_access_flags(int frameno, int spi)
3283 {
3284         return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3285 }
3286
3287 static int insn_stack_access_spi(int insn_flags)
3288 {
3289         return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3290 }
3291
3292 static int insn_stack_access_frameno(int insn_flags)
3293 {
3294         return insn_flags & INSN_F_FRAMENO_MASK;
3295 }
3296
3297 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3298 {
3299         env->insn_aux_data[idx].jmp_point = true;
3300 }
3301
3302 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3303 {
3304         return env->insn_aux_data[insn_idx].jmp_point;
3305 }
3306
3307 /* for any branch, call, exit record the history of jmps in the given state */
3308 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3309                             int insn_flags)
3310 {
3311         u32 cnt = cur->jmp_history_cnt;
3312         struct bpf_jmp_history_entry *p;
3313         size_t alloc_size;
3314
3315         /* combine instruction flags if we already recorded this instruction */
3316         if (env->cur_hist_ent) {
3317                 /* atomic instructions push insn_flags twice, for READ and
3318                  * WRITE sides, but they should agree on stack slot
3319                  */
3320                 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3321                           (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3322                           "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3323                           env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3324                 env->cur_hist_ent->flags |= insn_flags;
3325                 return 0;
3326         }
3327
3328         cnt++;
3329         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3330         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3331         if (!p)
3332                 return -ENOMEM;
3333         cur->jmp_history = p;
3334
3335         p = &cur->jmp_history[cnt - 1];
3336         p->idx = env->insn_idx;
3337         p->prev_idx = env->prev_insn_idx;
3338         p->flags = insn_flags;
3339         cur->jmp_history_cnt = cnt;
3340         env->cur_hist_ent = p;
3341
3342         return 0;
3343 }
3344
3345 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3346                                                         u32 hist_end, int insn_idx)
3347 {
3348         if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3349                 return &st->jmp_history[hist_end - 1];
3350         return NULL;
3351 }
3352
3353 /* Backtrack one insn at a time. If idx is not at the top of recorded
3354  * history then previous instruction came from straight line execution.
3355  * Return -ENOENT if we exhausted all instructions within given state.
3356  *
3357  * It's legal to have a bit of a looping with the same starting and ending
3358  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3359  * instruction index is the same as state's first_idx doesn't mean we are
3360  * done. If there is still some jump history left, we should keep going. We
3361  * need to take into account that we might have a jump history between given
3362  * state's parent and itself, due to checkpointing. In this case, we'll have
3363  * history entry recording a jump from last instruction of parent state and
3364  * first instruction of given state.
3365  */
3366 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3367                              u32 *history)
3368 {
3369         u32 cnt = *history;
3370
3371         if (i == st->first_insn_idx) {
3372                 if (cnt == 0)
3373                         return -ENOENT;
3374                 if (cnt == 1 && st->jmp_history[0].idx == i)
3375                         return -ENOENT;
3376         }
3377
3378         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3379                 i = st->jmp_history[cnt - 1].prev_idx;
3380                 (*history)--;
3381         } else {
3382                 i--;
3383         }
3384         return i;
3385 }
3386
3387 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3388 {
3389         const struct btf_type *func;
3390         struct btf *desc_btf;
3391
3392         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3393                 return NULL;
3394
3395         desc_btf = find_kfunc_desc_btf(data, insn->off);
3396         if (IS_ERR(desc_btf))
3397                 return "<error>";
3398
3399         func = btf_type_by_id(desc_btf, insn->imm);
3400         return btf_name_by_offset(desc_btf, func->name_off);
3401 }
3402
3403 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3404 {
3405         bt->frame = frame;
3406 }
3407
3408 static inline void bt_reset(struct backtrack_state *bt)
3409 {
3410         struct bpf_verifier_env *env = bt->env;
3411
3412         memset(bt, 0, sizeof(*bt));
3413         bt->env = env;
3414 }
3415
3416 static inline u32 bt_empty(struct backtrack_state *bt)
3417 {
3418         u64 mask = 0;
3419         int i;
3420
3421         for (i = 0; i <= bt->frame; i++)
3422                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3423
3424         return mask == 0;
3425 }
3426
3427 static inline int bt_subprog_enter(struct backtrack_state *bt)
3428 {
3429         if (bt->frame == MAX_CALL_FRAMES - 1) {
3430                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3431                 WARN_ONCE(1, "verifier backtracking bug");
3432                 return -EFAULT;
3433         }
3434         bt->frame++;
3435         return 0;
3436 }
3437
3438 static inline int bt_subprog_exit(struct backtrack_state *bt)
3439 {
3440         if (bt->frame == 0) {
3441                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3442                 WARN_ONCE(1, "verifier backtracking bug");
3443                 return -EFAULT;
3444         }
3445         bt->frame--;
3446         return 0;
3447 }
3448
3449 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3450 {
3451         bt->reg_masks[frame] |= 1 << reg;
3452 }
3453
3454 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3455 {
3456         bt->reg_masks[frame] &= ~(1 << reg);
3457 }
3458
3459 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3460 {
3461         bt_set_frame_reg(bt, bt->frame, reg);
3462 }
3463
3464 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3465 {
3466         bt_clear_frame_reg(bt, bt->frame, reg);
3467 }
3468
3469 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3470 {
3471         bt->stack_masks[frame] |= 1ull << slot;
3472 }
3473
3474 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3475 {
3476         bt->stack_masks[frame] &= ~(1ull << slot);
3477 }
3478
3479 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3480 {
3481         return bt->reg_masks[frame];
3482 }
3483
3484 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3485 {
3486         return bt->reg_masks[bt->frame];
3487 }
3488
3489 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3490 {
3491         return bt->stack_masks[frame];
3492 }
3493
3494 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3495 {
3496         return bt->stack_masks[bt->frame];
3497 }
3498
3499 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3500 {
3501         return bt->reg_masks[bt->frame] & (1 << reg);
3502 }
3503
3504 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3505 {
3506         return bt->stack_masks[frame] & (1ull << slot);
3507 }
3508
3509 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3510 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3511 {
3512         DECLARE_BITMAP(mask, 64);
3513         bool first = true;
3514         int i, n;
3515
3516         buf[0] = '\0';
3517
3518         bitmap_from_u64(mask, reg_mask);
3519         for_each_set_bit(i, mask, 32) {
3520                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3521                 first = false;
3522                 buf += n;
3523                 buf_sz -= n;
3524                 if (buf_sz < 0)
3525                         break;
3526         }
3527 }
3528 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3529 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3530 {
3531         DECLARE_BITMAP(mask, 64);
3532         bool first = true;
3533         int i, n;
3534
3535         buf[0] = '\0';
3536
3537         bitmap_from_u64(mask, stack_mask);
3538         for_each_set_bit(i, mask, 64) {
3539                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3540                 first = false;
3541                 buf += n;
3542                 buf_sz -= n;
3543                 if (buf_sz < 0)
3544                         break;
3545         }
3546 }
3547
3548 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3549
3550 /* For given verifier state backtrack_insn() is called from the last insn to
3551  * the first insn. Its purpose is to compute a bitmask of registers and
3552  * stack slots that needs precision in the parent verifier state.
3553  *
3554  * @idx is an index of the instruction we are currently processing;
3555  * @subseq_idx is an index of the subsequent instruction that:
3556  *   - *would be* executed next, if jump history is viewed in forward order;
3557  *   - *was* processed previously during backtracking.
3558  */
3559 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3560                           struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3561 {
3562         const struct bpf_insn_cbs cbs = {
3563                 .cb_call        = disasm_kfunc_name,
3564                 .cb_print       = verbose,
3565                 .private_data   = env,
3566         };
3567         struct bpf_insn *insn = env->prog->insnsi + idx;
3568         u8 class = BPF_CLASS(insn->code);
3569         u8 opcode = BPF_OP(insn->code);
3570         u8 mode = BPF_MODE(insn->code);
3571         u32 dreg = insn->dst_reg;
3572         u32 sreg = insn->src_reg;
3573         u32 spi, i, fr;
3574
3575         if (insn->code == 0)
3576                 return 0;
3577         if (env->log.level & BPF_LOG_LEVEL2) {
3578                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3579                 verbose(env, "mark_precise: frame%d: regs=%s ",
3580                         bt->frame, env->tmp_str_buf);
3581                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3582                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3583                 verbose(env, "%d: ", idx);
3584                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3585         }
3586
3587         if (class == BPF_ALU || class == BPF_ALU64) {
3588                 if (!bt_is_reg_set(bt, dreg))
3589                         return 0;
3590                 if (opcode == BPF_END || opcode == BPF_NEG) {
3591                         /* sreg is reserved and unused
3592                          * dreg still need precision before this insn
3593                          */
3594                         return 0;
3595                 } else if (opcode == BPF_MOV) {
3596                         if (BPF_SRC(insn->code) == BPF_X) {
3597                                 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3598                                  * dreg needs precision after this insn
3599                                  * sreg needs precision before this insn
3600                                  */
3601                                 bt_clear_reg(bt, dreg);
3602                                 bt_set_reg(bt, sreg);
3603                         } else {
3604                                 /* dreg = K
3605                                  * dreg needs precision after this insn.
3606                                  * Corresponding register is already marked
3607                                  * as precise=true in this verifier state.
3608                                  * No further markings in parent are necessary
3609                                  */
3610                                 bt_clear_reg(bt, dreg);
3611                         }
3612                 } else {
3613                         if (BPF_SRC(insn->code) == BPF_X) {
3614                                 /* dreg += sreg
3615                                  * both dreg and sreg need precision
3616                                  * before this insn
3617                                  */
3618                                 bt_set_reg(bt, sreg);
3619                         } /* else dreg += K
3620                            * dreg still needs precision before this insn
3621                            */
3622                 }
3623         } else if (class == BPF_LDX) {
3624                 if (!bt_is_reg_set(bt, dreg))
3625                         return 0;
3626                 bt_clear_reg(bt, dreg);
3627
3628                 /* scalars can only be spilled into stack w/o losing precision.
3629                  * Load from any other memory can be zero extended.
3630                  * The desire to keep that precision is already indicated
3631                  * by 'precise' mark in corresponding register of this state.
3632                  * No further tracking necessary.
3633                  */
3634                 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3635                         return 0;
3636                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3637                  * that [fp - off] slot contains scalar that needs to be
3638                  * tracked with precision
3639                  */
3640                 spi = insn_stack_access_spi(hist->flags);
3641                 fr = insn_stack_access_frameno(hist->flags);
3642                 bt_set_frame_slot(bt, fr, spi);
3643         } else if (class == BPF_STX || class == BPF_ST) {
3644                 if (bt_is_reg_set(bt, dreg))
3645                         /* stx & st shouldn't be using _scalar_ dst_reg
3646                          * to access memory. It means backtracking
3647                          * encountered a case of pointer subtraction.
3648                          */
3649                         return -ENOTSUPP;
3650                 /* scalars can only be spilled into stack */
3651                 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3652                         return 0;
3653                 spi = insn_stack_access_spi(hist->flags);
3654                 fr = insn_stack_access_frameno(hist->flags);
3655                 if (!bt_is_frame_slot_set(bt, fr, spi))
3656                         return 0;
3657                 bt_clear_frame_slot(bt, fr, spi);
3658                 if (class == BPF_STX)
3659                         bt_set_reg(bt, sreg);
3660         } else if (class == BPF_JMP || class == BPF_JMP32) {
3661                 if (bpf_pseudo_call(insn)) {
3662                         int subprog_insn_idx, subprog;
3663
3664                         subprog_insn_idx = idx + insn->imm + 1;
3665                         subprog = find_subprog(env, subprog_insn_idx);
3666                         if (subprog < 0)
3667                                 return -EFAULT;
3668
3669                         if (subprog_is_global(env, subprog)) {
3670                                 /* check that jump history doesn't have any
3671                                  * extra instructions from subprog; the next
3672                                  * instruction after call to global subprog
3673                                  * should be literally next instruction in
3674                                  * caller program
3675                                  */
3676                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3677                                 /* r1-r5 are invalidated after subprog call,
3678                                  * so for global func call it shouldn't be set
3679                                  * anymore
3680                                  */
3681                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3682                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3683                                         WARN_ONCE(1, "verifier backtracking bug");
3684                                         return -EFAULT;
3685                                 }
3686                                 /* global subprog always sets R0 */
3687                                 bt_clear_reg(bt, BPF_REG_0);
3688                                 return 0;
3689                         } else {
3690                                 /* static subprog call instruction, which
3691                                  * means that we are exiting current subprog,
3692                                  * so only r1-r5 could be still requested as
3693                                  * precise, r0 and r6-r10 or any stack slot in
3694                                  * the current frame should be zero by now
3695                                  */
3696                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3697                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3698                                         WARN_ONCE(1, "verifier backtracking bug");
3699                                         return -EFAULT;
3700                                 }
3701                                 /* we are now tracking register spills correctly,
3702                                  * so any instance of leftover slots is a bug
3703                                  */
3704                                 if (bt_stack_mask(bt) != 0) {
3705                                         verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3706                                         WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3707                                         return -EFAULT;
3708                                 }
3709                                 /* propagate r1-r5 to the caller */
3710                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3711                                         if (bt_is_reg_set(bt, i)) {
3712                                                 bt_clear_reg(bt, i);
3713                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3714                                         }
3715                                 }
3716                                 if (bt_subprog_exit(bt))
3717                                         return -EFAULT;
3718                                 return 0;
3719                         }
3720                 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3721                         /* exit from callback subprog to callback-calling helper or
3722                          * kfunc call. Use idx/subseq_idx check to discern it from
3723                          * straight line code backtracking.
3724                          * Unlike the subprog call handling above, we shouldn't
3725                          * propagate precision of r1-r5 (if any requested), as they are
3726                          * not actually arguments passed directly to callback subprogs
3727                          */
3728                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3729                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3730                                 WARN_ONCE(1, "verifier backtracking bug");
3731                                 return -EFAULT;
3732                         }
3733                         if (bt_stack_mask(bt) != 0) {
3734                                 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3735                                 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3736                                 return -EFAULT;
3737                         }
3738                         /* clear r1-r5 in callback subprog's mask */
3739                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3740                                 bt_clear_reg(bt, i);
3741                         if (bt_subprog_exit(bt))
3742                                 return -EFAULT;
3743                         return 0;
3744                 } else if (opcode == BPF_CALL) {
3745                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3746                          * catch this error later. Make backtracking conservative
3747                          * with ENOTSUPP.
3748                          */
3749                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3750                                 return -ENOTSUPP;
3751                         /* regular helper call sets R0 */
3752                         bt_clear_reg(bt, BPF_REG_0);
3753                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3754                                 /* if backtracing was looking for registers R1-R5
3755                                  * they should have been found already.
3756                                  */
3757                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3758                                 WARN_ONCE(1, "verifier backtracking bug");
3759                                 return -EFAULT;
3760                         }
3761                 } else if (opcode == BPF_EXIT) {
3762                         bool r0_precise;
3763
3764                         /* Backtracking to a nested function call, 'idx' is a part of
3765                          * the inner frame 'subseq_idx' is a part of the outer frame.
3766                          * In case of a regular function call, instructions giving
3767                          * precision to registers R1-R5 should have been found already.
3768                          * In case of a callback, it is ok to have R1-R5 marked for
3769                          * backtracking, as these registers are set by the function
3770                          * invoking callback.
3771                          */
3772                         if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3773                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3774                                         bt_clear_reg(bt, i);
3775                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3776                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3777                                 WARN_ONCE(1, "verifier backtracking bug");
3778                                 return -EFAULT;
3779                         }
3780
3781                         /* BPF_EXIT in subprog or callback always returns
3782                          * right after the call instruction, so by checking
3783                          * whether the instruction at subseq_idx-1 is subprog
3784                          * call or not we can distinguish actual exit from
3785                          * *subprog* from exit from *callback*. In the former
3786                          * case, we need to propagate r0 precision, if
3787                          * necessary. In the former we never do that.
3788                          */
3789                         r0_precise = subseq_idx - 1 >= 0 &&
3790                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3791                                      bt_is_reg_set(bt, BPF_REG_0);
3792
3793                         bt_clear_reg(bt, BPF_REG_0);
3794                         if (bt_subprog_enter(bt))
3795                                 return -EFAULT;
3796
3797                         if (r0_precise)
3798                                 bt_set_reg(bt, BPF_REG_0);
3799                         /* r6-r9 and stack slots will stay set in caller frame
3800                          * bitmasks until we return back from callee(s)
3801                          */
3802                         return 0;
3803                 } else if (BPF_SRC(insn->code) == BPF_X) {
3804                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3805                                 return 0;
3806                         /* dreg <cond> sreg
3807                          * Both dreg and sreg need precision before
3808                          * this insn. If only sreg was marked precise
3809                          * before it would be equally necessary to
3810                          * propagate it to dreg.
3811                          */
3812                         bt_set_reg(bt, dreg);
3813                         bt_set_reg(bt, sreg);
3814                          /* else dreg <cond> K
3815                           * Only dreg still needs precision before
3816                           * this insn, so for the K-based conditional
3817                           * there is nothing new to be marked.
3818                           */
3819                 }
3820         } else if (class == BPF_LD) {
3821                 if (!bt_is_reg_set(bt, dreg))
3822                         return 0;
3823                 bt_clear_reg(bt, dreg);
3824                 /* It's ld_imm64 or ld_abs or ld_ind.
3825                  * For ld_imm64 no further tracking of precision
3826                  * into parent is necessary
3827                  */
3828                 if (mode == BPF_IND || mode == BPF_ABS)
3829                         /* to be analyzed */
3830                         return -ENOTSUPP;
3831         }
3832         return 0;
3833 }
3834
3835 /* the scalar precision tracking algorithm:
3836  * . at the start all registers have precise=false.
3837  * . scalar ranges are tracked as normal through alu and jmp insns.
3838  * . once precise value of the scalar register is used in:
3839  *   .  ptr + scalar alu
3840  *   . if (scalar cond K|scalar)
3841  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3842  *   backtrack through the verifier states and mark all registers and
3843  *   stack slots with spilled constants that these scalar regisers
3844  *   should be precise.
3845  * . during state pruning two registers (or spilled stack slots)
3846  *   are equivalent if both are not precise.
3847  *
3848  * Note the verifier cannot simply walk register parentage chain,
3849  * since many different registers and stack slots could have been
3850  * used to compute single precise scalar.
3851  *
3852  * The approach of starting with precise=true for all registers and then
3853  * backtrack to mark a register as not precise when the verifier detects
3854  * that program doesn't care about specific value (e.g., when helper
3855  * takes register as ARG_ANYTHING parameter) is not safe.
3856  *
3857  * It's ok to walk single parentage chain of the verifier states.
3858  * It's possible that this backtracking will go all the way till 1st insn.
3859  * All other branches will be explored for needing precision later.
3860  *
3861  * The backtracking needs to deal with cases like:
3862  *   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)
3863  * r9 -= r8
3864  * r5 = r9
3865  * if r5 > 0x79f goto pc+7
3866  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3867  * r5 += 1
3868  * ...
3869  * call bpf_perf_event_output#25
3870  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3871  *
3872  * and this case:
3873  * r6 = 1
3874  * call foo // uses callee's r6 inside to compute r0
3875  * r0 += r6
3876  * if r0 == 0 goto
3877  *
3878  * to track above reg_mask/stack_mask needs to be independent for each frame.
3879  *
3880  * Also if parent's curframe > frame where backtracking started,
3881  * the verifier need to mark registers in both frames, otherwise callees
3882  * may incorrectly prune callers. This is similar to
3883  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3884  *
3885  * For now backtracking falls back into conservative marking.
3886  */
3887 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3888                                      struct bpf_verifier_state *st)
3889 {
3890         struct bpf_func_state *func;
3891         struct bpf_reg_state *reg;
3892         int i, j;
3893
3894         if (env->log.level & BPF_LOG_LEVEL2) {
3895                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3896                         st->curframe);
3897         }
3898
3899         /* big hammer: mark all scalars precise in this path.
3900          * pop_stack may still get !precise scalars.
3901          * We also skip current state and go straight to first parent state,
3902          * because precision markings in current non-checkpointed state are
3903          * not needed. See why in the comment in __mark_chain_precision below.
3904          */
3905         for (st = st->parent; st; st = st->parent) {
3906                 for (i = 0; i <= st->curframe; i++) {
3907                         func = st->frame[i];
3908                         for (j = 0; j < BPF_REG_FP; j++) {
3909                                 reg = &func->regs[j];
3910                                 if (reg->type != SCALAR_VALUE || reg->precise)
3911                                         continue;
3912                                 reg->precise = true;
3913                                 if (env->log.level & BPF_LOG_LEVEL2) {
3914                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3915                                                 i, j);
3916                                 }
3917                         }
3918                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3919                                 if (!is_spilled_reg(&func->stack[j]))
3920                                         continue;
3921                                 reg = &func->stack[j].spilled_ptr;
3922                                 if (reg->type != SCALAR_VALUE || reg->precise)
3923                                         continue;
3924                                 reg->precise = true;
3925                                 if (env->log.level & BPF_LOG_LEVEL2) {
3926                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3927                                                 i, -(j + 1) * 8);
3928                                 }
3929                         }
3930                 }
3931         }
3932 }
3933
3934 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3935 {
3936         struct bpf_func_state *func;
3937         struct bpf_reg_state *reg;
3938         int i, j;
3939
3940         for (i = 0; i <= st->curframe; i++) {
3941                 func = st->frame[i];
3942                 for (j = 0; j < BPF_REG_FP; j++) {
3943                         reg = &func->regs[j];
3944                         if (reg->type != SCALAR_VALUE)
3945                                 continue;
3946                         reg->precise = false;
3947                 }
3948                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3949                         if (!is_spilled_reg(&func->stack[j]))
3950                                 continue;
3951                         reg = &func->stack[j].spilled_ptr;
3952                         if (reg->type != SCALAR_VALUE)
3953                                 continue;
3954                         reg->precise = false;
3955                 }
3956         }
3957 }
3958
3959 static bool idset_contains(struct bpf_idset *s, u32 id)
3960 {
3961         u32 i;
3962
3963         for (i = 0; i < s->count; ++i)
3964                 if (s->ids[i] == id)
3965                         return true;
3966
3967         return false;
3968 }
3969
3970 static int idset_push(struct bpf_idset *s, u32 id)
3971 {
3972         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3973                 return -EFAULT;
3974         s->ids[s->count++] = id;
3975         return 0;
3976 }
3977
3978 static void idset_reset(struct bpf_idset *s)
3979 {
3980         s->count = 0;
3981 }
3982
3983 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3984  * Mark all registers with these IDs as precise.
3985  */
3986 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3987 {
3988         struct bpf_idset *precise_ids = &env->idset_scratch;
3989         struct backtrack_state *bt = &env->bt;
3990         struct bpf_func_state *func;
3991         struct bpf_reg_state *reg;
3992         DECLARE_BITMAP(mask, 64);
3993         int i, fr;
3994
3995         idset_reset(precise_ids);
3996
3997         for (fr = bt->frame; fr >= 0; fr--) {
3998                 func = st->frame[fr];
3999
4000                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4001                 for_each_set_bit(i, mask, 32) {
4002                         reg = &func->regs[i];
4003                         if (!reg->id || reg->type != SCALAR_VALUE)
4004                                 continue;
4005                         if (idset_push(precise_ids, reg->id))
4006                                 return -EFAULT;
4007                 }
4008
4009                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4010                 for_each_set_bit(i, mask, 64) {
4011                         if (i >= func->allocated_stack / BPF_REG_SIZE)
4012                                 break;
4013                         if (!is_spilled_scalar_reg(&func->stack[i]))
4014                                 continue;
4015                         reg = &func->stack[i].spilled_ptr;
4016                         if (!reg->id)
4017                                 continue;
4018                         if (idset_push(precise_ids, reg->id))
4019                                 return -EFAULT;
4020                 }
4021         }
4022
4023         for (fr = 0; fr <= st->curframe; ++fr) {
4024                 func = st->frame[fr];
4025
4026                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4027                         reg = &func->regs[i];
4028                         if (!reg->id)
4029                                 continue;
4030                         if (!idset_contains(precise_ids, reg->id))
4031                                 continue;
4032                         bt_set_frame_reg(bt, fr, i);
4033                 }
4034                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4035                         if (!is_spilled_scalar_reg(&func->stack[i]))
4036                                 continue;
4037                         reg = &func->stack[i].spilled_ptr;
4038                         if (!reg->id)
4039                                 continue;
4040                         if (!idset_contains(precise_ids, reg->id))
4041                                 continue;
4042                         bt_set_frame_slot(bt, fr, i);
4043                 }
4044         }
4045
4046         return 0;
4047 }
4048
4049 /*
4050  * __mark_chain_precision() backtracks BPF program instruction sequence and
4051  * chain of verifier states making sure that register *regno* (if regno >= 0)
4052  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4053  * SCALARS, as well as any other registers and slots that contribute to
4054  * a tracked state of given registers/stack slots, depending on specific BPF
4055  * assembly instructions (see backtrack_insns() for exact instruction handling
4056  * logic). This backtracking relies on recorded jmp_history and is able to
4057  * traverse entire chain of parent states. This process ends only when all the
4058  * necessary registers/slots and their transitive dependencies are marked as
4059  * precise.
4060  *
4061  * One important and subtle aspect is that precise marks *do not matter* in
4062  * the currently verified state (current state). It is important to understand
4063  * why this is the case.
4064  *
4065  * First, note that current state is the state that is not yet "checkpointed",
4066  * i.e., it is not yet put into env->explored_states, and it has no children
4067  * states as well. It's ephemeral, and can end up either a) being discarded if
4068  * compatible explored state is found at some point or BPF_EXIT instruction is
4069  * reached or b) checkpointed and put into env->explored_states, branching out
4070  * into one or more children states.
4071  *
4072  * In the former case, precise markings in current state are completely
4073  * ignored by state comparison code (see regsafe() for details). Only
4074  * checkpointed ("old") state precise markings are important, and if old
4075  * state's register/slot is precise, regsafe() assumes current state's
4076  * register/slot as precise and checks value ranges exactly and precisely. If
4077  * states turn out to be compatible, current state's necessary precise
4078  * markings and any required parent states' precise markings are enforced
4079  * after the fact with propagate_precision() logic, after the fact. But it's
4080  * important to realize that in this case, even after marking current state
4081  * registers/slots as precise, we immediately discard current state. So what
4082  * actually matters is any of the precise markings propagated into current
4083  * state's parent states, which are always checkpointed (due to b) case above).
4084  * As such, for scenario a) it doesn't matter if current state has precise
4085  * markings set or not.
4086  *
4087  * Now, for the scenario b), checkpointing and forking into child(ren)
4088  * state(s). Note that before current state gets to checkpointing step, any
4089  * processed instruction always assumes precise SCALAR register/slot
4090  * knowledge: if precise value or range is useful to prune jump branch, BPF
4091  * verifier takes this opportunity enthusiastically. Similarly, when
4092  * register's value is used to calculate offset or memory address, exact
4093  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4094  * what we mentioned above about state comparison ignoring precise markings
4095  * during state comparison, BPF verifier ignores and also assumes precise
4096  * markings *at will* during instruction verification process. But as verifier
4097  * assumes precision, it also propagates any precision dependencies across
4098  * parent states, which are not yet finalized, so can be further restricted
4099  * based on new knowledge gained from restrictions enforced by their children
4100  * states. This is so that once those parent states are finalized, i.e., when
4101  * they have no more active children state, state comparison logic in
4102  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4103  * required for correctness.
4104  *
4105  * To build a bit more intuition, note also that once a state is checkpointed,
4106  * the path we took to get to that state is not important. This is crucial
4107  * property for state pruning. When state is checkpointed and finalized at
4108  * some instruction index, it can be correctly and safely used to "short
4109  * circuit" any *compatible* state that reaches exactly the same instruction
4110  * index. I.e., if we jumped to that instruction from a completely different
4111  * code path than original finalized state was derived from, it doesn't
4112  * matter, current state can be discarded because from that instruction
4113  * forward having a compatible state will ensure we will safely reach the
4114  * exit. States describe preconditions for further exploration, but completely
4115  * forget the history of how we got here.
4116  *
4117  * This also means that even if we needed precise SCALAR range to get to
4118  * finalized state, but from that point forward *that same* SCALAR register is
4119  * never used in a precise context (i.e., it's precise value is not needed for
4120  * correctness), it's correct and safe to mark such register as "imprecise"
4121  * (i.e., precise marking set to false). This is what we rely on when we do
4122  * not set precise marking in current state. If no child state requires
4123  * precision for any given SCALAR register, it's safe to dictate that it can
4124  * be imprecise. If any child state does require this register to be precise,
4125  * we'll mark it precise later retroactively during precise markings
4126  * propagation from child state to parent states.
4127  *
4128  * Skipping precise marking setting in current state is a mild version of
4129  * relying on the above observation. But we can utilize this property even
4130  * more aggressively by proactively forgetting any precise marking in the
4131  * current state (which we inherited from the parent state), right before we
4132  * checkpoint it and branch off into new child state. This is done by
4133  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4134  * finalized states which help in short circuiting more future states.
4135  */
4136 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4137 {
4138         struct backtrack_state *bt = &env->bt;
4139         struct bpf_verifier_state *st = env->cur_state;
4140         int first_idx = st->first_insn_idx;
4141         int last_idx = env->insn_idx;
4142         int subseq_idx = -1;
4143         struct bpf_func_state *func;
4144         struct bpf_reg_state *reg;
4145         bool skip_first = true;
4146         int i, fr, err;
4147
4148         if (!env->bpf_capable)
4149                 return 0;
4150
4151         /* set frame number from which we are starting to backtrack */
4152         bt_init(bt, env->cur_state->curframe);
4153
4154         /* Do sanity checks against current state of register and/or stack
4155          * slot, but don't set precise flag in current state, as precision
4156          * tracking in the current state is unnecessary.
4157          */
4158         func = st->frame[bt->frame];
4159         if (regno >= 0) {
4160                 reg = &func->regs[regno];
4161                 if (reg->type != SCALAR_VALUE) {
4162                         WARN_ONCE(1, "backtracing misuse");
4163                         return -EFAULT;
4164                 }
4165                 bt_set_reg(bt, regno);
4166         }
4167
4168         if (bt_empty(bt))
4169                 return 0;
4170
4171         for (;;) {
4172                 DECLARE_BITMAP(mask, 64);
4173                 u32 history = st->jmp_history_cnt;
4174                 struct bpf_jmp_history_entry *hist;
4175
4176                 if (env->log.level & BPF_LOG_LEVEL2) {
4177                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4178                                 bt->frame, last_idx, first_idx, subseq_idx);
4179                 }
4180
4181                 /* If some register with scalar ID is marked as precise,
4182                  * make sure that all registers sharing this ID are also precise.
4183                  * This is needed to estimate effect of find_equal_scalars().
4184                  * Do this at the last instruction of each state,
4185                  * bpf_reg_state::id fields are valid for these instructions.
4186                  *
4187                  * Allows to track precision in situation like below:
4188                  *
4189                  *     r2 = unknown value
4190                  *     ...
4191                  *   --- state #0 ---
4192                  *     ...
4193                  *     r1 = r2                 // r1 and r2 now share the same ID
4194                  *     ...
4195                  *   --- state #1 {r1.id = A, r2.id = A} ---
4196                  *     ...
4197                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4198                  *     ...
4199                  *   --- state #2 {r1.id = A, r2.id = A} ---
4200                  *     r3 = r10
4201                  *     r3 += r1                // need to mark both r1 and r2
4202                  */
4203                 if (mark_precise_scalar_ids(env, st))
4204                         return -EFAULT;
4205
4206                 if (last_idx < 0) {
4207                         /* we are at the entry into subprog, which
4208                          * is expected for global funcs, but only if
4209                          * requested precise registers are R1-R5
4210                          * (which are global func's input arguments)
4211                          */
4212                         if (st->curframe == 0 &&
4213                             st->frame[0]->subprogno > 0 &&
4214                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4215                             bt_stack_mask(bt) == 0 &&
4216                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4217                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4218                                 for_each_set_bit(i, mask, 32) {
4219                                         reg = &st->frame[0]->regs[i];
4220                                         bt_clear_reg(bt, i);
4221                                         if (reg->type == SCALAR_VALUE)
4222                                                 reg->precise = true;
4223                                 }
4224                                 return 0;
4225                         }
4226
4227                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4228                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4229                         WARN_ONCE(1, "verifier backtracking bug");
4230                         return -EFAULT;
4231                 }
4232
4233                 for (i = last_idx;;) {
4234                         if (skip_first) {
4235                                 err = 0;
4236                                 skip_first = false;
4237                         } else {
4238                                 hist = get_jmp_hist_entry(st, history, i);
4239                                 err = backtrack_insn(env, i, subseq_idx, hist, bt);
4240                         }
4241                         if (err == -ENOTSUPP) {
4242                                 mark_all_scalars_precise(env, env->cur_state);
4243                                 bt_reset(bt);
4244                                 return 0;
4245                         } else if (err) {
4246                                 return err;
4247                         }
4248                         if (bt_empty(bt))
4249                                 /* Found assignment(s) into tracked register in this state.
4250                                  * Since this state is already marked, just return.
4251                                  * Nothing to be tracked further in the parent state.
4252                                  */
4253                                 return 0;
4254                         subseq_idx = i;
4255                         i = get_prev_insn_idx(st, i, &history);
4256                         if (i == -ENOENT)
4257                                 break;
4258                         if (i >= env->prog->len) {
4259                                 /* This can happen if backtracking reached insn 0
4260                                  * and there are still reg_mask or stack_mask
4261                                  * to backtrack.
4262                                  * It means the backtracking missed the spot where
4263                                  * particular register was initialized with a constant.
4264                                  */
4265                                 verbose(env, "BUG backtracking idx %d\n", i);
4266                                 WARN_ONCE(1, "verifier backtracking bug");
4267                                 return -EFAULT;
4268                         }
4269                 }
4270                 st = st->parent;
4271                 if (!st)
4272                         break;
4273
4274                 for (fr = bt->frame; fr >= 0; fr--) {
4275                         func = st->frame[fr];
4276                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4277                         for_each_set_bit(i, mask, 32) {
4278                                 reg = &func->regs[i];
4279                                 if (reg->type != SCALAR_VALUE) {
4280                                         bt_clear_frame_reg(bt, fr, i);
4281                                         continue;
4282                                 }
4283                                 if (reg->precise)
4284                                         bt_clear_frame_reg(bt, fr, i);
4285                                 else
4286                                         reg->precise = true;
4287                         }
4288
4289                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4290                         for_each_set_bit(i, mask, 64) {
4291                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4292                                         verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4293                                                 i, func->allocated_stack / BPF_REG_SIZE);
4294                                         WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4295                                         return -EFAULT;
4296                                 }
4297
4298                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4299                                         bt_clear_frame_slot(bt, fr, i);
4300                                         continue;
4301                                 }
4302                                 reg = &func->stack[i].spilled_ptr;
4303                                 if (reg->precise)
4304                                         bt_clear_frame_slot(bt, fr, i);
4305                                 else
4306                                         reg->precise = true;
4307                         }
4308                         if (env->log.level & BPF_LOG_LEVEL2) {
4309                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4310                                              bt_frame_reg_mask(bt, fr));
4311                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4312                                         fr, env->tmp_str_buf);
4313                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4314                                                bt_frame_stack_mask(bt, fr));
4315                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4316                                 print_verifier_state(env, func, true);
4317                         }
4318                 }
4319
4320                 if (bt_empty(bt))
4321                         return 0;
4322
4323                 subseq_idx = first_idx;
4324                 last_idx = st->last_insn_idx;
4325                 first_idx = st->first_insn_idx;
4326         }
4327
4328         /* if we still have requested precise regs or slots, we missed
4329          * something (e.g., stack access through non-r10 register), so
4330          * fallback to marking all precise
4331          */
4332         if (!bt_empty(bt)) {
4333                 mark_all_scalars_precise(env, env->cur_state);
4334                 bt_reset(bt);
4335         }
4336
4337         return 0;
4338 }
4339
4340 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4341 {
4342         return __mark_chain_precision(env, regno);
4343 }
4344
4345 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4346  * desired reg and stack masks across all relevant frames
4347  */
4348 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4349 {
4350         return __mark_chain_precision(env, -1);
4351 }
4352
4353 static bool is_spillable_regtype(enum bpf_reg_type type)
4354 {
4355         switch (base_type(type)) {
4356         case PTR_TO_MAP_VALUE:
4357         case PTR_TO_STACK:
4358         case PTR_TO_CTX:
4359         case PTR_TO_PACKET:
4360         case PTR_TO_PACKET_META:
4361         case PTR_TO_PACKET_END:
4362         case PTR_TO_FLOW_KEYS:
4363         case CONST_PTR_TO_MAP:
4364         case PTR_TO_SOCKET:
4365         case PTR_TO_SOCK_COMMON:
4366         case PTR_TO_TCP_SOCK:
4367         case PTR_TO_XDP_SOCK:
4368         case PTR_TO_BTF_ID:
4369         case PTR_TO_BUF:
4370         case PTR_TO_MEM:
4371         case PTR_TO_FUNC:
4372         case PTR_TO_MAP_KEY:
4373                 return true;
4374         default:
4375                 return false;
4376         }
4377 }
4378
4379 /* Does this register contain a constant zero? */
4380 static bool register_is_null(struct bpf_reg_state *reg)
4381 {
4382         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4383 }
4384
4385 /* check if register is a constant scalar value */
4386 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4387 {
4388         return reg->type == SCALAR_VALUE &&
4389                tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4390 }
4391
4392 /* assuming is_reg_const() is true, return constant value of a register */
4393 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4394 {
4395         return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4396 }
4397
4398 static bool __is_pointer_value(bool allow_ptr_leaks,
4399                                const struct bpf_reg_state *reg)
4400 {
4401         if (allow_ptr_leaks)
4402                 return false;
4403
4404         return reg->type != SCALAR_VALUE;
4405 }
4406
4407 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4408                                         struct bpf_reg_state *src_reg)
4409 {
4410         if (src_reg->type == SCALAR_VALUE && !src_reg->id &&
4411             !tnum_is_const(src_reg->var_off))
4412                 /* Ensure that src_reg has a valid ID that will be copied to
4413                  * dst_reg and then will be used by find_equal_scalars() to
4414                  * propagate min/max range.
4415                  */
4416                 src_reg->id = ++env->id_gen;
4417 }
4418
4419 /* Copy src state preserving dst->parent and dst->live fields */
4420 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4421 {
4422         struct bpf_reg_state *parent = dst->parent;
4423         enum bpf_reg_liveness live = dst->live;
4424
4425         *dst = *src;
4426         dst->parent = parent;
4427         dst->live = live;
4428 }
4429
4430 static void save_register_state(struct bpf_verifier_env *env,
4431                                 struct bpf_func_state *state,
4432                                 int spi, struct bpf_reg_state *reg,
4433                                 int size)
4434 {
4435         int i;
4436
4437         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4438         if (size == BPF_REG_SIZE)
4439                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4440
4441         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4442                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4443
4444         /* size < 8 bytes spill */
4445         for (; i; i--)
4446                 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4447 }
4448
4449 static bool is_bpf_st_mem(struct bpf_insn *insn)
4450 {
4451         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4452 }
4453
4454 static int get_reg_width(struct bpf_reg_state *reg)
4455 {
4456         return fls64(reg->umax_value);
4457 }
4458
4459 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4460  * stack boundary and alignment are checked in check_mem_access()
4461  */
4462 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4463                                        /* stack frame we're writing to */
4464                                        struct bpf_func_state *state,
4465                                        int off, int size, int value_regno,
4466                                        int insn_idx)
4467 {
4468         struct bpf_func_state *cur; /* state of the current function */
4469         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4470         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4471         struct bpf_reg_state *reg = NULL;
4472         int insn_flags = insn_stack_access_flags(state->frameno, spi);
4473
4474         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4475          * so it's aligned access and [off, off + size) are within stack limits
4476          */
4477         if (!env->allow_ptr_leaks &&
4478             is_spilled_reg(&state->stack[spi]) &&
4479             size != BPF_REG_SIZE) {
4480                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4481                 return -EACCES;
4482         }
4483
4484         cur = env->cur_state->frame[env->cur_state->curframe];
4485         if (value_regno >= 0)
4486                 reg = &cur->regs[value_regno];
4487         if (!env->bypass_spec_v4) {
4488                 bool sanitize = reg && is_spillable_regtype(reg->type);
4489
4490                 for (i = 0; i < size; i++) {
4491                         u8 type = state->stack[spi].slot_type[i];
4492
4493                         if (type != STACK_MISC && type != STACK_ZERO) {
4494                                 sanitize = true;
4495                                 break;
4496                         }
4497                 }
4498
4499                 if (sanitize)
4500                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4501         }
4502
4503         err = destroy_if_dynptr_stack_slot(env, state, spi);
4504         if (err)
4505                 return err;
4506
4507         mark_stack_slot_scratched(env, spi);
4508         if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4509                 bool reg_value_fits;
4510
4511                 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4512                 /* Make sure that reg had an ID to build a relation on spill. */
4513                 if (reg_value_fits)
4514                         assign_scalar_id_before_mov(env, reg);
4515                 save_register_state(env, state, spi, reg, size);
4516                 /* Break the relation on a narrowing spill. */
4517                 if (!reg_value_fits)
4518                         state->stack[spi].spilled_ptr.id = 0;
4519         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4520                    env->bpf_capable) {
4521                 struct bpf_reg_state fake_reg = {};
4522
4523                 __mark_reg_known(&fake_reg, insn->imm);
4524                 fake_reg.type = SCALAR_VALUE;
4525                 save_register_state(env, state, spi, &fake_reg, size);
4526         } else if (reg && is_spillable_regtype(reg->type)) {
4527                 /* register containing pointer is being spilled into stack */
4528                 if (size != BPF_REG_SIZE) {
4529                         verbose_linfo(env, insn_idx, "; ");
4530                         verbose(env, "invalid size of register spill\n");
4531                         return -EACCES;
4532                 }
4533                 if (state != cur && reg->type == PTR_TO_STACK) {
4534                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4535                         return -EINVAL;
4536                 }
4537                 save_register_state(env, state, spi, reg, size);
4538         } else {
4539                 u8 type = STACK_MISC;
4540
4541                 /* regular write of data into stack destroys any spilled ptr */
4542                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4543                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4544                 if (is_stack_slot_special(&state->stack[spi]))
4545                         for (i = 0; i < BPF_REG_SIZE; i++)
4546                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4547
4548                 /* only mark the slot as written if all 8 bytes were written
4549                  * otherwise read propagation may incorrectly stop too soon
4550                  * when stack slots are partially written.
4551                  * This heuristic means that read propagation will be
4552                  * conservative, since it will add reg_live_read marks
4553                  * to stack slots all the way to first state when programs
4554                  * writes+reads less than 8 bytes
4555                  */
4556                 if (size == BPF_REG_SIZE)
4557                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4558
4559                 /* when we zero initialize stack slots mark them as such */
4560                 if ((reg && register_is_null(reg)) ||
4561                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4562                         /* STACK_ZERO case happened because register spill
4563                          * wasn't properly aligned at the stack slot boundary,
4564                          * so it's not a register spill anymore; force
4565                          * originating register to be precise to make
4566                          * STACK_ZERO correct for subsequent states
4567                          */
4568                         err = mark_chain_precision(env, value_regno);
4569                         if (err)
4570                                 return err;
4571                         type = STACK_ZERO;
4572                 }
4573
4574                 /* Mark slots affected by this stack write. */
4575                 for (i = 0; i < size; i++)
4576                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4577                 insn_flags = 0; /* not a register spill */
4578         }
4579
4580         if (insn_flags)
4581                 return push_jmp_history(env, env->cur_state, insn_flags);
4582         return 0;
4583 }
4584
4585 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4586  * known to contain a variable offset.
4587  * This function checks whether the write is permitted and conservatively
4588  * tracks the effects of the write, considering that each stack slot in the
4589  * dynamic range is potentially written to.
4590  *
4591  * 'off' includes 'regno->off'.
4592  * 'value_regno' can be -1, meaning that an unknown value is being written to
4593  * the stack.
4594  *
4595  * Spilled pointers in range are not marked as written because we don't know
4596  * what's going to be actually written. This means that read propagation for
4597  * future reads cannot be terminated by this write.
4598  *
4599  * For privileged programs, uninitialized stack slots are considered
4600  * initialized by this write (even though we don't know exactly what offsets
4601  * are going to be written to). The idea is that we don't want the verifier to
4602  * reject future reads that access slots written to through variable offsets.
4603  */
4604 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4605                                      /* func where register points to */
4606                                      struct bpf_func_state *state,
4607                                      int ptr_regno, int off, int size,
4608                                      int value_regno, int insn_idx)
4609 {
4610         struct bpf_func_state *cur; /* state of the current function */
4611         int min_off, max_off;
4612         int i, err;
4613         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4614         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4615         bool writing_zero = false;
4616         /* set if the fact that we're writing a zero is used to let any
4617          * stack slots remain STACK_ZERO
4618          */
4619         bool zero_used = false;
4620
4621         cur = env->cur_state->frame[env->cur_state->curframe];
4622         ptr_reg = &cur->regs[ptr_regno];
4623         min_off = ptr_reg->smin_value + off;
4624         max_off = ptr_reg->smax_value + off + size;
4625         if (value_regno >= 0)
4626                 value_reg = &cur->regs[value_regno];
4627         if ((value_reg && register_is_null(value_reg)) ||
4628             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4629                 writing_zero = true;
4630
4631         for (i = min_off; i < max_off; i++) {
4632                 int spi;
4633
4634                 spi = __get_spi(i);
4635                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4636                 if (err)
4637                         return err;
4638         }
4639
4640         /* Variable offset writes destroy any spilled pointers in range. */
4641         for (i = min_off; i < max_off; i++) {
4642                 u8 new_type, *stype;
4643                 int slot, spi;
4644
4645                 slot = -i - 1;
4646                 spi = slot / BPF_REG_SIZE;
4647                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4648                 mark_stack_slot_scratched(env, spi);
4649
4650                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4651                         /* Reject the write if range we may write to has not
4652                          * been initialized beforehand. If we didn't reject
4653                          * here, the ptr status would be erased below (even
4654                          * though not all slots are actually overwritten),
4655                          * possibly opening the door to leaks.
4656                          *
4657                          * We do however catch STACK_INVALID case below, and
4658                          * only allow reading possibly uninitialized memory
4659                          * later for CAP_PERFMON, as the write may not happen to
4660                          * that slot.
4661                          */
4662                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4663                                 insn_idx, i);
4664                         return -EINVAL;
4665                 }
4666
4667                 /* If writing_zero and the spi slot contains a spill of value 0,
4668                  * maintain the spill type.
4669                  */
4670                 if (writing_zero && *stype == STACK_SPILL &&
4671                     is_spilled_scalar_reg(&state->stack[spi])) {
4672                         struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4673
4674                         if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4675                                 zero_used = true;
4676                                 continue;
4677                         }
4678                 }
4679
4680                 /* Erase all other spilled pointers. */
4681                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4682
4683                 /* Update the slot type. */
4684                 new_type = STACK_MISC;
4685                 if (writing_zero && *stype == STACK_ZERO) {
4686                         new_type = STACK_ZERO;
4687                         zero_used = true;
4688                 }
4689                 /* If the slot is STACK_INVALID, we check whether it's OK to
4690                  * pretend that it will be initialized by this write. The slot
4691                  * might not actually be written to, and so if we mark it as
4692                  * initialized future reads might leak uninitialized memory.
4693                  * For privileged programs, we will accept such reads to slots
4694                  * that may or may not be written because, if we're reject
4695                  * them, the error would be too confusing.
4696                  */
4697                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4698                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4699                                         insn_idx, i);
4700                         return -EINVAL;
4701                 }
4702                 *stype = new_type;
4703         }
4704         if (zero_used) {
4705                 /* backtracking doesn't work for STACK_ZERO yet. */
4706                 err = mark_chain_precision(env, value_regno);
4707                 if (err)
4708                         return err;
4709         }
4710         return 0;
4711 }
4712
4713 /* When register 'dst_regno' is assigned some values from stack[min_off,
4714  * max_off), we set the register's type according to the types of the
4715  * respective stack slots. If all the stack values are known to be zeros, then
4716  * so is the destination reg. Otherwise, the register is considered to be
4717  * SCALAR. This function does not deal with register filling; the caller must
4718  * ensure that all spilled registers in the stack range have been marked as
4719  * read.
4720  */
4721 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4722                                 /* func where src register points to */
4723                                 struct bpf_func_state *ptr_state,
4724                                 int min_off, int max_off, int dst_regno)
4725 {
4726         struct bpf_verifier_state *vstate = env->cur_state;
4727         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4728         int i, slot, spi;
4729         u8 *stype;
4730         int zeros = 0;
4731
4732         for (i = min_off; i < max_off; i++) {
4733                 slot = -i - 1;
4734                 spi = slot / BPF_REG_SIZE;
4735                 mark_stack_slot_scratched(env, spi);
4736                 stype = ptr_state->stack[spi].slot_type;
4737                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4738                         break;
4739                 zeros++;
4740         }
4741         if (zeros == max_off - min_off) {
4742                 /* Any access_size read into register is zero extended,
4743                  * so the whole register == const_zero.
4744                  */
4745                 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4746         } else {
4747                 /* have read misc data from the stack */
4748                 mark_reg_unknown(env, state->regs, dst_regno);
4749         }
4750         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4751 }
4752
4753 /* Read the stack at 'off' and put the results into the register indicated by
4754  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4755  * spilled reg.
4756  *
4757  * 'dst_regno' can be -1, meaning that the read value is not going to a
4758  * register.
4759  *
4760  * The access is assumed to be within the current stack bounds.
4761  */
4762 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4763                                       /* func where src register points to */
4764                                       struct bpf_func_state *reg_state,
4765                                       int off, int size, int dst_regno)
4766 {
4767         struct bpf_verifier_state *vstate = env->cur_state;
4768         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4769         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4770         struct bpf_reg_state *reg;
4771         u8 *stype, type;
4772         int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4773
4774         stype = reg_state->stack[spi].slot_type;
4775         reg = &reg_state->stack[spi].spilled_ptr;
4776
4777         mark_stack_slot_scratched(env, spi);
4778
4779         if (is_spilled_reg(&reg_state->stack[spi])) {
4780                 u8 spill_size = 1;
4781
4782                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4783                         spill_size++;
4784
4785                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4786                         if (reg->type != SCALAR_VALUE) {
4787                                 verbose_linfo(env, env->insn_idx, "; ");
4788                                 verbose(env, "invalid size of register fill\n");
4789                                 return -EACCES;
4790                         }
4791
4792                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4793                         if (dst_regno < 0)
4794                                 return 0;
4795
4796                         if (size <= spill_size &&
4797                             bpf_stack_narrow_access_ok(off, size, spill_size)) {
4798                                 /* The earlier check_reg_arg() has decided the
4799                                  * subreg_def for this insn.  Save it first.
4800                                  */
4801                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4802
4803                                 copy_register_state(&state->regs[dst_regno], reg);
4804                                 state->regs[dst_regno].subreg_def = subreg_def;
4805
4806                                 /* Break the relation on a narrowing fill.
4807                                  * coerce_reg_to_size will adjust the boundaries.
4808                                  */
4809                                 if (get_reg_width(reg) > size * BITS_PER_BYTE)
4810                                         state->regs[dst_regno].id = 0;
4811                         } else {
4812                                 int spill_cnt = 0, zero_cnt = 0;
4813
4814                                 for (i = 0; i < size; i++) {
4815                                         type = stype[(slot - i) % BPF_REG_SIZE];
4816                                         if (type == STACK_SPILL) {
4817                                                 spill_cnt++;
4818                                                 continue;
4819                                         }
4820                                         if (type == STACK_MISC)
4821                                                 continue;
4822                                         if (type == STACK_ZERO) {
4823                                                 zero_cnt++;
4824                                                 continue;
4825                                         }
4826                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4827                                                 continue;
4828                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4829                                                 off, i, size);
4830                                         return -EACCES;
4831                                 }
4832
4833                                 if (spill_cnt == size &&
4834                                     tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4835                                         __mark_reg_const_zero(env, &state->regs[dst_regno]);
4836                                         /* this IS register fill, so keep insn_flags */
4837                                 } else if (zero_cnt == size) {
4838                                         /* similarly to mark_reg_stack_read(), preserve zeroes */
4839                                         __mark_reg_const_zero(env, &state->regs[dst_regno]);
4840                                         insn_flags = 0; /* not restoring original register state */
4841                                 } else {
4842                                         mark_reg_unknown(env, state->regs, dst_regno);
4843                                         insn_flags = 0; /* not restoring original register state */
4844                                 }
4845                         }
4846                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4847                 } else if (dst_regno >= 0) {
4848                         /* restore register state from stack */
4849                         copy_register_state(&state->regs[dst_regno], reg);
4850                         /* mark reg as written since spilled pointer state likely
4851                          * has its liveness marks cleared by is_state_visited()
4852                          * which resets stack/reg liveness for state transitions
4853                          */
4854                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4855                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4856                         /* If dst_regno==-1, the caller is asking us whether
4857                          * it is acceptable to use this value as a SCALAR_VALUE
4858                          * (e.g. for XADD).
4859                          * We must not allow unprivileged callers to do that
4860                          * with spilled pointers.
4861                          */
4862                         verbose(env, "leaking pointer from stack off %d\n",
4863                                 off);
4864                         return -EACCES;
4865                 }
4866                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4867         } else {
4868                 for (i = 0; i < size; i++) {
4869                         type = stype[(slot - i) % BPF_REG_SIZE];
4870                         if (type == STACK_MISC)
4871                                 continue;
4872                         if (type == STACK_ZERO)
4873                                 continue;
4874                         if (type == STACK_INVALID && env->allow_uninit_stack)
4875                                 continue;
4876                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4877                                 off, i, size);
4878                         return -EACCES;
4879                 }
4880                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4881                 if (dst_regno >= 0)
4882                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4883                 insn_flags = 0; /* we are not restoring spilled register */
4884         }
4885         if (insn_flags)
4886                 return push_jmp_history(env, env->cur_state, insn_flags);
4887         return 0;
4888 }
4889
4890 enum bpf_access_src {
4891         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4892         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4893 };
4894
4895 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4896                                          int regno, int off, int access_size,
4897                                          bool zero_size_allowed,
4898                                          enum bpf_access_src type,
4899                                          struct bpf_call_arg_meta *meta);
4900
4901 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4902 {
4903         return cur_regs(env) + regno;
4904 }
4905
4906 /* Read the stack at 'ptr_regno + off' and put the result into the register
4907  * 'dst_regno'.
4908  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4909  * but not its variable offset.
4910  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4911  *
4912  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4913  * filling registers (i.e. reads of spilled register cannot be detected when
4914  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4915  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4916  * offset; for a fixed offset check_stack_read_fixed_off should be used
4917  * instead.
4918  */
4919 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4920                                     int ptr_regno, int off, int size, int dst_regno)
4921 {
4922         /* The state of the source register. */
4923         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4924         struct bpf_func_state *ptr_state = func(env, reg);
4925         int err;
4926         int min_off, max_off;
4927
4928         /* Note that we pass a NULL meta, so raw access will not be permitted.
4929          */
4930         err = check_stack_range_initialized(env, ptr_regno, off, size,
4931                                             false, ACCESS_DIRECT, NULL);
4932         if (err)
4933                 return err;
4934
4935         min_off = reg->smin_value + off;
4936         max_off = reg->smax_value + off;
4937         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4938         return 0;
4939 }
4940
4941 /* check_stack_read dispatches to check_stack_read_fixed_off or
4942  * check_stack_read_var_off.
4943  *
4944  * The caller must ensure that the offset falls within the allocated stack
4945  * bounds.
4946  *
4947  * 'dst_regno' is a register which will receive the value from the stack. It
4948  * can be -1, meaning that the read value is not going to a register.
4949  */
4950 static int check_stack_read(struct bpf_verifier_env *env,
4951                             int ptr_regno, int off, int size,
4952                             int dst_regno)
4953 {
4954         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4955         struct bpf_func_state *state = func(env, reg);
4956         int err;
4957         /* Some accesses are only permitted with a static offset. */
4958         bool var_off = !tnum_is_const(reg->var_off);
4959
4960         /* The offset is required to be static when reads don't go to a
4961          * register, in order to not leak pointers (see
4962          * check_stack_read_fixed_off).
4963          */
4964         if (dst_regno < 0 && var_off) {
4965                 char tn_buf[48];
4966
4967                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4968                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4969                         tn_buf, off, size);
4970                 return -EACCES;
4971         }
4972         /* Variable offset is prohibited for unprivileged mode for simplicity
4973          * since it requires corresponding support in Spectre masking for stack
4974          * ALU. See also retrieve_ptr_limit(). The check in
4975          * check_stack_access_for_ptr_arithmetic() called by
4976          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4977          * with variable offsets, therefore no check is required here. Further,
4978          * just checking it here would be insufficient as speculative stack
4979          * writes could still lead to unsafe speculative behaviour.
4980          */
4981         if (!var_off) {
4982                 off += reg->var_off.value;
4983                 err = check_stack_read_fixed_off(env, state, off, size,
4984                                                  dst_regno);
4985         } else {
4986                 /* Variable offset stack reads need more conservative handling
4987                  * than fixed offset ones. Note that dst_regno >= 0 on this
4988                  * branch.
4989                  */
4990                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4991                                                dst_regno);
4992         }
4993         return err;
4994 }
4995
4996
4997 /* check_stack_write dispatches to check_stack_write_fixed_off or
4998  * check_stack_write_var_off.
4999  *
5000  * 'ptr_regno' is the register used as a pointer into the stack.
5001  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5002  * 'value_regno' is the register whose value we're writing to the stack. It can
5003  * be -1, meaning that we're not writing from a register.
5004  *
5005  * The caller must ensure that the offset falls within the maximum stack size.
5006  */
5007 static int check_stack_write(struct bpf_verifier_env *env,
5008                              int ptr_regno, int off, int size,
5009                              int value_regno, int insn_idx)
5010 {
5011         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5012         struct bpf_func_state *state = func(env, reg);
5013         int err;
5014
5015         if (tnum_is_const(reg->var_off)) {
5016                 off += reg->var_off.value;
5017                 err = check_stack_write_fixed_off(env, state, off, size,
5018                                                   value_regno, insn_idx);
5019         } else {
5020                 /* Variable offset stack reads need more conservative handling
5021                  * than fixed offset ones.
5022                  */
5023                 err = check_stack_write_var_off(env, state,
5024                                                 ptr_regno, off, size,
5025                                                 value_regno, insn_idx);
5026         }
5027         return err;
5028 }
5029
5030 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5031                                  int off, int size, enum bpf_access_type type)
5032 {
5033         struct bpf_reg_state *regs = cur_regs(env);
5034         struct bpf_map *map = regs[regno].map_ptr;
5035         u32 cap = bpf_map_flags_to_cap(map);
5036
5037         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5038                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5039                         map->value_size, off, size);
5040                 return -EACCES;
5041         }
5042
5043         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5044                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5045                         map->value_size, off, size);
5046                 return -EACCES;
5047         }
5048
5049         return 0;
5050 }
5051
5052 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5053 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5054                               int off, int size, u32 mem_size,
5055                               bool zero_size_allowed)
5056 {
5057         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5058         struct bpf_reg_state *reg;
5059
5060         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5061                 return 0;
5062
5063         reg = &cur_regs(env)[regno];
5064         switch (reg->type) {
5065         case PTR_TO_MAP_KEY:
5066                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5067                         mem_size, off, size);
5068                 break;
5069         case PTR_TO_MAP_VALUE:
5070                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5071                         mem_size, off, size);
5072                 break;
5073         case PTR_TO_PACKET:
5074         case PTR_TO_PACKET_META:
5075         case PTR_TO_PACKET_END:
5076                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5077                         off, size, regno, reg->id, off, mem_size);
5078                 break;
5079         case PTR_TO_MEM:
5080         default:
5081                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5082                         mem_size, off, size);
5083         }
5084
5085         return -EACCES;
5086 }
5087
5088 /* check read/write into a memory region with possible variable offset */
5089 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5090                                    int off, int size, u32 mem_size,
5091                                    bool zero_size_allowed)
5092 {
5093         struct bpf_verifier_state *vstate = env->cur_state;
5094         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5095         struct bpf_reg_state *reg = &state->regs[regno];
5096         int err;
5097
5098         /* We may have adjusted the register pointing to memory region, so we
5099          * need to try adding each of min_value and max_value to off
5100          * to make sure our theoretical access will be safe.
5101          *
5102          * The minimum value is only important with signed
5103          * comparisons where we can't assume the floor of a
5104          * value is 0.  If we are using signed variables for our
5105          * index'es we need to make sure that whatever we use
5106          * will have a set floor within our range.
5107          */
5108         if (reg->smin_value < 0 &&
5109             (reg->smin_value == S64_MIN ||
5110              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5111               reg->smin_value + off < 0)) {
5112                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5113                         regno);
5114                 return -EACCES;
5115         }
5116         err = __check_mem_access(env, regno, reg->smin_value + off, size,
5117                                  mem_size, zero_size_allowed);
5118         if (err) {
5119                 verbose(env, "R%d min value is outside of the allowed memory range\n",
5120                         regno);
5121                 return err;
5122         }
5123
5124         /* If we haven't set a max value then we need to bail since we can't be
5125          * sure we won't do bad things.
5126          * If reg->umax_value + off could overflow, treat that as unbounded too.
5127          */
5128         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5129                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5130                         regno);
5131                 return -EACCES;
5132         }
5133         err = __check_mem_access(env, regno, reg->umax_value + off, size,
5134                                  mem_size, zero_size_allowed);
5135         if (err) {
5136                 verbose(env, "R%d max value is outside of the allowed memory range\n",
5137                         regno);
5138                 return err;
5139         }
5140
5141         return 0;
5142 }
5143
5144 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5145                                const struct bpf_reg_state *reg, int regno,
5146                                bool fixed_off_ok)
5147 {
5148         /* Access to this pointer-typed register or passing it to a helper
5149          * is only allowed in its original, unmodified form.
5150          */
5151
5152         if (reg->off < 0) {
5153                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5154                         reg_type_str(env, reg->type), regno, reg->off);
5155                 return -EACCES;
5156         }
5157
5158         if (!fixed_off_ok && reg->off) {
5159                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5160                         reg_type_str(env, reg->type), regno, reg->off);
5161                 return -EACCES;
5162         }
5163
5164         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5165                 char tn_buf[48];
5166
5167                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5168                 verbose(env, "variable %s access var_off=%s disallowed\n",
5169                         reg_type_str(env, reg->type), tn_buf);
5170                 return -EACCES;
5171         }
5172
5173         return 0;
5174 }
5175
5176 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5177                              const struct bpf_reg_state *reg, int regno)
5178 {
5179         return __check_ptr_off_reg(env, reg, regno, false);
5180 }
5181
5182 static int map_kptr_match_type(struct bpf_verifier_env *env,
5183                                struct btf_field *kptr_field,
5184                                struct bpf_reg_state *reg, u32 regno)
5185 {
5186         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5187         int perm_flags;
5188         const char *reg_name = "";
5189
5190         if (btf_is_kernel(reg->btf)) {
5191                 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5192
5193                 /* Only unreferenced case accepts untrusted pointers */
5194                 if (kptr_field->type == BPF_KPTR_UNREF)
5195                         perm_flags |= PTR_UNTRUSTED;
5196         } else {
5197                 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5198                 if (kptr_field->type == BPF_KPTR_PERCPU)
5199                         perm_flags |= MEM_PERCPU;
5200         }
5201
5202         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5203                 goto bad_type;
5204
5205         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5206         reg_name = btf_type_name(reg->btf, reg->btf_id);
5207
5208         /* For ref_ptr case, release function check should ensure we get one
5209          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5210          * normal store of unreferenced kptr, we must ensure var_off is zero.
5211          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5212          * reg->off and reg->ref_obj_id are not needed here.
5213          */
5214         if (__check_ptr_off_reg(env, reg, regno, true))
5215                 return -EACCES;
5216
5217         /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5218          * we also need to take into account the reg->off.
5219          *
5220          * We want to support cases like:
5221          *
5222          * struct foo {
5223          *         struct bar br;
5224          *         struct baz bz;
5225          * };
5226          *
5227          * struct foo *v;
5228          * v = func();        // PTR_TO_BTF_ID
5229          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5230          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5231          *                    // first member type of struct after comparison fails
5232          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5233          *                    // to match type
5234          *
5235          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5236          * is zero. We must also ensure that btf_struct_ids_match does not walk
5237          * the struct to match type against first member of struct, i.e. reject
5238          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5239          * strict mode to true for type match.
5240          */
5241         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5242                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5243                                   kptr_field->type != BPF_KPTR_UNREF))
5244                 goto bad_type;
5245         return 0;
5246 bad_type:
5247         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5248                 reg_type_str(env, reg->type), reg_name);
5249         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5250         if (kptr_field->type == BPF_KPTR_UNREF)
5251                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5252                         targ_name);
5253         else
5254                 verbose(env, "\n");
5255         return -EINVAL;
5256 }
5257
5258 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5259  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5260  */
5261 static bool in_rcu_cs(struct bpf_verifier_env *env)
5262 {
5263         return env->cur_state->active_rcu_lock ||
5264                env->cur_state->active_lock.ptr ||
5265                !env->prog->aux->sleepable;
5266 }
5267
5268 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5269 BTF_SET_START(rcu_protected_types)
5270 BTF_ID(struct, prog_test_ref_kfunc)
5271 #ifdef CONFIG_CGROUPS
5272 BTF_ID(struct, cgroup)
5273 #endif
5274 BTF_ID(struct, bpf_cpumask)
5275 BTF_ID(struct, task_struct)
5276 BTF_SET_END(rcu_protected_types)
5277
5278 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5279 {
5280         if (!btf_is_kernel(btf))
5281                 return true;
5282         return btf_id_set_contains(&rcu_protected_types, btf_id);
5283 }
5284
5285 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5286 {
5287         struct btf_struct_meta *meta;
5288
5289         if (btf_is_kernel(kptr_field->kptr.btf))
5290                 return NULL;
5291
5292         meta = btf_find_struct_meta(kptr_field->kptr.btf,
5293                                     kptr_field->kptr.btf_id);
5294
5295         return meta ? meta->record : NULL;
5296 }
5297
5298 static bool rcu_safe_kptr(const struct btf_field *field)
5299 {
5300         const struct btf_field_kptr *kptr = &field->kptr;
5301
5302         return field->type == BPF_KPTR_PERCPU ||
5303                (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5304 }
5305
5306 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5307 {
5308         struct btf_record *rec;
5309         u32 ret;
5310
5311         ret = PTR_MAYBE_NULL;
5312         if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5313                 ret |= MEM_RCU;
5314                 if (kptr_field->type == BPF_KPTR_PERCPU)
5315                         ret |= MEM_PERCPU;
5316                 else if (!btf_is_kernel(kptr_field->kptr.btf))
5317                         ret |= MEM_ALLOC;
5318
5319                 rec = kptr_pointee_btf_record(kptr_field);
5320                 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5321                         ret |= NON_OWN_REF;
5322         } else {
5323                 ret |= PTR_UNTRUSTED;
5324         }
5325
5326         return ret;
5327 }
5328
5329 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5330                                  int value_regno, int insn_idx,
5331                                  struct btf_field *kptr_field)
5332 {
5333         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5334         int class = BPF_CLASS(insn->code);
5335         struct bpf_reg_state *val_reg;
5336
5337         /* Things we already checked for in check_map_access and caller:
5338          *  - Reject cases where variable offset may touch kptr
5339          *  - size of access (must be BPF_DW)
5340          *  - tnum_is_const(reg->var_off)
5341          *  - kptr_field->offset == off + reg->var_off.value
5342          */
5343         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5344         if (BPF_MODE(insn->code) != BPF_MEM) {
5345                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5346                 return -EACCES;
5347         }
5348
5349         /* We only allow loading referenced kptr, since it will be marked as
5350          * untrusted, similar to unreferenced kptr.
5351          */
5352         if (class != BPF_LDX &&
5353             (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5354                 verbose(env, "store to referenced kptr disallowed\n");
5355                 return -EACCES;
5356         }
5357
5358         if (class == BPF_LDX) {
5359                 val_reg = reg_state(env, value_regno);
5360                 /* We can simply mark the value_regno receiving the pointer
5361                  * value from map as PTR_TO_BTF_ID, with the correct type.
5362                  */
5363                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5364                                 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5365                 /* For mark_ptr_or_null_reg */
5366                 val_reg->id = ++env->id_gen;
5367         } else if (class == BPF_STX) {
5368                 val_reg = reg_state(env, value_regno);
5369                 if (!register_is_null(val_reg) &&
5370                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5371                         return -EACCES;
5372         } else if (class == BPF_ST) {
5373                 if (insn->imm) {
5374                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5375                                 kptr_field->offset);
5376                         return -EACCES;
5377                 }
5378         } else {
5379                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5380                 return -EACCES;
5381         }
5382         return 0;
5383 }
5384
5385 /* check read/write into a map element with possible variable offset */
5386 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5387                             int off, int size, bool zero_size_allowed,
5388                             enum bpf_access_src src)
5389 {
5390         struct bpf_verifier_state *vstate = env->cur_state;
5391         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5392         struct bpf_reg_state *reg = &state->regs[regno];
5393         struct bpf_map *map = reg->map_ptr;
5394         struct btf_record *rec;
5395         int err, i;
5396
5397         err = check_mem_region_access(env, regno, off, size, map->value_size,
5398                                       zero_size_allowed);
5399         if (err)
5400                 return err;
5401
5402         if (IS_ERR_OR_NULL(map->record))
5403                 return 0;
5404         rec = map->record;
5405         for (i = 0; i < rec->cnt; i++) {
5406                 struct btf_field *field = &rec->fields[i];
5407                 u32 p = field->offset;
5408
5409                 /* If any part of a field  can be touched by load/store, reject
5410                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5411                  * it is sufficient to check x1 < y2 && y1 < x2.
5412                  */
5413                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5414                     p < reg->umax_value + off + size) {
5415                         switch (field->type) {
5416                         case BPF_KPTR_UNREF:
5417                         case BPF_KPTR_REF:
5418                         case BPF_KPTR_PERCPU:
5419                                 if (src != ACCESS_DIRECT) {
5420                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5421                                         return -EACCES;
5422                                 }
5423                                 if (!tnum_is_const(reg->var_off)) {
5424                                         verbose(env, "kptr access cannot have variable offset\n");
5425                                         return -EACCES;
5426                                 }
5427                                 if (p != off + reg->var_off.value) {
5428                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5429                                                 p, off + reg->var_off.value);
5430                                         return -EACCES;
5431                                 }
5432                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5433                                         verbose(env, "kptr access size must be BPF_DW\n");
5434                                         return -EACCES;
5435                                 }
5436                                 break;
5437                         default:
5438                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5439                                         btf_field_type_name(field->type));
5440                                 return -EACCES;
5441                         }
5442                 }
5443         }
5444         return 0;
5445 }
5446
5447 #define MAX_PACKET_OFF 0xffff
5448
5449 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5450                                        const struct bpf_call_arg_meta *meta,
5451                                        enum bpf_access_type t)
5452 {
5453         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5454
5455         switch (prog_type) {
5456         /* Program types only with direct read access go here! */
5457         case BPF_PROG_TYPE_LWT_IN:
5458         case BPF_PROG_TYPE_LWT_OUT:
5459         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5460         case BPF_PROG_TYPE_SK_REUSEPORT:
5461         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5462         case BPF_PROG_TYPE_CGROUP_SKB:
5463                 if (t == BPF_WRITE)
5464                         return false;
5465                 fallthrough;
5466
5467         /* Program types with direct read + write access go here! */
5468         case BPF_PROG_TYPE_SCHED_CLS:
5469         case BPF_PROG_TYPE_SCHED_ACT:
5470         case BPF_PROG_TYPE_XDP:
5471         case BPF_PROG_TYPE_LWT_XMIT:
5472         case BPF_PROG_TYPE_SK_SKB:
5473         case BPF_PROG_TYPE_SK_MSG:
5474                 if (meta)
5475                         return meta->pkt_access;
5476
5477                 env->seen_direct_write = true;
5478                 return true;
5479
5480         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5481                 if (t == BPF_WRITE)
5482                         env->seen_direct_write = true;
5483
5484                 return true;
5485
5486         default:
5487                 return false;
5488         }
5489 }
5490
5491 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5492                                int size, bool zero_size_allowed)
5493 {
5494         struct bpf_reg_state *regs = cur_regs(env);
5495         struct bpf_reg_state *reg = &regs[regno];
5496         int err;
5497
5498         /* We may have added a variable offset to the packet pointer; but any
5499          * reg->range we have comes after that.  We are only checking the fixed
5500          * offset.
5501          */
5502
5503         /* We don't allow negative numbers, because we aren't tracking enough
5504          * detail to prove they're safe.
5505          */
5506         if (reg->smin_value < 0) {
5507                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5508                         regno);
5509                 return -EACCES;
5510         }
5511
5512         err = reg->range < 0 ? -EINVAL :
5513               __check_mem_access(env, regno, off, size, reg->range,
5514                                  zero_size_allowed);
5515         if (err) {
5516                 verbose(env, "R%d offset is outside of the packet\n", regno);
5517                 return err;
5518         }
5519
5520         /* __check_mem_access has made sure "off + size - 1" is within u16.
5521          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5522          * otherwise find_good_pkt_pointers would have refused to set range info
5523          * that __check_mem_access would have rejected this pkt access.
5524          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5525          */
5526         env->prog->aux->max_pkt_offset =
5527                 max_t(u32, env->prog->aux->max_pkt_offset,
5528                       off + reg->umax_value + size - 1);
5529
5530         return err;
5531 }
5532
5533 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5534 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5535                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5536                             struct btf **btf, u32 *btf_id)
5537 {
5538         struct bpf_insn_access_aux info = {
5539                 .reg_type = *reg_type,
5540                 .log = &env->log,
5541         };
5542
5543         if (env->ops->is_valid_access &&
5544             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5545                 /* A non zero info.ctx_field_size indicates that this field is a
5546                  * candidate for later verifier transformation to load the whole
5547                  * field and then apply a mask when accessed with a narrower
5548                  * access than actual ctx access size. A zero info.ctx_field_size
5549                  * will only allow for whole field access and rejects any other
5550                  * type of narrower access.
5551                  */
5552                 *reg_type = info.reg_type;
5553
5554                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5555                         *btf = info.btf;
5556                         *btf_id = info.btf_id;
5557                 } else {
5558                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5559                 }
5560                 /* remember the offset of last byte accessed in ctx */
5561                 if (env->prog->aux->max_ctx_offset < off + size)
5562                         env->prog->aux->max_ctx_offset = off + size;
5563                 return 0;
5564         }
5565
5566         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5567         return -EACCES;
5568 }
5569
5570 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5571                                   int size)
5572 {
5573         if (size < 0 || off < 0 ||
5574             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5575                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5576                         off, size);
5577                 return -EACCES;
5578         }
5579         return 0;
5580 }
5581
5582 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5583                              u32 regno, int off, int size,
5584                              enum bpf_access_type t)
5585 {
5586         struct bpf_reg_state *regs = cur_regs(env);
5587         struct bpf_reg_state *reg = &regs[regno];
5588         struct bpf_insn_access_aux info = {};
5589         bool valid;
5590
5591         if (reg->smin_value < 0) {
5592                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5593                         regno);
5594                 return -EACCES;
5595         }
5596
5597         switch (reg->type) {
5598         case PTR_TO_SOCK_COMMON:
5599                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5600                 break;
5601         case PTR_TO_SOCKET:
5602                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5603                 break;
5604         case PTR_TO_TCP_SOCK:
5605                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5606                 break;
5607         case PTR_TO_XDP_SOCK:
5608                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5609                 break;
5610         default:
5611                 valid = false;
5612         }
5613
5614
5615         if (valid) {
5616                 env->insn_aux_data[insn_idx].ctx_field_size =
5617                         info.ctx_field_size;
5618                 return 0;
5619         }
5620
5621         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5622                 regno, reg_type_str(env, reg->type), off, size);
5623
5624         return -EACCES;
5625 }
5626
5627 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5628 {
5629         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5630 }
5631
5632 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5633 {
5634         const struct bpf_reg_state *reg = reg_state(env, regno);
5635
5636         return reg->type == PTR_TO_CTX;
5637 }
5638
5639 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5640 {
5641         const struct bpf_reg_state *reg = reg_state(env, regno);
5642
5643         return type_is_sk_pointer(reg->type);
5644 }
5645
5646 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5647 {
5648         const struct bpf_reg_state *reg = reg_state(env, regno);
5649
5650         return type_is_pkt_pointer(reg->type);
5651 }
5652
5653 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5654 {
5655         const struct bpf_reg_state *reg = reg_state(env, regno);
5656
5657         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5658         return reg->type == PTR_TO_FLOW_KEYS;
5659 }
5660
5661 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5662 #ifdef CONFIG_NET
5663         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5664         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5665         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5666 #endif
5667         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5668 };
5669
5670 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5671 {
5672         /* A referenced register is always trusted. */
5673         if (reg->ref_obj_id)
5674                 return true;
5675
5676         /* Types listed in the reg2btf_ids are always trusted */
5677         if (reg2btf_ids[base_type(reg->type)])
5678                 return true;
5679
5680         /* If a register is not referenced, it is trusted if it has the
5681          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5682          * other type modifiers may be safe, but we elect to take an opt-in
5683          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5684          * not.
5685          *
5686          * Eventually, we should make PTR_TRUSTED the single source of truth
5687          * for whether a register is trusted.
5688          */
5689         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5690                !bpf_type_has_unsafe_modifiers(reg->type);
5691 }
5692
5693 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5694 {
5695         return reg->type & MEM_RCU;
5696 }
5697
5698 static void clear_trusted_flags(enum bpf_type_flag *flag)
5699 {
5700         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5701 }
5702
5703 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5704                                    const struct bpf_reg_state *reg,
5705                                    int off, int size, bool strict)
5706 {
5707         struct tnum reg_off;
5708         int ip_align;
5709
5710         /* Byte size accesses are always allowed. */
5711         if (!strict || size == 1)
5712                 return 0;
5713
5714         /* For platforms that do not have a Kconfig enabling
5715          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5716          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5717          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5718          * to this code only in strict mode where we want to emulate
5719          * the NET_IP_ALIGN==2 checking.  Therefore use an
5720          * unconditional IP align value of '2'.
5721          */
5722         ip_align = 2;
5723
5724         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5725         if (!tnum_is_aligned(reg_off, size)) {
5726                 char tn_buf[48];
5727
5728                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5729                 verbose(env,
5730                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5731                         ip_align, tn_buf, reg->off, off, size);
5732                 return -EACCES;
5733         }
5734
5735         return 0;
5736 }
5737
5738 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5739                                        const struct bpf_reg_state *reg,
5740                                        const char *pointer_desc,
5741                                        int off, int size, bool strict)
5742 {
5743         struct tnum reg_off;
5744
5745         /* Byte size accesses are always allowed. */
5746         if (!strict || size == 1)
5747                 return 0;
5748
5749         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5750         if (!tnum_is_aligned(reg_off, size)) {
5751                 char tn_buf[48];
5752
5753                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5754                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5755                         pointer_desc, tn_buf, reg->off, off, size);
5756                 return -EACCES;
5757         }
5758
5759         return 0;
5760 }
5761
5762 static int check_ptr_alignment(struct bpf_verifier_env *env,
5763                                const struct bpf_reg_state *reg, int off,
5764                                int size, bool strict_alignment_once)
5765 {
5766         bool strict = env->strict_alignment || strict_alignment_once;
5767         const char *pointer_desc = "";
5768
5769         switch (reg->type) {
5770         case PTR_TO_PACKET:
5771         case PTR_TO_PACKET_META:
5772                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5773                  * right in front, treat it the very same way.
5774                  */
5775                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5776         case PTR_TO_FLOW_KEYS:
5777                 pointer_desc = "flow keys ";
5778                 break;
5779         case PTR_TO_MAP_KEY:
5780                 pointer_desc = "key ";
5781                 break;
5782         case PTR_TO_MAP_VALUE:
5783                 pointer_desc = "value ";
5784                 break;
5785         case PTR_TO_CTX:
5786                 pointer_desc = "context ";
5787                 break;
5788         case PTR_TO_STACK:
5789                 pointer_desc = "stack ";
5790                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5791                  * and check_stack_read_fixed_off() relies on stack accesses being
5792                  * aligned.
5793                  */
5794                 strict = true;
5795                 break;
5796         case PTR_TO_SOCKET:
5797                 pointer_desc = "sock ";
5798                 break;
5799         case PTR_TO_SOCK_COMMON:
5800                 pointer_desc = "sock_common ";
5801                 break;
5802         case PTR_TO_TCP_SOCK:
5803                 pointer_desc = "tcp_sock ";
5804                 break;
5805         case PTR_TO_XDP_SOCK:
5806                 pointer_desc = "xdp_sock ";
5807                 break;
5808         default:
5809                 break;
5810         }
5811         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5812                                            strict);
5813 }
5814
5815 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5816 {
5817         if (env->prog->jit_requested)
5818                 return round_up(stack_depth, 16);
5819
5820         /* round up to 32-bytes, since this is granularity
5821          * of interpreter stack size
5822          */
5823         return round_up(max_t(u32, stack_depth, 1), 32);
5824 }
5825
5826 /* starting from main bpf function walk all instructions of the function
5827  * and recursively walk all callees that given function can call.
5828  * Ignore jump and exit insns.
5829  * Since recursion is prevented by check_cfg() this algorithm
5830  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5831  */
5832 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5833 {
5834         struct bpf_subprog_info *subprog = env->subprog_info;
5835         struct bpf_insn *insn = env->prog->insnsi;
5836         int depth = 0, frame = 0, i, subprog_end;
5837         bool tail_call_reachable = false;
5838         int ret_insn[MAX_CALL_FRAMES];
5839         int ret_prog[MAX_CALL_FRAMES];
5840         int j;
5841
5842         i = subprog[idx].start;
5843 process_func:
5844         /* protect against potential stack overflow that might happen when
5845          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5846          * depth for such case down to 256 so that the worst case scenario
5847          * would result in 8k stack size (32 which is tailcall limit * 256 =
5848          * 8k).
5849          *
5850          * To get the idea what might happen, see an example:
5851          * func1 -> sub rsp, 128
5852          *  subfunc1 -> sub rsp, 256
5853          *  tailcall1 -> add rsp, 256
5854          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5855          *   subfunc2 -> sub rsp, 64
5856          *   subfunc22 -> sub rsp, 128
5857          *   tailcall2 -> add rsp, 128
5858          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5859          *
5860          * tailcall will unwind the current stack frame but it will not get rid
5861          * of caller's stack as shown on the example above.
5862          */
5863         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5864                 verbose(env,
5865                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5866                         depth);
5867                 return -EACCES;
5868         }
5869         depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5870         if (depth > MAX_BPF_STACK) {
5871                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5872                         frame + 1, depth);
5873                 return -EACCES;
5874         }
5875 continue_func:
5876         subprog_end = subprog[idx + 1].start;
5877         for (; i < subprog_end; i++) {
5878                 int next_insn, sidx;
5879
5880                 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5881                         bool err = false;
5882
5883                         if (!is_bpf_throw_kfunc(insn + i))
5884                                 continue;
5885                         if (subprog[idx].is_cb)
5886                                 err = true;
5887                         for (int c = 0; c < frame && !err; c++) {
5888                                 if (subprog[ret_prog[c]].is_cb) {
5889                                         err = true;
5890                                         break;
5891                                 }
5892                         }
5893                         if (!err)
5894                                 continue;
5895                         verbose(env,
5896                                 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5897                                 i, idx);
5898                         return -EINVAL;
5899                 }
5900
5901                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5902                         continue;
5903                 /* remember insn and function to return to */
5904                 ret_insn[frame] = i + 1;
5905                 ret_prog[frame] = idx;
5906
5907                 /* find the callee */
5908                 next_insn = i + insn[i].imm + 1;
5909                 sidx = find_subprog(env, next_insn);
5910                 if (sidx < 0) {
5911                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5912                                   next_insn);
5913                         return -EFAULT;
5914                 }
5915                 if (subprog[sidx].is_async_cb) {
5916                         if (subprog[sidx].has_tail_call) {
5917                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5918                                 return -EFAULT;
5919                         }
5920                         /* async callbacks don't increase bpf prog stack size unless called directly */
5921                         if (!bpf_pseudo_call(insn + i))
5922                                 continue;
5923                         if (subprog[sidx].is_exception_cb) {
5924                                 verbose(env, "insn %d cannot call exception cb directly\n", i);
5925                                 return -EINVAL;
5926                         }
5927                 }
5928                 i = next_insn;
5929                 idx = sidx;
5930
5931                 if (subprog[idx].has_tail_call)
5932                         tail_call_reachable = true;
5933
5934                 frame++;
5935                 if (frame >= MAX_CALL_FRAMES) {
5936                         verbose(env, "the call stack of %d frames is too deep !\n",
5937                                 frame);
5938                         return -E2BIG;
5939                 }
5940                 goto process_func;
5941         }
5942         /* if tail call got detected across bpf2bpf calls then mark each of the
5943          * currently present subprog frames as tail call reachable subprogs;
5944          * this info will be utilized by JIT so that we will be preserving the
5945          * tail call counter throughout bpf2bpf calls combined with tailcalls
5946          */
5947         if (tail_call_reachable)
5948                 for (j = 0; j < frame; j++) {
5949                         if (subprog[ret_prog[j]].is_exception_cb) {
5950                                 verbose(env, "cannot tail call within exception cb\n");
5951                                 return -EINVAL;
5952                         }
5953                         subprog[ret_prog[j]].tail_call_reachable = true;
5954                 }
5955         if (subprog[0].tail_call_reachable)
5956                 env->prog->aux->tail_call_reachable = true;
5957
5958         /* end of for() loop means the last insn of the 'subprog'
5959          * was reached. Doesn't matter whether it was JA or EXIT
5960          */
5961         if (frame == 0)
5962                 return 0;
5963         depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5964         frame--;
5965         i = ret_insn[frame];
5966         idx = ret_prog[frame];
5967         goto continue_func;
5968 }
5969
5970 static int check_max_stack_depth(struct bpf_verifier_env *env)
5971 {
5972         struct bpf_subprog_info *si = env->subprog_info;
5973         int ret;
5974
5975         for (int i = 0; i < env->subprog_cnt; i++) {
5976                 if (!i || si[i].is_async_cb) {
5977                         ret = check_max_stack_depth_subprog(env, i);
5978                         if (ret < 0)
5979                                 return ret;
5980                 }
5981                 continue;
5982         }
5983         return 0;
5984 }
5985
5986 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5987 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5988                                   const struct bpf_insn *insn, int idx)
5989 {
5990         int start = idx + insn->imm + 1, subprog;
5991
5992         subprog = find_subprog(env, start);
5993         if (subprog < 0) {
5994                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5995                           start);
5996                 return -EFAULT;
5997         }
5998         return env->subprog_info[subprog].stack_depth;
5999 }
6000 #endif
6001
6002 static int __check_buffer_access(struct bpf_verifier_env *env,
6003                                  const char *buf_info,
6004                                  const struct bpf_reg_state *reg,
6005                                  int regno, int off, int size)
6006 {
6007         if (off < 0) {
6008                 verbose(env,
6009                         "R%d invalid %s buffer access: off=%d, size=%d\n",
6010                         regno, buf_info, off, size);
6011                 return -EACCES;
6012         }
6013         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6014                 char tn_buf[48];
6015
6016                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6017                 verbose(env,
6018                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6019                         regno, off, tn_buf);
6020                 return -EACCES;
6021         }
6022
6023         return 0;
6024 }
6025
6026 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6027                                   const struct bpf_reg_state *reg,
6028                                   int regno, int off, int size)
6029 {
6030         int err;
6031
6032         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6033         if (err)
6034                 return err;
6035
6036         if (off + size > env->prog->aux->max_tp_access)
6037                 env->prog->aux->max_tp_access = off + size;
6038
6039         return 0;
6040 }
6041
6042 static int check_buffer_access(struct bpf_verifier_env *env,
6043                                const struct bpf_reg_state *reg,
6044                                int regno, int off, int size,
6045                                bool zero_size_allowed,
6046                                u32 *max_access)
6047 {
6048         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6049         int err;
6050
6051         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6052         if (err)
6053                 return err;
6054
6055         if (off + size > *max_access)
6056                 *max_access = off + size;
6057
6058         return 0;
6059 }
6060
6061 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6062 static void zext_32_to_64(struct bpf_reg_state *reg)
6063 {
6064         reg->var_off = tnum_subreg(reg->var_off);
6065         __reg_assign_32_into_64(reg);
6066 }
6067
6068 /* truncate register to smaller size (in bytes)
6069  * must be called with size < BPF_REG_SIZE
6070  */
6071 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6072 {
6073         u64 mask;
6074
6075         /* clear high bits in bit representation */
6076         reg->var_off = tnum_cast(reg->var_off, size);
6077
6078         /* fix arithmetic bounds */
6079         mask = ((u64)1 << (size * 8)) - 1;
6080         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6081                 reg->umin_value &= mask;
6082                 reg->umax_value &= mask;
6083         } else {
6084                 reg->umin_value = 0;
6085                 reg->umax_value = mask;
6086         }
6087         reg->smin_value = reg->umin_value;
6088         reg->smax_value = reg->umax_value;
6089
6090         /* If size is smaller than 32bit register the 32bit register
6091          * values are also truncated so we push 64-bit bounds into
6092          * 32-bit bounds. Above were truncated < 32-bits already.
6093          */
6094         if (size < 4)
6095                 __mark_reg32_unbounded(reg);
6096
6097         reg_bounds_sync(reg);
6098 }
6099
6100 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6101 {
6102         if (size == 1) {
6103                 reg->smin_value = reg->s32_min_value = S8_MIN;
6104                 reg->smax_value = reg->s32_max_value = S8_MAX;
6105         } else if (size == 2) {
6106                 reg->smin_value = reg->s32_min_value = S16_MIN;
6107                 reg->smax_value = reg->s32_max_value = S16_MAX;
6108         } else {
6109                 /* size == 4 */
6110                 reg->smin_value = reg->s32_min_value = S32_MIN;
6111                 reg->smax_value = reg->s32_max_value = S32_MAX;
6112         }
6113         reg->umin_value = reg->u32_min_value = 0;
6114         reg->umax_value = U64_MAX;
6115         reg->u32_max_value = U32_MAX;
6116         reg->var_off = tnum_unknown;
6117 }
6118
6119 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6120 {
6121         s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6122         u64 top_smax_value, top_smin_value;
6123         u64 num_bits = size * 8;
6124
6125         if (tnum_is_const(reg->var_off)) {
6126                 u64_cval = reg->var_off.value;
6127                 if (size == 1)
6128                         reg->var_off = tnum_const((s8)u64_cval);
6129                 else if (size == 2)
6130                         reg->var_off = tnum_const((s16)u64_cval);
6131                 else
6132                         /* size == 4 */
6133                         reg->var_off = tnum_const((s32)u64_cval);
6134
6135                 u64_cval = reg->var_off.value;
6136                 reg->smax_value = reg->smin_value = u64_cval;
6137                 reg->umax_value = reg->umin_value = u64_cval;
6138                 reg->s32_max_value = reg->s32_min_value = u64_cval;
6139                 reg->u32_max_value = reg->u32_min_value = u64_cval;
6140                 return;
6141         }
6142
6143         top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6144         top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6145
6146         if (top_smax_value != top_smin_value)
6147                 goto out;
6148
6149         /* find the s64_min and s64_min after sign extension */
6150         if (size == 1) {
6151                 init_s64_max = (s8)reg->smax_value;
6152                 init_s64_min = (s8)reg->smin_value;
6153         } else if (size == 2) {
6154                 init_s64_max = (s16)reg->smax_value;
6155                 init_s64_min = (s16)reg->smin_value;
6156         } else {
6157                 init_s64_max = (s32)reg->smax_value;
6158                 init_s64_min = (s32)reg->smin_value;
6159         }
6160
6161         s64_max = max(init_s64_max, init_s64_min);
6162         s64_min = min(init_s64_max, init_s64_min);
6163
6164         /* both of s64_max/s64_min positive or negative */
6165         if ((s64_max >= 0) == (s64_min >= 0)) {
6166                 reg->smin_value = reg->s32_min_value = s64_min;
6167                 reg->smax_value = reg->s32_max_value = s64_max;
6168                 reg->umin_value = reg->u32_min_value = s64_min;
6169                 reg->umax_value = reg->u32_max_value = s64_max;
6170                 reg->var_off = tnum_range(s64_min, s64_max);
6171                 return;
6172         }
6173
6174 out:
6175         set_sext64_default_val(reg, size);
6176 }
6177
6178 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6179 {
6180         if (size == 1) {
6181                 reg->s32_min_value = S8_MIN;
6182                 reg->s32_max_value = S8_MAX;
6183         } else {
6184                 /* size == 2 */
6185                 reg->s32_min_value = S16_MIN;
6186                 reg->s32_max_value = S16_MAX;
6187         }
6188         reg->u32_min_value = 0;
6189         reg->u32_max_value = U32_MAX;
6190 }
6191
6192 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6193 {
6194         s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6195         u32 top_smax_value, top_smin_value;
6196         u32 num_bits = size * 8;
6197
6198         if (tnum_is_const(reg->var_off)) {
6199                 u32_val = reg->var_off.value;
6200                 if (size == 1)
6201                         reg->var_off = tnum_const((s8)u32_val);
6202                 else
6203                         reg->var_off = tnum_const((s16)u32_val);
6204
6205                 u32_val = reg->var_off.value;
6206                 reg->s32_min_value = reg->s32_max_value = u32_val;
6207                 reg->u32_min_value = reg->u32_max_value = u32_val;
6208                 return;
6209         }
6210
6211         top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6212         top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6213
6214         if (top_smax_value != top_smin_value)
6215                 goto out;
6216
6217         /* find the s32_min and s32_min after sign extension */
6218         if (size == 1) {
6219                 init_s32_max = (s8)reg->s32_max_value;
6220                 init_s32_min = (s8)reg->s32_min_value;
6221         } else {
6222                 /* size == 2 */
6223                 init_s32_max = (s16)reg->s32_max_value;
6224                 init_s32_min = (s16)reg->s32_min_value;
6225         }
6226         s32_max = max(init_s32_max, init_s32_min);
6227         s32_min = min(init_s32_max, init_s32_min);
6228
6229         if ((s32_min >= 0) == (s32_max >= 0)) {
6230                 reg->s32_min_value = s32_min;
6231                 reg->s32_max_value = s32_max;
6232                 reg->u32_min_value = (u32)s32_min;
6233                 reg->u32_max_value = (u32)s32_max;
6234                 return;
6235         }
6236
6237 out:
6238         set_sext32_default_val(reg, size);
6239 }
6240
6241 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6242 {
6243         /* A map is considered read-only if the following condition are true:
6244          *
6245          * 1) BPF program side cannot change any of the map content. The
6246          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6247          *    and was set at map creation time.
6248          * 2) The map value(s) have been initialized from user space by a
6249          *    loader and then "frozen", such that no new map update/delete
6250          *    operations from syscall side are possible for the rest of
6251          *    the map's lifetime from that point onwards.
6252          * 3) Any parallel/pending map update/delete operations from syscall
6253          *    side have been completed. Only after that point, it's safe to
6254          *    assume that map value(s) are immutable.
6255          */
6256         return (map->map_flags & BPF_F_RDONLY_PROG) &&
6257                READ_ONCE(map->frozen) &&
6258                !bpf_map_write_active(map);
6259 }
6260
6261 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6262                                bool is_ldsx)
6263 {
6264         void *ptr;
6265         u64 addr;
6266         int err;
6267
6268         err = map->ops->map_direct_value_addr(map, &addr, off);
6269         if (err)
6270                 return err;
6271         ptr = (void *)(long)addr + off;
6272
6273         switch (size) {
6274         case sizeof(u8):
6275                 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6276                 break;
6277         case sizeof(u16):
6278                 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6279                 break;
6280         case sizeof(u32):
6281                 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6282                 break;
6283         case sizeof(u64):
6284                 *val = *(u64 *)ptr;
6285                 break;
6286         default:
6287                 return -EINVAL;
6288         }
6289         return 0;
6290 }
6291
6292 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6293 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6294 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6295
6296 /*
6297  * Allow list few fields as RCU trusted or full trusted.
6298  * This logic doesn't allow mix tagging and will be removed once GCC supports
6299  * btf_type_tag.
6300  */
6301
6302 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6303 BTF_TYPE_SAFE_RCU(struct task_struct) {
6304         const cpumask_t *cpus_ptr;
6305         struct css_set __rcu *cgroups;
6306         struct task_struct __rcu *real_parent;
6307         struct task_struct *group_leader;
6308 };
6309
6310 BTF_TYPE_SAFE_RCU(struct cgroup) {
6311         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6312         struct kernfs_node *kn;
6313 };
6314
6315 BTF_TYPE_SAFE_RCU(struct css_set) {
6316         struct cgroup *dfl_cgrp;
6317 };
6318
6319 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6320 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6321         struct file __rcu *exe_file;
6322 };
6323
6324 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6325  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6326  */
6327 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6328         struct sock *sk;
6329 };
6330
6331 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6332         struct sock *sk;
6333 };
6334
6335 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6336 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6337         struct seq_file *seq;
6338 };
6339
6340 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6341         struct bpf_iter_meta *meta;
6342         struct task_struct *task;
6343 };
6344
6345 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6346         struct file *file;
6347 };
6348
6349 BTF_TYPE_SAFE_TRUSTED(struct file) {
6350         struct inode *f_inode;
6351 };
6352
6353 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6354         /* no negative dentry-s in places where bpf can see it */
6355         struct inode *d_inode;
6356 };
6357
6358 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6359         struct sock *sk;
6360 };
6361
6362 static bool type_is_rcu(struct bpf_verifier_env *env,
6363                         struct bpf_reg_state *reg,
6364                         const char *field_name, u32 btf_id)
6365 {
6366         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6367         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6368         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6369
6370         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6371 }
6372
6373 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6374                                 struct bpf_reg_state *reg,
6375                                 const char *field_name, u32 btf_id)
6376 {
6377         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6378         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6379         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6380
6381         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6382 }
6383
6384 static bool type_is_trusted(struct bpf_verifier_env *env,
6385                             struct bpf_reg_state *reg,
6386                             const char *field_name, u32 btf_id)
6387 {
6388         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6389         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6390         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6391         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6392         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6393         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6394
6395         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6396 }
6397
6398 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6399                                    struct bpf_reg_state *regs,
6400                                    int regno, int off, int size,
6401                                    enum bpf_access_type atype,
6402                                    int value_regno)
6403 {
6404         struct bpf_reg_state *reg = regs + regno;
6405         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6406         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6407         const char *field_name = NULL;
6408         enum bpf_type_flag flag = 0;
6409         u32 btf_id = 0;
6410         int ret;
6411
6412         if (!env->allow_ptr_leaks) {
6413                 verbose(env,
6414                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6415                         tname);
6416                 return -EPERM;
6417         }
6418         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6419                 verbose(env,
6420                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6421                         tname);
6422                 return -EINVAL;
6423         }
6424         if (off < 0) {
6425                 verbose(env,
6426                         "R%d is ptr_%s invalid negative access: off=%d\n",
6427                         regno, tname, off);
6428                 return -EACCES;
6429         }
6430         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6431                 char tn_buf[48];
6432
6433                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6434                 verbose(env,
6435                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6436                         regno, tname, off, tn_buf);
6437                 return -EACCES;
6438         }
6439
6440         if (reg->type & MEM_USER) {
6441                 verbose(env,
6442                         "R%d is ptr_%s access user memory: off=%d\n",
6443                         regno, tname, off);
6444                 return -EACCES;
6445         }
6446
6447         if (reg->type & MEM_PERCPU) {
6448                 verbose(env,
6449                         "R%d is ptr_%s access percpu memory: off=%d\n",
6450                         regno, tname, off);
6451                 return -EACCES;
6452         }
6453
6454         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6455                 if (!btf_is_kernel(reg->btf)) {
6456                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6457                         return -EFAULT;
6458                 }
6459                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6460         } else {
6461                 /* Writes are permitted with default btf_struct_access for
6462                  * program allocated objects (which always have ref_obj_id > 0),
6463                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6464                  */
6465                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6466                         verbose(env, "only read is supported\n");
6467                         return -EACCES;
6468                 }
6469
6470                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6471                     !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6472                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6473                         return -EFAULT;
6474                 }
6475
6476                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6477         }
6478
6479         if (ret < 0)
6480                 return ret;
6481
6482         if (ret != PTR_TO_BTF_ID) {
6483                 /* just mark; */
6484
6485         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6486                 /* If this is an untrusted pointer, all pointers formed by walking it
6487                  * also inherit the untrusted flag.
6488                  */
6489                 flag = PTR_UNTRUSTED;
6490
6491         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6492                 /* By default any pointer obtained from walking a trusted pointer is no
6493                  * longer trusted, unless the field being accessed has explicitly been
6494                  * marked as inheriting its parent's state of trust (either full or RCU).
6495                  * For example:
6496                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6497                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6498                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6499                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6500                  *
6501                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6502                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6503                  */
6504                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6505                         flag |= PTR_TRUSTED;
6506                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6507                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6508                                 /* ignore __rcu tag and mark it MEM_RCU */
6509                                 flag |= MEM_RCU;
6510                         } else if (flag & MEM_RCU ||
6511                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6512                                 /* __rcu tagged pointers can be NULL */
6513                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6514
6515                                 /* We always trust them */
6516                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6517                                     flag & PTR_UNTRUSTED)
6518                                         flag &= ~PTR_UNTRUSTED;
6519                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6520                                 /* keep as-is */
6521                         } else {
6522                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6523                                 clear_trusted_flags(&flag);
6524                         }
6525                 } else {
6526                         /*
6527                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6528                          * aggressively mark as untrusted otherwise such
6529                          * pointers will be plain PTR_TO_BTF_ID without flags
6530                          * and will be allowed to be passed into helpers for
6531                          * compat reasons.
6532                          */
6533                         flag = PTR_UNTRUSTED;
6534                 }
6535         } else {
6536                 /* Old compat. Deprecated */
6537                 clear_trusted_flags(&flag);
6538         }
6539
6540         if (atype == BPF_READ && value_regno >= 0)
6541                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6542
6543         return 0;
6544 }
6545
6546 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6547                                    struct bpf_reg_state *regs,
6548                                    int regno, int off, int size,
6549                                    enum bpf_access_type atype,
6550                                    int value_regno)
6551 {
6552         struct bpf_reg_state *reg = regs + regno;
6553         struct bpf_map *map = reg->map_ptr;
6554         struct bpf_reg_state map_reg;
6555         enum bpf_type_flag flag = 0;
6556         const struct btf_type *t;
6557         const char *tname;
6558         u32 btf_id;
6559         int ret;
6560
6561         if (!btf_vmlinux) {
6562                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6563                 return -ENOTSUPP;
6564         }
6565
6566         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6567                 verbose(env, "map_ptr access not supported for map type %d\n",
6568                         map->map_type);
6569                 return -ENOTSUPP;
6570         }
6571
6572         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6573         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6574
6575         if (!env->allow_ptr_leaks) {
6576                 verbose(env,
6577                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6578                         tname);
6579                 return -EPERM;
6580         }
6581
6582         if (off < 0) {
6583                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6584                         regno, tname, off);
6585                 return -EACCES;
6586         }
6587
6588         if (atype != BPF_READ) {
6589                 verbose(env, "only read from %s is supported\n", tname);
6590                 return -EACCES;
6591         }
6592
6593         /* Simulate access to a PTR_TO_BTF_ID */
6594         memset(&map_reg, 0, sizeof(map_reg));
6595         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6596         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6597         if (ret < 0)
6598                 return ret;
6599
6600         if (value_regno >= 0)
6601                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6602
6603         return 0;
6604 }
6605
6606 /* Check that the stack access at the given offset is within bounds. The
6607  * maximum valid offset is -1.
6608  *
6609  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6610  * -state->allocated_stack for reads.
6611  */
6612 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6613                                           s64 off,
6614                                           struct bpf_func_state *state,
6615                                           enum bpf_access_type t)
6616 {
6617         int min_valid_off;
6618
6619         if (t == BPF_WRITE || env->allow_uninit_stack)
6620                 min_valid_off = -MAX_BPF_STACK;
6621         else
6622                 min_valid_off = -state->allocated_stack;
6623
6624         if (off < min_valid_off || off > -1)
6625                 return -EACCES;
6626         return 0;
6627 }
6628
6629 /* Check that the stack access at 'regno + off' falls within the maximum stack
6630  * bounds.
6631  *
6632  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6633  */
6634 static int check_stack_access_within_bounds(
6635                 struct bpf_verifier_env *env,
6636                 int regno, int off, int access_size,
6637                 enum bpf_access_src src, enum bpf_access_type type)
6638 {
6639         struct bpf_reg_state *regs = cur_regs(env);
6640         struct bpf_reg_state *reg = regs + regno;
6641         struct bpf_func_state *state = func(env, reg);
6642         s64 min_off, max_off;
6643         int err;
6644         char *err_extra;
6645
6646         if (src == ACCESS_HELPER)
6647                 /* We don't know if helpers are reading or writing (or both). */
6648                 err_extra = " indirect access to";
6649         else if (type == BPF_READ)
6650                 err_extra = " read from";
6651         else
6652                 err_extra = " write to";
6653
6654         if (tnum_is_const(reg->var_off)) {
6655                 min_off = (s64)reg->var_off.value + off;
6656                 max_off = min_off + access_size;
6657         } else {
6658                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6659                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6660                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6661                                 err_extra, regno);
6662                         return -EACCES;
6663                 }
6664                 min_off = reg->smin_value + off;
6665                 max_off = reg->smax_value + off + access_size;
6666         }
6667
6668         err = check_stack_slot_within_bounds(env, min_off, state, type);
6669         if (!err && max_off > 0)
6670                 err = -EINVAL; /* out of stack access into non-negative offsets */
6671
6672         if (err) {
6673                 if (tnum_is_const(reg->var_off)) {
6674                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6675                                 err_extra, regno, off, access_size);
6676                 } else {
6677                         char tn_buf[48];
6678
6679                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6680                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6681                                 err_extra, regno, tn_buf, off, access_size);
6682                 }
6683                 return err;
6684         }
6685
6686         /* Note that there is no stack access with offset zero, so the needed stack
6687          * size is -min_off, not -min_off+1.
6688          */
6689         return grow_stack_state(env, state, -min_off /* size */);
6690 }
6691
6692 /* check whether memory at (regno + off) is accessible for t = (read | write)
6693  * if t==write, value_regno is a register which value is stored into memory
6694  * if t==read, value_regno is a register which will receive the value from memory
6695  * if t==write && value_regno==-1, some unknown value is stored into memory
6696  * if t==read && value_regno==-1, don't care what we read from memory
6697  */
6698 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6699                             int off, int bpf_size, enum bpf_access_type t,
6700                             int value_regno, bool strict_alignment_once, bool is_ldsx)
6701 {
6702         struct bpf_reg_state *regs = cur_regs(env);
6703         struct bpf_reg_state *reg = regs + regno;
6704         int size, err = 0;
6705
6706         size = bpf_size_to_bytes(bpf_size);
6707         if (size < 0)
6708                 return size;
6709
6710         /* alignment checks will add in reg->off themselves */
6711         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6712         if (err)
6713                 return err;
6714
6715         /* for access checks, reg->off is just part of off */
6716         off += reg->off;
6717
6718         if (reg->type == PTR_TO_MAP_KEY) {
6719                 if (t == BPF_WRITE) {
6720                         verbose(env, "write to change key R%d not allowed\n", regno);
6721                         return -EACCES;
6722                 }
6723
6724                 err = check_mem_region_access(env, regno, off, size,
6725                                               reg->map_ptr->key_size, false);
6726                 if (err)
6727                         return err;
6728                 if (value_regno >= 0)
6729                         mark_reg_unknown(env, regs, value_regno);
6730         } else if (reg->type == PTR_TO_MAP_VALUE) {
6731                 struct btf_field *kptr_field = NULL;
6732
6733                 if (t == BPF_WRITE && value_regno >= 0 &&
6734                     is_pointer_value(env, value_regno)) {
6735                         verbose(env, "R%d leaks addr into map\n", value_regno);
6736                         return -EACCES;
6737                 }
6738                 err = check_map_access_type(env, regno, off, size, t);
6739                 if (err)
6740                         return err;
6741                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6742                 if (err)
6743                         return err;
6744                 if (tnum_is_const(reg->var_off))
6745                         kptr_field = btf_record_find(reg->map_ptr->record,
6746                                                      off + reg->var_off.value, BPF_KPTR);
6747                 if (kptr_field) {
6748                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6749                 } else if (t == BPF_READ && value_regno >= 0) {
6750                         struct bpf_map *map = reg->map_ptr;
6751
6752                         /* if map is read-only, track its contents as scalars */
6753                         if (tnum_is_const(reg->var_off) &&
6754                             bpf_map_is_rdonly(map) &&
6755                             map->ops->map_direct_value_addr) {
6756                                 int map_off = off + reg->var_off.value;
6757                                 u64 val = 0;
6758
6759                                 err = bpf_map_direct_read(map, map_off, size,
6760                                                           &val, is_ldsx);
6761                                 if (err)
6762                                         return err;
6763
6764                                 regs[value_regno].type = SCALAR_VALUE;
6765                                 __mark_reg_known(&regs[value_regno], val);
6766                         } else {
6767                                 mark_reg_unknown(env, regs, value_regno);
6768                         }
6769                 }
6770         } else if (base_type(reg->type) == PTR_TO_MEM) {
6771                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6772
6773                 if (type_may_be_null(reg->type)) {
6774                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6775                                 reg_type_str(env, reg->type));
6776                         return -EACCES;
6777                 }
6778
6779                 if (t == BPF_WRITE && rdonly_mem) {
6780                         verbose(env, "R%d cannot write into %s\n",
6781                                 regno, reg_type_str(env, reg->type));
6782                         return -EACCES;
6783                 }
6784
6785                 if (t == BPF_WRITE && value_regno >= 0 &&
6786                     is_pointer_value(env, value_regno)) {
6787                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6788                         return -EACCES;
6789                 }
6790
6791                 err = check_mem_region_access(env, regno, off, size,
6792                                               reg->mem_size, false);
6793                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6794                         mark_reg_unknown(env, regs, value_regno);
6795         } else if (reg->type == PTR_TO_CTX) {
6796                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6797                 struct btf *btf = NULL;
6798                 u32 btf_id = 0;
6799
6800                 if (t == BPF_WRITE && value_regno >= 0 &&
6801                     is_pointer_value(env, value_regno)) {
6802                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6803                         return -EACCES;
6804                 }
6805
6806                 err = check_ptr_off_reg(env, reg, regno);
6807                 if (err < 0)
6808                         return err;
6809
6810                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6811                                        &btf_id);
6812                 if (err)
6813                         verbose_linfo(env, insn_idx, "; ");
6814                 if (!err && t == BPF_READ && value_regno >= 0) {
6815                         /* ctx access returns either a scalar, or a
6816                          * PTR_TO_PACKET[_META,_END]. In the latter
6817                          * case, we know the offset is zero.
6818                          */
6819                         if (reg_type == SCALAR_VALUE) {
6820                                 mark_reg_unknown(env, regs, value_regno);
6821                         } else {
6822                                 mark_reg_known_zero(env, regs,
6823                                                     value_regno);
6824                                 if (type_may_be_null(reg_type))
6825                                         regs[value_regno].id = ++env->id_gen;
6826                                 /* A load of ctx field could have different
6827                                  * actual load size with the one encoded in the
6828                                  * insn. When the dst is PTR, it is for sure not
6829                                  * a sub-register.
6830                                  */
6831                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6832                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6833                                         regs[value_regno].btf = btf;
6834                                         regs[value_regno].btf_id = btf_id;
6835                                 }
6836                         }
6837                         regs[value_regno].type = reg_type;
6838                 }
6839
6840         } else if (reg->type == PTR_TO_STACK) {
6841                 /* Basic bounds checks. */
6842                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6843                 if (err)
6844                         return err;
6845
6846                 if (t == BPF_READ)
6847                         err = check_stack_read(env, regno, off, size,
6848                                                value_regno);
6849                 else
6850                         err = check_stack_write(env, regno, off, size,
6851                                                 value_regno, insn_idx);
6852         } else if (reg_is_pkt_pointer(reg)) {
6853                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6854                         verbose(env, "cannot write into packet\n");
6855                         return -EACCES;
6856                 }
6857                 if (t == BPF_WRITE && value_regno >= 0 &&
6858                     is_pointer_value(env, value_regno)) {
6859                         verbose(env, "R%d leaks addr into packet\n",
6860                                 value_regno);
6861                         return -EACCES;
6862                 }
6863                 err = check_packet_access(env, regno, off, size, false);
6864                 if (!err && t == BPF_READ && value_regno >= 0)
6865                         mark_reg_unknown(env, regs, value_regno);
6866         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6867                 if (t == BPF_WRITE && value_regno >= 0 &&
6868                     is_pointer_value(env, value_regno)) {
6869                         verbose(env, "R%d leaks addr into flow keys\n",
6870                                 value_regno);
6871                         return -EACCES;
6872                 }
6873
6874                 err = check_flow_keys_access(env, off, size);
6875                 if (!err && t == BPF_READ && value_regno >= 0)
6876                         mark_reg_unknown(env, regs, value_regno);
6877         } else if (type_is_sk_pointer(reg->type)) {
6878                 if (t == BPF_WRITE) {
6879                         verbose(env, "R%d cannot write into %s\n",
6880                                 regno, reg_type_str(env, reg->type));
6881                         return -EACCES;
6882                 }
6883                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6884                 if (!err && value_regno >= 0)
6885                         mark_reg_unknown(env, regs, value_regno);
6886         } else if (reg->type == PTR_TO_TP_BUFFER) {
6887                 err = check_tp_buffer_access(env, reg, regno, off, size);
6888                 if (!err && t == BPF_READ && value_regno >= 0)
6889                         mark_reg_unknown(env, regs, value_regno);
6890         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6891                    !type_may_be_null(reg->type)) {
6892                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6893                                               value_regno);
6894         } else if (reg->type == CONST_PTR_TO_MAP) {
6895                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6896                                               value_regno);
6897         } else if (base_type(reg->type) == PTR_TO_BUF) {
6898                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6899                 u32 *max_access;
6900
6901                 if (rdonly_mem) {
6902                         if (t == BPF_WRITE) {
6903                                 verbose(env, "R%d cannot write into %s\n",
6904                                         regno, reg_type_str(env, reg->type));
6905                                 return -EACCES;
6906                         }
6907                         max_access = &env->prog->aux->max_rdonly_access;
6908                 } else {
6909                         max_access = &env->prog->aux->max_rdwr_access;
6910                 }
6911
6912                 err = check_buffer_access(env, reg, regno, off, size, false,
6913                                           max_access);
6914
6915                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6916                         mark_reg_unknown(env, regs, value_regno);
6917         } else {
6918                 verbose(env, "R%d invalid mem access '%s'\n", regno,
6919                         reg_type_str(env, reg->type));
6920                 return -EACCES;
6921         }
6922
6923         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6924             regs[value_regno].type == SCALAR_VALUE) {
6925                 if (!is_ldsx)
6926                         /* b/h/w load zero-extends, mark upper bits as known 0 */
6927                         coerce_reg_to_size(&regs[value_regno], size);
6928                 else
6929                         coerce_reg_to_size_sx(&regs[value_regno], size);
6930         }
6931         return err;
6932 }
6933
6934 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6935 {
6936         int load_reg;
6937         int err;
6938
6939         switch (insn->imm) {
6940         case BPF_ADD:
6941         case BPF_ADD | BPF_FETCH:
6942         case BPF_AND:
6943         case BPF_AND | BPF_FETCH:
6944         case BPF_OR:
6945         case BPF_OR | BPF_FETCH:
6946         case BPF_XOR:
6947         case BPF_XOR | BPF_FETCH:
6948         case BPF_XCHG:
6949         case BPF_CMPXCHG:
6950                 break;
6951         default:
6952                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6953                 return -EINVAL;
6954         }
6955
6956         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6957                 verbose(env, "invalid atomic operand size\n");
6958                 return -EINVAL;
6959         }
6960
6961         /* check src1 operand */
6962         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6963         if (err)
6964                 return err;
6965
6966         /* check src2 operand */
6967         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6968         if (err)
6969                 return err;
6970
6971         if (insn->imm == BPF_CMPXCHG) {
6972                 /* Check comparison of R0 with memory location */
6973                 const u32 aux_reg = BPF_REG_0;
6974
6975                 err = check_reg_arg(env, aux_reg, SRC_OP);
6976                 if (err)
6977                         return err;
6978
6979                 if (is_pointer_value(env, aux_reg)) {
6980                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6981                         return -EACCES;
6982                 }
6983         }
6984
6985         if (is_pointer_value(env, insn->src_reg)) {
6986                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6987                 return -EACCES;
6988         }
6989
6990         if (is_ctx_reg(env, insn->dst_reg) ||
6991             is_pkt_reg(env, insn->dst_reg) ||
6992             is_flow_key_reg(env, insn->dst_reg) ||
6993             is_sk_reg(env, insn->dst_reg)) {
6994                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6995                         insn->dst_reg,
6996                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6997                 return -EACCES;
6998         }
6999
7000         if (insn->imm & BPF_FETCH) {
7001                 if (insn->imm == BPF_CMPXCHG)
7002                         load_reg = BPF_REG_0;
7003                 else
7004                         load_reg = insn->src_reg;
7005
7006                 /* check and record load of old value */
7007                 err = check_reg_arg(env, load_reg, DST_OP);
7008                 if (err)
7009                         return err;
7010         } else {
7011                 /* This instruction accesses a memory location but doesn't
7012                  * actually load it into a register.
7013                  */
7014                 load_reg = -1;
7015         }
7016
7017         /* Check whether we can read the memory, with second call for fetch
7018          * case to simulate the register fill.
7019          */
7020         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7021                                BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7022         if (!err && load_reg >= 0)
7023                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7024                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
7025                                        true, false);
7026         if (err)
7027                 return err;
7028
7029         /* Check whether we can write into the same memory. */
7030         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7031                                BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7032         if (err)
7033                 return err;
7034         return 0;
7035 }
7036
7037 /* When register 'regno' is used to read the stack (either directly or through
7038  * a helper function) make sure that it's within stack boundary and, depending
7039  * on the access type and privileges, that all elements of the stack are
7040  * initialized.
7041  *
7042  * 'off' includes 'regno->off', but not its dynamic part (if any).
7043  *
7044  * All registers that have been spilled on the stack in the slots within the
7045  * read offsets are marked as read.
7046  */
7047 static int check_stack_range_initialized(
7048                 struct bpf_verifier_env *env, int regno, int off,
7049                 int access_size, bool zero_size_allowed,
7050                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7051 {
7052         struct bpf_reg_state *reg = reg_state(env, regno);
7053         struct bpf_func_state *state = func(env, reg);
7054         int err, min_off, max_off, i, j, slot, spi;
7055         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7056         enum bpf_access_type bounds_check_type;
7057         /* Some accesses can write anything into the stack, others are
7058          * read-only.
7059          */
7060         bool clobber = false;
7061
7062         if (access_size == 0 && !zero_size_allowed) {
7063                 verbose(env, "invalid zero-sized read\n");
7064                 return -EACCES;
7065         }
7066
7067         if (type == ACCESS_HELPER) {
7068                 /* The bounds checks for writes are more permissive than for
7069                  * reads. However, if raw_mode is not set, we'll do extra
7070                  * checks below.
7071                  */
7072                 bounds_check_type = BPF_WRITE;
7073                 clobber = true;
7074         } else {
7075                 bounds_check_type = BPF_READ;
7076         }
7077         err = check_stack_access_within_bounds(env, regno, off, access_size,
7078                                                type, bounds_check_type);
7079         if (err)
7080                 return err;
7081
7082
7083         if (tnum_is_const(reg->var_off)) {
7084                 min_off = max_off = reg->var_off.value + off;
7085         } else {
7086                 /* Variable offset is prohibited for unprivileged mode for
7087                  * simplicity since it requires corresponding support in
7088                  * Spectre masking for stack ALU.
7089                  * See also retrieve_ptr_limit().
7090                  */
7091                 if (!env->bypass_spec_v1) {
7092                         char tn_buf[48];
7093
7094                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7095                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7096                                 regno, err_extra, tn_buf);
7097                         return -EACCES;
7098                 }
7099                 /* Only initialized buffer on stack is allowed to be accessed
7100                  * with variable offset. With uninitialized buffer it's hard to
7101                  * guarantee that whole memory is marked as initialized on
7102                  * helper return since specific bounds are unknown what may
7103                  * cause uninitialized stack leaking.
7104                  */
7105                 if (meta && meta->raw_mode)
7106                         meta = NULL;
7107
7108                 min_off = reg->smin_value + off;
7109                 max_off = reg->smax_value + off;
7110         }
7111
7112         if (meta && meta->raw_mode) {
7113                 /* Ensure we won't be overwriting dynptrs when simulating byte
7114                  * by byte access in check_helper_call using meta.access_size.
7115                  * This would be a problem if we have a helper in the future
7116                  * which takes:
7117                  *
7118                  *      helper(uninit_mem, len, dynptr)
7119                  *
7120                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7121                  * may end up writing to dynptr itself when touching memory from
7122                  * arg 1. This can be relaxed on a case by case basis for known
7123                  * safe cases, but reject due to the possibilitiy of aliasing by
7124                  * default.
7125                  */
7126                 for (i = min_off; i < max_off + access_size; i++) {
7127                         int stack_off = -i - 1;
7128
7129                         spi = __get_spi(i);
7130                         /* raw_mode may write past allocated_stack */
7131                         if (state->allocated_stack <= stack_off)
7132                                 continue;
7133                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7134                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7135                                 return -EACCES;
7136                         }
7137                 }
7138                 meta->access_size = access_size;
7139                 meta->regno = regno;
7140                 return 0;
7141         }
7142
7143         for (i = min_off; i < max_off + access_size; i++) {
7144                 u8 *stype;
7145
7146                 slot = -i - 1;
7147                 spi = slot / BPF_REG_SIZE;
7148                 if (state->allocated_stack <= slot) {
7149                         verbose(env, "verifier bug: allocated_stack too small");
7150                         return -EFAULT;
7151                 }
7152
7153                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7154                 if (*stype == STACK_MISC)
7155                         goto mark;
7156                 if ((*stype == STACK_ZERO) ||
7157                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7158                         if (clobber) {
7159                                 /* helper can write anything into the stack */
7160                                 *stype = STACK_MISC;
7161                         }
7162                         goto mark;
7163                 }
7164
7165                 if (is_spilled_reg(&state->stack[spi]) &&
7166                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7167                      env->allow_ptr_leaks)) {
7168                         if (clobber) {
7169                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7170                                 for (j = 0; j < BPF_REG_SIZE; j++)
7171                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7172                         }
7173                         goto mark;
7174                 }
7175
7176                 if (tnum_is_const(reg->var_off)) {
7177                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7178                                 err_extra, regno, min_off, i - min_off, access_size);
7179                 } else {
7180                         char tn_buf[48];
7181
7182                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7183                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7184                                 err_extra, regno, tn_buf, i - min_off, access_size);
7185                 }
7186                 return -EACCES;
7187 mark:
7188                 /* reading any byte out of 8-byte 'spill_slot' will cause
7189                  * the whole slot to be marked as 'read'
7190                  */
7191                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7192                               state->stack[spi].spilled_ptr.parent,
7193                               REG_LIVE_READ64);
7194                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7195                  * be sure that whether stack slot is written to or not. Hence,
7196                  * we must still conservatively propagate reads upwards even if
7197                  * helper may write to the entire memory range.
7198                  */
7199         }
7200         return 0;
7201 }
7202
7203 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7204                                    int access_size, bool zero_size_allowed,
7205                                    struct bpf_call_arg_meta *meta)
7206 {
7207         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7208         u32 *max_access;
7209
7210         switch (base_type(reg->type)) {
7211         case PTR_TO_PACKET:
7212         case PTR_TO_PACKET_META:
7213                 return check_packet_access(env, regno, reg->off, access_size,
7214                                            zero_size_allowed);
7215         case PTR_TO_MAP_KEY:
7216                 if (meta && meta->raw_mode) {
7217                         verbose(env, "R%d cannot write into %s\n", regno,
7218                                 reg_type_str(env, reg->type));
7219                         return -EACCES;
7220                 }
7221                 return check_mem_region_access(env, regno, reg->off, access_size,
7222                                                reg->map_ptr->key_size, false);
7223         case PTR_TO_MAP_VALUE:
7224                 if (check_map_access_type(env, regno, reg->off, access_size,
7225                                           meta && meta->raw_mode ? BPF_WRITE :
7226                                           BPF_READ))
7227                         return -EACCES;
7228                 return check_map_access(env, regno, reg->off, access_size,
7229                                         zero_size_allowed, ACCESS_HELPER);
7230         case PTR_TO_MEM:
7231                 if (type_is_rdonly_mem(reg->type)) {
7232                         if (meta && meta->raw_mode) {
7233                                 verbose(env, "R%d cannot write into %s\n", regno,
7234                                         reg_type_str(env, reg->type));
7235                                 return -EACCES;
7236                         }
7237                 }
7238                 return check_mem_region_access(env, regno, reg->off,
7239                                                access_size, reg->mem_size,
7240                                                zero_size_allowed);
7241         case PTR_TO_BUF:
7242                 if (type_is_rdonly_mem(reg->type)) {
7243                         if (meta && meta->raw_mode) {
7244                                 verbose(env, "R%d cannot write into %s\n", regno,
7245                                         reg_type_str(env, reg->type));
7246                                 return -EACCES;
7247                         }
7248
7249                         max_access = &env->prog->aux->max_rdonly_access;
7250                 } else {
7251                         max_access = &env->prog->aux->max_rdwr_access;
7252                 }
7253                 return check_buffer_access(env, reg, regno, reg->off,
7254                                            access_size, zero_size_allowed,
7255                                            max_access);
7256         case PTR_TO_STACK:
7257                 return check_stack_range_initialized(
7258                                 env,
7259                                 regno, reg->off, access_size,
7260                                 zero_size_allowed, ACCESS_HELPER, meta);
7261         case PTR_TO_BTF_ID:
7262                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7263                                                access_size, BPF_READ, -1);
7264         case PTR_TO_CTX:
7265                 /* in case the function doesn't know how to access the context,
7266                  * (because we are in a program of type SYSCALL for example), we
7267                  * can not statically check its size.
7268                  * Dynamically check it now.
7269                  */
7270                 if (!env->ops->convert_ctx_access) {
7271                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7272                         int offset = access_size - 1;
7273
7274                         /* Allow zero-byte read from PTR_TO_CTX */
7275                         if (access_size == 0)
7276                                 return zero_size_allowed ? 0 : -EACCES;
7277
7278                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7279                                                 atype, -1, false, false);
7280                 }
7281
7282                 fallthrough;
7283         default: /* scalar_value or invalid ptr */
7284                 /* Allow zero-byte read from NULL, regardless of pointer type */
7285                 if (zero_size_allowed && access_size == 0 &&
7286                     register_is_null(reg))
7287                         return 0;
7288
7289                 verbose(env, "R%d type=%s ", regno,
7290                         reg_type_str(env, reg->type));
7291                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7292                 return -EACCES;
7293         }
7294 }
7295
7296 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7297  * size.
7298  *
7299  * @regno is the register containing the access size. regno-1 is the register
7300  * containing the pointer.
7301  */
7302 static int check_mem_size_reg(struct bpf_verifier_env *env,
7303                               struct bpf_reg_state *reg, u32 regno,
7304                               bool zero_size_allowed,
7305                               struct bpf_call_arg_meta *meta)
7306 {
7307         int err;
7308
7309         /* This is used to refine r0 return value bounds for helpers
7310          * that enforce this value as an upper bound on return values.
7311          * See do_refine_retval_range() for helpers that can refine
7312          * the return value. C type of helper is u32 so we pull register
7313          * bound from umax_value however, if negative verifier errors
7314          * out. Only upper bounds can be learned because retval is an
7315          * int type and negative retvals are allowed.
7316          */
7317         meta->msize_max_value = reg->umax_value;
7318
7319         /* The register is SCALAR_VALUE; the access check
7320          * happens using its boundaries.
7321          */
7322         if (!tnum_is_const(reg->var_off))
7323                 /* For unprivileged variable accesses, disable raw
7324                  * mode so that the program is required to
7325                  * initialize all the memory that the helper could
7326                  * just partially fill up.
7327                  */
7328                 meta = NULL;
7329
7330         if (reg->smin_value < 0) {
7331                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7332                         regno);
7333                 return -EACCES;
7334         }
7335
7336         if (reg->umin_value == 0 && !zero_size_allowed) {
7337                 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7338                         regno, reg->umin_value, reg->umax_value);
7339                 return -EACCES;
7340         }
7341
7342         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7343                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7344                         regno);
7345                 return -EACCES;
7346         }
7347         err = check_helper_mem_access(env, regno - 1,
7348                                       reg->umax_value,
7349                                       zero_size_allowed, meta);
7350         if (!err)
7351                 err = mark_chain_precision(env, regno);
7352         return err;
7353 }
7354
7355 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7356                          u32 regno, u32 mem_size)
7357 {
7358         bool may_be_null = type_may_be_null(reg->type);
7359         struct bpf_reg_state saved_reg;
7360         struct bpf_call_arg_meta meta;
7361         int err;
7362
7363         if (register_is_null(reg))
7364                 return 0;
7365
7366         memset(&meta, 0, sizeof(meta));
7367         /* Assuming that the register contains a value check if the memory
7368          * access is safe. Temporarily save and restore the register's state as
7369          * the conversion shouldn't be visible to a caller.
7370          */
7371         if (may_be_null) {
7372                 saved_reg = *reg;
7373                 mark_ptr_not_null_reg(reg);
7374         }
7375
7376         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7377         /* Check access for BPF_WRITE */
7378         meta.raw_mode = true;
7379         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7380
7381         if (may_be_null)
7382                 *reg = saved_reg;
7383
7384         return err;
7385 }
7386
7387 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7388                                     u32 regno)
7389 {
7390         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7391         bool may_be_null = type_may_be_null(mem_reg->type);
7392         struct bpf_reg_state saved_reg;
7393         struct bpf_call_arg_meta meta;
7394         int err;
7395
7396         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7397
7398         memset(&meta, 0, sizeof(meta));
7399
7400         if (may_be_null) {
7401                 saved_reg = *mem_reg;
7402                 mark_ptr_not_null_reg(mem_reg);
7403         }
7404
7405         err = check_mem_size_reg(env, reg, regno, true, &meta);
7406         /* Check access for BPF_WRITE */
7407         meta.raw_mode = true;
7408         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7409
7410         if (may_be_null)
7411                 *mem_reg = saved_reg;
7412         return err;
7413 }
7414
7415 /* Implementation details:
7416  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7417  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7418  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7419  * Two separate bpf_obj_new will also have different reg->id.
7420  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7421  * clears reg->id after value_or_null->value transition, since the verifier only
7422  * cares about the range of access to valid map value pointer and doesn't care
7423  * about actual address of the map element.
7424  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7425  * reg->id > 0 after value_or_null->value transition. By doing so
7426  * two bpf_map_lookups will be considered two different pointers that
7427  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7428  * returned from bpf_obj_new.
7429  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7430  * dead-locks.
7431  * Since only one bpf_spin_lock is allowed the checks are simpler than
7432  * reg_is_refcounted() logic. The verifier needs to remember only
7433  * one spin_lock instead of array of acquired_refs.
7434  * cur_state->active_lock remembers which map value element or allocated
7435  * object got locked and clears it after bpf_spin_unlock.
7436  */
7437 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7438                              bool is_lock)
7439 {
7440         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7441         struct bpf_verifier_state *cur = env->cur_state;
7442         bool is_const = tnum_is_const(reg->var_off);
7443         u64 val = reg->var_off.value;
7444         struct bpf_map *map = NULL;
7445         struct btf *btf = NULL;
7446         struct btf_record *rec;
7447
7448         if (!is_const) {
7449                 verbose(env,
7450                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7451                         regno);
7452                 return -EINVAL;
7453         }
7454         if (reg->type == PTR_TO_MAP_VALUE) {
7455                 map = reg->map_ptr;
7456                 if (!map->btf) {
7457                         verbose(env,
7458                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7459                                 map->name);
7460                         return -EINVAL;
7461                 }
7462         } else {
7463                 btf = reg->btf;
7464         }
7465
7466         rec = reg_btf_record(reg);
7467         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7468                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7469                         map ? map->name : "kptr");
7470                 return -EINVAL;
7471         }
7472         if (rec->spin_lock_off != val + reg->off) {
7473                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7474                         val + reg->off, rec->spin_lock_off);
7475                 return -EINVAL;
7476         }
7477         if (is_lock) {
7478                 if (cur->active_lock.ptr) {
7479                         verbose(env,
7480                                 "Locking two bpf_spin_locks are not allowed\n");
7481                         return -EINVAL;
7482                 }
7483                 if (map)
7484                         cur->active_lock.ptr = map;
7485                 else
7486                         cur->active_lock.ptr = btf;
7487                 cur->active_lock.id = reg->id;
7488         } else {
7489                 void *ptr;
7490
7491                 if (map)
7492                         ptr = map;
7493                 else
7494                         ptr = btf;
7495
7496                 if (!cur->active_lock.ptr) {
7497                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7498                         return -EINVAL;
7499                 }
7500                 if (cur->active_lock.ptr != ptr ||
7501                     cur->active_lock.id != reg->id) {
7502                         verbose(env, "bpf_spin_unlock of different lock\n");
7503                         return -EINVAL;
7504                 }
7505
7506                 invalidate_non_owning_refs(env);
7507
7508                 cur->active_lock.ptr = NULL;
7509                 cur->active_lock.id = 0;
7510         }
7511         return 0;
7512 }
7513
7514 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7515                               struct bpf_call_arg_meta *meta)
7516 {
7517         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7518         bool is_const = tnum_is_const(reg->var_off);
7519         struct bpf_map *map = reg->map_ptr;
7520         u64 val = reg->var_off.value;
7521
7522         if (!is_const) {
7523                 verbose(env,
7524                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7525                         regno);
7526                 return -EINVAL;
7527         }
7528         if (!map->btf) {
7529                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7530                         map->name);
7531                 return -EINVAL;
7532         }
7533         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7534                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7535                 return -EINVAL;
7536         }
7537         if (map->record->timer_off != val + reg->off) {
7538                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7539                         val + reg->off, map->record->timer_off);
7540                 return -EINVAL;
7541         }
7542         if (meta->map_ptr) {
7543                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7544                 return -EFAULT;
7545         }
7546         meta->map_uid = reg->map_uid;
7547         meta->map_ptr = map;
7548         return 0;
7549 }
7550
7551 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7552                              struct bpf_call_arg_meta *meta)
7553 {
7554         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7555         struct bpf_map *map_ptr = reg->map_ptr;
7556         struct btf_field *kptr_field;
7557         u32 kptr_off;
7558
7559         if (!tnum_is_const(reg->var_off)) {
7560                 verbose(env,
7561                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7562                         regno);
7563                 return -EINVAL;
7564         }
7565         if (!map_ptr->btf) {
7566                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7567                         map_ptr->name);
7568                 return -EINVAL;
7569         }
7570         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7571                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7572                 return -EINVAL;
7573         }
7574
7575         meta->map_ptr = map_ptr;
7576         kptr_off = reg->off + reg->var_off.value;
7577         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7578         if (!kptr_field) {
7579                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7580                 return -EACCES;
7581         }
7582         if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7583                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7584                 return -EACCES;
7585         }
7586         meta->kptr_field = kptr_field;
7587         return 0;
7588 }
7589
7590 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7591  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7592  *
7593  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7594  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7595  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7596  *
7597  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7598  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7599  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7600  * mutate the view of the dynptr and also possibly destroy it. In the latter
7601  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7602  * memory that dynptr points to.
7603  *
7604  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7605  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7606  * readonly dynptr view yet, hence only the first case is tracked and checked.
7607  *
7608  * This is consistent with how C applies the const modifier to a struct object,
7609  * where the pointer itself inside bpf_dynptr becomes const but not what it
7610  * points to.
7611  *
7612  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7613  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7614  */
7615 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7616                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7617 {
7618         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7619         int err;
7620
7621         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7622          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7623          */
7624         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7625                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7626                 return -EFAULT;
7627         }
7628
7629         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7630          *               constructing a mutable bpf_dynptr object.
7631          *
7632          *               Currently, this is only possible with PTR_TO_STACK
7633          *               pointing to a region of at least 16 bytes which doesn't
7634          *               contain an existing bpf_dynptr.
7635          *
7636          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7637          *               mutated or destroyed. However, the memory it points to
7638          *               may be mutated.
7639          *
7640          *  None       - Points to a initialized dynptr that can be mutated and
7641          *               destroyed, including mutation of the memory it points
7642          *               to.
7643          */
7644         if (arg_type & MEM_UNINIT) {
7645                 int i;
7646
7647                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7648                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7649                         return -EINVAL;
7650                 }
7651
7652                 /* we write BPF_DW bits (8 bytes) at a time */
7653                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7654                         err = check_mem_access(env, insn_idx, regno,
7655                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7656                         if (err)
7657                                 return err;
7658                 }
7659
7660                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7661         } else /* MEM_RDONLY and None case from above */ {
7662                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7663                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7664                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7665                         return -EINVAL;
7666                 }
7667
7668                 if (!is_dynptr_reg_valid_init(env, reg)) {
7669                         verbose(env,
7670                                 "Expected an initialized dynptr as arg #%d\n",
7671                                 regno);
7672                         return -EINVAL;
7673                 }
7674
7675                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7676                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7677                         verbose(env,
7678                                 "Expected a dynptr of type %s as arg #%d\n",
7679                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7680                         return -EINVAL;
7681                 }
7682
7683                 err = mark_dynptr_read(env, reg);
7684         }
7685         return err;
7686 }
7687
7688 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7689 {
7690         struct bpf_func_state *state = func(env, reg);
7691
7692         return state->stack[spi].spilled_ptr.ref_obj_id;
7693 }
7694
7695 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7696 {
7697         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7698 }
7699
7700 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7701 {
7702         return meta->kfunc_flags & KF_ITER_NEW;
7703 }
7704
7705 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7706 {
7707         return meta->kfunc_flags & KF_ITER_NEXT;
7708 }
7709
7710 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7711 {
7712         return meta->kfunc_flags & KF_ITER_DESTROY;
7713 }
7714
7715 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7716 {
7717         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7718          * kfunc is iter state pointer
7719          */
7720         return arg == 0 && is_iter_kfunc(meta);
7721 }
7722
7723 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7724                             struct bpf_kfunc_call_arg_meta *meta)
7725 {
7726         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7727         const struct btf_type *t;
7728         const struct btf_param *arg;
7729         int spi, err, i, nr_slots;
7730         u32 btf_id;
7731
7732         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7733         arg = &btf_params(meta->func_proto)[0];
7734         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7735         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7736         nr_slots = t->size / BPF_REG_SIZE;
7737
7738         if (is_iter_new_kfunc(meta)) {
7739                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7740                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7741                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7742                                 iter_type_str(meta->btf, btf_id), regno);
7743                         return -EINVAL;
7744                 }
7745
7746                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7747                         err = check_mem_access(env, insn_idx, regno,
7748                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7749                         if (err)
7750                                 return err;
7751                 }
7752
7753                 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7754                 if (err)
7755                         return err;
7756         } else {
7757                 /* iter_next() or iter_destroy() expect initialized iter state*/
7758                 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7759                 switch (err) {
7760                 case 0:
7761                         break;
7762                 case -EINVAL:
7763                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7764                                 iter_type_str(meta->btf, btf_id), regno);
7765                         return err;
7766                 case -EPROTO:
7767                         verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7768                         return err;
7769                 default:
7770                         return err;
7771                 }
7772
7773                 spi = iter_get_spi(env, reg, nr_slots);
7774                 if (spi < 0)
7775                         return spi;
7776
7777                 err = mark_iter_read(env, reg, spi, nr_slots);
7778                 if (err)
7779                         return err;
7780
7781                 /* remember meta->iter info for process_iter_next_call() */
7782                 meta->iter.spi = spi;
7783                 meta->iter.frameno = reg->frameno;
7784                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7785
7786                 if (is_iter_destroy_kfunc(meta)) {
7787                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7788                         if (err)
7789                                 return err;
7790                 }
7791         }
7792
7793         return 0;
7794 }
7795
7796 /* Look for a previous loop entry at insn_idx: nearest parent state
7797  * stopped at insn_idx with callsites matching those in cur->frame.
7798  */
7799 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7800                                                   struct bpf_verifier_state *cur,
7801                                                   int insn_idx)
7802 {
7803         struct bpf_verifier_state_list *sl;
7804         struct bpf_verifier_state *st;
7805
7806         /* Explored states are pushed in stack order, most recent states come first */
7807         sl = *explored_state(env, insn_idx);
7808         for (; sl; sl = sl->next) {
7809                 /* If st->branches != 0 state is a part of current DFS verification path,
7810                  * hence cur & st for a loop.
7811                  */
7812                 st = &sl->state;
7813                 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7814                     st->dfs_depth < cur->dfs_depth)
7815                         return st;
7816         }
7817
7818         return NULL;
7819 }
7820
7821 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7822 static bool regs_exact(const struct bpf_reg_state *rold,
7823                        const struct bpf_reg_state *rcur,
7824                        struct bpf_idmap *idmap);
7825
7826 static void maybe_widen_reg(struct bpf_verifier_env *env,
7827                             struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7828                             struct bpf_idmap *idmap)
7829 {
7830         if (rold->type != SCALAR_VALUE)
7831                 return;
7832         if (rold->type != rcur->type)
7833                 return;
7834         if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7835                 return;
7836         __mark_reg_unknown(env, rcur);
7837 }
7838
7839 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7840                                    struct bpf_verifier_state *old,
7841                                    struct bpf_verifier_state *cur)
7842 {
7843         struct bpf_func_state *fold, *fcur;
7844         int i, fr;
7845
7846         reset_idmap_scratch(env);
7847         for (fr = old->curframe; fr >= 0; fr--) {
7848                 fold = old->frame[fr];
7849                 fcur = cur->frame[fr];
7850
7851                 for (i = 0; i < MAX_BPF_REG; i++)
7852                         maybe_widen_reg(env,
7853                                         &fold->regs[i],
7854                                         &fcur->regs[i],
7855                                         &env->idmap_scratch);
7856
7857                 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7858                         if (!is_spilled_reg(&fold->stack[i]) ||
7859                             !is_spilled_reg(&fcur->stack[i]))
7860                                 continue;
7861
7862                         maybe_widen_reg(env,
7863                                         &fold->stack[i].spilled_ptr,
7864                                         &fcur->stack[i].spilled_ptr,
7865                                         &env->idmap_scratch);
7866                 }
7867         }
7868         return 0;
7869 }
7870
7871 /* process_iter_next_call() is called when verifier gets to iterator's next
7872  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7873  * to it as just "iter_next()" in comments below.
7874  *
7875  * BPF verifier relies on a crucial contract for any iter_next()
7876  * implementation: it should *eventually* return NULL, and once that happens
7877  * it should keep returning NULL. That is, once iterator exhausts elements to
7878  * iterate, it should never reset or spuriously return new elements.
7879  *
7880  * With the assumption of such contract, process_iter_next_call() simulates
7881  * a fork in the verifier state to validate loop logic correctness and safety
7882  * without having to simulate infinite amount of iterations.
7883  *
7884  * In current state, we first assume that iter_next() returned NULL and
7885  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7886  * conditions we should not form an infinite loop and should eventually reach
7887  * exit.
7888  *
7889  * Besides that, we also fork current state and enqueue it for later
7890  * verification. In a forked state we keep iterator state as ACTIVE
7891  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7892  * also bump iteration depth to prevent erroneous infinite loop detection
7893  * later on (see iter_active_depths_differ() comment for details). In this
7894  * state we assume that we'll eventually loop back to another iter_next()
7895  * calls (it could be in exactly same location or in some other instruction,
7896  * it doesn't matter, we don't make any unnecessary assumptions about this,
7897  * everything revolves around iterator state in a stack slot, not which
7898  * instruction is calling iter_next()). When that happens, we either will come
7899  * to iter_next() with equivalent state and can conclude that next iteration
7900  * will proceed in exactly the same way as we just verified, so it's safe to
7901  * assume that loop converges. If not, we'll go on another iteration
7902  * simulation with a different input state, until all possible starting states
7903  * are validated or we reach maximum number of instructions limit.
7904  *
7905  * This way, we will either exhaustively discover all possible input states
7906  * that iterator loop can start with and eventually will converge, or we'll
7907  * effectively regress into bounded loop simulation logic and either reach
7908  * maximum number of instructions if loop is not provably convergent, or there
7909  * is some statically known limit on number of iterations (e.g., if there is
7910  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7911  *
7912  * Iteration convergence logic in is_state_visited() relies on exact
7913  * states comparison, which ignores read and precision marks.
7914  * This is necessary because read and precision marks are not finalized
7915  * while in the loop. Exact comparison might preclude convergence for
7916  * simple programs like below:
7917  *
7918  *     i = 0;
7919  *     while(iter_next(&it))
7920  *       i++;
7921  *
7922  * At each iteration step i++ would produce a new distinct state and
7923  * eventually instruction processing limit would be reached.
7924  *
7925  * To avoid such behavior speculatively forget (widen) range for
7926  * imprecise scalar registers, if those registers were not precise at the
7927  * end of the previous iteration and do not match exactly.
7928  *
7929  * This is a conservative heuristic that allows to verify wide range of programs,
7930  * however it precludes verification of programs that conjure an
7931  * imprecise value on the first loop iteration and use it as precise on a second.
7932  * For example, the following safe program would fail to verify:
7933  *
7934  *     struct bpf_num_iter it;
7935  *     int arr[10];
7936  *     int i = 0, a = 0;
7937  *     bpf_iter_num_new(&it, 0, 10);
7938  *     while (bpf_iter_num_next(&it)) {
7939  *       if (a == 0) {
7940  *         a = 1;
7941  *         i = 7; // Because i changed verifier would forget
7942  *                // it's range on second loop entry.
7943  *       } else {
7944  *         arr[i] = 42; // This would fail to verify.
7945  *       }
7946  *     }
7947  *     bpf_iter_num_destroy(&it);
7948  */
7949 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7950                                   struct bpf_kfunc_call_arg_meta *meta)
7951 {
7952         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7953         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7954         struct bpf_reg_state *cur_iter, *queued_iter;
7955         int iter_frameno = meta->iter.frameno;
7956         int iter_spi = meta->iter.spi;
7957
7958         BTF_TYPE_EMIT(struct bpf_iter);
7959
7960         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7961
7962         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7963             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7964                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7965                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7966                 return -EFAULT;
7967         }
7968
7969         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7970                 /* Because iter_next() call is a checkpoint is_state_visitied()
7971                  * should guarantee parent state with same call sites and insn_idx.
7972                  */
7973                 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7974                     !same_callsites(cur_st->parent, cur_st)) {
7975                         verbose(env, "bug: bad parent state for iter next call");
7976                         return -EFAULT;
7977                 }
7978                 /* Note cur_st->parent in the call below, it is necessary to skip
7979                  * checkpoint created for cur_st by is_state_visited()
7980                  * right at this instruction.
7981                  */
7982                 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7983                 /* branch out active iter state */
7984                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7985                 if (!queued_st)
7986                         return -ENOMEM;
7987
7988                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7989                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7990                 queued_iter->iter.depth++;
7991                 if (prev_st)
7992                         widen_imprecise_scalars(env, prev_st, queued_st);
7993
7994                 queued_fr = queued_st->frame[queued_st->curframe];
7995                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7996         }
7997
7998         /* switch to DRAINED state, but keep the depth unchanged */
7999         /* mark current iter state as drained and assume returned NULL */
8000         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8001         __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8002
8003         return 0;
8004 }
8005
8006 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8007 {
8008         return type == ARG_CONST_SIZE ||
8009                type == ARG_CONST_SIZE_OR_ZERO;
8010 }
8011
8012 static bool arg_type_is_release(enum bpf_arg_type type)
8013 {
8014         return type & OBJ_RELEASE;
8015 }
8016
8017 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8018 {
8019         return base_type(type) == ARG_PTR_TO_DYNPTR;
8020 }
8021
8022 static int int_ptr_type_to_size(enum bpf_arg_type type)
8023 {
8024         if (type == ARG_PTR_TO_INT)
8025                 return sizeof(u32);
8026         else if (type == ARG_PTR_TO_LONG)
8027                 return sizeof(u64);
8028
8029         return -EINVAL;
8030 }
8031
8032 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8033                                  const struct bpf_call_arg_meta *meta,
8034                                  enum bpf_arg_type *arg_type)
8035 {
8036         if (!meta->map_ptr) {
8037                 /* kernel subsystem misconfigured verifier */
8038                 verbose(env, "invalid map_ptr to access map->type\n");
8039                 return -EACCES;
8040         }
8041
8042         switch (meta->map_ptr->map_type) {
8043         case BPF_MAP_TYPE_SOCKMAP:
8044         case BPF_MAP_TYPE_SOCKHASH:
8045                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8046                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8047                 } else {
8048                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
8049                         return -EINVAL;
8050                 }
8051                 break;
8052         case BPF_MAP_TYPE_BLOOM_FILTER:
8053                 if (meta->func_id == BPF_FUNC_map_peek_elem)
8054                         *arg_type = ARG_PTR_TO_MAP_VALUE;
8055                 break;
8056         default:
8057                 break;
8058         }
8059         return 0;
8060 }
8061
8062 struct bpf_reg_types {
8063         const enum bpf_reg_type types[10];
8064         u32 *btf_id;
8065 };
8066
8067 static const struct bpf_reg_types sock_types = {
8068         .types = {
8069                 PTR_TO_SOCK_COMMON,
8070                 PTR_TO_SOCKET,
8071                 PTR_TO_TCP_SOCK,
8072                 PTR_TO_XDP_SOCK,
8073         },
8074 };
8075
8076 #ifdef CONFIG_NET
8077 static const struct bpf_reg_types btf_id_sock_common_types = {
8078         .types = {
8079                 PTR_TO_SOCK_COMMON,
8080                 PTR_TO_SOCKET,
8081                 PTR_TO_TCP_SOCK,
8082                 PTR_TO_XDP_SOCK,
8083                 PTR_TO_BTF_ID,
8084                 PTR_TO_BTF_ID | PTR_TRUSTED,
8085         },
8086         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8087 };
8088 #endif
8089
8090 static const struct bpf_reg_types mem_types = {
8091         .types = {
8092                 PTR_TO_STACK,
8093                 PTR_TO_PACKET,
8094                 PTR_TO_PACKET_META,
8095                 PTR_TO_MAP_KEY,
8096                 PTR_TO_MAP_VALUE,
8097                 PTR_TO_MEM,
8098                 PTR_TO_MEM | MEM_RINGBUF,
8099                 PTR_TO_BUF,
8100                 PTR_TO_BTF_ID | PTR_TRUSTED,
8101         },
8102 };
8103
8104 static const struct bpf_reg_types int_ptr_types = {
8105         .types = {
8106                 PTR_TO_STACK,
8107                 PTR_TO_PACKET,
8108                 PTR_TO_PACKET_META,
8109                 PTR_TO_MAP_KEY,
8110                 PTR_TO_MAP_VALUE,
8111         },
8112 };
8113
8114 static const struct bpf_reg_types spin_lock_types = {
8115         .types = {
8116                 PTR_TO_MAP_VALUE,
8117                 PTR_TO_BTF_ID | MEM_ALLOC,
8118         }
8119 };
8120
8121 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8122 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8123 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8124 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8125 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8126 static const struct bpf_reg_types btf_ptr_types = {
8127         .types = {
8128                 PTR_TO_BTF_ID,
8129                 PTR_TO_BTF_ID | PTR_TRUSTED,
8130                 PTR_TO_BTF_ID | MEM_RCU,
8131         },
8132 };
8133 static const struct bpf_reg_types percpu_btf_ptr_types = {
8134         .types = {
8135                 PTR_TO_BTF_ID | MEM_PERCPU,
8136                 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8137                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8138         }
8139 };
8140 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8141 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8142 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8143 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8144 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8145 static const struct bpf_reg_types dynptr_types = {
8146         .types = {
8147                 PTR_TO_STACK,
8148                 CONST_PTR_TO_DYNPTR,
8149         }
8150 };
8151
8152 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8153         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
8154         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
8155         [ARG_CONST_SIZE]                = &scalar_types,
8156         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
8157         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
8158         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
8159         [ARG_PTR_TO_CTX]                = &context_types,
8160         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
8161 #ifdef CONFIG_NET
8162         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8163 #endif
8164         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
8165         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
8166         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
8167         [ARG_PTR_TO_MEM]                = &mem_types,
8168         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
8169         [ARG_PTR_TO_INT]                = &int_ptr_types,
8170         [ARG_PTR_TO_LONG]               = &int_ptr_types,
8171         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
8172         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
8173         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
8174         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
8175         [ARG_PTR_TO_TIMER]              = &timer_types,
8176         [ARG_PTR_TO_KPTR]               = &kptr_types,
8177         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
8178 };
8179
8180 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8181                           enum bpf_arg_type arg_type,
8182                           const u32 *arg_btf_id,
8183                           struct bpf_call_arg_meta *meta)
8184 {
8185         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8186         enum bpf_reg_type expected, type = reg->type;
8187         const struct bpf_reg_types *compatible;
8188         int i, j;
8189
8190         compatible = compatible_reg_types[base_type(arg_type)];
8191         if (!compatible) {
8192                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8193                 return -EFAULT;
8194         }
8195
8196         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8197          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8198          *
8199          * Same for MAYBE_NULL:
8200          *
8201          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8202          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8203          *
8204          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8205          *
8206          * Therefore we fold these flags depending on the arg_type before comparison.
8207          */
8208         if (arg_type & MEM_RDONLY)
8209                 type &= ~MEM_RDONLY;
8210         if (arg_type & PTR_MAYBE_NULL)
8211                 type &= ~PTR_MAYBE_NULL;
8212         if (base_type(arg_type) == ARG_PTR_TO_MEM)
8213                 type &= ~DYNPTR_TYPE_FLAG_MASK;
8214
8215         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8216                 type &= ~MEM_ALLOC;
8217                 type &= ~MEM_PERCPU;
8218         }
8219
8220         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8221                 expected = compatible->types[i];
8222                 if (expected == NOT_INIT)
8223                         break;
8224
8225                 if (type == expected)
8226                         goto found;
8227         }
8228
8229         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8230         for (j = 0; j + 1 < i; j++)
8231                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8232         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8233         return -EACCES;
8234
8235 found:
8236         if (base_type(reg->type) != PTR_TO_BTF_ID)
8237                 return 0;
8238
8239         if (compatible == &mem_types) {
8240                 if (!(arg_type & MEM_RDONLY)) {
8241                         verbose(env,
8242                                 "%s() may write into memory pointed by R%d type=%s\n",
8243                                 func_id_name(meta->func_id),
8244                                 regno, reg_type_str(env, reg->type));
8245                         return -EACCES;
8246                 }
8247                 return 0;
8248         }
8249
8250         switch ((int)reg->type) {
8251         case PTR_TO_BTF_ID:
8252         case PTR_TO_BTF_ID | PTR_TRUSTED:
8253         case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8254         case PTR_TO_BTF_ID | MEM_RCU:
8255         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8256         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8257         {
8258                 /* For bpf_sk_release, it needs to match against first member
8259                  * 'struct sock_common', hence make an exception for it. This
8260                  * allows bpf_sk_release to work for multiple socket types.
8261                  */
8262                 bool strict_type_match = arg_type_is_release(arg_type) &&
8263                                          meta->func_id != BPF_FUNC_sk_release;
8264
8265                 if (type_may_be_null(reg->type) &&
8266                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8267                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8268                         return -EACCES;
8269                 }
8270
8271                 if (!arg_btf_id) {
8272                         if (!compatible->btf_id) {
8273                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8274                                 return -EFAULT;
8275                         }
8276                         arg_btf_id = compatible->btf_id;
8277                 }
8278
8279                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8280                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8281                                 return -EACCES;
8282                 } else {
8283                         if (arg_btf_id == BPF_PTR_POISON) {
8284                                 verbose(env, "verifier internal error:");
8285                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8286                                         regno);
8287                                 return -EACCES;
8288                         }
8289
8290                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8291                                                   btf_vmlinux, *arg_btf_id,
8292                                                   strict_type_match)) {
8293                                 verbose(env, "R%d is of type %s but %s is expected\n",
8294                                         regno, btf_type_name(reg->btf, reg->btf_id),
8295                                         btf_type_name(btf_vmlinux, *arg_btf_id));
8296                                 return -EACCES;
8297                         }
8298                 }
8299                 break;
8300         }
8301         case PTR_TO_BTF_ID | MEM_ALLOC:
8302         case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8303                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8304                     meta->func_id != BPF_FUNC_kptr_xchg) {
8305                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8306                         return -EFAULT;
8307                 }
8308                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8309                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8310                                 return -EACCES;
8311                 }
8312                 break;
8313         case PTR_TO_BTF_ID | MEM_PERCPU:
8314         case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8315         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8316                 /* Handled by helper specific checks */
8317                 break;
8318         default:
8319                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8320                 return -EFAULT;
8321         }
8322         return 0;
8323 }
8324
8325 static struct btf_field *
8326 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8327 {
8328         struct btf_field *field;
8329         struct btf_record *rec;
8330
8331         rec = reg_btf_record(reg);
8332         if (!rec)
8333                 return NULL;
8334
8335         field = btf_record_find(rec, off, fields);
8336         if (!field)
8337                 return NULL;
8338
8339         return field;
8340 }
8341
8342 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8343                                   const struct bpf_reg_state *reg, int regno,
8344                                   enum bpf_arg_type arg_type)
8345 {
8346         u32 type = reg->type;
8347
8348         /* When referenced register is passed to release function, its fixed
8349          * offset must be 0.
8350          *
8351          * We will check arg_type_is_release reg has ref_obj_id when storing
8352          * meta->release_regno.
8353          */
8354         if (arg_type_is_release(arg_type)) {
8355                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8356                  * may not directly point to the object being released, but to
8357                  * dynptr pointing to such object, which might be at some offset
8358                  * on the stack. In that case, we simply to fallback to the
8359                  * default handling.
8360                  */
8361                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8362                         return 0;
8363
8364                 /* Doing check_ptr_off_reg check for the offset will catch this
8365                  * because fixed_off_ok is false, but checking here allows us
8366                  * to give the user a better error message.
8367                  */
8368                 if (reg->off) {
8369                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8370                                 regno);
8371                         return -EINVAL;
8372                 }
8373                 return __check_ptr_off_reg(env, reg, regno, false);
8374         }
8375
8376         switch (type) {
8377         /* Pointer types where both fixed and variable offset is explicitly allowed: */
8378         case PTR_TO_STACK:
8379         case PTR_TO_PACKET:
8380         case PTR_TO_PACKET_META:
8381         case PTR_TO_MAP_KEY:
8382         case PTR_TO_MAP_VALUE:
8383         case PTR_TO_MEM:
8384         case PTR_TO_MEM | MEM_RDONLY:
8385         case PTR_TO_MEM | MEM_RINGBUF:
8386         case PTR_TO_BUF:
8387         case PTR_TO_BUF | MEM_RDONLY:
8388         case SCALAR_VALUE:
8389                 return 0;
8390         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8391          * fixed offset.
8392          */
8393         case PTR_TO_BTF_ID:
8394         case PTR_TO_BTF_ID | MEM_ALLOC:
8395         case PTR_TO_BTF_ID | PTR_TRUSTED:
8396         case PTR_TO_BTF_ID | MEM_RCU:
8397         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8398         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8399                 /* When referenced PTR_TO_BTF_ID is passed to release function,
8400                  * its fixed offset must be 0. In the other cases, fixed offset
8401                  * can be non-zero. This was already checked above. So pass
8402                  * fixed_off_ok as true to allow fixed offset for all other
8403                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8404                  * still need to do checks instead of returning.
8405                  */
8406                 return __check_ptr_off_reg(env, reg, regno, true);
8407         default:
8408                 return __check_ptr_off_reg(env, reg, regno, false);
8409         }
8410 }
8411
8412 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8413                                                 const struct bpf_func_proto *fn,
8414                                                 struct bpf_reg_state *regs)
8415 {
8416         struct bpf_reg_state *state = NULL;
8417         int i;
8418
8419         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8420                 if (arg_type_is_dynptr(fn->arg_type[i])) {
8421                         if (state) {
8422                                 verbose(env, "verifier internal error: multiple dynptr args\n");
8423                                 return NULL;
8424                         }
8425                         state = &regs[BPF_REG_1 + i];
8426                 }
8427
8428         if (!state)
8429                 verbose(env, "verifier internal error: no dynptr arg found\n");
8430
8431         return state;
8432 }
8433
8434 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8435 {
8436         struct bpf_func_state *state = func(env, reg);
8437         int spi;
8438
8439         if (reg->type == CONST_PTR_TO_DYNPTR)
8440                 return reg->id;
8441         spi = dynptr_get_spi(env, reg);
8442         if (spi < 0)
8443                 return spi;
8444         return state->stack[spi].spilled_ptr.id;
8445 }
8446
8447 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8448 {
8449         struct bpf_func_state *state = func(env, reg);
8450         int spi;
8451
8452         if (reg->type == CONST_PTR_TO_DYNPTR)
8453                 return reg->ref_obj_id;
8454         spi = dynptr_get_spi(env, reg);
8455         if (spi < 0)
8456                 return spi;
8457         return state->stack[spi].spilled_ptr.ref_obj_id;
8458 }
8459
8460 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8461                                             struct bpf_reg_state *reg)
8462 {
8463         struct bpf_func_state *state = func(env, reg);
8464         int spi;
8465
8466         if (reg->type == CONST_PTR_TO_DYNPTR)
8467                 return reg->dynptr.type;
8468
8469         spi = __get_spi(reg->off);
8470         if (spi < 0) {
8471                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8472                 return BPF_DYNPTR_TYPE_INVALID;
8473         }
8474
8475         return state->stack[spi].spilled_ptr.dynptr.type;
8476 }
8477
8478 static int check_reg_const_str(struct bpf_verifier_env *env,
8479                                struct bpf_reg_state *reg, u32 regno)
8480 {
8481         struct bpf_map *map = reg->map_ptr;
8482         int err;
8483         int map_off;
8484         u64 map_addr;
8485         char *str_ptr;
8486
8487         if (reg->type != PTR_TO_MAP_VALUE)
8488                 return -EINVAL;
8489
8490         if (!bpf_map_is_rdonly(map)) {
8491                 verbose(env, "R%d does not point to a readonly map'\n", regno);
8492                 return -EACCES;
8493         }
8494
8495         if (!tnum_is_const(reg->var_off)) {
8496                 verbose(env, "R%d is not a constant address'\n", regno);
8497                 return -EACCES;
8498         }
8499
8500         if (!map->ops->map_direct_value_addr) {
8501                 verbose(env, "no direct value access support for this map type\n");
8502                 return -EACCES;
8503         }
8504
8505         err = check_map_access(env, regno, reg->off,
8506                                map->value_size - reg->off, false,
8507                                ACCESS_HELPER);
8508         if (err)
8509                 return err;
8510
8511         map_off = reg->off + reg->var_off.value;
8512         err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8513         if (err) {
8514                 verbose(env, "direct value access on string failed\n");
8515                 return err;
8516         }
8517
8518         str_ptr = (char *)(long)(map_addr);
8519         if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8520                 verbose(env, "string is not zero-terminated\n");
8521                 return -EINVAL;
8522         }
8523         return 0;
8524 }
8525
8526 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8527                           struct bpf_call_arg_meta *meta,
8528                           const struct bpf_func_proto *fn,
8529                           int insn_idx)
8530 {
8531         u32 regno = BPF_REG_1 + arg;
8532         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8533         enum bpf_arg_type arg_type = fn->arg_type[arg];
8534         enum bpf_reg_type type = reg->type;
8535         u32 *arg_btf_id = NULL;
8536         int err = 0;
8537
8538         if (arg_type == ARG_DONTCARE)
8539                 return 0;
8540
8541         err = check_reg_arg(env, regno, SRC_OP);
8542         if (err)
8543                 return err;
8544
8545         if (arg_type == ARG_ANYTHING) {
8546                 if (is_pointer_value(env, regno)) {
8547                         verbose(env, "R%d leaks addr into helper function\n",
8548                                 regno);
8549                         return -EACCES;
8550                 }
8551                 return 0;
8552         }
8553
8554         if (type_is_pkt_pointer(type) &&
8555             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8556                 verbose(env, "helper access to the packet is not allowed\n");
8557                 return -EACCES;
8558         }
8559
8560         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8561                 err = resolve_map_arg_type(env, meta, &arg_type);
8562                 if (err)
8563                         return err;
8564         }
8565
8566         if (register_is_null(reg) && type_may_be_null(arg_type))
8567                 /* A NULL register has a SCALAR_VALUE type, so skip
8568                  * type checking.
8569                  */
8570                 goto skip_type_check;
8571
8572         /* arg_btf_id and arg_size are in a union. */
8573         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8574             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8575                 arg_btf_id = fn->arg_btf_id[arg];
8576
8577         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8578         if (err)
8579                 return err;
8580
8581         err = check_func_arg_reg_off(env, reg, regno, arg_type);
8582         if (err)
8583                 return err;
8584
8585 skip_type_check:
8586         if (arg_type_is_release(arg_type)) {
8587                 if (arg_type_is_dynptr(arg_type)) {
8588                         struct bpf_func_state *state = func(env, reg);
8589                         int spi;
8590
8591                         /* Only dynptr created on stack can be released, thus
8592                          * the get_spi and stack state checks for spilled_ptr
8593                          * should only be done before process_dynptr_func for
8594                          * PTR_TO_STACK.
8595                          */
8596                         if (reg->type == PTR_TO_STACK) {
8597                                 spi = dynptr_get_spi(env, reg);
8598                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8599                                         verbose(env, "arg %d is an unacquired reference\n", regno);
8600                                         return -EINVAL;
8601                                 }
8602                         } else {
8603                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8604                                 return -EINVAL;
8605                         }
8606                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8607                         verbose(env, "R%d must be referenced when passed to release function\n",
8608                                 regno);
8609                         return -EINVAL;
8610                 }
8611                 if (meta->release_regno) {
8612                         verbose(env, "verifier internal error: more than one release argument\n");
8613                         return -EFAULT;
8614                 }
8615                 meta->release_regno = regno;
8616         }
8617
8618         if (reg->ref_obj_id) {
8619                 if (meta->ref_obj_id) {
8620                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8621                                 regno, reg->ref_obj_id,
8622                                 meta->ref_obj_id);
8623                         return -EFAULT;
8624                 }
8625                 meta->ref_obj_id = reg->ref_obj_id;
8626         }
8627
8628         switch (base_type(arg_type)) {
8629         case ARG_CONST_MAP_PTR:
8630                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8631                 if (meta->map_ptr) {
8632                         /* Use map_uid (which is unique id of inner map) to reject:
8633                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8634                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8635                          * if (inner_map1 && inner_map2) {
8636                          *     timer = bpf_map_lookup_elem(inner_map1);
8637                          *     if (timer)
8638                          *         // mismatch would have been allowed
8639                          *         bpf_timer_init(timer, inner_map2);
8640                          * }
8641                          *
8642                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8643                          */
8644                         if (meta->map_ptr != reg->map_ptr ||
8645                             meta->map_uid != reg->map_uid) {
8646                                 verbose(env,
8647                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8648                                         meta->map_uid, reg->map_uid);
8649                                 return -EINVAL;
8650                         }
8651                 }
8652                 meta->map_ptr = reg->map_ptr;
8653                 meta->map_uid = reg->map_uid;
8654                 break;
8655         case ARG_PTR_TO_MAP_KEY:
8656                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8657                  * check that [key, key + map->key_size) are within
8658                  * stack limits and initialized
8659                  */
8660                 if (!meta->map_ptr) {
8661                         /* in function declaration map_ptr must come before
8662                          * map_key, so that it's verified and known before
8663                          * we have to check map_key here. Otherwise it means
8664                          * that kernel subsystem misconfigured verifier
8665                          */
8666                         verbose(env, "invalid map_ptr to access map->key\n");
8667                         return -EACCES;
8668                 }
8669                 err = check_helper_mem_access(env, regno,
8670                                               meta->map_ptr->key_size, false,
8671                                               NULL);
8672                 break;
8673         case ARG_PTR_TO_MAP_VALUE:
8674                 if (type_may_be_null(arg_type) && register_is_null(reg))
8675                         return 0;
8676
8677                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8678                  * check [value, value + map->value_size) validity
8679                  */
8680                 if (!meta->map_ptr) {
8681                         /* kernel subsystem misconfigured verifier */
8682                         verbose(env, "invalid map_ptr to access map->value\n");
8683                         return -EACCES;
8684                 }
8685                 meta->raw_mode = arg_type & MEM_UNINIT;
8686                 err = check_helper_mem_access(env, regno,
8687                                               meta->map_ptr->value_size, false,
8688                                               meta);
8689                 break;
8690         case ARG_PTR_TO_PERCPU_BTF_ID:
8691                 if (!reg->btf_id) {
8692                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8693                         return -EACCES;
8694                 }
8695                 meta->ret_btf = reg->btf;
8696                 meta->ret_btf_id = reg->btf_id;
8697                 break;
8698         case ARG_PTR_TO_SPIN_LOCK:
8699                 if (in_rbtree_lock_required_cb(env)) {
8700                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8701                         return -EACCES;
8702                 }
8703                 if (meta->func_id == BPF_FUNC_spin_lock) {
8704                         err = process_spin_lock(env, regno, true);
8705                         if (err)
8706                                 return err;
8707                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8708                         err = process_spin_lock(env, regno, false);
8709                         if (err)
8710                                 return err;
8711                 } else {
8712                         verbose(env, "verifier internal error\n");
8713                         return -EFAULT;
8714                 }
8715                 break;
8716         case ARG_PTR_TO_TIMER:
8717                 err = process_timer_func(env, regno, meta);
8718                 if (err)
8719                         return err;
8720                 break;
8721         case ARG_PTR_TO_FUNC:
8722                 meta->subprogno = reg->subprogno;
8723                 break;
8724         case ARG_PTR_TO_MEM:
8725                 /* The access to this pointer is only checked when we hit the
8726                  * next is_mem_size argument below.
8727                  */
8728                 meta->raw_mode = arg_type & MEM_UNINIT;
8729                 if (arg_type & MEM_FIXED_SIZE) {
8730                         err = check_helper_mem_access(env, regno,
8731                                                       fn->arg_size[arg], false,
8732                                                       meta);
8733                 }
8734                 break;
8735         case ARG_CONST_SIZE:
8736                 err = check_mem_size_reg(env, reg, regno, false, meta);
8737                 break;
8738         case ARG_CONST_SIZE_OR_ZERO:
8739                 err = check_mem_size_reg(env, reg, regno, true, meta);
8740                 break;
8741         case ARG_PTR_TO_DYNPTR:
8742                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8743                 if (err)
8744                         return err;
8745                 break;
8746         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8747                 if (!tnum_is_const(reg->var_off)) {
8748                         verbose(env, "R%d is not a known constant'\n",
8749                                 regno);
8750                         return -EACCES;
8751                 }
8752                 meta->mem_size = reg->var_off.value;
8753                 err = mark_chain_precision(env, regno);
8754                 if (err)
8755                         return err;
8756                 break;
8757         case ARG_PTR_TO_INT:
8758         case ARG_PTR_TO_LONG:
8759         {
8760                 int size = int_ptr_type_to_size(arg_type);
8761
8762                 err = check_helper_mem_access(env, regno, size, false, meta);
8763                 if (err)
8764                         return err;
8765                 err = check_ptr_alignment(env, reg, 0, size, true);
8766                 break;
8767         }
8768         case ARG_PTR_TO_CONST_STR:
8769         {
8770                 err = check_reg_const_str(env, reg, regno);
8771                 if (err)
8772                         return err;
8773                 break;
8774         }
8775         case ARG_PTR_TO_KPTR:
8776                 err = process_kptr_func(env, regno, meta);
8777                 if (err)
8778                         return err;
8779                 break;
8780         }
8781
8782         return err;
8783 }
8784
8785 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8786 {
8787         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8788         enum bpf_prog_type type = resolve_prog_type(env->prog);
8789
8790         if (func_id != BPF_FUNC_map_update_elem)
8791                 return false;
8792
8793         /* It's not possible to get access to a locked struct sock in these
8794          * contexts, so updating is safe.
8795          */
8796         switch (type) {
8797         case BPF_PROG_TYPE_TRACING:
8798                 if (eatype == BPF_TRACE_ITER)
8799                         return true;
8800                 break;
8801         case BPF_PROG_TYPE_SOCKET_FILTER:
8802         case BPF_PROG_TYPE_SCHED_CLS:
8803         case BPF_PROG_TYPE_SCHED_ACT:
8804         case BPF_PROG_TYPE_XDP:
8805         case BPF_PROG_TYPE_SK_REUSEPORT:
8806         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8807         case BPF_PROG_TYPE_SK_LOOKUP:
8808                 return true;
8809         default:
8810                 break;
8811         }
8812
8813         verbose(env, "cannot update sockmap in this context\n");
8814         return false;
8815 }
8816
8817 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8818 {
8819         return env->prog->jit_requested &&
8820                bpf_jit_supports_subprog_tailcalls();
8821 }
8822
8823 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8824                                         struct bpf_map *map, int func_id)
8825 {
8826         if (!map)
8827                 return 0;
8828
8829         /* We need a two way check, first is from map perspective ... */
8830         switch (map->map_type) {
8831         case BPF_MAP_TYPE_PROG_ARRAY:
8832                 if (func_id != BPF_FUNC_tail_call)
8833                         goto error;
8834                 break;
8835         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8836                 if (func_id != BPF_FUNC_perf_event_read &&
8837                     func_id != BPF_FUNC_perf_event_output &&
8838                     func_id != BPF_FUNC_skb_output &&
8839                     func_id != BPF_FUNC_perf_event_read_value &&
8840                     func_id != BPF_FUNC_xdp_output)
8841                         goto error;
8842                 break;
8843         case BPF_MAP_TYPE_RINGBUF:
8844                 if (func_id != BPF_FUNC_ringbuf_output &&
8845                     func_id != BPF_FUNC_ringbuf_reserve &&
8846                     func_id != BPF_FUNC_ringbuf_query &&
8847                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8848                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8849                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8850                         goto error;
8851                 break;
8852         case BPF_MAP_TYPE_USER_RINGBUF:
8853                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8854                         goto error;
8855                 break;
8856         case BPF_MAP_TYPE_STACK_TRACE:
8857                 if (func_id != BPF_FUNC_get_stackid)
8858                         goto error;
8859                 break;
8860         case BPF_MAP_TYPE_CGROUP_ARRAY:
8861                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8862                     func_id != BPF_FUNC_current_task_under_cgroup)
8863                         goto error;
8864                 break;
8865         case BPF_MAP_TYPE_CGROUP_STORAGE:
8866         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8867                 if (func_id != BPF_FUNC_get_local_storage)
8868                         goto error;
8869                 break;
8870         case BPF_MAP_TYPE_DEVMAP:
8871         case BPF_MAP_TYPE_DEVMAP_HASH:
8872                 if (func_id != BPF_FUNC_redirect_map &&
8873                     func_id != BPF_FUNC_map_lookup_elem)
8874                         goto error;
8875                 break;
8876         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8877          * appear.
8878          */
8879         case BPF_MAP_TYPE_CPUMAP:
8880                 if (func_id != BPF_FUNC_redirect_map)
8881                         goto error;
8882                 break;
8883         case BPF_MAP_TYPE_XSKMAP:
8884                 if (func_id != BPF_FUNC_redirect_map &&
8885                     func_id != BPF_FUNC_map_lookup_elem)
8886                         goto error;
8887                 break;
8888         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8889         case BPF_MAP_TYPE_HASH_OF_MAPS:
8890                 if (func_id != BPF_FUNC_map_lookup_elem)
8891                         goto error;
8892                 break;
8893         case BPF_MAP_TYPE_SOCKMAP:
8894                 if (func_id != BPF_FUNC_sk_redirect_map &&
8895                     func_id != BPF_FUNC_sock_map_update &&
8896                     func_id != BPF_FUNC_map_delete_elem &&
8897                     func_id != BPF_FUNC_msg_redirect_map &&
8898                     func_id != BPF_FUNC_sk_select_reuseport &&
8899                     func_id != BPF_FUNC_map_lookup_elem &&
8900                     !may_update_sockmap(env, func_id))
8901                         goto error;
8902                 break;
8903         case BPF_MAP_TYPE_SOCKHASH:
8904                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8905                     func_id != BPF_FUNC_sock_hash_update &&
8906                     func_id != BPF_FUNC_map_delete_elem &&
8907                     func_id != BPF_FUNC_msg_redirect_hash &&
8908                     func_id != BPF_FUNC_sk_select_reuseport &&
8909                     func_id != BPF_FUNC_map_lookup_elem &&
8910                     !may_update_sockmap(env, func_id))
8911                         goto error;
8912                 break;
8913         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8914                 if (func_id != BPF_FUNC_sk_select_reuseport)
8915                         goto error;
8916                 break;
8917         case BPF_MAP_TYPE_QUEUE:
8918         case BPF_MAP_TYPE_STACK:
8919                 if (func_id != BPF_FUNC_map_peek_elem &&
8920                     func_id != BPF_FUNC_map_pop_elem &&
8921                     func_id != BPF_FUNC_map_push_elem)
8922                         goto error;
8923                 break;
8924         case BPF_MAP_TYPE_SK_STORAGE:
8925                 if (func_id != BPF_FUNC_sk_storage_get &&
8926                     func_id != BPF_FUNC_sk_storage_delete &&
8927                     func_id != BPF_FUNC_kptr_xchg)
8928                         goto error;
8929                 break;
8930         case BPF_MAP_TYPE_INODE_STORAGE:
8931                 if (func_id != BPF_FUNC_inode_storage_get &&
8932                     func_id != BPF_FUNC_inode_storage_delete &&
8933                     func_id != BPF_FUNC_kptr_xchg)
8934                         goto error;
8935                 break;
8936         case BPF_MAP_TYPE_TASK_STORAGE:
8937                 if (func_id != BPF_FUNC_task_storage_get &&
8938                     func_id != BPF_FUNC_task_storage_delete &&
8939                     func_id != BPF_FUNC_kptr_xchg)
8940                         goto error;
8941                 break;
8942         case BPF_MAP_TYPE_CGRP_STORAGE:
8943                 if (func_id != BPF_FUNC_cgrp_storage_get &&
8944                     func_id != BPF_FUNC_cgrp_storage_delete &&
8945                     func_id != BPF_FUNC_kptr_xchg)
8946                         goto error;
8947                 break;
8948         case BPF_MAP_TYPE_BLOOM_FILTER:
8949                 if (func_id != BPF_FUNC_map_peek_elem &&
8950                     func_id != BPF_FUNC_map_push_elem)
8951                         goto error;
8952                 break;
8953         default:
8954                 break;
8955         }
8956
8957         /* ... and second from the function itself. */
8958         switch (func_id) {
8959         case BPF_FUNC_tail_call:
8960                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8961                         goto error;
8962                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8963                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8964                         return -EINVAL;
8965                 }
8966                 break;
8967         case BPF_FUNC_perf_event_read:
8968         case BPF_FUNC_perf_event_output:
8969         case BPF_FUNC_perf_event_read_value:
8970         case BPF_FUNC_skb_output:
8971         case BPF_FUNC_xdp_output:
8972                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8973                         goto error;
8974                 break;
8975         case BPF_FUNC_ringbuf_output:
8976         case BPF_FUNC_ringbuf_reserve:
8977         case BPF_FUNC_ringbuf_query:
8978         case BPF_FUNC_ringbuf_reserve_dynptr:
8979         case BPF_FUNC_ringbuf_submit_dynptr:
8980         case BPF_FUNC_ringbuf_discard_dynptr:
8981                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8982                         goto error;
8983                 break;
8984         case BPF_FUNC_user_ringbuf_drain:
8985                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8986                         goto error;
8987                 break;
8988         case BPF_FUNC_get_stackid:
8989                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8990                         goto error;
8991                 break;
8992         case BPF_FUNC_current_task_under_cgroup:
8993         case BPF_FUNC_skb_under_cgroup:
8994                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8995                         goto error;
8996                 break;
8997         case BPF_FUNC_redirect_map:
8998                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8999                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9000                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
9001                     map->map_type != BPF_MAP_TYPE_XSKMAP)
9002                         goto error;
9003                 break;
9004         case BPF_FUNC_sk_redirect_map:
9005         case BPF_FUNC_msg_redirect_map:
9006         case BPF_FUNC_sock_map_update:
9007                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9008                         goto error;
9009                 break;
9010         case BPF_FUNC_sk_redirect_hash:
9011         case BPF_FUNC_msg_redirect_hash:
9012         case BPF_FUNC_sock_hash_update:
9013                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9014                         goto error;
9015                 break;
9016         case BPF_FUNC_get_local_storage:
9017                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9018                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9019                         goto error;
9020                 break;
9021         case BPF_FUNC_sk_select_reuseport:
9022                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9023                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9024                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
9025                         goto error;
9026                 break;
9027         case BPF_FUNC_map_pop_elem:
9028                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9029                     map->map_type != BPF_MAP_TYPE_STACK)
9030                         goto error;
9031                 break;
9032         case BPF_FUNC_map_peek_elem:
9033         case BPF_FUNC_map_push_elem:
9034                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9035                     map->map_type != BPF_MAP_TYPE_STACK &&
9036                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9037                         goto error;
9038                 break;
9039         case BPF_FUNC_map_lookup_percpu_elem:
9040                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9041                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9042                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9043                         goto error;
9044                 break;
9045         case BPF_FUNC_sk_storage_get:
9046         case BPF_FUNC_sk_storage_delete:
9047                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9048                         goto error;
9049                 break;
9050         case BPF_FUNC_inode_storage_get:
9051         case BPF_FUNC_inode_storage_delete:
9052                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9053                         goto error;
9054                 break;
9055         case BPF_FUNC_task_storage_get:
9056         case BPF_FUNC_task_storage_delete:
9057                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9058                         goto error;
9059                 break;
9060         case BPF_FUNC_cgrp_storage_get:
9061         case BPF_FUNC_cgrp_storage_delete:
9062                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9063                         goto error;
9064                 break;
9065         default:
9066                 break;
9067         }
9068
9069         return 0;
9070 error:
9071         verbose(env, "cannot pass map_type %d into func %s#%d\n",
9072                 map->map_type, func_id_name(func_id), func_id);
9073         return -EINVAL;
9074 }
9075
9076 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9077 {
9078         int count = 0;
9079
9080         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9081                 count++;
9082         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9083                 count++;
9084         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9085                 count++;
9086         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9087                 count++;
9088         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9089                 count++;
9090
9091         /* We only support one arg being in raw mode at the moment,
9092          * which is sufficient for the helper functions we have
9093          * right now.
9094          */
9095         return count <= 1;
9096 }
9097
9098 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9099 {
9100         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9101         bool has_size = fn->arg_size[arg] != 0;
9102         bool is_next_size = false;
9103
9104         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9105                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9106
9107         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9108                 return is_next_size;
9109
9110         return has_size == is_next_size || is_next_size == is_fixed;
9111 }
9112
9113 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9114 {
9115         /* bpf_xxx(..., buf, len) call will access 'len'
9116          * bytes from memory 'buf'. Both arg types need
9117          * to be paired, so make sure there's no buggy
9118          * helper function specification.
9119          */
9120         if (arg_type_is_mem_size(fn->arg1_type) ||
9121             check_args_pair_invalid(fn, 0) ||
9122             check_args_pair_invalid(fn, 1) ||
9123             check_args_pair_invalid(fn, 2) ||
9124             check_args_pair_invalid(fn, 3) ||
9125             check_args_pair_invalid(fn, 4))
9126                 return false;
9127
9128         return true;
9129 }
9130
9131 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9132 {
9133         int i;
9134
9135         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9136                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9137                         return !!fn->arg_btf_id[i];
9138                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9139                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
9140                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9141                     /* arg_btf_id and arg_size are in a union. */
9142                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9143                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9144                         return false;
9145         }
9146
9147         return true;
9148 }
9149
9150 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9151 {
9152         return check_raw_mode_ok(fn) &&
9153                check_arg_pair_ok(fn) &&
9154                check_btf_id_ok(fn) ? 0 : -EINVAL;
9155 }
9156
9157 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9158  * are now invalid, so turn them into unknown SCALAR_VALUE.
9159  *
9160  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9161  * since these slices point to packet data.
9162  */
9163 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9164 {
9165         struct bpf_func_state *state;
9166         struct bpf_reg_state *reg;
9167
9168         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9169                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9170                         mark_reg_invalid(env, reg);
9171         }));
9172 }
9173
9174 enum {
9175         AT_PKT_END = -1,
9176         BEYOND_PKT_END = -2,
9177 };
9178
9179 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9180 {
9181         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9182         struct bpf_reg_state *reg = &state->regs[regn];
9183
9184         if (reg->type != PTR_TO_PACKET)
9185                 /* PTR_TO_PACKET_META is not supported yet */
9186                 return;
9187
9188         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9189          * How far beyond pkt_end it goes is unknown.
9190          * if (!range_open) it's the case of pkt >= pkt_end
9191          * if (range_open) it's the case of pkt > pkt_end
9192          * hence this pointer is at least 1 byte bigger than pkt_end
9193          */
9194         if (range_open)
9195                 reg->range = BEYOND_PKT_END;
9196         else
9197                 reg->range = AT_PKT_END;
9198 }
9199
9200 /* The pointer with the specified id has released its reference to kernel
9201  * resources. Identify all copies of the same pointer and clear the reference.
9202  */
9203 static int release_reference(struct bpf_verifier_env *env,
9204                              int ref_obj_id)
9205 {
9206         struct bpf_func_state *state;
9207         struct bpf_reg_state *reg;
9208         int err;
9209
9210         err = release_reference_state(cur_func(env), ref_obj_id);
9211         if (err)
9212                 return err;
9213
9214         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9215                 if (reg->ref_obj_id == ref_obj_id)
9216                         mark_reg_invalid(env, reg);
9217         }));
9218
9219         return 0;
9220 }
9221
9222 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9223 {
9224         struct bpf_func_state *unused;
9225         struct bpf_reg_state *reg;
9226
9227         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9228                 if (type_is_non_owning_ref(reg->type))
9229                         mark_reg_invalid(env, reg);
9230         }));
9231 }
9232
9233 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9234                                     struct bpf_reg_state *regs)
9235 {
9236         int i;
9237
9238         /* after the call registers r0 - r5 were scratched */
9239         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9240                 mark_reg_not_init(env, regs, caller_saved[i]);
9241                 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9242         }
9243 }
9244
9245 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9246                                    struct bpf_func_state *caller,
9247                                    struct bpf_func_state *callee,
9248                                    int insn_idx);
9249
9250 static int set_callee_state(struct bpf_verifier_env *env,
9251                             struct bpf_func_state *caller,
9252                             struct bpf_func_state *callee, int insn_idx);
9253
9254 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9255                             set_callee_state_fn set_callee_state_cb,
9256                             struct bpf_verifier_state *state)
9257 {
9258         struct bpf_func_state *caller, *callee;
9259         int err;
9260
9261         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9262                 verbose(env, "the call stack of %d frames is too deep\n",
9263                         state->curframe + 2);
9264                 return -E2BIG;
9265         }
9266
9267         if (state->frame[state->curframe + 1]) {
9268                 verbose(env, "verifier bug. Frame %d already allocated\n",
9269                         state->curframe + 1);
9270                 return -EFAULT;
9271         }
9272
9273         caller = state->frame[state->curframe];
9274         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9275         if (!callee)
9276                 return -ENOMEM;
9277         state->frame[state->curframe + 1] = callee;
9278
9279         /* callee cannot access r0, r6 - r9 for reading and has to write
9280          * into its own stack before reading from it.
9281          * callee can read/write into caller's stack
9282          */
9283         init_func_state(env, callee,
9284                         /* remember the callsite, it will be used by bpf_exit */
9285                         callsite,
9286                         state->curframe + 1 /* frameno within this callchain */,
9287                         subprog /* subprog number within this prog */);
9288         /* Transfer references to the callee */
9289         err = copy_reference_state(callee, caller);
9290         err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9291         if (err)
9292                 goto err_out;
9293
9294         /* only increment it after check_reg_arg() finished */
9295         state->curframe++;
9296
9297         return 0;
9298
9299 err_out:
9300         free_func_state(callee);
9301         state->frame[state->curframe + 1] = NULL;
9302         return err;
9303 }
9304
9305 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9306                                     const struct btf *btf,
9307                                     struct bpf_reg_state *regs)
9308 {
9309         struct bpf_subprog_info *sub = subprog_info(env, subprog);
9310         struct bpf_verifier_log *log = &env->log;
9311         u32 i;
9312         int ret;
9313
9314         ret = btf_prepare_func_args(env, subprog);
9315         if (ret)
9316                 return ret;
9317
9318         /* check that BTF function arguments match actual types that the
9319          * verifier sees.
9320          */
9321         for (i = 0; i < sub->arg_cnt; i++) {
9322                 u32 regno = i + 1;
9323                 struct bpf_reg_state *reg = &regs[regno];
9324                 struct bpf_subprog_arg_info *arg = &sub->args[i];
9325
9326                 if (arg->arg_type == ARG_ANYTHING) {
9327                         if (reg->type != SCALAR_VALUE) {
9328                                 bpf_log(log, "R%d is not a scalar\n", regno);
9329                                 return -EINVAL;
9330                         }
9331                 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
9332                         ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9333                         if (ret < 0)
9334                                 return ret;
9335                         /* If function expects ctx type in BTF check that caller
9336                          * is passing PTR_TO_CTX.
9337                          */
9338                         if (reg->type != PTR_TO_CTX) {
9339                                 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9340                                 return -EINVAL;
9341                         }
9342                 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9343                         ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9344                         if (ret < 0)
9345                                 return ret;
9346                         if (check_mem_reg(env, reg, regno, arg->mem_size))
9347                                 return -EINVAL;
9348                         if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9349                                 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9350                                 return -EINVAL;
9351                         }
9352                 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9353                         ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9354                         if (ret)
9355                                 return ret;
9356                 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9357                         struct bpf_call_arg_meta meta;
9358                         int err;
9359
9360                         if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9361                                 continue;
9362
9363                         memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9364                         err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9365                         err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9366                         if (err)
9367                                 return err;
9368                 } else {
9369                         bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9370                                 i, arg->arg_type);
9371                         return -EFAULT;
9372                 }
9373         }
9374
9375         return 0;
9376 }
9377
9378 /* Compare BTF of a function call with given bpf_reg_state.
9379  * Returns:
9380  * EFAULT - there is a verifier bug. Abort verification.
9381  * EINVAL - there is a type mismatch or BTF is not available.
9382  * 0 - BTF matches with what bpf_reg_state expects.
9383  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9384  */
9385 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9386                                   struct bpf_reg_state *regs)
9387 {
9388         struct bpf_prog *prog = env->prog;
9389         struct btf *btf = prog->aux->btf;
9390         u32 btf_id;
9391         int err;
9392
9393         if (!prog->aux->func_info)
9394                 return -EINVAL;
9395
9396         btf_id = prog->aux->func_info[subprog].type_id;
9397         if (!btf_id)
9398                 return -EFAULT;
9399
9400         if (prog->aux->func_info_aux[subprog].unreliable)
9401                 return -EINVAL;
9402
9403         err = btf_check_func_arg_match(env, subprog, btf, regs);
9404         /* Compiler optimizations can remove arguments from static functions
9405          * or mismatched type can be passed into a global function.
9406          * In such cases mark the function as unreliable from BTF point of view.
9407          */
9408         if (err)
9409                 prog->aux->func_info_aux[subprog].unreliable = true;
9410         return err;
9411 }
9412
9413 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9414                               int insn_idx, int subprog,
9415                               set_callee_state_fn set_callee_state_cb)
9416 {
9417         struct bpf_verifier_state *state = env->cur_state, *callback_state;
9418         struct bpf_func_state *caller, *callee;
9419         int err;
9420
9421         caller = state->frame[state->curframe];
9422         err = btf_check_subprog_call(env, subprog, caller->regs);
9423         if (err == -EFAULT)
9424                 return err;
9425
9426         /* set_callee_state is used for direct subprog calls, but we are
9427          * interested in validating only BPF helpers that can call subprogs as
9428          * callbacks
9429          */
9430         env->subprog_info[subprog].is_cb = true;
9431         if (bpf_pseudo_kfunc_call(insn) &&
9432             !is_sync_callback_calling_kfunc(insn->imm)) {
9433                 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9434                         func_id_name(insn->imm), insn->imm);
9435                 return -EFAULT;
9436         } else if (!bpf_pseudo_kfunc_call(insn) &&
9437                    !is_callback_calling_function(insn->imm)) { /* helper */
9438                 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9439                         func_id_name(insn->imm), insn->imm);
9440                 return -EFAULT;
9441         }
9442
9443         if (insn->code == (BPF_JMP | BPF_CALL) &&
9444             insn->src_reg == 0 &&
9445             insn->imm == BPF_FUNC_timer_set_callback) {
9446                 struct bpf_verifier_state *async_cb;
9447
9448                 /* there is no real recursion here. timer callbacks are async */
9449                 env->subprog_info[subprog].is_async_cb = true;
9450                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9451                                          insn_idx, subprog);
9452                 if (!async_cb)
9453                         return -EFAULT;
9454                 callee = async_cb->frame[0];
9455                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9456
9457                 /* Convert bpf_timer_set_callback() args into timer callback args */
9458                 err = set_callee_state_cb(env, caller, callee, insn_idx);
9459                 if (err)
9460                         return err;
9461
9462                 return 0;
9463         }
9464
9465         /* for callback functions enqueue entry to callback and
9466          * proceed with next instruction within current frame.
9467          */
9468         callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9469         if (!callback_state)
9470                 return -ENOMEM;
9471
9472         err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9473                                callback_state);
9474         if (err)
9475                 return err;
9476
9477         callback_state->callback_unroll_depth++;
9478         callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9479         caller->callback_depth = 0;
9480         return 0;
9481 }
9482
9483 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9484                            int *insn_idx)
9485 {
9486         struct bpf_verifier_state *state = env->cur_state;
9487         struct bpf_func_state *caller;
9488         int err, subprog, target_insn;
9489
9490         target_insn = *insn_idx + insn->imm + 1;
9491         subprog = find_subprog(env, target_insn);
9492         if (subprog < 0) {
9493                 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9494                 return -EFAULT;
9495         }
9496
9497         caller = state->frame[state->curframe];
9498         err = btf_check_subprog_call(env, subprog, caller->regs);
9499         if (err == -EFAULT)
9500                 return err;
9501         if (subprog_is_global(env, subprog)) {
9502                 const char *sub_name = subprog_name(env, subprog);
9503
9504                 /* Only global subprogs cannot be called with a lock held. */
9505                 if (env->cur_state->active_lock.ptr) {
9506                         verbose(env, "global function calls are not allowed while holding a lock,\n"
9507                                      "use static function instead\n");
9508                         return -EINVAL;
9509                 }
9510
9511                 if (err) {
9512                         verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9513                                 subprog, sub_name);
9514                         return err;
9515                 }
9516
9517                 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9518                         subprog, sub_name);
9519                 /* mark global subprog for verifying after main prog */
9520                 subprog_aux(env, subprog)->called = true;
9521                 clear_caller_saved_regs(env, caller->regs);
9522
9523                 /* All global functions return a 64-bit SCALAR_VALUE */
9524                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9525                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9526
9527                 /* continue with next insn after call */
9528                 return 0;
9529         }
9530
9531         /* for regular function entry setup new frame and continue
9532          * from that frame.
9533          */
9534         err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9535         if (err)
9536                 return err;
9537
9538         clear_caller_saved_regs(env, caller->regs);
9539
9540         /* and go analyze first insn of the callee */
9541         *insn_idx = env->subprog_info[subprog].start - 1;
9542
9543         if (env->log.level & BPF_LOG_LEVEL) {
9544                 verbose(env, "caller:\n");
9545                 print_verifier_state(env, caller, true);
9546                 verbose(env, "callee:\n");
9547                 print_verifier_state(env, state->frame[state->curframe], true);
9548         }
9549
9550         return 0;
9551 }
9552
9553 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9554                                    struct bpf_func_state *caller,
9555                                    struct bpf_func_state *callee)
9556 {
9557         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9558          *      void *callback_ctx, u64 flags);
9559          * callback_fn(struct bpf_map *map, void *key, void *value,
9560          *      void *callback_ctx);
9561          */
9562         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9563
9564         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9565         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9566         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9567
9568         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9569         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9570         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9571
9572         /* pointer to stack or null */
9573         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9574
9575         /* unused */
9576         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9577         return 0;
9578 }
9579
9580 static int set_callee_state(struct bpf_verifier_env *env,
9581                             struct bpf_func_state *caller,
9582                             struct bpf_func_state *callee, int insn_idx)
9583 {
9584         int i;
9585
9586         /* copy r1 - r5 args that callee can access.  The copy includes parent
9587          * pointers, which connects us up to the liveness chain
9588          */
9589         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9590                 callee->regs[i] = caller->regs[i];
9591         return 0;
9592 }
9593
9594 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9595                                        struct bpf_func_state *caller,
9596                                        struct bpf_func_state *callee,
9597                                        int insn_idx)
9598 {
9599         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9600         struct bpf_map *map;
9601         int err;
9602
9603         if (bpf_map_ptr_poisoned(insn_aux)) {
9604                 verbose(env, "tail_call abusing map_ptr\n");
9605                 return -EINVAL;
9606         }
9607
9608         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9609         if (!map->ops->map_set_for_each_callback_args ||
9610             !map->ops->map_for_each_callback) {
9611                 verbose(env, "callback function not allowed for map\n");
9612                 return -ENOTSUPP;
9613         }
9614
9615         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9616         if (err)
9617                 return err;
9618
9619         callee->in_callback_fn = true;
9620         callee->callback_ret_range = retval_range(0, 1);
9621         return 0;
9622 }
9623
9624 static int set_loop_callback_state(struct bpf_verifier_env *env,
9625                                    struct bpf_func_state *caller,
9626                                    struct bpf_func_state *callee,
9627                                    int insn_idx)
9628 {
9629         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9630          *          u64 flags);
9631          * callback_fn(u32 index, void *callback_ctx);
9632          */
9633         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9634         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9635
9636         /* unused */
9637         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9638         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9639         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9640
9641         callee->in_callback_fn = true;
9642         callee->callback_ret_range = retval_range(0, 1);
9643         return 0;
9644 }
9645
9646 static int set_timer_callback_state(struct bpf_verifier_env *env,
9647                                     struct bpf_func_state *caller,
9648                                     struct bpf_func_state *callee,
9649                                     int insn_idx)
9650 {
9651         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9652
9653         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9654          * callback_fn(struct bpf_map *map, void *key, void *value);
9655          */
9656         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9657         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9658         callee->regs[BPF_REG_1].map_ptr = map_ptr;
9659
9660         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9661         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9662         callee->regs[BPF_REG_2].map_ptr = map_ptr;
9663
9664         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9665         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9666         callee->regs[BPF_REG_3].map_ptr = map_ptr;
9667
9668         /* unused */
9669         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9670         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9671         callee->in_async_callback_fn = true;
9672         callee->callback_ret_range = retval_range(0, 1);
9673         return 0;
9674 }
9675
9676 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9677                                        struct bpf_func_state *caller,
9678                                        struct bpf_func_state *callee,
9679                                        int insn_idx)
9680 {
9681         /* bpf_find_vma(struct task_struct *task, u64 addr,
9682          *               void *callback_fn, void *callback_ctx, u64 flags)
9683          * (callback_fn)(struct task_struct *task,
9684          *               struct vm_area_struct *vma, void *callback_ctx);
9685          */
9686         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9687
9688         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9689         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9690         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9691         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9692
9693         /* pointer to stack or null */
9694         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9695
9696         /* unused */
9697         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9698         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9699         callee->in_callback_fn = true;
9700         callee->callback_ret_range = retval_range(0, 1);
9701         return 0;
9702 }
9703
9704 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9705                                            struct bpf_func_state *caller,
9706                                            struct bpf_func_state *callee,
9707                                            int insn_idx)
9708 {
9709         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9710          *                        callback_ctx, u64 flags);
9711          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9712          */
9713         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9714         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9715         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9716
9717         /* unused */
9718         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9719         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9720         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9721
9722         callee->in_callback_fn = true;
9723         callee->callback_ret_range = retval_range(0, 1);
9724         return 0;
9725 }
9726
9727 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9728                                          struct bpf_func_state *caller,
9729                                          struct bpf_func_state *callee,
9730                                          int insn_idx)
9731 {
9732         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9733          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9734          *
9735          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9736          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9737          * by this point, so look at 'root'
9738          */
9739         struct btf_field *field;
9740
9741         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9742                                       BPF_RB_ROOT);
9743         if (!field || !field->graph_root.value_btf_id)
9744                 return -EFAULT;
9745
9746         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9747         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9748         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9749         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9750
9751         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9752         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9753         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9754         callee->in_callback_fn = true;
9755         callee->callback_ret_range = retval_range(0, 1);
9756         return 0;
9757 }
9758
9759 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9760
9761 /* Are we currently verifying the callback for a rbtree helper that must
9762  * be called with lock held? If so, no need to complain about unreleased
9763  * lock
9764  */
9765 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9766 {
9767         struct bpf_verifier_state *state = env->cur_state;
9768         struct bpf_insn *insn = env->prog->insnsi;
9769         struct bpf_func_state *callee;
9770         int kfunc_btf_id;
9771
9772         if (!state->curframe)
9773                 return false;
9774
9775         callee = state->frame[state->curframe];
9776
9777         if (!callee->in_callback_fn)
9778                 return false;
9779
9780         kfunc_btf_id = insn[callee->callsite].imm;
9781         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9782 }
9783
9784 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9785 {
9786         return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9787 }
9788
9789 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9790 {
9791         struct bpf_verifier_state *state = env->cur_state, *prev_st;
9792         struct bpf_func_state *caller, *callee;
9793         struct bpf_reg_state *r0;
9794         bool in_callback_fn;
9795         int err;
9796
9797         callee = state->frame[state->curframe];
9798         r0 = &callee->regs[BPF_REG_0];
9799         if (r0->type == PTR_TO_STACK) {
9800                 /* technically it's ok to return caller's stack pointer
9801                  * (or caller's caller's pointer) back to the caller,
9802                  * since these pointers are valid. Only current stack
9803                  * pointer will be invalid as soon as function exits,
9804                  * but let's be conservative
9805                  */
9806                 verbose(env, "cannot return stack pointer to the caller\n");
9807                 return -EINVAL;
9808         }
9809
9810         caller = state->frame[state->curframe - 1];
9811         if (callee->in_callback_fn) {
9812                 if (r0->type != SCALAR_VALUE) {
9813                         verbose(env, "R0 not a scalar value\n");
9814                         return -EACCES;
9815                 }
9816
9817                 /* we are going to rely on register's precise value */
9818                 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9819                 err = err ?: mark_chain_precision(env, BPF_REG_0);
9820                 if (err)
9821                         return err;
9822
9823                 /* enforce R0 return value range */
9824                 if (!retval_range_within(callee->callback_ret_range, r0)) {
9825                         verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9826                                                "At callback return", "R0");
9827                         return -EINVAL;
9828                 }
9829                 if (!calls_callback(env, callee->callsite)) {
9830                         verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9831                                 *insn_idx, callee->callsite);
9832                         return -EFAULT;
9833                 }
9834         } else {
9835                 /* return to the caller whatever r0 had in the callee */
9836                 caller->regs[BPF_REG_0] = *r0;
9837         }
9838
9839         /* callback_fn frame should have released its own additions to parent's
9840          * reference state at this point, or check_reference_leak would
9841          * complain, hence it must be the same as the caller. There is no need
9842          * to copy it back.
9843          */
9844         if (!callee->in_callback_fn) {
9845                 /* Transfer references to the caller */
9846                 err = copy_reference_state(caller, callee);
9847                 if (err)
9848                         return err;
9849         }
9850
9851         /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9852          * there function call logic would reschedule callback visit. If iteration
9853          * converges is_state_visited() would prune that visit eventually.
9854          */
9855         in_callback_fn = callee->in_callback_fn;
9856         if (in_callback_fn)
9857                 *insn_idx = callee->callsite;
9858         else
9859                 *insn_idx = callee->callsite + 1;
9860
9861         if (env->log.level & BPF_LOG_LEVEL) {
9862                 verbose(env, "returning from callee:\n");
9863                 print_verifier_state(env, callee, true);
9864                 verbose(env, "to caller at %d:\n", *insn_idx);
9865                 print_verifier_state(env, caller, true);
9866         }
9867         /* clear everything in the callee. In case of exceptional exits using
9868          * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9869         free_func_state(callee);
9870         state->frame[state->curframe--] = NULL;
9871
9872         /* for callbacks widen imprecise scalars to make programs like below verify:
9873          *
9874          *   struct ctx { int i; }
9875          *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9876          *   ...
9877          *   struct ctx = { .i = 0; }
9878          *   bpf_loop(100, cb, &ctx, 0);
9879          *
9880          * This is similar to what is done in process_iter_next_call() for open
9881          * coded iterators.
9882          */
9883         prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9884         if (prev_st) {
9885                 err = widen_imprecise_scalars(env, prev_st, state);
9886                 if (err)
9887                         return err;
9888         }
9889         return 0;
9890 }
9891
9892 static int do_refine_retval_range(struct bpf_verifier_env *env,
9893                                   struct bpf_reg_state *regs, int ret_type,
9894                                   int func_id,
9895                                   struct bpf_call_arg_meta *meta)
9896 {
9897         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9898
9899         if (ret_type != RET_INTEGER)
9900                 return 0;
9901
9902         switch (func_id) {
9903         case BPF_FUNC_get_stack:
9904         case BPF_FUNC_get_task_stack:
9905         case BPF_FUNC_probe_read_str:
9906         case BPF_FUNC_probe_read_kernel_str:
9907         case BPF_FUNC_probe_read_user_str:
9908                 ret_reg->smax_value = meta->msize_max_value;
9909                 ret_reg->s32_max_value = meta->msize_max_value;
9910                 ret_reg->smin_value = -MAX_ERRNO;
9911                 ret_reg->s32_min_value = -MAX_ERRNO;
9912                 reg_bounds_sync(ret_reg);
9913                 break;
9914         case BPF_FUNC_get_smp_processor_id:
9915                 ret_reg->umax_value = nr_cpu_ids - 1;
9916                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9917                 ret_reg->smax_value = nr_cpu_ids - 1;
9918                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9919                 ret_reg->umin_value = 0;
9920                 ret_reg->u32_min_value = 0;
9921                 ret_reg->smin_value = 0;
9922                 ret_reg->s32_min_value = 0;
9923                 reg_bounds_sync(ret_reg);
9924                 break;
9925         }
9926
9927         return reg_bounds_sanity_check(env, ret_reg, "retval");
9928 }
9929
9930 static int
9931 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9932                 int func_id, int insn_idx)
9933 {
9934         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9935         struct bpf_map *map = meta->map_ptr;
9936
9937         if (func_id != BPF_FUNC_tail_call &&
9938             func_id != BPF_FUNC_map_lookup_elem &&
9939             func_id != BPF_FUNC_map_update_elem &&
9940             func_id != BPF_FUNC_map_delete_elem &&
9941             func_id != BPF_FUNC_map_push_elem &&
9942             func_id != BPF_FUNC_map_pop_elem &&
9943             func_id != BPF_FUNC_map_peek_elem &&
9944             func_id != BPF_FUNC_for_each_map_elem &&
9945             func_id != BPF_FUNC_redirect_map &&
9946             func_id != BPF_FUNC_map_lookup_percpu_elem)
9947                 return 0;
9948
9949         if (map == NULL) {
9950                 verbose(env, "kernel subsystem misconfigured verifier\n");
9951                 return -EINVAL;
9952         }
9953
9954         /* In case of read-only, some additional restrictions
9955          * need to be applied in order to prevent altering the
9956          * state of the map from program side.
9957          */
9958         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9959             (func_id == BPF_FUNC_map_delete_elem ||
9960              func_id == BPF_FUNC_map_update_elem ||
9961              func_id == BPF_FUNC_map_push_elem ||
9962              func_id == BPF_FUNC_map_pop_elem)) {
9963                 verbose(env, "write into map forbidden\n");
9964                 return -EACCES;
9965         }
9966
9967         if (!BPF_MAP_PTR(aux->map_ptr_state))
9968                 bpf_map_ptr_store(aux, meta->map_ptr,
9969                                   !meta->map_ptr->bypass_spec_v1);
9970         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9971                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9972                                   !meta->map_ptr->bypass_spec_v1);
9973         return 0;
9974 }
9975
9976 static int
9977 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9978                 int func_id, int insn_idx)
9979 {
9980         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9981         struct bpf_reg_state *regs = cur_regs(env), *reg;
9982         struct bpf_map *map = meta->map_ptr;
9983         u64 val, max;
9984         int err;
9985
9986         if (func_id != BPF_FUNC_tail_call)
9987                 return 0;
9988         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9989                 verbose(env, "kernel subsystem misconfigured verifier\n");
9990                 return -EINVAL;
9991         }
9992
9993         reg = &regs[BPF_REG_3];
9994         val = reg->var_off.value;
9995         max = map->max_entries;
9996
9997         if (!(is_reg_const(reg, false) && val < max)) {
9998                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9999                 return 0;
10000         }
10001
10002         err = mark_chain_precision(env, BPF_REG_3);
10003         if (err)
10004                 return err;
10005         if (bpf_map_key_unseen(aux))
10006                 bpf_map_key_store(aux, val);
10007         else if (!bpf_map_key_poisoned(aux) &&
10008                   bpf_map_key_immediate(aux) != val)
10009                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10010         return 0;
10011 }
10012
10013 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10014 {
10015         struct bpf_func_state *state = cur_func(env);
10016         bool refs_lingering = false;
10017         int i;
10018
10019         if (!exception_exit && state->frameno && !state->in_callback_fn)
10020                 return 0;
10021
10022         for (i = 0; i < state->acquired_refs; i++) {
10023                 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10024                         continue;
10025                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10026                         state->refs[i].id, state->refs[i].insn_idx);
10027                 refs_lingering = true;
10028         }
10029         return refs_lingering ? -EINVAL : 0;
10030 }
10031
10032 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10033                                    struct bpf_reg_state *regs)
10034 {
10035         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10036         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10037         struct bpf_map *fmt_map = fmt_reg->map_ptr;
10038         struct bpf_bprintf_data data = {};
10039         int err, fmt_map_off, num_args;
10040         u64 fmt_addr;
10041         char *fmt;
10042
10043         /* data must be an array of u64 */
10044         if (data_len_reg->var_off.value % 8)
10045                 return -EINVAL;
10046         num_args = data_len_reg->var_off.value / 8;
10047
10048         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10049          * and map_direct_value_addr is set.
10050          */
10051         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10052         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10053                                                   fmt_map_off);
10054         if (err) {
10055                 verbose(env, "verifier bug\n");
10056                 return -EFAULT;
10057         }
10058         fmt = (char *)(long)fmt_addr + fmt_map_off;
10059
10060         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10061          * can focus on validating the format specifiers.
10062          */
10063         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10064         if (err < 0)
10065                 verbose(env, "Invalid format string\n");
10066
10067         return err;
10068 }
10069
10070 static int check_get_func_ip(struct bpf_verifier_env *env)
10071 {
10072         enum bpf_prog_type type = resolve_prog_type(env->prog);
10073         int func_id = BPF_FUNC_get_func_ip;
10074
10075         if (type == BPF_PROG_TYPE_TRACING) {
10076                 if (!bpf_prog_has_trampoline(env->prog)) {
10077                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10078                                 func_id_name(func_id), func_id);
10079                         return -ENOTSUPP;
10080                 }
10081                 return 0;
10082         } else if (type == BPF_PROG_TYPE_KPROBE) {
10083                 return 0;
10084         }
10085
10086         verbose(env, "func %s#%d not supported for program type %d\n",
10087                 func_id_name(func_id), func_id, type);
10088         return -ENOTSUPP;
10089 }
10090
10091 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10092 {
10093         return &env->insn_aux_data[env->insn_idx];
10094 }
10095
10096 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10097 {
10098         struct bpf_reg_state *regs = cur_regs(env);
10099         struct bpf_reg_state *reg = &regs[BPF_REG_4];
10100         bool reg_is_null = register_is_null(reg);
10101
10102         if (reg_is_null)
10103                 mark_chain_precision(env, BPF_REG_4);
10104
10105         return reg_is_null;
10106 }
10107
10108 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10109 {
10110         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10111
10112         if (!state->initialized) {
10113                 state->initialized = 1;
10114                 state->fit_for_inline = loop_flag_is_zero(env);
10115                 state->callback_subprogno = subprogno;
10116                 return;
10117         }
10118
10119         if (!state->fit_for_inline)
10120                 return;
10121
10122         state->fit_for_inline = (loop_flag_is_zero(env) &&
10123                                  state->callback_subprogno == subprogno);
10124 }
10125
10126 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10127                              int *insn_idx_p)
10128 {
10129         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10130         bool returns_cpu_specific_alloc_ptr = false;
10131         const struct bpf_func_proto *fn = NULL;
10132         enum bpf_return_type ret_type;
10133         enum bpf_type_flag ret_flag;
10134         struct bpf_reg_state *regs;
10135         struct bpf_call_arg_meta meta;
10136         int insn_idx = *insn_idx_p;
10137         bool changes_data;
10138         int i, err, func_id;
10139
10140         /* find function prototype */
10141         func_id = insn->imm;
10142         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10143                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10144                         func_id);
10145                 return -EINVAL;
10146         }
10147
10148         if (env->ops->get_func_proto)
10149                 fn = env->ops->get_func_proto(func_id, env->prog);
10150         if (!fn) {
10151                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10152                         func_id);
10153                 return -EINVAL;
10154         }
10155
10156         /* eBPF programs must be GPL compatible to use GPL-ed functions */
10157         if (!env->prog->gpl_compatible && fn->gpl_only) {
10158                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10159                 return -EINVAL;
10160         }
10161
10162         if (fn->allowed && !fn->allowed(env->prog)) {
10163                 verbose(env, "helper call is not allowed in probe\n");
10164                 return -EINVAL;
10165         }
10166
10167         if (!env->prog->aux->sleepable && fn->might_sleep) {
10168                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10169                 return -EINVAL;
10170         }
10171
10172         /* With LD_ABS/IND some JITs save/restore skb from r1. */
10173         changes_data = bpf_helper_changes_pkt_data(fn->func);
10174         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10175                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10176                         func_id_name(func_id), func_id);
10177                 return -EINVAL;
10178         }
10179
10180         memset(&meta, 0, sizeof(meta));
10181         meta.pkt_access = fn->pkt_access;
10182
10183         err = check_func_proto(fn, func_id);
10184         if (err) {
10185                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10186                         func_id_name(func_id), func_id);
10187                 return err;
10188         }
10189
10190         if (env->cur_state->active_rcu_lock) {
10191                 if (fn->might_sleep) {
10192                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10193                                 func_id_name(func_id), func_id);
10194                         return -EINVAL;
10195                 }
10196
10197                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10198                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10199         }
10200
10201         meta.func_id = func_id;
10202         /* check args */
10203         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10204                 err = check_func_arg(env, i, &meta, fn, insn_idx);
10205                 if (err)
10206                         return err;
10207         }
10208
10209         err = record_func_map(env, &meta, func_id, insn_idx);
10210         if (err)
10211                 return err;
10212
10213         err = record_func_key(env, &meta, func_id, insn_idx);
10214         if (err)
10215                 return err;
10216
10217         /* Mark slots with STACK_MISC in case of raw mode, stack offset
10218          * is inferred from register state.
10219          */
10220         for (i = 0; i < meta.access_size; i++) {
10221                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10222                                        BPF_WRITE, -1, false, false);
10223                 if (err)
10224                         return err;
10225         }
10226
10227         regs = cur_regs(env);
10228
10229         if (meta.release_regno) {
10230                 err = -EINVAL;
10231                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10232                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10233                  * is safe to do directly.
10234                  */
10235                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10236                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10237                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10238                                 return -EFAULT;
10239                         }
10240                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10241                 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10242                         u32 ref_obj_id = meta.ref_obj_id;
10243                         bool in_rcu = in_rcu_cs(env);
10244                         struct bpf_func_state *state;
10245                         struct bpf_reg_state *reg;
10246
10247                         err = release_reference_state(cur_func(env), ref_obj_id);
10248                         if (!err) {
10249                                 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10250                                         if (reg->ref_obj_id == ref_obj_id) {
10251                                                 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10252                                                         reg->ref_obj_id = 0;
10253                                                         reg->type &= ~MEM_ALLOC;
10254                                                         reg->type |= MEM_RCU;
10255                                                 } else {
10256                                                         mark_reg_invalid(env, reg);
10257                                                 }
10258                                         }
10259                                 }));
10260                         }
10261                 } else if (meta.ref_obj_id) {
10262                         err = release_reference(env, meta.ref_obj_id);
10263                 } else if (register_is_null(&regs[meta.release_regno])) {
10264                         /* meta.ref_obj_id can only be 0 if register that is meant to be
10265                          * released is NULL, which must be > R0.
10266                          */
10267                         err = 0;
10268                 }
10269                 if (err) {
10270                         verbose(env, "func %s#%d reference has not been acquired before\n",
10271                                 func_id_name(func_id), func_id);
10272                         return err;
10273                 }
10274         }
10275
10276         switch (func_id) {
10277         case BPF_FUNC_tail_call:
10278                 err = check_reference_leak(env, false);
10279                 if (err) {
10280                         verbose(env, "tail_call would lead to reference leak\n");
10281                         return err;
10282                 }
10283                 break;
10284         case BPF_FUNC_get_local_storage:
10285                 /* check that flags argument in get_local_storage(map, flags) is 0,
10286                  * this is required because get_local_storage() can't return an error.
10287                  */
10288                 if (!register_is_null(&regs[BPF_REG_2])) {
10289                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10290                         return -EINVAL;
10291                 }
10292                 break;
10293         case BPF_FUNC_for_each_map_elem:
10294                 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10295                                          set_map_elem_callback_state);
10296                 break;
10297         case BPF_FUNC_timer_set_callback:
10298                 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10299                                          set_timer_callback_state);
10300                 break;
10301         case BPF_FUNC_find_vma:
10302                 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10303                                          set_find_vma_callback_state);
10304                 break;
10305         case BPF_FUNC_snprintf:
10306                 err = check_bpf_snprintf_call(env, regs);
10307                 break;
10308         case BPF_FUNC_loop:
10309                 update_loop_inline_state(env, meta.subprogno);
10310                 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10311                  * is finished, thus mark it precise.
10312                  */
10313                 err = mark_chain_precision(env, BPF_REG_1);
10314                 if (err)
10315                         return err;
10316                 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10317                         err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10318                                                  set_loop_callback_state);
10319                 } else {
10320                         cur_func(env)->callback_depth = 0;
10321                         if (env->log.level & BPF_LOG_LEVEL2)
10322                                 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10323                                         env->cur_state->curframe);
10324                 }
10325                 break;
10326         case BPF_FUNC_dynptr_from_mem:
10327                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10328                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10329                                 reg_type_str(env, regs[BPF_REG_1].type));
10330                         return -EACCES;
10331                 }
10332                 break;
10333         case BPF_FUNC_set_retval:
10334                 if (prog_type == BPF_PROG_TYPE_LSM &&
10335                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10336                         if (!env->prog->aux->attach_func_proto->type) {
10337                                 /* Make sure programs that attach to void
10338                                  * hooks don't try to modify return value.
10339                                  */
10340                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10341                                 return -EINVAL;
10342                         }
10343                 }
10344                 break;
10345         case BPF_FUNC_dynptr_data:
10346         {
10347                 struct bpf_reg_state *reg;
10348                 int id, ref_obj_id;
10349
10350                 reg = get_dynptr_arg_reg(env, fn, regs);
10351                 if (!reg)
10352                         return -EFAULT;
10353
10354
10355                 if (meta.dynptr_id) {
10356                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10357                         return -EFAULT;
10358                 }
10359                 if (meta.ref_obj_id) {
10360                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10361                         return -EFAULT;
10362                 }
10363
10364                 id = dynptr_id(env, reg);
10365                 if (id < 0) {
10366                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10367                         return id;
10368                 }
10369
10370                 ref_obj_id = dynptr_ref_obj_id(env, reg);
10371                 if (ref_obj_id < 0) {
10372                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10373                         return ref_obj_id;
10374                 }
10375
10376                 meta.dynptr_id = id;
10377                 meta.ref_obj_id = ref_obj_id;
10378
10379                 break;
10380         }
10381         case BPF_FUNC_dynptr_write:
10382         {
10383                 enum bpf_dynptr_type dynptr_type;
10384                 struct bpf_reg_state *reg;
10385
10386                 reg = get_dynptr_arg_reg(env, fn, regs);
10387                 if (!reg)
10388                         return -EFAULT;
10389
10390                 dynptr_type = dynptr_get_type(env, reg);
10391                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10392                         return -EFAULT;
10393
10394                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10395                         /* this will trigger clear_all_pkt_pointers(), which will
10396                          * invalidate all dynptr slices associated with the skb
10397                          */
10398                         changes_data = true;
10399
10400                 break;
10401         }
10402         case BPF_FUNC_per_cpu_ptr:
10403         case BPF_FUNC_this_cpu_ptr:
10404         {
10405                 struct bpf_reg_state *reg = &regs[BPF_REG_1];
10406                 const struct btf_type *type;
10407
10408                 if (reg->type & MEM_RCU) {
10409                         type = btf_type_by_id(reg->btf, reg->btf_id);
10410                         if (!type || !btf_type_is_struct(type)) {
10411                                 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10412                                 return -EFAULT;
10413                         }
10414                         returns_cpu_specific_alloc_ptr = true;
10415                         env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10416                 }
10417                 break;
10418         }
10419         case BPF_FUNC_user_ringbuf_drain:
10420                 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10421                                          set_user_ringbuf_callback_state);
10422                 break;
10423         }
10424
10425         if (err)
10426                 return err;
10427
10428         /* reset caller saved regs */
10429         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10430                 mark_reg_not_init(env, regs, caller_saved[i]);
10431                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10432         }
10433
10434         /* helper call returns 64-bit value. */
10435         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10436
10437         /* update return register (already marked as written above) */
10438         ret_type = fn->ret_type;
10439         ret_flag = type_flag(ret_type);
10440
10441         switch (base_type(ret_type)) {
10442         case RET_INTEGER:
10443                 /* sets type to SCALAR_VALUE */
10444                 mark_reg_unknown(env, regs, BPF_REG_0);
10445                 break;
10446         case RET_VOID:
10447                 regs[BPF_REG_0].type = NOT_INIT;
10448                 break;
10449         case RET_PTR_TO_MAP_VALUE:
10450                 /* There is no offset yet applied, variable or fixed */
10451                 mark_reg_known_zero(env, regs, BPF_REG_0);
10452                 /* remember map_ptr, so that check_map_access()
10453                  * can check 'value_size' boundary of memory access
10454                  * to map element returned from bpf_map_lookup_elem()
10455                  */
10456                 if (meta.map_ptr == NULL) {
10457                         verbose(env,
10458                                 "kernel subsystem misconfigured verifier\n");
10459                         return -EINVAL;
10460                 }
10461                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10462                 regs[BPF_REG_0].map_uid = meta.map_uid;
10463                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10464                 if (!type_may_be_null(ret_type) &&
10465                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10466                         regs[BPF_REG_0].id = ++env->id_gen;
10467                 }
10468                 break;
10469         case RET_PTR_TO_SOCKET:
10470                 mark_reg_known_zero(env, regs, BPF_REG_0);
10471                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10472                 break;
10473         case RET_PTR_TO_SOCK_COMMON:
10474                 mark_reg_known_zero(env, regs, BPF_REG_0);
10475                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10476                 break;
10477         case RET_PTR_TO_TCP_SOCK:
10478                 mark_reg_known_zero(env, regs, BPF_REG_0);
10479                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10480                 break;
10481         case RET_PTR_TO_MEM:
10482                 mark_reg_known_zero(env, regs, BPF_REG_0);
10483                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10484                 regs[BPF_REG_0].mem_size = meta.mem_size;
10485                 break;
10486         case RET_PTR_TO_MEM_OR_BTF_ID:
10487         {
10488                 const struct btf_type *t;
10489
10490                 mark_reg_known_zero(env, regs, BPF_REG_0);
10491                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10492                 if (!btf_type_is_struct(t)) {
10493                         u32 tsize;
10494                         const struct btf_type *ret;
10495                         const char *tname;
10496
10497                         /* resolve the type size of ksym. */
10498                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10499                         if (IS_ERR(ret)) {
10500                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10501                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10502                                         tname, PTR_ERR(ret));
10503                                 return -EINVAL;
10504                         }
10505                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10506                         regs[BPF_REG_0].mem_size = tsize;
10507                 } else {
10508                         if (returns_cpu_specific_alloc_ptr) {
10509                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10510                         } else {
10511                                 /* MEM_RDONLY may be carried from ret_flag, but it
10512                                  * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10513                                  * it will confuse the check of PTR_TO_BTF_ID in
10514                                  * check_mem_access().
10515                                  */
10516                                 ret_flag &= ~MEM_RDONLY;
10517                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10518                         }
10519
10520                         regs[BPF_REG_0].btf = meta.ret_btf;
10521                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10522                 }
10523                 break;
10524         }
10525         case RET_PTR_TO_BTF_ID:
10526         {
10527                 struct btf *ret_btf;
10528                 int ret_btf_id;
10529
10530                 mark_reg_known_zero(env, regs, BPF_REG_0);
10531                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10532                 if (func_id == BPF_FUNC_kptr_xchg) {
10533                         ret_btf = meta.kptr_field->kptr.btf;
10534                         ret_btf_id = meta.kptr_field->kptr.btf_id;
10535                         if (!btf_is_kernel(ret_btf)) {
10536                                 regs[BPF_REG_0].type |= MEM_ALLOC;
10537                                 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10538                                         regs[BPF_REG_0].type |= MEM_PERCPU;
10539                         }
10540                 } else {
10541                         if (fn->ret_btf_id == BPF_PTR_POISON) {
10542                                 verbose(env, "verifier internal error:");
10543                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10544                                         func_id_name(func_id));
10545                                 return -EINVAL;
10546                         }
10547                         ret_btf = btf_vmlinux;
10548                         ret_btf_id = *fn->ret_btf_id;
10549                 }
10550                 if (ret_btf_id == 0) {
10551                         verbose(env, "invalid return type %u of func %s#%d\n",
10552                                 base_type(ret_type), func_id_name(func_id),
10553                                 func_id);
10554                         return -EINVAL;
10555                 }
10556                 regs[BPF_REG_0].btf = ret_btf;
10557                 regs[BPF_REG_0].btf_id = ret_btf_id;
10558                 break;
10559         }
10560         default:
10561                 verbose(env, "unknown return type %u of func %s#%d\n",
10562                         base_type(ret_type), func_id_name(func_id), func_id);
10563                 return -EINVAL;
10564         }
10565
10566         if (type_may_be_null(regs[BPF_REG_0].type))
10567                 regs[BPF_REG_0].id = ++env->id_gen;
10568
10569         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10570                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10571                         func_id_name(func_id), func_id);
10572                 return -EFAULT;
10573         }
10574
10575         if (is_dynptr_ref_function(func_id))
10576                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10577
10578         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10579                 /* For release_reference() */
10580                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10581         } else if (is_acquire_function(func_id, meta.map_ptr)) {
10582                 int id = acquire_reference_state(env, insn_idx);
10583
10584                 if (id < 0)
10585                         return id;
10586                 /* For mark_ptr_or_null_reg() */
10587                 regs[BPF_REG_0].id = id;
10588                 /* For release_reference() */
10589                 regs[BPF_REG_0].ref_obj_id = id;
10590         }
10591
10592         err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10593         if (err)
10594                 return err;
10595
10596         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10597         if (err)
10598                 return err;
10599
10600         if ((func_id == BPF_FUNC_get_stack ||
10601              func_id == BPF_FUNC_get_task_stack) &&
10602             !env->prog->has_callchain_buf) {
10603                 const char *err_str;
10604
10605 #ifdef CONFIG_PERF_EVENTS
10606                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10607                 err_str = "cannot get callchain buffer for func %s#%d\n";
10608 #else
10609                 err = -ENOTSUPP;
10610                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10611 #endif
10612                 if (err) {
10613                         verbose(env, err_str, func_id_name(func_id), func_id);
10614                         return err;
10615                 }
10616
10617                 env->prog->has_callchain_buf = true;
10618         }
10619
10620         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10621                 env->prog->call_get_stack = true;
10622
10623         if (func_id == BPF_FUNC_get_func_ip) {
10624                 if (check_get_func_ip(env))
10625                         return -ENOTSUPP;
10626                 env->prog->call_get_func_ip = true;
10627         }
10628
10629         if (changes_data)
10630                 clear_all_pkt_pointers(env);
10631         return 0;
10632 }
10633
10634 /* mark_btf_func_reg_size() is used when the reg size is determined by
10635  * the BTF func_proto's return value size and argument.
10636  */
10637 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10638                                    size_t reg_size)
10639 {
10640         struct bpf_reg_state *reg = &cur_regs(env)[regno];
10641
10642         if (regno == BPF_REG_0) {
10643                 /* Function return value */
10644                 reg->live |= REG_LIVE_WRITTEN;
10645                 reg->subreg_def = reg_size == sizeof(u64) ?
10646                         DEF_NOT_SUBREG : env->insn_idx + 1;
10647         } else {
10648                 /* Function argument */
10649                 if (reg_size == sizeof(u64)) {
10650                         mark_insn_zext(env, reg);
10651                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10652                 } else {
10653                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10654                 }
10655         }
10656 }
10657
10658 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10659 {
10660         return meta->kfunc_flags & KF_ACQUIRE;
10661 }
10662
10663 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10664 {
10665         return meta->kfunc_flags & KF_RELEASE;
10666 }
10667
10668 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10669 {
10670         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10671 }
10672
10673 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10674 {
10675         return meta->kfunc_flags & KF_SLEEPABLE;
10676 }
10677
10678 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10679 {
10680         return meta->kfunc_flags & KF_DESTRUCTIVE;
10681 }
10682
10683 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10684 {
10685         return meta->kfunc_flags & KF_RCU;
10686 }
10687
10688 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10689 {
10690         return meta->kfunc_flags & KF_RCU_PROTECTED;
10691 }
10692
10693 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10694                                   const struct btf_param *arg,
10695                                   const struct bpf_reg_state *reg)
10696 {
10697         const struct btf_type *t;
10698
10699         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10700         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10701                 return false;
10702
10703         return btf_param_match_suffix(btf, arg, "__sz");
10704 }
10705
10706 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10707                                         const struct btf_param *arg,
10708                                         const struct bpf_reg_state *reg)
10709 {
10710         const struct btf_type *t;
10711
10712         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10713         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10714                 return false;
10715
10716         return btf_param_match_suffix(btf, arg, "__szk");
10717 }
10718
10719 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10720 {
10721         return btf_param_match_suffix(btf, arg, "__opt");
10722 }
10723
10724 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10725 {
10726         return btf_param_match_suffix(btf, arg, "__k");
10727 }
10728
10729 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10730 {
10731         return btf_param_match_suffix(btf, arg, "__ign");
10732 }
10733
10734 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10735 {
10736         return btf_param_match_suffix(btf, arg, "__alloc");
10737 }
10738
10739 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10740 {
10741         return btf_param_match_suffix(btf, arg, "__uninit");
10742 }
10743
10744 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10745 {
10746         return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10747 }
10748
10749 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10750 {
10751         return btf_param_match_suffix(btf, arg, "__nullable");
10752 }
10753
10754 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10755 {
10756         return btf_param_match_suffix(btf, arg, "__str");
10757 }
10758
10759 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10760                                           const struct btf_param *arg,
10761                                           const char *name)
10762 {
10763         int len, target_len = strlen(name);
10764         const char *param_name;
10765
10766         param_name = btf_name_by_offset(btf, arg->name_off);
10767         if (str_is_empty(param_name))
10768                 return false;
10769         len = strlen(param_name);
10770         if (len != target_len)
10771                 return false;
10772         if (strcmp(param_name, name))
10773                 return false;
10774
10775         return true;
10776 }
10777
10778 enum {
10779         KF_ARG_DYNPTR_ID,
10780         KF_ARG_LIST_HEAD_ID,
10781         KF_ARG_LIST_NODE_ID,
10782         KF_ARG_RB_ROOT_ID,
10783         KF_ARG_RB_NODE_ID,
10784 };
10785
10786 BTF_ID_LIST(kf_arg_btf_ids)
10787 BTF_ID(struct, bpf_dynptr_kern)
10788 BTF_ID(struct, bpf_list_head)
10789 BTF_ID(struct, bpf_list_node)
10790 BTF_ID(struct, bpf_rb_root)
10791 BTF_ID(struct, bpf_rb_node)
10792
10793 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10794                                     const struct btf_param *arg, int type)
10795 {
10796         const struct btf_type *t;
10797         u32 res_id;
10798
10799         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10800         if (!t)
10801                 return false;
10802         if (!btf_type_is_ptr(t))
10803                 return false;
10804         t = btf_type_skip_modifiers(btf, t->type, &res_id);
10805         if (!t)
10806                 return false;
10807         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10808 }
10809
10810 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10811 {
10812         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10813 }
10814
10815 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10816 {
10817         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10818 }
10819
10820 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10821 {
10822         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10823 }
10824
10825 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10826 {
10827         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10828 }
10829
10830 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10831 {
10832         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10833 }
10834
10835 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10836                                   const struct btf_param *arg)
10837 {
10838         const struct btf_type *t;
10839
10840         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10841         if (!t)
10842                 return false;
10843
10844         return true;
10845 }
10846
10847 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10848 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10849                                         const struct btf *btf,
10850                                         const struct btf_type *t, int rec)
10851 {
10852         const struct btf_type *member_type;
10853         const struct btf_member *member;
10854         u32 i;
10855
10856         if (!btf_type_is_struct(t))
10857                 return false;
10858
10859         for_each_member(i, t, member) {
10860                 const struct btf_array *array;
10861
10862                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10863                 if (btf_type_is_struct(member_type)) {
10864                         if (rec >= 3) {
10865                                 verbose(env, "max struct nesting depth exceeded\n");
10866                                 return false;
10867                         }
10868                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10869                                 return false;
10870                         continue;
10871                 }
10872                 if (btf_type_is_array(member_type)) {
10873                         array = btf_array(member_type);
10874                         if (!array->nelems)
10875                                 return false;
10876                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10877                         if (!btf_type_is_scalar(member_type))
10878                                 return false;
10879                         continue;
10880                 }
10881                 if (!btf_type_is_scalar(member_type))
10882                         return false;
10883         }
10884         return true;
10885 }
10886
10887 enum kfunc_ptr_arg_type {
10888         KF_ARG_PTR_TO_CTX,
10889         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10890         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10891         KF_ARG_PTR_TO_DYNPTR,
10892         KF_ARG_PTR_TO_ITER,
10893         KF_ARG_PTR_TO_LIST_HEAD,
10894         KF_ARG_PTR_TO_LIST_NODE,
10895         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10896         KF_ARG_PTR_TO_MEM,
10897         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10898         KF_ARG_PTR_TO_CALLBACK,
10899         KF_ARG_PTR_TO_RB_ROOT,
10900         KF_ARG_PTR_TO_RB_NODE,
10901         KF_ARG_PTR_TO_NULL,
10902         KF_ARG_PTR_TO_CONST_STR,
10903 };
10904
10905 enum special_kfunc_type {
10906         KF_bpf_obj_new_impl,
10907         KF_bpf_obj_drop_impl,
10908         KF_bpf_refcount_acquire_impl,
10909         KF_bpf_list_push_front_impl,
10910         KF_bpf_list_push_back_impl,
10911         KF_bpf_list_pop_front,
10912         KF_bpf_list_pop_back,
10913         KF_bpf_cast_to_kern_ctx,
10914         KF_bpf_rdonly_cast,
10915         KF_bpf_rcu_read_lock,
10916         KF_bpf_rcu_read_unlock,
10917         KF_bpf_rbtree_remove,
10918         KF_bpf_rbtree_add_impl,
10919         KF_bpf_rbtree_first,
10920         KF_bpf_dynptr_from_skb,
10921         KF_bpf_dynptr_from_xdp,
10922         KF_bpf_dynptr_slice,
10923         KF_bpf_dynptr_slice_rdwr,
10924         KF_bpf_dynptr_clone,
10925         KF_bpf_percpu_obj_new_impl,
10926         KF_bpf_percpu_obj_drop_impl,
10927         KF_bpf_throw,
10928         KF_bpf_iter_css_task_new,
10929 };
10930
10931 BTF_SET_START(special_kfunc_set)
10932 BTF_ID(func, bpf_obj_new_impl)
10933 BTF_ID(func, bpf_obj_drop_impl)
10934 BTF_ID(func, bpf_refcount_acquire_impl)
10935 BTF_ID(func, bpf_list_push_front_impl)
10936 BTF_ID(func, bpf_list_push_back_impl)
10937 BTF_ID(func, bpf_list_pop_front)
10938 BTF_ID(func, bpf_list_pop_back)
10939 BTF_ID(func, bpf_cast_to_kern_ctx)
10940 BTF_ID(func, bpf_rdonly_cast)
10941 BTF_ID(func, bpf_rbtree_remove)
10942 BTF_ID(func, bpf_rbtree_add_impl)
10943 BTF_ID(func, bpf_rbtree_first)
10944 BTF_ID(func, bpf_dynptr_from_skb)
10945 BTF_ID(func, bpf_dynptr_from_xdp)
10946 BTF_ID(func, bpf_dynptr_slice)
10947 BTF_ID(func, bpf_dynptr_slice_rdwr)
10948 BTF_ID(func, bpf_dynptr_clone)
10949 BTF_ID(func, bpf_percpu_obj_new_impl)
10950 BTF_ID(func, bpf_percpu_obj_drop_impl)
10951 BTF_ID(func, bpf_throw)
10952 #ifdef CONFIG_CGROUPS
10953 BTF_ID(func, bpf_iter_css_task_new)
10954 #endif
10955 BTF_SET_END(special_kfunc_set)
10956
10957 BTF_ID_LIST(special_kfunc_list)
10958 BTF_ID(func, bpf_obj_new_impl)
10959 BTF_ID(func, bpf_obj_drop_impl)
10960 BTF_ID(func, bpf_refcount_acquire_impl)
10961 BTF_ID(func, bpf_list_push_front_impl)
10962 BTF_ID(func, bpf_list_push_back_impl)
10963 BTF_ID(func, bpf_list_pop_front)
10964 BTF_ID(func, bpf_list_pop_back)
10965 BTF_ID(func, bpf_cast_to_kern_ctx)
10966 BTF_ID(func, bpf_rdonly_cast)
10967 BTF_ID(func, bpf_rcu_read_lock)
10968 BTF_ID(func, bpf_rcu_read_unlock)
10969 BTF_ID(func, bpf_rbtree_remove)
10970 BTF_ID(func, bpf_rbtree_add_impl)
10971 BTF_ID(func, bpf_rbtree_first)
10972 BTF_ID(func, bpf_dynptr_from_skb)
10973 BTF_ID(func, bpf_dynptr_from_xdp)
10974 BTF_ID(func, bpf_dynptr_slice)
10975 BTF_ID(func, bpf_dynptr_slice_rdwr)
10976 BTF_ID(func, bpf_dynptr_clone)
10977 BTF_ID(func, bpf_percpu_obj_new_impl)
10978 BTF_ID(func, bpf_percpu_obj_drop_impl)
10979 BTF_ID(func, bpf_throw)
10980 #ifdef CONFIG_CGROUPS
10981 BTF_ID(func, bpf_iter_css_task_new)
10982 #else
10983 BTF_ID_UNUSED
10984 #endif
10985
10986 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10987 {
10988         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10989             meta->arg_owning_ref) {
10990                 return false;
10991         }
10992
10993         return meta->kfunc_flags & KF_RET_NULL;
10994 }
10995
10996 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10997 {
10998         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10999 }
11000
11001 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11002 {
11003         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11004 }
11005
11006 static enum kfunc_ptr_arg_type
11007 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11008                        struct bpf_kfunc_call_arg_meta *meta,
11009                        const struct btf_type *t, const struct btf_type *ref_t,
11010                        const char *ref_tname, const struct btf_param *args,
11011                        int argno, int nargs)
11012 {
11013         u32 regno = argno + 1;
11014         struct bpf_reg_state *regs = cur_regs(env);
11015         struct bpf_reg_state *reg = &regs[regno];
11016         bool arg_mem_size = false;
11017
11018         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11019                 return KF_ARG_PTR_TO_CTX;
11020
11021         /* In this function, we verify the kfunc's BTF as per the argument type,
11022          * leaving the rest of the verification with respect to the register
11023          * type to our caller. When a set of conditions hold in the BTF type of
11024          * arguments, we resolve it to a known kfunc_ptr_arg_type.
11025          */
11026         if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11027                 return KF_ARG_PTR_TO_CTX;
11028
11029         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11030                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11031
11032         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11033                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11034
11035         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11036                 return KF_ARG_PTR_TO_DYNPTR;
11037
11038         if (is_kfunc_arg_iter(meta, argno))
11039                 return KF_ARG_PTR_TO_ITER;
11040
11041         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11042                 return KF_ARG_PTR_TO_LIST_HEAD;
11043
11044         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11045                 return KF_ARG_PTR_TO_LIST_NODE;
11046
11047         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11048                 return KF_ARG_PTR_TO_RB_ROOT;
11049
11050         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11051                 return KF_ARG_PTR_TO_RB_NODE;
11052
11053         if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11054                 return KF_ARG_PTR_TO_CONST_STR;
11055
11056         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11057                 if (!btf_type_is_struct(ref_t)) {
11058                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11059                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11060                         return -EINVAL;
11061                 }
11062                 return KF_ARG_PTR_TO_BTF_ID;
11063         }
11064
11065         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11066                 return KF_ARG_PTR_TO_CALLBACK;
11067
11068         if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11069                 return KF_ARG_PTR_TO_NULL;
11070
11071         if (argno + 1 < nargs &&
11072             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11073              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11074                 arg_mem_size = true;
11075
11076         /* This is the catch all argument type of register types supported by
11077          * check_helper_mem_access. However, we only allow when argument type is
11078          * pointer to scalar, or struct composed (recursively) of scalars. When
11079          * arg_mem_size is true, the pointer can be void *.
11080          */
11081         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11082             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11083                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11084                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11085                 return -EINVAL;
11086         }
11087         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11088 }
11089
11090 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11091                                         struct bpf_reg_state *reg,
11092                                         const struct btf_type *ref_t,
11093                                         const char *ref_tname, u32 ref_id,
11094                                         struct bpf_kfunc_call_arg_meta *meta,
11095                                         int argno)
11096 {
11097         const struct btf_type *reg_ref_t;
11098         bool strict_type_match = false;
11099         const struct btf *reg_btf;
11100         const char *reg_ref_tname;
11101         u32 reg_ref_id;
11102
11103         if (base_type(reg->type) == PTR_TO_BTF_ID) {
11104                 reg_btf = reg->btf;
11105                 reg_ref_id = reg->btf_id;
11106         } else {
11107                 reg_btf = btf_vmlinux;
11108                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11109         }
11110
11111         /* Enforce strict type matching for calls to kfuncs that are acquiring
11112          * or releasing a reference, or are no-cast aliases. We do _not_
11113          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11114          * as we want to enable BPF programs to pass types that are bitwise
11115          * equivalent without forcing them to explicitly cast with something
11116          * like bpf_cast_to_kern_ctx().
11117          *
11118          * For example, say we had a type like the following:
11119          *
11120          * struct bpf_cpumask {
11121          *      cpumask_t cpumask;
11122          *      refcount_t usage;
11123          * };
11124          *
11125          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11126          * to a struct cpumask, so it would be safe to pass a struct
11127          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11128          *
11129          * The philosophy here is similar to how we allow scalars of different
11130          * types to be passed to kfuncs as long as the size is the same. The
11131          * only difference here is that we're simply allowing
11132          * btf_struct_ids_match() to walk the struct at the 0th offset, and
11133          * resolve types.
11134          */
11135         if (is_kfunc_acquire(meta) ||
11136             (is_kfunc_release(meta) && reg->ref_obj_id) ||
11137             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11138                 strict_type_match = true;
11139
11140         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11141
11142         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11143         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11144         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11145                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11146                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11147                         btf_type_str(reg_ref_t), reg_ref_tname);
11148                 return -EINVAL;
11149         }
11150         return 0;
11151 }
11152
11153 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11154 {
11155         struct bpf_verifier_state *state = env->cur_state;
11156         struct btf_record *rec = reg_btf_record(reg);
11157
11158         if (!state->active_lock.ptr) {
11159                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11160                 return -EFAULT;
11161         }
11162
11163         if (type_flag(reg->type) & NON_OWN_REF) {
11164                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11165                 return -EFAULT;
11166         }
11167
11168         reg->type |= NON_OWN_REF;
11169         if (rec->refcount_off >= 0)
11170                 reg->type |= MEM_RCU;
11171
11172         return 0;
11173 }
11174
11175 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11176 {
11177         struct bpf_func_state *state, *unused;
11178         struct bpf_reg_state *reg;
11179         int i;
11180
11181         state = cur_func(env);
11182
11183         if (!ref_obj_id) {
11184                 verbose(env, "verifier internal error: ref_obj_id is zero for "
11185                              "owning -> non-owning conversion\n");
11186                 return -EFAULT;
11187         }
11188
11189         for (i = 0; i < state->acquired_refs; i++) {
11190                 if (state->refs[i].id != ref_obj_id)
11191                         continue;
11192
11193                 /* Clear ref_obj_id here so release_reference doesn't clobber
11194                  * the whole reg
11195                  */
11196                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11197                         if (reg->ref_obj_id == ref_obj_id) {
11198                                 reg->ref_obj_id = 0;
11199                                 ref_set_non_owning(env, reg);
11200                         }
11201                 }));
11202                 return 0;
11203         }
11204
11205         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11206         return -EFAULT;
11207 }
11208
11209 /* Implementation details:
11210  *
11211  * Each register points to some region of memory, which we define as an
11212  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11213  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11214  * allocation. The lock and the data it protects are colocated in the same
11215  * memory region.
11216  *
11217  * Hence, everytime a register holds a pointer value pointing to such
11218  * allocation, the verifier preserves a unique reg->id for it.
11219  *
11220  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11221  * bpf_spin_lock is called.
11222  *
11223  * To enable this, lock state in the verifier captures two values:
11224  *      active_lock.ptr = Register's type specific pointer
11225  *      active_lock.id  = A unique ID for each register pointer value
11226  *
11227  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11228  * supported register types.
11229  *
11230  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11231  * allocated objects is the reg->btf pointer.
11232  *
11233  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11234  * can establish the provenance of the map value statically for each distinct
11235  * lookup into such maps. They always contain a single map value hence unique
11236  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11237  *
11238  * So, in case of global variables, they use array maps with max_entries = 1,
11239  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11240  * into the same map value as max_entries is 1, as described above).
11241  *
11242  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11243  * outer map pointer (in verifier context), but each lookup into an inner map
11244  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11245  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11246  * will get different reg->id assigned to each lookup, hence different
11247  * active_lock.id.
11248  *
11249  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11250  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11251  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11252  */
11253 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11254 {
11255         void *ptr;
11256         u32 id;
11257
11258         switch ((int)reg->type) {
11259         case PTR_TO_MAP_VALUE:
11260                 ptr = reg->map_ptr;
11261                 break;
11262         case PTR_TO_BTF_ID | MEM_ALLOC:
11263                 ptr = reg->btf;
11264                 break;
11265         default:
11266                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11267                 return -EFAULT;
11268         }
11269         id = reg->id;
11270
11271         if (!env->cur_state->active_lock.ptr)
11272                 return -EINVAL;
11273         if (env->cur_state->active_lock.ptr != ptr ||
11274             env->cur_state->active_lock.id != id) {
11275                 verbose(env, "held lock and object are not in the same allocation\n");
11276                 return -EINVAL;
11277         }
11278         return 0;
11279 }
11280
11281 static bool is_bpf_list_api_kfunc(u32 btf_id)
11282 {
11283         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11284                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11285                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11286                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11287 }
11288
11289 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11290 {
11291         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11292                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11293                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11294 }
11295
11296 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11297 {
11298         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11299                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11300 }
11301
11302 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11303 {
11304         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11305 }
11306
11307 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11308 {
11309         return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11310                insn->imm == special_kfunc_list[KF_bpf_throw];
11311 }
11312
11313 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11314 {
11315         return is_bpf_rbtree_api_kfunc(btf_id);
11316 }
11317
11318 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11319                                           enum btf_field_type head_field_type,
11320                                           u32 kfunc_btf_id)
11321 {
11322         bool ret;
11323
11324         switch (head_field_type) {
11325         case BPF_LIST_HEAD:
11326                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11327                 break;
11328         case BPF_RB_ROOT:
11329                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11330                 break;
11331         default:
11332                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11333                         btf_field_type_name(head_field_type));
11334                 return false;
11335         }
11336
11337         if (!ret)
11338                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11339                         btf_field_type_name(head_field_type));
11340         return ret;
11341 }
11342
11343 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11344                                           enum btf_field_type node_field_type,
11345                                           u32 kfunc_btf_id)
11346 {
11347         bool ret;
11348
11349         switch (node_field_type) {
11350         case BPF_LIST_NODE:
11351                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11352                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11353                 break;
11354         case BPF_RB_NODE:
11355                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11356                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11357                 break;
11358         default:
11359                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11360                         btf_field_type_name(node_field_type));
11361                 return false;
11362         }
11363
11364         if (!ret)
11365                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11366                         btf_field_type_name(node_field_type));
11367         return ret;
11368 }
11369
11370 static int
11371 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11372                                    struct bpf_reg_state *reg, u32 regno,
11373                                    struct bpf_kfunc_call_arg_meta *meta,
11374                                    enum btf_field_type head_field_type,
11375                                    struct btf_field **head_field)
11376 {
11377         const char *head_type_name;
11378         struct btf_field *field;
11379         struct btf_record *rec;
11380         u32 head_off;
11381
11382         if (meta->btf != btf_vmlinux) {
11383                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11384                 return -EFAULT;
11385         }
11386
11387         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11388                 return -EFAULT;
11389
11390         head_type_name = btf_field_type_name(head_field_type);
11391         if (!tnum_is_const(reg->var_off)) {
11392                 verbose(env,
11393                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11394                         regno, head_type_name);
11395                 return -EINVAL;
11396         }
11397
11398         rec = reg_btf_record(reg);
11399         head_off = reg->off + reg->var_off.value;
11400         field = btf_record_find(rec, head_off, head_field_type);
11401         if (!field) {
11402                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11403                 return -EINVAL;
11404         }
11405
11406         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11407         if (check_reg_allocation_locked(env, reg)) {
11408                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11409                         rec->spin_lock_off, head_type_name);
11410                 return -EINVAL;
11411         }
11412
11413         if (*head_field) {
11414                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11415                 return -EFAULT;
11416         }
11417         *head_field = field;
11418         return 0;
11419 }
11420
11421 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11422                                            struct bpf_reg_state *reg, u32 regno,
11423                                            struct bpf_kfunc_call_arg_meta *meta)
11424 {
11425         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11426                                                           &meta->arg_list_head.field);
11427 }
11428
11429 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11430                                              struct bpf_reg_state *reg, u32 regno,
11431                                              struct bpf_kfunc_call_arg_meta *meta)
11432 {
11433         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11434                                                           &meta->arg_rbtree_root.field);
11435 }
11436
11437 static int
11438 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11439                                    struct bpf_reg_state *reg, u32 regno,
11440                                    struct bpf_kfunc_call_arg_meta *meta,
11441                                    enum btf_field_type head_field_type,
11442                                    enum btf_field_type node_field_type,
11443                                    struct btf_field **node_field)
11444 {
11445         const char *node_type_name;
11446         const struct btf_type *et, *t;
11447         struct btf_field *field;
11448         u32 node_off;
11449
11450         if (meta->btf != btf_vmlinux) {
11451                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11452                 return -EFAULT;
11453         }
11454
11455         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11456                 return -EFAULT;
11457
11458         node_type_name = btf_field_type_name(node_field_type);
11459         if (!tnum_is_const(reg->var_off)) {
11460                 verbose(env,
11461                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11462                         regno, node_type_name);
11463                 return -EINVAL;
11464         }
11465
11466         node_off = reg->off + reg->var_off.value;
11467         field = reg_find_field_offset(reg, node_off, node_field_type);
11468         if (!field || field->offset != node_off) {
11469                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11470                 return -EINVAL;
11471         }
11472
11473         field = *node_field;
11474
11475         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11476         t = btf_type_by_id(reg->btf, reg->btf_id);
11477         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11478                                   field->graph_root.value_btf_id, true)) {
11479                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11480                         "in struct %s, but arg is at offset=%d in struct %s\n",
11481                         btf_field_type_name(head_field_type),
11482                         btf_field_type_name(node_field_type),
11483                         field->graph_root.node_offset,
11484                         btf_name_by_offset(field->graph_root.btf, et->name_off),
11485                         node_off, btf_name_by_offset(reg->btf, t->name_off));
11486                 return -EINVAL;
11487         }
11488         meta->arg_btf = reg->btf;
11489         meta->arg_btf_id = reg->btf_id;
11490
11491         if (node_off != field->graph_root.node_offset) {
11492                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11493                         node_off, btf_field_type_name(node_field_type),
11494                         field->graph_root.node_offset,
11495                         btf_name_by_offset(field->graph_root.btf, et->name_off));
11496                 return -EINVAL;
11497         }
11498
11499         return 0;
11500 }
11501
11502 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11503                                            struct bpf_reg_state *reg, u32 regno,
11504                                            struct bpf_kfunc_call_arg_meta *meta)
11505 {
11506         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11507                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
11508                                                   &meta->arg_list_head.field);
11509 }
11510
11511 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11512                                              struct bpf_reg_state *reg, u32 regno,
11513                                              struct bpf_kfunc_call_arg_meta *meta)
11514 {
11515         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11516                                                   BPF_RB_ROOT, BPF_RB_NODE,
11517                                                   &meta->arg_rbtree_root.field);
11518 }
11519
11520 /*
11521  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11522  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11523  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11524  * them can only be attached to some specific hook points.
11525  */
11526 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11527 {
11528         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11529
11530         switch (prog_type) {
11531         case BPF_PROG_TYPE_LSM:
11532                 return true;
11533         case BPF_PROG_TYPE_TRACING:
11534                 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11535                         return true;
11536                 fallthrough;
11537         default:
11538                 return env->prog->aux->sleepable;
11539         }
11540 }
11541
11542 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11543                             int insn_idx)
11544 {
11545         const char *func_name = meta->func_name, *ref_tname;
11546         const struct btf *btf = meta->btf;
11547         const struct btf_param *args;
11548         struct btf_record *rec;
11549         u32 i, nargs;
11550         int ret;
11551
11552         args = (const struct btf_param *)(meta->func_proto + 1);
11553         nargs = btf_type_vlen(meta->func_proto);
11554         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11555                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11556                         MAX_BPF_FUNC_REG_ARGS);
11557                 return -EINVAL;
11558         }
11559
11560         /* Check that BTF function arguments match actual types that the
11561          * verifier sees.
11562          */
11563         for (i = 0; i < nargs; i++) {
11564                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11565                 const struct btf_type *t, *ref_t, *resolve_ret;
11566                 enum bpf_arg_type arg_type = ARG_DONTCARE;
11567                 u32 regno = i + 1, ref_id, type_size;
11568                 bool is_ret_buf_sz = false;
11569                 int kf_arg_type;
11570
11571                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11572
11573                 if (is_kfunc_arg_ignore(btf, &args[i]))
11574                         continue;
11575
11576                 if (btf_type_is_scalar(t)) {
11577                         if (reg->type != SCALAR_VALUE) {
11578                                 verbose(env, "R%d is not a scalar\n", regno);
11579                                 return -EINVAL;
11580                         }
11581
11582                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11583                                 if (meta->arg_constant.found) {
11584                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11585                                         return -EFAULT;
11586                                 }
11587                                 if (!tnum_is_const(reg->var_off)) {
11588                                         verbose(env, "R%d must be a known constant\n", regno);
11589                                         return -EINVAL;
11590                                 }
11591                                 ret = mark_chain_precision(env, regno);
11592                                 if (ret < 0)
11593                                         return ret;
11594                                 meta->arg_constant.found = true;
11595                                 meta->arg_constant.value = reg->var_off.value;
11596                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11597                                 meta->r0_rdonly = true;
11598                                 is_ret_buf_sz = true;
11599                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11600                                 is_ret_buf_sz = true;
11601                         }
11602
11603                         if (is_ret_buf_sz) {
11604                                 if (meta->r0_size) {
11605                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11606                                         return -EINVAL;
11607                                 }
11608
11609                                 if (!tnum_is_const(reg->var_off)) {
11610                                         verbose(env, "R%d is not a const\n", regno);
11611                                         return -EINVAL;
11612                                 }
11613
11614                                 meta->r0_size = reg->var_off.value;
11615                                 ret = mark_chain_precision(env, regno);
11616                                 if (ret)
11617                                         return ret;
11618                         }
11619                         continue;
11620                 }
11621
11622                 if (!btf_type_is_ptr(t)) {
11623                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11624                         return -EINVAL;
11625                 }
11626
11627                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11628                     (register_is_null(reg) || type_may_be_null(reg->type)) &&
11629                         !is_kfunc_arg_nullable(meta->btf, &args[i])) {
11630                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11631                         return -EACCES;
11632                 }
11633
11634                 if (reg->ref_obj_id) {
11635                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
11636                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11637                                         regno, reg->ref_obj_id,
11638                                         meta->ref_obj_id);
11639                                 return -EFAULT;
11640                         }
11641                         meta->ref_obj_id = reg->ref_obj_id;
11642                         if (is_kfunc_release(meta))
11643                                 meta->release_regno = regno;
11644                 }
11645
11646                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11647                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11648
11649                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11650                 if (kf_arg_type < 0)
11651                         return kf_arg_type;
11652
11653                 switch (kf_arg_type) {
11654                 case KF_ARG_PTR_TO_NULL:
11655                         continue;
11656                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11657                 case KF_ARG_PTR_TO_BTF_ID:
11658                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11659                                 break;
11660
11661                         if (!is_trusted_reg(reg)) {
11662                                 if (!is_kfunc_rcu(meta)) {
11663                                         verbose(env, "R%d must be referenced or trusted\n", regno);
11664                                         return -EINVAL;
11665                                 }
11666                                 if (!is_rcu_reg(reg)) {
11667                                         verbose(env, "R%d must be a rcu pointer\n", regno);
11668                                         return -EINVAL;
11669                                 }
11670                         }
11671
11672                         fallthrough;
11673                 case KF_ARG_PTR_TO_CTX:
11674                         /* Trusted arguments have the same offset checks as release arguments */
11675                         arg_type |= OBJ_RELEASE;
11676                         break;
11677                 case KF_ARG_PTR_TO_DYNPTR:
11678                 case KF_ARG_PTR_TO_ITER:
11679                 case KF_ARG_PTR_TO_LIST_HEAD:
11680                 case KF_ARG_PTR_TO_LIST_NODE:
11681                 case KF_ARG_PTR_TO_RB_ROOT:
11682                 case KF_ARG_PTR_TO_RB_NODE:
11683                 case KF_ARG_PTR_TO_MEM:
11684                 case KF_ARG_PTR_TO_MEM_SIZE:
11685                 case KF_ARG_PTR_TO_CALLBACK:
11686                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11687                 case KF_ARG_PTR_TO_CONST_STR:
11688                         /* Trusted by default */
11689                         break;
11690                 default:
11691                         WARN_ON_ONCE(1);
11692                         return -EFAULT;
11693                 }
11694
11695                 if (is_kfunc_release(meta) && reg->ref_obj_id)
11696                         arg_type |= OBJ_RELEASE;
11697                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11698                 if (ret < 0)
11699                         return ret;
11700
11701                 switch (kf_arg_type) {
11702                 case KF_ARG_PTR_TO_CTX:
11703                         if (reg->type != PTR_TO_CTX) {
11704                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11705                                 return -EINVAL;
11706                         }
11707
11708                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11709                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11710                                 if (ret < 0)
11711                                         return -EINVAL;
11712                                 meta->ret_btf_id  = ret;
11713                         }
11714                         break;
11715                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11716                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11717                                 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11718                                         verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11719                                         return -EINVAL;
11720                                 }
11721                         } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11722                                 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11723                                         verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11724                                         return -EINVAL;
11725                                 }
11726                         } else {
11727                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11728                                 return -EINVAL;
11729                         }
11730                         if (!reg->ref_obj_id) {
11731                                 verbose(env, "allocated object must be referenced\n");
11732                                 return -EINVAL;
11733                         }
11734                         if (meta->btf == btf_vmlinux) {
11735                                 meta->arg_btf = reg->btf;
11736                                 meta->arg_btf_id = reg->btf_id;
11737                         }
11738                         break;
11739                 case KF_ARG_PTR_TO_DYNPTR:
11740                 {
11741                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11742                         int clone_ref_obj_id = 0;
11743
11744                         if (reg->type != PTR_TO_STACK &&
11745                             reg->type != CONST_PTR_TO_DYNPTR) {
11746                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11747                                 return -EINVAL;
11748                         }
11749
11750                         if (reg->type == CONST_PTR_TO_DYNPTR)
11751                                 dynptr_arg_type |= MEM_RDONLY;
11752
11753                         if (is_kfunc_arg_uninit(btf, &args[i]))
11754                                 dynptr_arg_type |= MEM_UNINIT;
11755
11756                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11757                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11758                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11759                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11760                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11761                                    (dynptr_arg_type & MEM_UNINIT)) {
11762                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11763
11764                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11765                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11766                                         return -EFAULT;
11767                                 }
11768
11769                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11770                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11771                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11772                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11773                                         return -EFAULT;
11774                                 }
11775                         }
11776
11777                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11778                         if (ret < 0)
11779                                 return ret;
11780
11781                         if (!(dynptr_arg_type & MEM_UNINIT)) {
11782                                 int id = dynptr_id(env, reg);
11783
11784                                 if (id < 0) {
11785                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11786                                         return id;
11787                                 }
11788                                 meta->initialized_dynptr.id = id;
11789                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11790                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11791                         }
11792
11793                         break;
11794                 }
11795                 case KF_ARG_PTR_TO_ITER:
11796                         if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11797                                 if (!check_css_task_iter_allowlist(env)) {
11798                                         verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11799                                         return -EINVAL;
11800                                 }
11801                         }
11802                         ret = process_iter_arg(env, regno, insn_idx, meta);
11803                         if (ret < 0)
11804                                 return ret;
11805                         break;
11806                 case KF_ARG_PTR_TO_LIST_HEAD:
11807                         if (reg->type != PTR_TO_MAP_VALUE &&
11808                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11809                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11810                                 return -EINVAL;
11811                         }
11812                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11813                                 verbose(env, "allocated object must be referenced\n");
11814                                 return -EINVAL;
11815                         }
11816                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11817                         if (ret < 0)
11818                                 return ret;
11819                         break;
11820                 case KF_ARG_PTR_TO_RB_ROOT:
11821                         if (reg->type != PTR_TO_MAP_VALUE &&
11822                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11823                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11824                                 return -EINVAL;
11825                         }
11826                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11827                                 verbose(env, "allocated object must be referenced\n");
11828                                 return -EINVAL;
11829                         }
11830                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11831                         if (ret < 0)
11832                                 return ret;
11833                         break;
11834                 case KF_ARG_PTR_TO_LIST_NODE:
11835                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11836                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11837                                 return -EINVAL;
11838                         }
11839                         if (!reg->ref_obj_id) {
11840                                 verbose(env, "allocated object must be referenced\n");
11841                                 return -EINVAL;
11842                         }
11843                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11844                         if (ret < 0)
11845                                 return ret;
11846                         break;
11847                 case KF_ARG_PTR_TO_RB_NODE:
11848                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11849                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11850                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
11851                                         return -EINVAL;
11852                                 }
11853                                 if (in_rbtree_lock_required_cb(env)) {
11854                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11855                                         return -EINVAL;
11856                                 }
11857                         } else {
11858                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11859                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
11860                                         return -EINVAL;
11861                                 }
11862                                 if (!reg->ref_obj_id) {
11863                                         verbose(env, "allocated object must be referenced\n");
11864                                         return -EINVAL;
11865                                 }
11866                         }
11867
11868                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11869                         if (ret < 0)
11870                                 return ret;
11871                         break;
11872                 case KF_ARG_PTR_TO_BTF_ID:
11873                         /* Only base_type is checked, further checks are done here */
11874                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11875                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11876                             !reg2btf_ids[base_type(reg->type)]) {
11877                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11878                                 verbose(env, "expected %s or socket\n",
11879                                         reg_type_str(env, base_type(reg->type) |
11880                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11881                                 return -EINVAL;
11882                         }
11883                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11884                         if (ret < 0)
11885                                 return ret;
11886                         break;
11887                 case KF_ARG_PTR_TO_MEM:
11888                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11889                         if (IS_ERR(resolve_ret)) {
11890                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11891                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11892                                 return -EINVAL;
11893                         }
11894                         ret = check_mem_reg(env, reg, regno, type_size);
11895                         if (ret < 0)
11896                                 return ret;
11897                         break;
11898                 case KF_ARG_PTR_TO_MEM_SIZE:
11899                 {
11900                         struct bpf_reg_state *buff_reg = &regs[regno];
11901                         const struct btf_param *buff_arg = &args[i];
11902                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11903                         const struct btf_param *size_arg = &args[i + 1];
11904
11905                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11906                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11907                                 if (ret < 0) {
11908                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11909                                         return ret;
11910                                 }
11911                         }
11912
11913                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11914                                 if (meta->arg_constant.found) {
11915                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11916                                         return -EFAULT;
11917                                 }
11918                                 if (!tnum_is_const(size_reg->var_off)) {
11919                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11920                                         return -EINVAL;
11921                                 }
11922                                 meta->arg_constant.found = true;
11923                                 meta->arg_constant.value = size_reg->var_off.value;
11924                         }
11925
11926                         /* Skip next '__sz' or '__szk' argument */
11927                         i++;
11928                         break;
11929                 }
11930                 case KF_ARG_PTR_TO_CALLBACK:
11931                         if (reg->type != PTR_TO_FUNC) {
11932                                 verbose(env, "arg%d expected pointer to func\n", i);
11933                                 return -EINVAL;
11934                         }
11935                         meta->subprogno = reg->subprogno;
11936                         break;
11937                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11938                         if (!type_is_ptr_alloc_obj(reg->type)) {
11939                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11940                                 return -EINVAL;
11941                         }
11942                         if (!type_is_non_owning_ref(reg->type))
11943                                 meta->arg_owning_ref = true;
11944
11945                         rec = reg_btf_record(reg);
11946                         if (!rec) {
11947                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11948                                 return -EFAULT;
11949                         }
11950
11951                         if (rec->refcount_off < 0) {
11952                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11953                                 return -EINVAL;
11954                         }
11955
11956                         meta->arg_btf = reg->btf;
11957                         meta->arg_btf_id = reg->btf_id;
11958                         break;
11959                 case KF_ARG_PTR_TO_CONST_STR:
11960                         if (reg->type != PTR_TO_MAP_VALUE) {
11961                                 verbose(env, "arg#%d doesn't point to a const string\n", i);
11962                                 return -EINVAL;
11963                         }
11964                         ret = check_reg_const_str(env, reg, regno);
11965                         if (ret)
11966                                 return ret;
11967                         break;
11968                 }
11969         }
11970
11971         if (is_kfunc_release(meta) && !meta->release_regno) {
11972                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11973                         func_name);
11974                 return -EINVAL;
11975         }
11976
11977         return 0;
11978 }
11979
11980 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11981                             struct bpf_insn *insn,
11982                             struct bpf_kfunc_call_arg_meta *meta,
11983                             const char **kfunc_name)
11984 {
11985         const struct btf_type *func, *func_proto;
11986         u32 func_id, *kfunc_flags;
11987         const char *func_name;
11988         struct btf *desc_btf;
11989
11990         if (kfunc_name)
11991                 *kfunc_name = NULL;
11992
11993         if (!insn->imm)
11994                 return -EINVAL;
11995
11996         desc_btf = find_kfunc_desc_btf(env, insn->off);
11997         if (IS_ERR(desc_btf))
11998                 return PTR_ERR(desc_btf);
11999
12000         func_id = insn->imm;
12001         func = btf_type_by_id(desc_btf, func_id);
12002         func_name = btf_name_by_offset(desc_btf, func->name_off);
12003         if (kfunc_name)
12004                 *kfunc_name = func_name;
12005         func_proto = btf_type_by_id(desc_btf, func->type);
12006
12007         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12008         if (!kfunc_flags) {
12009                 return -EACCES;
12010         }
12011
12012         memset(meta, 0, sizeof(*meta));
12013         meta->btf = desc_btf;
12014         meta->func_id = func_id;
12015         meta->kfunc_flags = *kfunc_flags;
12016         meta->func_proto = func_proto;
12017         meta->func_name = func_name;
12018
12019         return 0;
12020 }
12021
12022 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12023
12024 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12025                             int *insn_idx_p)
12026 {
12027         const struct btf_type *t, *ptr_type;
12028         u32 i, nargs, ptr_type_id, release_ref_obj_id;
12029         struct bpf_reg_state *regs = cur_regs(env);
12030         const char *func_name, *ptr_type_name;
12031         bool sleepable, rcu_lock, rcu_unlock;
12032         struct bpf_kfunc_call_arg_meta meta;
12033         struct bpf_insn_aux_data *insn_aux;
12034         int err, insn_idx = *insn_idx_p;
12035         const struct btf_param *args;
12036         const struct btf_type *ret_t;
12037         struct btf *desc_btf;
12038
12039         /* skip for now, but return error when we find this in fixup_kfunc_call */
12040         if (!insn->imm)
12041                 return 0;
12042
12043         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12044         if (err == -EACCES && func_name)
12045                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
12046         if (err)
12047                 return err;
12048         desc_btf = meta.btf;
12049         insn_aux = &env->insn_aux_data[insn_idx];
12050
12051         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12052
12053         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12054                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12055                 return -EACCES;
12056         }
12057
12058         sleepable = is_kfunc_sleepable(&meta);
12059         if (sleepable && !env->prog->aux->sleepable) {
12060                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12061                 return -EACCES;
12062         }
12063
12064         /* Check the arguments */
12065         err = check_kfunc_args(env, &meta, insn_idx);
12066         if (err < 0)
12067                 return err;
12068
12069         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12070                 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12071                                          set_rbtree_add_callback_state);
12072                 if (err) {
12073                         verbose(env, "kfunc %s#%d failed callback verification\n",
12074                                 func_name, meta.func_id);
12075                         return err;
12076                 }
12077         }
12078
12079         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12080         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12081
12082         if (env->cur_state->active_rcu_lock) {
12083                 struct bpf_func_state *state;
12084                 struct bpf_reg_state *reg;
12085                 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12086
12087                 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12088                         verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12089                         return -EACCES;
12090                 }
12091
12092                 if (rcu_lock) {
12093                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12094                         return -EINVAL;
12095                 } else if (rcu_unlock) {
12096                         bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12097                                 if (reg->type & MEM_RCU) {
12098                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12099                                         reg->type |= PTR_UNTRUSTED;
12100                                 }
12101                         }));
12102                         env->cur_state->active_rcu_lock = false;
12103                 } else if (sleepable) {
12104                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12105                         return -EACCES;
12106                 }
12107         } else if (rcu_lock) {
12108                 env->cur_state->active_rcu_lock = true;
12109         } else if (rcu_unlock) {
12110                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12111                 return -EINVAL;
12112         }
12113
12114         /* In case of release function, we get register number of refcounted
12115          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12116          */
12117         if (meta.release_regno) {
12118                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12119                 if (err) {
12120                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12121                                 func_name, meta.func_id);
12122                         return err;
12123                 }
12124         }
12125
12126         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12127             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12128             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12129                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12130                 insn_aux->insert_off = regs[BPF_REG_2].off;
12131                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12132                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12133                 if (err) {
12134                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12135                                 func_name, meta.func_id);
12136                         return err;
12137                 }
12138
12139                 err = release_reference(env, release_ref_obj_id);
12140                 if (err) {
12141                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12142                                 func_name, meta.func_id);
12143                         return err;
12144                 }
12145         }
12146
12147         if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12148                 if (!bpf_jit_supports_exceptions()) {
12149                         verbose(env, "JIT does not support calling kfunc %s#%d\n",
12150                                 func_name, meta.func_id);
12151                         return -ENOTSUPP;
12152                 }
12153                 env->seen_exception = true;
12154
12155                 /* In the case of the default callback, the cookie value passed
12156                  * to bpf_throw becomes the return value of the program.
12157                  */
12158                 if (!env->exception_callback_subprog) {
12159                         err = check_return_code(env, BPF_REG_1, "R1");
12160                         if (err < 0)
12161                                 return err;
12162                 }
12163         }
12164
12165         for (i = 0; i < CALLER_SAVED_REGS; i++)
12166                 mark_reg_not_init(env, regs, caller_saved[i]);
12167
12168         /* Check return type */
12169         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12170
12171         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12172                 /* Only exception is bpf_obj_new_impl */
12173                 if (meta.btf != btf_vmlinux ||
12174                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12175                      meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12176                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12177                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12178                         return -EINVAL;
12179                 }
12180         }
12181
12182         if (btf_type_is_scalar(t)) {
12183                 mark_reg_unknown(env, regs, BPF_REG_0);
12184                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12185         } else if (btf_type_is_ptr(t)) {
12186                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12187
12188                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12189                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12190                             meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12191                                 struct btf_struct_meta *struct_meta;
12192                                 struct btf *ret_btf;
12193                                 u32 ret_btf_id;
12194
12195                                 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12196                                         return -ENOMEM;
12197
12198                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12199                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12200                                         return -EINVAL;
12201                                 }
12202
12203                                 ret_btf = env->prog->aux->btf;
12204                                 ret_btf_id = meta.arg_constant.value;
12205
12206                                 /* This may be NULL due to user not supplying a BTF */
12207                                 if (!ret_btf) {
12208                                         verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12209                                         return -EINVAL;
12210                                 }
12211
12212                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12213                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12214                                         verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12215                                         return -EINVAL;
12216                                 }
12217
12218                                 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12219                                         if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12220                                                 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12221                                                         ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12222                                                 return -EINVAL;
12223                                         }
12224
12225                                         if (!bpf_global_percpu_ma_set) {
12226                                                 mutex_lock(&bpf_percpu_ma_lock);
12227                                                 if (!bpf_global_percpu_ma_set) {
12228                                                         /* Charge memory allocated with bpf_global_percpu_ma to
12229                                                          * root memcg. The obj_cgroup for root memcg is NULL.
12230                                                          */
12231                                                         err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12232                                                         if (!err)
12233                                                                 bpf_global_percpu_ma_set = true;
12234                                                 }
12235                                                 mutex_unlock(&bpf_percpu_ma_lock);
12236                                                 if (err)
12237                                                         return err;
12238                                         }
12239
12240                                         mutex_lock(&bpf_percpu_ma_lock);
12241                                         err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12242                                         mutex_unlock(&bpf_percpu_ma_lock);
12243                                         if (err)
12244                                                 return err;
12245                                 }
12246
12247                                 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12248                                 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12249                                         if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12250                                                 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12251                                                 return -EINVAL;
12252                                         }
12253
12254                                         if (struct_meta) {
12255                                                 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12256                                                 return -EINVAL;
12257                                         }
12258                                 }
12259
12260                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12261                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12262                                 regs[BPF_REG_0].btf = ret_btf;
12263                                 regs[BPF_REG_0].btf_id = ret_btf_id;
12264                                 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12265                                         regs[BPF_REG_0].type |= MEM_PERCPU;
12266
12267                                 insn_aux->obj_new_size = ret_t->size;
12268                                 insn_aux->kptr_struct_meta = struct_meta;
12269                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12270                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12271                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12272                                 regs[BPF_REG_0].btf = meta.arg_btf;
12273                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12274
12275                                 insn_aux->kptr_struct_meta =
12276                                         btf_find_struct_meta(meta.arg_btf,
12277                                                              meta.arg_btf_id);
12278                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12279                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12280                                 struct btf_field *field = meta.arg_list_head.field;
12281
12282                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12283                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12284                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12285                                 struct btf_field *field = meta.arg_rbtree_root.field;
12286
12287                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12288                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12289                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12290                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12291                                 regs[BPF_REG_0].btf = desc_btf;
12292                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12293                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12294                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12295                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
12296                                         verbose(env,
12297                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12298                                         return -EINVAL;
12299                                 }
12300
12301                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12302                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12303                                 regs[BPF_REG_0].btf = desc_btf;
12304                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12305                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12306                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12307                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12308
12309                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12310
12311                                 if (!meta.arg_constant.found) {
12312                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12313                                         return -EFAULT;
12314                                 }
12315
12316                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12317
12318                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12319                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12320
12321                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12322                                         regs[BPF_REG_0].type |= MEM_RDONLY;
12323                                 } else {
12324                                         /* this will set env->seen_direct_write to true */
12325                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12326                                                 verbose(env, "the prog does not allow writes to packet data\n");
12327                                                 return -EINVAL;
12328                                         }
12329                                 }
12330
12331                                 if (!meta.initialized_dynptr.id) {
12332                                         verbose(env, "verifier internal error: no dynptr id\n");
12333                                         return -EFAULT;
12334                                 }
12335                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12336
12337                                 /* we don't need to set BPF_REG_0's ref obj id
12338                                  * because packet slices are not refcounted (see
12339                                  * dynptr_type_refcounted)
12340                                  */
12341                         } else {
12342                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
12343                                         meta.func_name);
12344                                 return -EFAULT;
12345                         }
12346                 } else if (!__btf_type_is_struct(ptr_type)) {
12347                         if (!meta.r0_size) {
12348                                 __u32 sz;
12349
12350                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12351                                         meta.r0_size = sz;
12352                                         meta.r0_rdonly = true;
12353                                 }
12354                         }
12355                         if (!meta.r0_size) {
12356                                 ptr_type_name = btf_name_by_offset(desc_btf,
12357                                                                    ptr_type->name_off);
12358                                 verbose(env,
12359                                         "kernel function %s returns pointer type %s %s is not supported\n",
12360                                         func_name,
12361                                         btf_type_str(ptr_type),
12362                                         ptr_type_name);
12363                                 return -EINVAL;
12364                         }
12365
12366                         mark_reg_known_zero(env, regs, BPF_REG_0);
12367                         regs[BPF_REG_0].type = PTR_TO_MEM;
12368                         regs[BPF_REG_0].mem_size = meta.r0_size;
12369
12370                         if (meta.r0_rdonly)
12371                                 regs[BPF_REG_0].type |= MEM_RDONLY;
12372
12373                         /* Ensures we don't access the memory after a release_reference() */
12374                         if (meta.ref_obj_id)
12375                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12376                 } else {
12377                         mark_reg_known_zero(env, regs, BPF_REG_0);
12378                         regs[BPF_REG_0].btf = desc_btf;
12379                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12380                         regs[BPF_REG_0].btf_id = ptr_type_id;
12381                 }
12382
12383                 if (is_kfunc_ret_null(&meta)) {
12384                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12385                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12386                         regs[BPF_REG_0].id = ++env->id_gen;
12387                 }
12388                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12389                 if (is_kfunc_acquire(&meta)) {
12390                         int id = acquire_reference_state(env, insn_idx);
12391
12392                         if (id < 0)
12393                                 return id;
12394                         if (is_kfunc_ret_null(&meta))
12395                                 regs[BPF_REG_0].id = id;
12396                         regs[BPF_REG_0].ref_obj_id = id;
12397                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12398                         ref_set_non_owning(env, &regs[BPF_REG_0]);
12399                 }
12400
12401                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12402                         regs[BPF_REG_0].id = ++env->id_gen;
12403         } else if (btf_type_is_void(t)) {
12404                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12405                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12406                             meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12407                                 insn_aux->kptr_struct_meta =
12408                                         btf_find_struct_meta(meta.arg_btf,
12409                                                              meta.arg_btf_id);
12410                         }
12411                 }
12412         }
12413
12414         nargs = btf_type_vlen(meta.func_proto);
12415         args = (const struct btf_param *)(meta.func_proto + 1);
12416         for (i = 0; i < nargs; i++) {
12417                 u32 regno = i + 1;
12418
12419                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12420                 if (btf_type_is_ptr(t))
12421                         mark_btf_func_reg_size(env, regno, sizeof(void *));
12422                 else
12423                         /* scalar. ensured by btf_check_kfunc_arg_match() */
12424                         mark_btf_func_reg_size(env, regno, t->size);
12425         }
12426
12427         if (is_iter_next_kfunc(&meta)) {
12428                 err = process_iter_next_call(env, insn_idx, &meta);
12429                 if (err)
12430                         return err;
12431         }
12432
12433         return 0;
12434 }
12435
12436 static bool signed_add_overflows(s64 a, s64 b)
12437 {
12438         /* Do the add in u64, where overflow is well-defined */
12439         s64 res = (s64)((u64)a + (u64)b);
12440
12441         if (b < 0)
12442                 return res > a;
12443         return res < a;
12444 }
12445
12446 static bool signed_add32_overflows(s32 a, s32 b)
12447 {
12448         /* Do the add in u32, where overflow is well-defined */
12449         s32 res = (s32)((u32)a + (u32)b);
12450
12451         if (b < 0)
12452                 return res > a;
12453         return res < a;
12454 }
12455
12456 static bool signed_sub_overflows(s64 a, s64 b)
12457 {
12458         /* Do the sub in u64, where overflow is well-defined */
12459         s64 res = (s64)((u64)a - (u64)b);
12460
12461         if (b < 0)
12462                 return res < a;
12463         return res > a;
12464 }
12465
12466 static bool signed_sub32_overflows(s32 a, s32 b)
12467 {
12468         /* Do the sub in u32, where overflow is well-defined */
12469         s32 res = (s32)((u32)a - (u32)b);
12470
12471         if (b < 0)
12472                 return res < a;
12473         return res > a;
12474 }
12475
12476 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12477                                   const struct bpf_reg_state *reg,
12478                                   enum bpf_reg_type type)
12479 {
12480         bool known = tnum_is_const(reg->var_off);
12481         s64 val = reg->var_off.value;
12482         s64 smin = reg->smin_value;
12483
12484         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12485                 verbose(env, "math between %s pointer and %lld is not allowed\n",
12486                         reg_type_str(env, type), val);
12487                 return false;
12488         }
12489
12490         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12491                 verbose(env, "%s pointer offset %d is not allowed\n",
12492                         reg_type_str(env, type), reg->off);
12493                 return false;
12494         }
12495
12496         if (smin == S64_MIN) {
12497                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12498                         reg_type_str(env, type));
12499                 return false;
12500         }
12501
12502         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12503                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12504                         smin, reg_type_str(env, type));
12505                 return false;
12506         }
12507
12508         return true;
12509 }
12510
12511 enum {
12512         REASON_BOUNDS   = -1,
12513         REASON_TYPE     = -2,
12514         REASON_PATHS    = -3,
12515         REASON_LIMIT    = -4,
12516         REASON_STACK    = -5,
12517 };
12518
12519 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12520                               u32 *alu_limit, bool mask_to_left)
12521 {
12522         u32 max = 0, ptr_limit = 0;
12523
12524         switch (ptr_reg->type) {
12525         case PTR_TO_STACK:
12526                 /* Offset 0 is out-of-bounds, but acceptable start for the
12527                  * left direction, see BPF_REG_FP. Also, unknown scalar
12528                  * offset where we would need to deal with min/max bounds is
12529                  * currently prohibited for unprivileged.
12530                  */
12531                 max = MAX_BPF_STACK + mask_to_left;
12532                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12533                 break;
12534         case PTR_TO_MAP_VALUE:
12535                 max = ptr_reg->map_ptr->value_size;
12536                 ptr_limit = (mask_to_left ?
12537                              ptr_reg->smin_value :
12538                              ptr_reg->umax_value) + ptr_reg->off;
12539                 break;
12540         default:
12541                 return REASON_TYPE;
12542         }
12543
12544         if (ptr_limit >= max)
12545                 return REASON_LIMIT;
12546         *alu_limit = ptr_limit;
12547         return 0;
12548 }
12549
12550 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12551                                     const struct bpf_insn *insn)
12552 {
12553         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12554 }
12555
12556 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12557                                        u32 alu_state, u32 alu_limit)
12558 {
12559         /* If we arrived here from different branches with different
12560          * state or limits to sanitize, then this won't work.
12561          */
12562         if (aux->alu_state &&
12563             (aux->alu_state != alu_state ||
12564              aux->alu_limit != alu_limit))
12565                 return REASON_PATHS;
12566
12567         /* Corresponding fixup done in do_misc_fixups(). */
12568         aux->alu_state = alu_state;
12569         aux->alu_limit = alu_limit;
12570         return 0;
12571 }
12572
12573 static int sanitize_val_alu(struct bpf_verifier_env *env,
12574                             struct bpf_insn *insn)
12575 {
12576         struct bpf_insn_aux_data *aux = cur_aux(env);
12577
12578         if (can_skip_alu_sanitation(env, insn))
12579                 return 0;
12580
12581         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12582 }
12583
12584 static bool sanitize_needed(u8 opcode)
12585 {
12586         return opcode == BPF_ADD || opcode == BPF_SUB;
12587 }
12588
12589 struct bpf_sanitize_info {
12590         struct bpf_insn_aux_data aux;
12591         bool mask_to_left;
12592 };
12593
12594 static struct bpf_verifier_state *
12595 sanitize_speculative_path(struct bpf_verifier_env *env,
12596                           const struct bpf_insn *insn,
12597                           u32 next_idx, u32 curr_idx)
12598 {
12599         struct bpf_verifier_state *branch;
12600         struct bpf_reg_state *regs;
12601
12602         branch = push_stack(env, next_idx, curr_idx, true);
12603         if (branch && insn) {
12604                 regs = branch->frame[branch->curframe]->regs;
12605                 if (BPF_SRC(insn->code) == BPF_K) {
12606                         mark_reg_unknown(env, regs, insn->dst_reg);
12607                 } else if (BPF_SRC(insn->code) == BPF_X) {
12608                         mark_reg_unknown(env, regs, insn->dst_reg);
12609                         mark_reg_unknown(env, regs, insn->src_reg);
12610                 }
12611         }
12612         return branch;
12613 }
12614
12615 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12616                             struct bpf_insn *insn,
12617                             const struct bpf_reg_state *ptr_reg,
12618                             const struct bpf_reg_state *off_reg,
12619                             struct bpf_reg_state *dst_reg,
12620                             struct bpf_sanitize_info *info,
12621                             const bool commit_window)
12622 {
12623         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12624         struct bpf_verifier_state *vstate = env->cur_state;
12625         bool off_is_imm = tnum_is_const(off_reg->var_off);
12626         bool off_is_neg = off_reg->smin_value < 0;
12627         bool ptr_is_dst_reg = ptr_reg == dst_reg;
12628         u8 opcode = BPF_OP(insn->code);
12629         u32 alu_state, alu_limit;
12630         struct bpf_reg_state tmp;
12631         bool ret;
12632         int err;
12633
12634         if (can_skip_alu_sanitation(env, insn))
12635                 return 0;
12636
12637         /* We already marked aux for masking from non-speculative
12638          * paths, thus we got here in the first place. We only care
12639          * to explore bad access from here.
12640          */
12641         if (vstate->speculative)
12642                 goto do_sim;
12643
12644         if (!commit_window) {
12645                 if (!tnum_is_const(off_reg->var_off) &&
12646                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12647                         return REASON_BOUNDS;
12648
12649                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12650                                      (opcode == BPF_SUB && !off_is_neg);
12651         }
12652
12653         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12654         if (err < 0)
12655                 return err;
12656
12657         if (commit_window) {
12658                 /* In commit phase we narrow the masking window based on
12659                  * the observed pointer move after the simulated operation.
12660                  */
12661                 alu_state = info->aux.alu_state;
12662                 alu_limit = abs(info->aux.alu_limit - alu_limit);
12663         } else {
12664                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12665                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12666                 alu_state |= ptr_is_dst_reg ?
12667                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12668
12669                 /* Limit pruning on unknown scalars to enable deep search for
12670                  * potential masking differences from other program paths.
12671                  */
12672                 if (!off_is_imm)
12673                         env->explore_alu_limits = true;
12674         }
12675
12676         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12677         if (err < 0)
12678                 return err;
12679 do_sim:
12680         /* If we're in commit phase, we're done here given we already
12681          * pushed the truncated dst_reg into the speculative verification
12682          * stack.
12683          *
12684          * Also, when register is a known constant, we rewrite register-based
12685          * operation to immediate-based, and thus do not need masking (and as
12686          * a consequence, do not need to simulate the zero-truncation either).
12687          */
12688         if (commit_window || off_is_imm)
12689                 return 0;
12690
12691         /* Simulate and find potential out-of-bounds access under
12692          * speculative execution from truncation as a result of
12693          * masking when off was not within expected range. If off
12694          * sits in dst, then we temporarily need to move ptr there
12695          * to simulate dst (== 0) +/-= ptr. Needed, for example,
12696          * for cases where we use K-based arithmetic in one direction
12697          * and truncated reg-based in the other in order to explore
12698          * bad access.
12699          */
12700         if (!ptr_is_dst_reg) {
12701                 tmp = *dst_reg;
12702                 copy_register_state(dst_reg, ptr_reg);
12703         }
12704         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12705                                         env->insn_idx);
12706         if (!ptr_is_dst_reg && ret)
12707                 *dst_reg = tmp;
12708         return !ret ? REASON_STACK : 0;
12709 }
12710
12711 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12712 {
12713         struct bpf_verifier_state *vstate = env->cur_state;
12714
12715         /* If we simulate paths under speculation, we don't update the
12716          * insn as 'seen' such that when we verify unreachable paths in
12717          * the non-speculative domain, sanitize_dead_code() can still
12718          * rewrite/sanitize them.
12719          */
12720         if (!vstate->speculative)
12721                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12722 }
12723
12724 static int sanitize_err(struct bpf_verifier_env *env,
12725                         const struct bpf_insn *insn, int reason,
12726                         const struct bpf_reg_state *off_reg,
12727                         const struct bpf_reg_state *dst_reg)
12728 {
12729         static const char *err = "pointer arithmetic with it prohibited for !root";
12730         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12731         u32 dst = insn->dst_reg, src = insn->src_reg;
12732
12733         switch (reason) {
12734         case REASON_BOUNDS:
12735                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12736                         off_reg == dst_reg ? dst : src, err);
12737                 break;
12738         case REASON_TYPE:
12739                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12740                         off_reg == dst_reg ? src : dst, err);
12741                 break;
12742         case REASON_PATHS:
12743                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12744                         dst, op, err);
12745                 break;
12746         case REASON_LIMIT:
12747                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12748                         dst, op, err);
12749                 break;
12750         case REASON_STACK:
12751                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12752                         dst, err);
12753                 break;
12754         default:
12755                 verbose(env, "verifier internal error: unknown reason (%d)\n",
12756                         reason);
12757                 break;
12758         }
12759
12760         return -EACCES;
12761 }
12762
12763 /* check that stack access falls within stack limits and that 'reg' doesn't
12764  * have a variable offset.
12765  *
12766  * Variable offset is prohibited for unprivileged mode for simplicity since it
12767  * requires corresponding support in Spectre masking for stack ALU.  See also
12768  * retrieve_ptr_limit().
12769  *
12770  *
12771  * 'off' includes 'reg->off'.
12772  */
12773 static int check_stack_access_for_ptr_arithmetic(
12774                                 struct bpf_verifier_env *env,
12775                                 int regno,
12776                                 const struct bpf_reg_state *reg,
12777                                 int off)
12778 {
12779         if (!tnum_is_const(reg->var_off)) {
12780                 char tn_buf[48];
12781
12782                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12783                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12784                         regno, tn_buf, off);
12785                 return -EACCES;
12786         }
12787
12788         if (off >= 0 || off < -MAX_BPF_STACK) {
12789                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12790                         "prohibited for !root; off=%d\n", regno, off);
12791                 return -EACCES;
12792         }
12793
12794         return 0;
12795 }
12796
12797 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12798                                  const struct bpf_insn *insn,
12799                                  const struct bpf_reg_state *dst_reg)
12800 {
12801         u32 dst = insn->dst_reg;
12802
12803         /* For unprivileged we require that resulting offset must be in bounds
12804          * in order to be able to sanitize access later on.
12805          */
12806         if (env->bypass_spec_v1)
12807                 return 0;
12808
12809         switch (dst_reg->type) {
12810         case PTR_TO_STACK:
12811                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12812                                         dst_reg->off + dst_reg->var_off.value))
12813                         return -EACCES;
12814                 break;
12815         case PTR_TO_MAP_VALUE:
12816                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12817                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12818                                 "prohibited for !root\n", dst);
12819                         return -EACCES;
12820                 }
12821                 break;
12822         default:
12823                 break;
12824         }
12825
12826         return 0;
12827 }
12828
12829 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12830  * Caller should also handle BPF_MOV case separately.
12831  * If we return -EACCES, caller may want to try again treating pointer as a
12832  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12833  */
12834 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12835                                    struct bpf_insn *insn,
12836                                    const struct bpf_reg_state *ptr_reg,
12837                                    const struct bpf_reg_state *off_reg)
12838 {
12839         struct bpf_verifier_state *vstate = env->cur_state;
12840         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12841         struct bpf_reg_state *regs = state->regs, *dst_reg;
12842         bool known = tnum_is_const(off_reg->var_off);
12843         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12844             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12845         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12846             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12847         struct bpf_sanitize_info info = {};
12848         u8 opcode = BPF_OP(insn->code);
12849         u32 dst = insn->dst_reg;
12850         int ret;
12851
12852         dst_reg = &regs[dst];
12853
12854         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12855             smin_val > smax_val || umin_val > umax_val) {
12856                 /* Taint dst register if offset had invalid bounds derived from
12857                  * e.g. dead branches.
12858                  */
12859                 __mark_reg_unknown(env, dst_reg);
12860                 return 0;
12861         }
12862
12863         if (BPF_CLASS(insn->code) != BPF_ALU64) {
12864                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12865                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12866                         __mark_reg_unknown(env, dst_reg);
12867                         return 0;
12868                 }
12869
12870                 verbose(env,
12871                         "R%d 32-bit pointer arithmetic prohibited\n",
12872                         dst);
12873                 return -EACCES;
12874         }
12875
12876         if (ptr_reg->type & PTR_MAYBE_NULL) {
12877                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12878                         dst, reg_type_str(env, ptr_reg->type));
12879                 return -EACCES;
12880         }
12881
12882         switch (base_type(ptr_reg->type)) {
12883         case PTR_TO_CTX:
12884         case PTR_TO_MAP_VALUE:
12885         case PTR_TO_MAP_KEY:
12886         case PTR_TO_STACK:
12887         case PTR_TO_PACKET_META:
12888         case PTR_TO_PACKET:
12889         case PTR_TO_TP_BUFFER:
12890         case PTR_TO_BTF_ID:
12891         case PTR_TO_MEM:
12892         case PTR_TO_BUF:
12893         case PTR_TO_FUNC:
12894         case CONST_PTR_TO_DYNPTR:
12895                 break;
12896         case PTR_TO_FLOW_KEYS:
12897                 if (known)
12898                         break;
12899                 fallthrough;
12900         case CONST_PTR_TO_MAP:
12901                 /* smin_val represents the known value */
12902                 if (known && smin_val == 0 && opcode == BPF_ADD)
12903                         break;
12904                 fallthrough;
12905         default:
12906                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12907                         dst, reg_type_str(env, ptr_reg->type));
12908                 return -EACCES;
12909         }
12910
12911         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12912          * The id may be overwritten later if we create a new variable offset.
12913          */
12914         dst_reg->type = ptr_reg->type;
12915         dst_reg->id = ptr_reg->id;
12916
12917         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12918             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12919                 return -EINVAL;
12920
12921         /* pointer types do not carry 32-bit bounds at the moment. */
12922         __mark_reg32_unbounded(dst_reg);
12923
12924         if (sanitize_needed(opcode)) {
12925                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12926                                        &info, false);
12927                 if (ret < 0)
12928                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12929         }
12930
12931         switch (opcode) {
12932         case BPF_ADD:
12933                 /* We can take a fixed offset as long as it doesn't overflow
12934                  * the s32 'off' field
12935                  */
12936                 if (known && (ptr_reg->off + smin_val ==
12937                               (s64)(s32)(ptr_reg->off + smin_val))) {
12938                         /* pointer += K.  Accumulate it into fixed offset */
12939                         dst_reg->smin_value = smin_ptr;
12940                         dst_reg->smax_value = smax_ptr;
12941                         dst_reg->umin_value = umin_ptr;
12942                         dst_reg->umax_value = umax_ptr;
12943                         dst_reg->var_off = ptr_reg->var_off;
12944                         dst_reg->off = ptr_reg->off + smin_val;
12945                         dst_reg->raw = ptr_reg->raw;
12946                         break;
12947                 }
12948                 /* A new variable offset is created.  Note that off_reg->off
12949                  * == 0, since it's a scalar.
12950                  * dst_reg gets the pointer type and since some positive
12951                  * integer value was added to the pointer, give it a new 'id'
12952                  * if it's a PTR_TO_PACKET.
12953                  * this creates a new 'base' pointer, off_reg (variable) gets
12954                  * added into the variable offset, and we copy the fixed offset
12955                  * from ptr_reg.
12956                  */
12957                 if (signed_add_overflows(smin_ptr, smin_val) ||
12958                     signed_add_overflows(smax_ptr, smax_val)) {
12959                         dst_reg->smin_value = S64_MIN;
12960                         dst_reg->smax_value = S64_MAX;
12961                 } else {
12962                         dst_reg->smin_value = smin_ptr + smin_val;
12963                         dst_reg->smax_value = smax_ptr + smax_val;
12964                 }
12965                 if (umin_ptr + umin_val < umin_ptr ||
12966                     umax_ptr + umax_val < umax_ptr) {
12967                         dst_reg->umin_value = 0;
12968                         dst_reg->umax_value = U64_MAX;
12969                 } else {
12970                         dst_reg->umin_value = umin_ptr + umin_val;
12971                         dst_reg->umax_value = umax_ptr + umax_val;
12972                 }
12973                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12974                 dst_reg->off = ptr_reg->off;
12975                 dst_reg->raw = ptr_reg->raw;
12976                 if (reg_is_pkt_pointer(ptr_reg)) {
12977                         dst_reg->id = ++env->id_gen;
12978                         /* something was added to pkt_ptr, set range to zero */
12979                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12980                 }
12981                 break;
12982         case BPF_SUB:
12983                 if (dst_reg == off_reg) {
12984                         /* scalar -= pointer.  Creates an unknown scalar */
12985                         verbose(env, "R%d tried to subtract pointer from scalar\n",
12986                                 dst);
12987                         return -EACCES;
12988                 }
12989                 /* We don't allow subtraction from FP, because (according to
12990                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12991                  * be able to deal with it.
12992                  */
12993                 if (ptr_reg->type == PTR_TO_STACK) {
12994                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12995                                 dst);
12996                         return -EACCES;
12997                 }
12998                 if (known && (ptr_reg->off - smin_val ==
12999                               (s64)(s32)(ptr_reg->off - smin_val))) {
13000                         /* pointer -= K.  Subtract it from fixed offset */
13001                         dst_reg->smin_value = smin_ptr;
13002                         dst_reg->smax_value = smax_ptr;
13003                         dst_reg->umin_value = umin_ptr;
13004                         dst_reg->umax_value = umax_ptr;
13005                         dst_reg->var_off = ptr_reg->var_off;
13006                         dst_reg->id = ptr_reg->id;
13007                         dst_reg->off = ptr_reg->off - smin_val;
13008                         dst_reg->raw = ptr_reg->raw;
13009                         break;
13010                 }
13011                 /* A new variable offset is created.  If the subtrahend is known
13012                  * nonnegative, then any reg->range we had before is still good.
13013                  */
13014                 if (signed_sub_overflows(smin_ptr, smax_val) ||
13015                     signed_sub_overflows(smax_ptr, smin_val)) {
13016                         /* Overflow possible, we know nothing */
13017                         dst_reg->smin_value = S64_MIN;
13018                         dst_reg->smax_value = S64_MAX;
13019                 } else {
13020                         dst_reg->smin_value = smin_ptr - smax_val;
13021                         dst_reg->smax_value = smax_ptr - smin_val;
13022                 }
13023                 if (umin_ptr < umax_val) {
13024                         /* Overflow possible, we know nothing */
13025                         dst_reg->umin_value = 0;
13026                         dst_reg->umax_value = U64_MAX;
13027                 } else {
13028                         /* Cannot overflow (as long as bounds are consistent) */
13029                         dst_reg->umin_value = umin_ptr - umax_val;
13030                         dst_reg->umax_value = umax_ptr - umin_val;
13031                 }
13032                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13033                 dst_reg->off = ptr_reg->off;
13034                 dst_reg->raw = ptr_reg->raw;
13035                 if (reg_is_pkt_pointer(ptr_reg)) {
13036                         dst_reg->id = ++env->id_gen;
13037                         /* something was added to pkt_ptr, set range to zero */
13038                         if (smin_val < 0)
13039                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13040                 }
13041                 break;
13042         case BPF_AND:
13043         case BPF_OR:
13044         case BPF_XOR:
13045                 /* bitwise ops on pointers are troublesome, prohibit. */
13046                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13047                         dst, bpf_alu_string[opcode >> 4]);
13048                 return -EACCES;
13049         default:
13050                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
13051                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13052                         dst, bpf_alu_string[opcode >> 4]);
13053                 return -EACCES;
13054         }
13055
13056         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13057                 return -EINVAL;
13058         reg_bounds_sync(dst_reg);
13059         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13060                 return -EACCES;
13061         if (sanitize_needed(opcode)) {
13062                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13063                                        &info, true);
13064                 if (ret < 0)
13065                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
13066         }
13067
13068         return 0;
13069 }
13070
13071 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13072                                  struct bpf_reg_state *src_reg)
13073 {
13074         s32 smin_val = src_reg->s32_min_value;
13075         s32 smax_val = src_reg->s32_max_value;
13076         u32 umin_val = src_reg->u32_min_value;
13077         u32 umax_val = src_reg->u32_max_value;
13078
13079         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13080             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13081                 dst_reg->s32_min_value = S32_MIN;
13082                 dst_reg->s32_max_value = S32_MAX;
13083         } else {
13084                 dst_reg->s32_min_value += smin_val;
13085                 dst_reg->s32_max_value += smax_val;
13086         }
13087         if (dst_reg->u32_min_value + umin_val < umin_val ||
13088             dst_reg->u32_max_value + umax_val < umax_val) {
13089                 dst_reg->u32_min_value = 0;
13090                 dst_reg->u32_max_value = U32_MAX;
13091         } else {
13092                 dst_reg->u32_min_value += umin_val;
13093                 dst_reg->u32_max_value += umax_val;
13094         }
13095 }
13096
13097 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13098                                struct bpf_reg_state *src_reg)
13099 {
13100         s64 smin_val = src_reg->smin_value;
13101         s64 smax_val = src_reg->smax_value;
13102         u64 umin_val = src_reg->umin_value;
13103         u64 umax_val = src_reg->umax_value;
13104
13105         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13106             signed_add_overflows(dst_reg->smax_value, smax_val)) {
13107                 dst_reg->smin_value = S64_MIN;
13108                 dst_reg->smax_value = S64_MAX;
13109         } else {
13110                 dst_reg->smin_value += smin_val;
13111                 dst_reg->smax_value += smax_val;
13112         }
13113         if (dst_reg->umin_value + umin_val < umin_val ||
13114             dst_reg->umax_value + umax_val < umax_val) {
13115                 dst_reg->umin_value = 0;
13116                 dst_reg->umax_value = U64_MAX;
13117         } else {
13118                 dst_reg->umin_value += umin_val;
13119                 dst_reg->umax_value += umax_val;
13120         }
13121 }
13122
13123 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13124                                  struct bpf_reg_state *src_reg)
13125 {
13126         s32 smin_val = src_reg->s32_min_value;
13127         s32 smax_val = src_reg->s32_max_value;
13128         u32 umin_val = src_reg->u32_min_value;
13129         u32 umax_val = src_reg->u32_max_value;
13130
13131         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13132             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13133                 /* Overflow possible, we know nothing */
13134                 dst_reg->s32_min_value = S32_MIN;
13135                 dst_reg->s32_max_value = S32_MAX;
13136         } else {
13137                 dst_reg->s32_min_value -= smax_val;
13138                 dst_reg->s32_max_value -= smin_val;
13139         }
13140         if (dst_reg->u32_min_value < umax_val) {
13141                 /* Overflow possible, we know nothing */
13142                 dst_reg->u32_min_value = 0;
13143                 dst_reg->u32_max_value = U32_MAX;
13144         } else {
13145                 /* Cannot overflow (as long as bounds are consistent) */
13146                 dst_reg->u32_min_value -= umax_val;
13147                 dst_reg->u32_max_value -= umin_val;
13148         }
13149 }
13150
13151 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13152                                struct bpf_reg_state *src_reg)
13153 {
13154         s64 smin_val = src_reg->smin_value;
13155         s64 smax_val = src_reg->smax_value;
13156         u64 umin_val = src_reg->umin_value;
13157         u64 umax_val = src_reg->umax_value;
13158
13159         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13160             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13161                 /* Overflow possible, we know nothing */
13162                 dst_reg->smin_value = S64_MIN;
13163                 dst_reg->smax_value = S64_MAX;
13164         } else {
13165                 dst_reg->smin_value -= smax_val;
13166                 dst_reg->smax_value -= smin_val;
13167         }
13168         if (dst_reg->umin_value < umax_val) {
13169                 /* Overflow possible, we know nothing */
13170                 dst_reg->umin_value = 0;
13171                 dst_reg->umax_value = U64_MAX;
13172         } else {
13173                 /* Cannot overflow (as long as bounds are consistent) */
13174                 dst_reg->umin_value -= umax_val;
13175                 dst_reg->umax_value -= umin_val;
13176         }
13177 }
13178
13179 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13180                                  struct bpf_reg_state *src_reg)
13181 {
13182         s32 smin_val = src_reg->s32_min_value;
13183         u32 umin_val = src_reg->u32_min_value;
13184         u32 umax_val = src_reg->u32_max_value;
13185
13186         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13187                 /* Ain't nobody got time to multiply that sign */
13188                 __mark_reg32_unbounded(dst_reg);
13189                 return;
13190         }
13191         /* Both values are positive, so we can work with unsigned and
13192          * copy the result to signed (unless it exceeds S32_MAX).
13193          */
13194         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13195                 /* Potential overflow, we know nothing */
13196                 __mark_reg32_unbounded(dst_reg);
13197                 return;
13198         }
13199         dst_reg->u32_min_value *= umin_val;
13200         dst_reg->u32_max_value *= umax_val;
13201         if (dst_reg->u32_max_value > S32_MAX) {
13202                 /* Overflow possible, we know nothing */
13203                 dst_reg->s32_min_value = S32_MIN;
13204                 dst_reg->s32_max_value = S32_MAX;
13205         } else {
13206                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13207                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13208         }
13209 }
13210
13211 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13212                                struct bpf_reg_state *src_reg)
13213 {
13214         s64 smin_val = src_reg->smin_value;
13215         u64 umin_val = src_reg->umin_value;
13216         u64 umax_val = src_reg->umax_value;
13217
13218         if (smin_val < 0 || dst_reg->smin_value < 0) {
13219                 /* Ain't nobody got time to multiply that sign */
13220                 __mark_reg64_unbounded(dst_reg);
13221                 return;
13222         }
13223         /* Both values are positive, so we can work with unsigned and
13224          * copy the result to signed (unless it exceeds S64_MAX).
13225          */
13226         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13227                 /* Potential overflow, we know nothing */
13228                 __mark_reg64_unbounded(dst_reg);
13229                 return;
13230         }
13231         dst_reg->umin_value *= umin_val;
13232         dst_reg->umax_value *= umax_val;
13233         if (dst_reg->umax_value > S64_MAX) {
13234                 /* Overflow possible, we know nothing */
13235                 dst_reg->smin_value = S64_MIN;
13236                 dst_reg->smax_value = S64_MAX;
13237         } else {
13238                 dst_reg->smin_value = dst_reg->umin_value;
13239                 dst_reg->smax_value = dst_reg->umax_value;
13240         }
13241 }
13242
13243 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13244                                  struct bpf_reg_state *src_reg)
13245 {
13246         bool src_known = tnum_subreg_is_const(src_reg->var_off);
13247         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13248         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13249         s32 smin_val = src_reg->s32_min_value;
13250         u32 umax_val = src_reg->u32_max_value;
13251
13252         if (src_known && dst_known) {
13253                 __mark_reg32_known(dst_reg, var32_off.value);
13254                 return;
13255         }
13256
13257         /* We get our minimum from the var_off, since that's inherently
13258          * bitwise.  Our maximum is the minimum of the operands' maxima.
13259          */
13260         dst_reg->u32_min_value = var32_off.value;
13261         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13262         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13263                 /* Lose signed bounds when ANDing negative numbers,
13264                  * ain't nobody got time for that.
13265                  */
13266                 dst_reg->s32_min_value = S32_MIN;
13267                 dst_reg->s32_max_value = S32_MAX;
13268         } else {
13269                 /* ANDing two positives gives a positive, so safe to
13270                  * cast result into s64.
13271                  */
13272                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13273                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13274         }
13275 }
13276
13277 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13278                                struct bpf_reg_state *src_reg)
13279 {
13280         bool src_known = tnum_is_const(src_reg->var_off);
13281         bool dst_known = tnum_is_const(dst_reg->var_off);
13282         s64 smin_val = src_reg->smin_value;
13283         u64 umax_val = src_reg->umax_value;
13284
13285         if (src_known && dst_known) {
13286                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13287                 return;
13288         }
13289
13290         /* We get our minimum from the var_off, since that's inherently
13291          * bitwise.  Our maximum is the minimum of the operands' maxima.
13292          */
13293         dst_reg->umin_value = dst_reg->var_off.value;
13294         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13295         if (dst_reg->smin_value < 0 || smin_val < 0) {
13296                 /* Lose signed bounds when ANDing negative numbers,
13297                  * ain't nobody got time for that.
13298                  */
13299                 dst_reg->smin_value = S64_MIN;
13300                 dst_reg->smax_value = S64_MAX;
13301         } else {
13302                 /* ANDing two positives gives a positive, so safe to
13303                  * cast result into s64.
13304                  */
13305                 dst_reg->smin_value = dst_reg->umin_value;
13306                 dst_reg->smax_value = dst_reg->umax_value;
13307         }
13308         /* We may learn something more from the var_off */
13309         __update_reg_bounds(dst_reg);
13310 }
13311
13312 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13313                                 struct bpf_reg_state *src_reg)
13314 {
13315         bool src_known = tnum_subreg_is_const(src_reg->var_off);
13316         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13317         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13318         s32 smin_val = src_reg->s32_min_value;
13319         u32 umin_val = src_reg->u32_min_value;
13320
13321         if (src_known && dst_known) {
13322                 __mark_reg32_known(dst_reg, var32_off.value);
13323                 return;
13324         }
13325
13326         /* We get our maximum from the var_off, and our minimum is the
13327          * maximum of the operands' minima
13328          */
13329         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13330         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13331         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13332                 /* Lose signed bounds when ORing negative numbers,
13333                  * ain't nobody got time for that.
13334                  */
13335                 dst_reg->s32_min_value = S32_MIN;
13336                 dst_reg->s32_max_value = S32_MAX;
13337         } else {
13338                 /* ORing two positives gives a positive, so safe to
13339                  * cast result into s64.
13340                  */
13341                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13342                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13343         }
13344 }
13345
13346 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13347                               struct bpf_reg_state *src_reg)
13348 {
13349         bool src_known = tnum_is_const(src_reg->var_off);
13350         bool dst_known = tnum_is_const(dst_reg->var_off);
13351         s64 smin_val = src_reg->smin_value;
13352         u64 umin_val = src_reg->umin_value;
13353
13354         if (src_known && dst_known) {
13355                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13356                 return;
13357         }
13358
13359         /* We get our maximum from the var_off, and our minimum is the
13360          * maximum of the operands' minima
13361          */
13362         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13363         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13364         if (dst_reg->smin_value < 0 || smin_val < 0) {
13365                 /* Lose signed bounds when ORing negative numbers,
13366                  * ain't nobody got time for that.
13367                  */
13368                 dst_reg->smin_value = S64_MIN;
13369                 dst_reg->smax_value = S64_MAX;
13370         } else {
13371                 /* ORing two positives gives a positive, so safe to
13372                  * cast result into s64.
13373                  */
13374                 dst_reg->smin_value = dst_reg->umin_value;
13375                 dst_reg->smax_value = dst_reg->umax_value;
13376         }
13377         /* We may learn something more from the var_off */
13378         __update_reg_bounds(dst_reg);
13379 }
13380
13381 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13382                                  struct bpf_reg_state *src_reg)
13383 {
13384         bool src_known = tnum_subreg_is_const(src_reg->var_off);
13385         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13386         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13387         s32 smin_val = src_reg->s32_min_value;
13388
13389         if (src_known && dst_known) {
13390                 __mark_reg32_known(dst_reg, var32_off.value);
13391                 return;
13392         }
13393
13394         /* We get both minimum and maximum from the var32_off. */
13395         dst_reg->u32_min_value = var32_off.value;
13396         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13397
13398         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13399                 /* XORing two positive sign numbers gives a positive,
13400                  * so safe to cast u32 result into s32.
13401                  */
13402                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13403                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13404         } else {
13405                 dst_reg->s32_min_value = S32_MIN;
13406                 dst_reg->s32_max_value = S32_MAX;
13407         }
13408 }
13409
13410 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13411                                struct bpf_reg_state *src_reg)
13412 {
13413         bool src_known = tnum_is_const(src_reg->var_off);
13414         bool dst_known = tnum_is_const(dst_reg->var_off);
13415         s64 smin_val = src_reg->smin_value;
13416
13417         if (src_known && dst_known) {
13418                 /* dst_reg->var_off.value has been updated earlier */
13419                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13420                 return;
13421         }
13422
13423         /* We get both minimum and maximum from the var_off. */
13424         dst_reg->umin_value = dst_reg->var_off.value;
13425         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13426
13427         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13428                 /* XORing two positive sign numbers gives a positive,
13429                  * so safe to cast u64 result into s64.
13430                  */
13431                 dst_reg->smin_value = dst_reg->umin_value;
13432                 dst_reg->smax_value = dst_reg->umax_value;
13433         } else {
13434                 dst_reg->smin_value = S64_MIN;
13435                 dst_reg->smax_value = S64_MAX;
13436         }
13437
13438         __update_reg_bounds(dst_reg);
13439 }
13440
13441 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13442                                    u64 umin_val, u64 umax_val)
13443 {
13444         /* We lose all sign bit information (except what we can pick
13445          * up from var_off)
13446          */
13447         dst_reg->s32_min_value = S32_MIN;
13448         dst_reg->s32_max_value = S32_MAX;
13449         /* If we might shift our top bit out, then we know nothing */
13450         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13451                 dst_reg->u32_min_value = 0;
13452                 dst_reg->u32_max_value = U32_MAX;
13453         } else {
13454                 dst_reg->u32_min_value <<= umin_val;
13455                 dst_reg->u32_max_value <<= umax_val;
13456         }
13457 }
13458
13459 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13460                                  struct bpf_reg_state *src_reg)
13461 {
13462         u32 umax_val = src_reg->u32_max_value;
13463         u32 umin_val = src_reg->u32_min_value;
13464         /* u32 alu operation will zext upper bits */
13465         struct tnum subreg = tnum_subreg(dst_reg->var_off);
13466
13467         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13468         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13469         /* Not required but being careful mark reg64 bounds as unknown so
13470          * that we are forced to pick them up from tnum and zext later and
13471          * if some path skips this step we are still safe.
13472          */
13473         __mark_reg64_unbounded(dst_reg);
13474         __update_reg32_bounds(dst_reg);
13475 }
13476
13477 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13478                                    u64 umin_val, u64 umax_val)
13479 {
13480         /* Special case <<32 because it is a common compiler pattern to sign
13481          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13482          * positive we know this shift will also be positive so we can track
13483          * bounds correctly. Otherwise we lose all sign bit information except
13484          * what we can pick up from var_off. Perhaps we can generalize this
13485          * later to shifts of any length.
13486          */
13487         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13488                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13489         else
13490                 dst_reg->smax_value = S64_MAX;
13491
13492         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13493                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13494         else
13495                 dst_reg->smin_value = S64_MIN;
13496
13497         /* If we might shift our top bit out, then we know nothing */
13498         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13499                 dst_reg->umin_value = 0;
13500                 dst_reg->umax_value = U64_MAX;
13501         } else {
13502                 dst_reg->umin_value <<= umin_val;
13503                 dst_reg->umax_value <<= umax_val;
13504         }
13505 }
13506
13507 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13508                                struct bpf_reg_state *src_reg)
13509 {
13510         u64 umax_val = src_reg->umax_value;
13511         u64 umin_val = src_reg->umin_value;
13512
13513         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13514         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13515         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13516
13517         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13518         /* We may learn something more from the var_off */
13519         __update_reg_bounds(dst_reg);
13520 }
13521
13522 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13523                                  struct bpf_reg_state *src_reg)
13524 {
13525         struct tnum subreg = tnum_subreg(dst_reg->var_off);
13526         u32 umax_val = src_reg->u32_max_value;
13527         u32 umin_val = src_reg->u32_min_value;
13528
13529         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13530          * be negative, then either:
13531          * 1) src_reg might be zero, so the sign bit of the result is
13532          *    unknown, so we lose our signed bounds
13533          * 2) it's known negative, thus the unsigned bounds capture the
13534          *    signed bounds
13535          * 3) the signed bounds cross zero, so they tell us nothing
13536          *    about the result
13537          * If the value in dst_reg is known nonnegative, then again the
13538          * unsigned bounds capture the signed bounds.
13539          * Thus, in all cases it suffices to blow away our signed bounds
13540          * and rely on inferring new ones from the unsigned bounds and
13541          * var_off of the result.
13542          */
13543         dst_reg->s32_min_value = S32_MIN;
13544         dst_reg->s32_max_value = S32_MAX;
13545
13546         dst_reg->var_off = tnum_rshift(subreg, umin_val);
13547         dst_reg->u32_min_value >>= umax_val;
13548         dst_reg->u32_max_value >>= umin_val;
13549
13550         __mark_reg64_unbounded(dst_reg);
13551         __update_reg32_bounds(dst_reg);
13552 }
13553
13554 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13555                                struct bpf_reg_state *src_reg)
13556 {
13557         u64 umax_val = src_reg->umax_value;
13558         u64 umin_val = src_reg->umin_value;
13559
13560         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13561          * be negative, then either:
13562          * 1) src_reg might be zero, so the sign bit of the result is
13563          *    unknown, so we lose our signed bounds
13564          * 2) it's known negative, thus the unsigned bounds capture the
13565          *    signed bounds
13566          * 3) the signed bounds cross zero, so they tell us nothing
13567          *    about the result
13568          * If the value in dst_reg is known nonnegative, then again the
13569          * unsigned bounds capture the signed bounds.
13570          * Thus, in all cases it suffices to blow away our signed bounds
13571          * and rely on inferring new ones from the unsigned bounds and
13572          * var_off of the result.
13573          */
13574         dst_reg->smin_value = S64_MIN;
13575         dst_reg->smax_value = S64_MAX;
13576         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13577         dst_reg->umin_value >>= umax_val;
13578         dst_reg->umax_value >>= umin_val;
13579
13580         /* Its not easy to operate on alu32 bounds here because it depends
13581          * on bits being shifted in. Take easy way out and mark unbounded
13582          * so we can recalculate later from tnum.
13583          */
13584         __mark_reg32_unbounded(dst_reg);
13585         __update_reg_bounds(dst_reg);
13586 }
13587
13588 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13589                                   struct bpf_reg_state *src_reg)
13590 {
13591         u64 umin_val = src_reg->u32_min_value;
13592
13593         /* Upon reaching here, src_known is true and
13594          * umax_val is equal to umin_val.
13595          */
13596         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13597         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13598
13599         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13600
13601         /* blow away the dst_reg umin_value/umax_value and rely on
13602          * dst_reg var_off to refine the result.
13603          */
13604         dst_reg->u32_min_value = 0;
13605         dst_reg->u32_max_value = U32_MAX;
13606
13607         __mark_reg64_unbounded(dst_reg);
13608         __update_reg32_bounds(dst_reg);
13609 }
13610
13611 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13612                                 struct bpf_reg_state *src_reg)
13613 {
13614         u64 umin_val = src_reg->umin_value;
13615
13616         /* Upon reaching here, src_known is true and umax_val is equal
13617          * to umin_val.
13618          */
13619         dst_reg->smin_value >>= umin_val;
13620         dst_reg->smax_value >>= umin_val;
13621
13622         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13623
13624         /* blow away the dst_reg umin_value/umax_value and rely on
13625          * dst_reg var_off to refine the result.
13626          */
13627         dst_reg->umin_value = 0;
13628         dst_reg->umax_value = U64_MAX;
13629
13630         /* Its not easy to operate on alu32 bounds here because it depends
13631          * on bits being shifted in from upper 32-bits. Take easy way out
13632          * and mark unbounded so we can recalculate later from tnum.
13633          */
13634         __mark_reg32_unbounded(dst_reg);
13635         __update_reg_bounds(dst_reg);
13636 }
13637
13638 /* WARNING: This function does calculations on 64-bit values, but the actual
13639  * execution may occur on 32-bit values. Therefore, things like bitshifts
13640  * need extra checks in the 32-bit case.
13641  */
13642 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13643                                       struct bpf_insn *insn,
13644                                       struct bpf_reg_state *dst_reg,
13645                                       struct bpf_reg_state src_reg)
13646 {
13647         struct bpf_reg_state *regs = cur_regs(env);
13648         u8 opcode = BPF_OP(insn->code);
13649         bool src_known;
13650         s64 smin_val, smax_val;
13651         u64 umin_val, umax_val;
13652         s32 s32_min_val, s32_max_val;
13653         u32 u32_min_val, u32_max_val;
13654         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13655         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13656         int ret;
13657
13658         smin_val = src_reg.smin_value;
13659         smax_val = src_reg.smax_value;
13660         umin_val = src_reg.umin_value;
13661         umax_val = src_reg.umax_value;
13662
13663         s32_min_val = src_reg.s32_min_value;
13664         s32_max_val = src_reg.s32_max_value;
13665         u32_min_val = src_reg.u32_min_value;
13666         u32_max_val = src_reg.u32_max_value;
13667
13668         if (alu32) {
13669                 src_known = tnum_subreg_is_const(src_reg.var_off);
13670                 if ((src_known &&
13671                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13672                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13673                         /* Taint dst register if offset had invalid bounds
13674                          * derived from e.g. dead branches.
13675                          */
13676                         __mark_reg_unknown(env, dst_reg);
13677                         return 0;
13678                 }
13679         } else {
13680                 src_known = tnum_is_const(src_reg.var_off);
13681                 if ((src_known &&
13682                      (smin_val != smax_val || umin_val != umax_val)) ||
13683                     smin_val > smax_val || umin_val > umax_val) {
13684                         /* Taint dst register if offset had invalid bounds
13685                          * derived from e.g. dead branches.
13686                          */
13687                         __mark_reg_unknown(env, dst_reg);
13688                         return 0;
13689                 }
13690         }
13691
13692         if (!src_known &&
13693             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13694                 __mark_reg_unknown(env, dst_reg);
13695                 return 0;
13696         }
13697
13698         if (sanitize_needed(opcode)) {
13699                 ret = sanitize_val_alu(env, insn);
13700                 if (ret < 0)
13701                         return sanitize_err(env, insn, ret, NULL, NULL);
13702         }
13703
13704         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13705          * There are two classes of instructions: The first class we track both
13706          * alu32 and alu64 sign/unsigned bounds independently this provides the
13707          * greatest amount of precision when alu operations are mixed with jmp32
13708          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13709          * and BPF_OR. This is possible because these ops have fairly easy to
13710          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13711          * See alu32 verifier tests for examples. The second class of
13712          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13713          * with regards to tracking sign/unsigned bounds because the bits may
13714          * cross subreg boundaries in the alu64 case. When this happens we mark
13715          * the reg unbounded in the subreg bound space and use the resulting
13716          * tnum to calculate an approximation of the sign/unsigned bounds.
13717          */
13718         switch (opcode) {
13719         case BPF_ADD:
13720                 scalar32_min_max_add(dst_reg, &src_reg);
13721                 scalar_min_max_add(dst_reg, &src_reg);
13722                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13723                 break;
13724         case BPF_SUB:
13725                 scalar32_min_max_sub(dst_reg, &src_reg);
13726                 scalar_min_max_sub(dst_reg, &src_reg);
13727                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13728                 break;
13729         case BPF_MUL:
13730                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13731                 scalar32_min_max_mul(dst_reg, &src_reg);
13732                 scalar_min_max_mul(dst_reg, &src_reg);
13733                 break;
13734         case BPF_AND:
13735                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13736                 scalar32_min_max_and(dst_reg, &src_reg);
13737                 scalar_min_max_and(dst_reg, &src_reg);
13738                 break;
13739         case BPF_OR:
13740                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13741                 scalar32_min_max_or(dst_reg, &src_reg);
13742                 scalar_min_max_or(dst_reg, &src_reg);
13743                 break;
13744         case BPF_XOR:
13745                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13746                 scalar32_min_max_xor(dst_reg, &src_reg);
13747                 scalar_min_max_xor(dst_reg, &src_reg);
13748                 break;
13749         case BPF_LSH:
13750                 if (umax_val >= insn_bitness) {
13751                         /* Shifts greater than 31 or 63 are undefined.
13752                          * This includes shifts by a negative number.
13753                          */
13754                         mark_reg_unknown(env, regs, insn->dst_reg);
13755                         break;
13756                 }
13757                 if (alu32)
13758                         scalar32_min_max_lsh(dst_reg, &src_reg);
13759                 else
13760                         scalar_min_max_lsh(dst_reg, &src_reg);
13761                 break;
13762         case BPF_RSH:
13763                 if (umax_val >= insn_bitness) {
13764                         /* Shifts greater than 31 or 63 are undefined.
13765                          * This includes shifts by a negative number.
13766                          */
13767                         mark_reg_unknown(env, regs, insn->dst_reg);
13768                         break;
13769                 }
13770                 if (alu32)
13771                         scalar32_min_max_rsh(dst_reg, &src_reg);
13772                 else
13773                         scalar_min_max_rsh(dst_reg, &src_reg);
13774                 break;
13775         case BPF_ARSH:
13776                 if (umax_val >= insn_bitness) {
13777                         /* Shifts greater than 31 or 63 are undefined.
13778                          * This includes shifts by a negative number.
13779                          */
13780                         mark_reg_unknown(env, regs, insn->dst_reg);
13781                         break;
13782                 }
13783                 if (alu32)
13784                         scalar32_min_max_arsh(dst_reg, &src_reg);
13785                 else
13786                         scalar_min_max_arsh(dst_reg, &src_reg);
13787                 break;
13788         default:
13789                 mark_reg_unknown(env, regs, insn->dst_reg);
13790                 break;
13791         }
13792
13793         /* ALU32 ops are zero extended into 64bit register */
13794         if (alu32)
13795                 zext_32_to_64(dst_reg);
13796         reg_bounds_sync(dst_reg);
13797         return 0;
13798 }
13799
13800 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13801  * and var_off.
13802  */
13803 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13804                                    struct bpf_insn *insn)
13805 {
13806         struct bpf_verifier_state *vstate = env->cur_state;
13807         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13808         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13809         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13810         u8 opcode = BPF_OP(insn->code);
13811         int err;
13812
13813         dst_reg = &regs[insn->dst_reg];
13814         src_reg = NULL;
13815         if (dst_reg->type != SCALAR_VALUE)
13816                 ptr_reg = dst_reg;
13817         else
13818                 /* Make sure ID is cleared otherwise dst_reg min/max could be
13819                  * incorrectly propagated into other registers by find_equal_scalars()
13820                  */
13821                 dst_reg->id = 0;
13822         if (BPF_SRC(insn->code) == BPF_X) {
13823                 src_reg = &regs[insn->src_reg];
13824                 if (src_reg->type != SCALAR_VALUE) {
13825                         if (dst_reg->type != SCALAR_VALUE) {
13826                                 /* Combining two pointers by any ALU op yields
13827                                  * an arbitrary scalar. Disallow all math except
13828                                  * pointer subtraction
13829                                  */
13830                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13831                                         mark_reg_unknown(env, regs, insn->dst_reg);
13832                                         return 0;
13833                                 }
13834                                 verbose(env, "R%d pointer %s pointer prohibited\n",
13835                                         insn->dst_reg,
13836                                         bpf_alu_string[opcode >> 4]);
13837                                 return -EACCES;
13838                         } else {
13839                                 /* scalar += pointer
13840                                  * This is legal, but we have to reverse our
13841                                  * src/dest handling in computing the range
13842                                  */
13843                                 err = mark_chain_precision(env, insn->dst_reg);
13844                                 if (err)
13845                                         return err;
13846                                 return adjust_ptr_min_max_vals(env, insn,
13847                                                                src_reg, dst_reg);
13848                         }
13849                 } else if (ptr_reg) {
13850                         /* pointer += scalar */
13851                         err = mark_chain_precision(env, insn->src_reg);
13852                         if (err)
13853                                 return err;
13854                         return adjust_ptr_min_max_vals(env, insn,
13855                                                        dst_reg, src_reg);
13856                 } else if (dst_reg->precise) {
13857                         /* if dst_reg is precise, src_reg should be precise as well */
13858                         err = mark_chain_precision(env, insn->src_reg);
13859                         if (err)
13860                                 return err;
13861                 }
13862         } else {
13863                 /* Pretend the src is a reg with a known value, since we only
13864                  * need to be able to read from this state.
13865                  */
13866                 off_reg.type = SCALAR_VALUE;
13867                 __mark_reg_known(&off_reg, insn->imm);
13868                 src_reg = &off_reg;
13869                 if (ptr_reg) /* pointer += K */
13870                         return adjust_ptr_min_max_vals(env, insn,
13871                                                        ptr_reg, src_reg);
13872         }
13873
13874         /* Got here implies adding two SCALAR_VALUEs */
13875         if (WARN_ON_ONCE(ptr_reg)) {
13876                 print_verifier_state(env, state, true);
13877                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13878                 return -EINVAL;
13879         }
13880         if (WARN_ON(!src_reg)) {
13881                 print_verifier_state(env, state, true);
13882                 verbose(env, "verifier internal error: no src_reg\n");
13883                 return -EINVAL;
13884         }
13885         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13886 }
13887
13888 /* check validity of 32-bit and 64-bit arithmetic operations */
13889 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13890 {
13891         struct bpf_reg_state *regs = cur_regs(env);
13892         u8 opcode = BPF_OP(insn->code);
13893         int err;
13894
13895         if (opcode == BPF_END || opcode == BPF_NEG) {
13896                 if (opcode == BPF_NEG) {
13897                         if (BPF_SRC(insn->code) != BPF_K ||
13898                             insn->src_reg != BPF_REG_0 ||
13899                             insn->off != 0 || insn->imm != 0) {
13900                                 verbose(env, "BPF_NEG uses reserved fields\n");
13901                                 return -EINVAL;
13902                         }
13903                 } else {
13904                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13905                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13906                             (BPF_CLASS(insn->code) == BPF_ALU64 &&
13907                              BPF_SRC(insn->code) != BPF_TO_LE)) {
13908                                 verbose(env, "BPF_END uses reserved fields\n");
13909                                 return -EINVAL;
13910                         }
13911                 }
13912
13913                 /* check src operand */
13914                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13915                 if (err)
13916                         return err;
13917
13918                 if (is_pointer_value(env, insn->dst_reg)) {
13919                         verbose(env, "R%d pointer arithmetic prohibited\n",
13920                                 insn->dst_reg);
13921                         return -EACCES;
13922                 }
13923
13924                 /* check dest operand */
13925                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13926                 if (err)
13927                         return err;
13928
13929         } else if (opcode == BPF_MOV) {
13930
13931                 if (BPF_SRC(insn->code) == BPF_X) {
13932                         if (insn->imm != 0) {
13933                                 verbose(env, "BPF_MOV uses reserved fields\n");
13934                                 return -EINVAL;
13935                         }
13936
13937                         if (BPF_CLASS(insn->code) == BPF_ALU) {
13938                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13939                                         verbose(env, "BPF_MOV uses reserved fields\n");
13940                                         return -EINVAL;
13941                                 }
13942                         } else {
13943                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13944                                     insn->off != 32) {
13945                                         verbose(env, "BPF_MOV uses reserved fields\n");
13946                                         return -EINVAL;
13947                                 }
13948                         }
13949
13950                         /* check src operand */
13951                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13952                         if (err)
13953                                 return err;
13954                 } else {
13955                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13956                                 verbose(env, "BPF_MOV uses reserved fields\n");
13957                                 return -EINVAL;
13958                         }
13959                 }
13960
13961                 /* check dest operand, mark as required later */
13962                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13963                 if (err)
13964                         return err;
13965
13966                 if (BPF_SRC(insn->code) == BPF_X) {
13967                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
13968                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13969
13970                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13971                                 if (insn->off == 0) {
13972                                         /* case: R1 = R2
13973                                          * copy register state to dest reg
13974                                          */
13975                                         assign_scalar_id_before_mov(env, src_reg);
13976                                         copy_register_state(dst_reg, src_reg);
13977                                         dst_reg->live |= REG_LIVE_WRITTEN;
13978                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13979                                 } else {
13980                                         /* case: R1 = (s8, s16 s32)R2 */
13981                                         if (is_pointer_value(env, insn->src_reg)) {
13982                                                 verbose(env,
13983                                                         "R%d sign-extension part of pointer\n",
13984                                                         insn->src_reg);
13985                                                 return -EACCES;
13986                                         } else if (src_reg->type == SCALAR_VALUE) {
13987                                                 bool no_sext;
13988
13989                                                 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13990                                                 if (no_sext)
13991                                                         assign_scalar_id_before_mov(env, src_reg);
13992                                                 copy_register_state(dst_reg, src_reg);
13993                                                 if (!no_sext)
13994                                                         dst_reg->id = 0;
13995                                                 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13996                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13997                                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
13998                                         } else {
13999                                                 mark_reg_unknown(env, regs, insn->dst_reg);
14000                                         }
14001                                 }
14002                         } else {
14003                                 /* R1 = (u32) R2 */
14004                                 if (is_pointer_value(env, insn->src_reg)) {
14005                                         verbose(env,
14006                                                 "R%d partial copy of pointer\n",
14007                                                 insn->src_reg);
14008                                         return -EACCES;
14009                                 } else if (src_reg->type == SCALAR_VALUE) {
14010                                         if (insn->off == 0) {
14011                                                 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14012
14013                                                 if (is_src_reg_u32)
14014                                                         assign_scalar_id_before_mov(env, src_reg);
14015                                                 copy_register_state(dst_reg, src_reg);
14016                                                 /* Make sure ID is cleared if src_reg is not in u32
14017                                                  * range otherwise dst_reg min/max could be incorrectly
14018                                                  * propagated into src_reg by find_equal_scalars()
14019                                                  */
14020                                                 if (!is_src_reg_u32)
14021                                                         dst_reg->id = 0;
14022                                                 dst_reg->live |= REG_LIVE_WRITTEN;
14023                                                 dst_reg->subreg_def = env->insn_idx + 1;
14024                                         } else {
14025                                                 /* case: W1 = (s8, s16)W2 */
14026                                                 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14027
14028                                                 if (no_sext)
14029                                                         assign_scalar_id_before_mov(env, src_reg);
14030                                                 copy_register_state(dst_reg, src_reg);
14031                                                 if (!no_sext)
14032                                                         dst_reg->id = 0;
14033                                                 dst_reg->live |= REG_LIVE_WRITTEN;
14034                                                 dst_reg->subreg_def = env->insn_idx + 1;
14035                                                 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14036                                         }
14037                                 } else {
14038                                         mark_reg_unknown(env, regs,
14039                                                          insn->dst_reg);
14040                                 }
14041                                 zext_32_to_64(dst_reg);
14042                                 reg_bounds_sync(dst_reg);
14043                         }
14044                 } else {
14045                         /* case: R = imm
14046                          * remember the value we stored into this reg
14047                          */
14048                         /* clear any state __mark_reg_known doesn't set */
14049                         mark_reg_unknown(env, regs, insn->dst_reg);
14050                         regs[insn->dst_reg].type = SCALAR_VALUE;
14051                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
14052                                 __mark_reg_known(regs + insn->dst_reg,
14053                                                  insn->imm);
14054                         } else {
14055                                 __mark_reg_known(regs + insn->dst_reg,
14056                                                  (u32)insn->imm);
14057                         }
14058                 }
14059
14060         } else if (opcode > BPF_END) {
14061                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14062                 return -EINVAL;
14063
14064         } else {        /* all other ALU ops: and, sub, xor, add, ... */
14065
14066                 if (BPF_SRC(insn->code) == BPF_X) {
14067                         if (insn->imm != 0 || insn->off > 1 ||
14068                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14069                                 verbose(env, "BPF_ALU uses reserved fields\n");
14070                                 return -EINVAL;
14071                         }
14072                         /* check src1 operand */
14073                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
14074                         if (err)
14075                                 return err;
14076                 } else {
14077                         if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14078                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14079                                 verbose(env, "BPF_ALU uses reserved fields\n");
14080                                 return -EINVAL;
14081                         }
14082                 }
14083
14084                 /* check src2 operand */
14085                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14086                 if (err)
14087                         return err;
14088
14089                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14090                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14091                         verbose(env, "div by zero\n");
14092                         return -EINVAL;
14093                 }
14094
14095                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14096                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14097                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14098
14099                         if (insn->imm < 0 || insn->imm >= size) {
14100                                 verbose(env, "invalid shift %d\n", insn->imm);
14101                                 return -EINVAL;
14102                         }
14103                 }
14104
14105                 /* check dest operand */
14106                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14107                 err = err ?: adjust_reg_min_max_vals(env, insn);
14108                 if (err)
14109                         return err;
14110         }
14111
14112         return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14113 }
14114
14115 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14116                                    struct bpf_reg_state *dst_reg,
14117                                    enum bpf_reg_type type,
14118                                    bool range_right_open)
14119 {
14120         struct bpf_func_state *state;
14121         struct bpf_reg_state *reg;
14122         int new_range;
14123
14124         if (dst_reg->off < 0 ||
14125             (dst_reg->off == 0 && range_right_open))
14126                 /* This doesn't give us any range */
14127                 return;
14128
14129         if (dst_reg->umax_value > MAX_PACKET_OFF ||
14130             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14131                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
14132                  * than pkt_end, but that's because it's also less than pkt.
14133                  */
14134                 return;
14135
14136         new_range = dst_reg->off;
14137         if (range_right_open)
14138                 new_range++;
14139
14140         /* Examples for register markings:
14141          *
14142          * pkt_data in dst register:
14143          *
14144          *   r2 = r3;
14145          *   r2 += 8;
14146          *   if (r2 > pkt_end) goto <handle exception>
14147          *   <access okay>
14148          *
14149          *   r2 = r3;
14150          *   r2 += 8;
14151          *   if (r2 < pkt_end) goto <access okay>
14152          *   <handle exception>
14153          *
14154          *   Where:
14155          *     r2 == dst_reg, pkt_end == src_reg
14156          *     r2=pkt(id=n,off=8,r=0)
14157          *     r3=pkt(id=n,off=0,r=0)
14158          *
14159          * pkt_data in src register:
14160          *
14161          *   r2 = r3;
14162          *   r2 += 8;
14163          *   if (pkt_end >= r2) goto <access okay>
14164          *   <handle exception>
14165          *
14166          *   r2 = r3;
14167          *   r2 += 8;
14168          *   if (pkt_end <= r2) goto <handle exception>
14169          *   <access okay>
14170          *
14171          *   Where:
14172          *     pkt_end == dst_reg, r2 == src_reg
14173          *     r2=pkt(id=n,off=8,r=0)
14174          *     r3=pkt(id=n,off=0,r=0)
14175          *
14176          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14177          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14178          * and [r3, r3 + 8-1) respectively is safe to access depending on
14179          * the check.
14180          */
14181
14182         /* If our ids match, then we must have the same max_value.  And we
14183          * don't care about the other reg's fixed offset, since if it's too big
14184          * the range won't allow anything.
14185          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14186          */
14187         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14188                 if (reg->type == type && reg->id == dst_reg->id)
14189                         /* keep the maximum range already checked */
14190                         reg->range = max(reg->range, new_range);
14191         }));
14192 }
14193
14194 /*
14195  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14196  */
14197 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14198                                   u8 opcode, bool is_jmp32)
14199 {
14200         struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14201         struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14202         u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14203         u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14204         s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14205         s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14206         u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14207         u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14208         s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14209         s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14210
14211         switch (opcode) {
14212         case BPF_JEQ:
14213                 /* constants, umin/umax and smin/smax checks would be
14214                  * redundant in this case because they all should match
14215                  */
14216                 if (tnum_is_const(t1) && tnum_is_const(t2))
14217                         return t1.value == t2.value;
14218                 /* non-overlapping ranges */
14219                 if (umin1 > umax2 || umax1 < umin2)
14220                         return 0;
14221                 if (smin1 > smax2 || smax1 < smin2)
14222                         return 0;
14223                 if (!is_jmp32) {
14224                         /* if 64-bit ranges are inconclusive, see if we can
14225                          * utilize 32-bit subrange knowledge to eliminate
14226                          * branches that can't be taken a priori
14227                          */
14228                         if (reg1->u32_min_value > reg2->u32_max_value ||
14229                             reg1->u32_max_value < reg2->u32_min_value)
14230                                 return 0;
14231                         if (reg1->s32_min_value > reg2->s32_max_value ||
14232                             reg1->s32_max_value < reg2->s32_min_value)
14233                                 return 0;
14234                 }
14235                 break;
14236         case BPF_JNE:
14237                 /* constants, umin/umax and smin/smax checks would be
14238                  * redundant in this case because they all should match
14239                  */
14240                 if (tnum_is_const(t1) && tnum_is_const(t2))
14241                         return t1.value != t2.value;
14242                 /* non-overlapping ranges */
14243                 if (umin1 > umax2 || umax1 < umin2)
14244                         return 1;
14245                 if (smin1 > smax2 || smax1 < smin2)
14246                         return 1;
14247                 if (!is_jmp32) {
14248                         /* if 64-bit ranges are inconclusive, see if we can
14249                          * utilize 32-bit subrange knowledge to eliminate
14250                          * branches that can't be taken a priori
14251                          */
14252                         if (reg1->u32_min_value > reg2->u32_max_value ||
14253                             reg1->u32_max_value < reg2->u32_min_value)
14254                                 return 1;
14255                         if (reg1->s32_min_value > reg2->s32_max_value ||
14256                             reg1->s32_max_value < reg2->s32_min_value)
14257                                 return 1;
14258                 }
14259                 break;
14260         case BPF_JSET:
14261                 if (!is_reg_const(reg2, is_jmp32)) {
14262                         swap(reg1, reg2);
14263                         swap(t1, t2);
14264                 }
14265                 if (!is_reg_const(reg2, is_jmp32))
14266                         return -1;
14267                 if ((~t1.mask & t1.value) & t2.value)
14268                         return 1;
14269                 if (!((t1.mask | t1.value) & t2.value))
14270                         return 0;
14271                 break;
14272         case BPF_JGT:
14273                 if (umin1 > umax2)
14274                         return 1;
14275                 else if (umax1 <= umin2)
14276                         return 0;
14277                 break;
14278         case BPF_JSGT:
14279                 if (smin1 > smax2)
14280                         return 1;
14281                 else if (smax1 <= smin2)
14282                         return 0;
14283                 break;
14284         case BPF_JLT:
14285                 if (umax1 < umin2)
14286                         return 1;
14287                 else if (umin1 >= umax2)
14288                         return 0;
14289                 break;
14290         case BPF_JSLT:
14291                 if (smax1 < smin2)
14292                         return 1;
14293                 else if (smin1 >= smax2)
14294                         return 0;
14295                 break;
14296         case BPF_JGE:
14297                 if (umin1 >= umax2)
14298                         return 1;
14299                 else if (umax1 < umin2)
14300                         return 0;
14301                 break;
14302         case BPF_JSGE:
14303                 if (smin1 >= smax2)
14304                         return 1;
14305                 else if (smax1 < smin2)
14306                         return 0;
14307                 break;
14308         case BPF_JLE:
14309                 if (umax1 <= umin2)
14310                         return 1;
14311                 else if (umin1 > umax2)
14312                         return 0;
14313                 break;
14314         case BPF_JSLE:
14315                 if (smax1 <= smin2)
14316                         return 1;
14317                 else if (smin1 > smax2)
14318                         return 0;
14319                 break;
14320         }
14321
14322         return -1;
14323 }
14324
14325 static int flip_opcode(u32 opcode)
14326 {
14327         /* How can we transform "a <op> b" into "b <op> a"? */
14328         static const u8 opcode_flip[16] = {
14329                 /* these stay the same */
14330                 [BPF_JEQ  >> 4] = BPF_JEQ,
14331                 [BPF_JNE  >> 4] = BPF_JNE,
14332                 [BPF_JSET >> 4] = BPF_JSET,
14333                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14334                 [BPF_JGE  >> 4] = BPF_JLE,
14335                 [BPF_JGT  >> 4] = BPF_JLT,
14336                 [BPF_JLE  >> 4] = BPF_JGE,
14337                 [BPF_JLT  >> 4] = BPF_JGT,
14338                 [BPF_JSGE >> 4] = BPF_JSLE,
14339                 [BPF_JSGT >> 4] = BPF_JSLT,
14340                 [BPF_JSLE >> 4] = BPF_JSGE,
14341                 [BPF_JSLT >> 4] = BPF_JSGT
14342         };
14343         return opcode_flip[opcode >> 4];
14344 }
14345
14346 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14347                                    struct bpf_reg_state *src_reg,
14348                                    u8 opcode)
14349 {
14350         struct bpf_reg_state *pkt;
14351
14352         if (src_reg->type == PTR_TO_PACKET_END) {
14353                 pkt = dst_reg;
14354         } else if (dst_reg->type == PTR_TO_PACKET_END) {
14355                 pkt = src_reg;
14356                 opcode = flip_opcode(opcode);
14357         } else {
14358                 return -1;
14359         }
14360
14361         if (pkt->range >= 0)
14362                 return -1;
14363
14364         switch (opcode) {
14365         case BPF_JLE:
14366                 /* pkt <= pkt_end */
14367                 fallthrough;
14368         case BPF_JGT:
14369                 /* pkt > pkt_end */
14370                 if (pkt->range == BEYOND_PKT_END)
14371                         /* pkt has at last one extra byte beyond pkt_end */
14372                         return opcode == BPF_JGT;
14373                 break;
14374         case BPF_JLT:
14375                 /* pkt < pkt_end */
14376                 fallthrough;
14377         case BPF_JGE:
14378                 /* pkt >= pkt_end */
14379                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14380                         return opcode == BPF_JGE;
14381                 break;
14382         }
14383         return -1;
14384 }
14385
14386 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14387  * and return:
14388  *  1 - branch will be taken and "goto target" will be executed
14389  *  0 - branch will not be taken and fall-through to next insn
14390  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14391  *      range [0,10]
14392  */
14393 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14394                            u8 opcode, bool is_jmp32)
14395 {
14396         if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14397                 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14398
14399         if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14400                 u64 val;
14401
14402                 /* arrange that reg2 is a scalar, and reg1 is a pointer */
14403                 if (!is_reg_const(reg2, is_jmp32)) {
14404                         opcode = flip_opcode(opcode);
14405                         swap(reg1, reg2);
14406                 }
14407                 /* and ensure that reg2 is a constant */
14408                 if (!is_reg_const(reg2, is_jmp32))
14409                         return -1;
14410
14411                 if (!reg_not_null(reg1))
14412                         return -1;
14413
14414                 /* If pointer is valid tests against zero will fail so we can
14415                  * use this to direct branch taken.
14416                  */
14417                 val = reg_const_value(reg2, is_jmp32);
14418                 if (val != 0)
14419                         return -1;
14420
14421                 switch (opcode) {
14422                 case BPF_JEQ:
14423                         return 0;
14424                 case BPF_JNE:
14425                         return 1;
14426                 default:
14427                         return -1;
14428                 }
14429         }
14430
14431         /* now deal with two scalars, but not necessarily constants */
14432         return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14433 }
14434
14435 /* Opcode that corresponds to a *false* branch condition.
14436  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14437  */
14438 static u8 rev_opcode(u8 opcode)
14439 {
14440         switch (opcode) {
14441         case BPF_JEQ:           return BPF_JNE;
14442         case BPF_JNE:           return BPF_JEQ;
14443         /* JSET doesn't have it's reverse opcode in BPF, so add
14444          * BPF_X flag to denote the reverse of that operation
14445          */
14446         case BPF_JSET:          return BPF_JSET | BPF_X;
14447         case BPF_JSET | BPF_X:  return BPF_JSET;
14448         case BPF_JGE:           return BPF_JLT;
14449         case BPF_JGT:           return BPF_JLE;
14450         case BPF_JLE:           return BPF_JGT;
14451         case BPF_JLT:           return BPF_JGE;
14452         case BPF_JSGE:          return BPF_JSLT;
14453         case BPF_JSGT:          return BPF_JSLE;
14454         case BPF_JSLE:          return BPF_JSGT;
14455         case BPF_JSLT:          return BPF_JSGE;
14456         default:                return 0;
14457         }
14458 }
14459
14460 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14461 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14462                                 u8 opcode, bool is_jmp32)
14463 {
14464         struct tnum t;
14465         u64 val;
14466
14467 again:
14468         switch (opcode) {
14469         case BPF_JEQ:
14470                 if (is_jmp32) {
14471                         reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14472                         reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14473                         reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14474                         reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14475                         reg2->u32_min_value = reg1->u32_min_value;
14476                         reg2->u32_max_value = reg1->u32_max_value;
14477                         reg2->s32_min_value = reg1->s32_min_value;
14478                         reg2->s32_max_value = reg1->s32_max_value;
14479
14480                         t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14481                         reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14482                         reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14483                 } else {
14484                         reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14485                         reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14486                         reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14487                         reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14488                         reg2->umin_value = reg1->umin_value;
14489                         reg2->umax_value = reg1->umax_value;
14490                         reg2->smin_value = reg1->smin_value;
14491                         reg2->smax_value = reg1->smax_value;
14492
14493                         reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14494                         reg2->var_off = reg1->var_off;
14495                 }
14496                 break;
14497         case BPF_JNE:
14498                 if (!is_reg_const(reg2, is_jmp32))
14499                         swap(reg1, reg2);
14500                 if (!is_reg_const(reg2, is_jmp32))
14501                         break;
14502
14503                 /* try to recompute the bound of reg1 if reg2 is a const and
14504                  * is exactly the edge of reg1.
14505                  */
14506                 val = reg_const_value(reg2, is_jmp32);
14507                 if (is_jmp32) {
14508                         /* u32_min_value is not equal to 0xffffffff at this point,
14509                          * because otherwise u32_max_value is 0xffffffff as well,
14510                          * in such a case both reg1 and reg2 would be constants,
14511                          * jump would be predicted and reg_set_min_max() won't
14512                          * be called.
14513                          *
14514                          * Same reasoning works for all {u,s}{min,max}{32,64} cases
14515                          * below.
14516                          */
14517                         if (reg1->u32_min_value == (u32)val)
14518                                 reg1->u32_min_value++;
14519                         if (reg1->u32_max_value == (u32)val)
14520                                 reg1->u32_max_value--;
14521                         if (reg1->s32_min_value == (s32)val)
14522                                 reg1->s32_min_value++;
14523                         if (reg1->s32_max_value == (s32)val)
14524                                 reg1->s32_max_value--;
14525                 } else {
14526                         if (reg1->umin_value == (u64)val)
14527                                 reg1->umin_value++;
14528                         if (reg1->umax_value == (u64)val)
14529                                 reg1->umax_value--;
14530                         if (reg1->smin_value == (s64)val)
14531                                 reg1->smin_value++;
14532                         if (reg1->smax_value == (s64)val)
14533                                 reg1->smax_value--;
14534                 }
14535                 break;
14536         case BPF_JSET:
14537                 if (!is_reg_const(reg2, is_jmp32))
14538                         swap(reg1, reg2);
14539                 if (!is_reg_const(reg2, is_jmp32))
14540                         break;
14541                 val = reg_const_value(reg2, is_jmp32);
14542                 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14543                  * requires single bit to learn something useful. E.g., if we
14544                  * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14545                  * are actually set? We can learn something definite only if
14546                  * it's a single-bit value to begin with.
14547                  *
14548                  * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14549                  * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14550                  * bit 1 is set, which we can readily use in adjustments.
14551                  */
14552                 if (!is_power_of_2(val))
14553                         break;
14554                 if (is_jmp32) {
14555                         t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14556                         reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14557                 } else {
14558                         reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14559                 }
14560                 break;
14561         case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14562                 if (!is_reg_const(reg2, is_jmp32))
14563                         swap(reg1, reg2);
14564                 if (!is_reg_const(reg2, is_jmp32))
14565                         break;
14566                 val = reg_const_value(reg2, is_jmp32);
14567                 if (is_jmp32) {
14568                         t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14569                         reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14570                 } else {
14571                         reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14572                 }
14573                 break;
14574         case BPF_JLE:
14575                 if (is_jmp32) {
14576                         reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14577                         reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14578                 } else {
14579                         reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14580                         reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14581                 }
14582                 break;
14583         case BPF_JLT:
14584                 if (is_jmp32) {
14585                         reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14586                         reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14587                 } else {
14588                         reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14589                         reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14590                 }
14591                 break;
14592         case BPF_JSLE:
14593                 if (is_jmp32) {
14594                         reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14595                         reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14596                 } else {
14597                         reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14598                         reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14599                 }
14600                 break;
14601         case BPF_JSLT:
14602                 if (is_jmp32) {
14603                         reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14604                         reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14605                 } else {
14606                         reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14607                         reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14608                 }
14609                 break;
14610         case BPF_JGE:
14611         case BPF_JGT:
14612         case BPF_JSGE:
14613         case BPF_JSGT:
14614                 /* just reuse LE/LT logic above */
14615                 opcode = flip_opcode(opcode);
14616                 swap(reg1, reg2);
14617                 goto again;
14618         default:
14619                 return;
14620         }
14621 }
14622
14623 /* Adjusts the register min/max values in the case that the dst_reg and
14624  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14625  * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14626  * Technically we can do similar adjustments for pointers to the same object,
14627  * but we don't support that right now.
14628  */
14629 static int reg_set_min_max(struct bpf_verifier_env *env,
14630                            struct bpf_reg_state *true_reg1,
14631                            struct bpf_reg_state *true_reg2,
14632                            struct bpf_reg_state *false_reg1,
14633                            struct bpf_reg_state *false_reg2,
14634                            u8 opcode, bool is_jmp32)
14635 {
14636         int err;
14637
14638         /* If either register is a pointer, we can't learn anything about its
14639          * variable offset from the compare (unless they were a pointer into
14640          * the same object, but we don't bother with that).
14641          */
14642         if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14643                 return 0;
14644
14645         /* fallthrough (FALSE) branch */
14646         regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14647         reg_bounds_sync(false_reg1);
14648         reg_bounds_sync(false_reg2);
14649
14650         /* jump (TRUE) branch */
14651         regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14652         reg_bounds_sync(true_reg1);
14653         reg_bounds_sync(true_reg2);
14654
14655         err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14656         err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14657         err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14658         err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14659         return err;
14660 }
14661
14662 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14663                                  struct bpf_reg_state *reg, u32 id,
14664                                  bool is_null)
14665 {
14666         if (type_may_be_null(reg->type) && reg->id == id &&
14667             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14668                 /* Old offset (both fixed and variable parts) should have been
14669                  * known-zero, because we don't allow pointer arithmetic on
14670                  * pointers that might be NULL. If we see this happening, don't
14671                  * convert the register.
14672                  *
14673                  * But in some cases, some helpers that return local kptrs
14674                  * advance offset for the returned pointer. In those cases, it
14675                  * is fine to expect to see reg->off.
14676                  */
14677                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14678                         return;
14679                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14680                     WARN_ON_ONCE(reg->off))
14681                         return;
14682
14683                 if (is_null) {
14684                         reg->type = SCALAR_VALUE;
14685                         /* We don't need id and ref_obj_id from this point
14686                          * onwards anymore, thus we should better reset it,
14687                          * so that state pruning has chances to take effect.
14688                          */
14689                         reg->id = 0;
14690                         reg->ref_obj_id = 0;
14691
14692                         return;
14693                 }
14694
14695                 mark_ptr_not_null_reg(reg);
14696
14697                 if (!reg_may_point_to_spin_lock(reg)) {
14698                         /* For not-NULL ptr, reg->ref_obj_id will be reset
14699                          * in release_reference().
14700                          *
14701                          * reg->id is still used by spin_lock ptr. Other
14702                          * than spin_lock ptr type, reg->id can be reset.
14703                          */
14704                         reg->id = 0;
14705                 }
14706         }
14707 }
14708
14709 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14710  * be folded together at some point.
14711  */
14712 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14713                                   bool is_null)
14714 {
14715         struct bpf_func_state *state = vstate->frame[vstate->curframe];
14716         struct bpf_reg_state *regs = state->regs, *reg;
14717         u32 ref_obj_id = regs[regno].ref_obj_id;
14718         u32 id = regs[regno].id;
14719
14720         if (ref_obj_id && ref_obj_id == id && is_null)
14721                 /* regs[regno] is in the " == NULL" branch.
14722                  * No one could have freed the reference state before
14723                  * doing the NULL check.
14724                  */
14725                 WARN_ON_ONCE(release_reference_state(state, id));
14726
14727         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14728                 mark_ptr_or_null_reg(state, reg, id, is_null);
14729         }));
14730 }
14731
14732 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14733                                    struct bpf_reg_state *dst_reg,
14734                                    struct bpf_reg_state *src_reg,
14735                                    struct bpf_verifier_state *this_branch,
14736                                    struct bpf_verifier_state *other_branch)
14737 {
14738         if (BPF_SRC(insn->code) != BPF_X)
14739                 return false;
14740
14741         /* Pointers are always 64-bit. */
14742         if (BPF_CLASS(insn->code) == BPF_JMP32)
14743                 return false;
14744
14745         switch (BPF_OP(insn->code)) {
14746         case BPF_JGT:
14747                 if ((dst_reg->type == PTR_TO_PACKET &&
14748                      src_reg->type == PTR_TO_PACKET_END) ||
14749                     (dst_reg->type == PTR_TO_PACKET_META &&
14750                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14751                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14752                         find_good_pkt_pointers(this_branch, dst_reg,
14753                                                dst_reg->type, false);
14754                         mark_pkt_end(other_branch, insn->dst_reg, true);
14755                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14756                             src_reg->type == PTR_TO_PACKET) ||
14757                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14758                             src_reg->type == PTR_TO_PACKET_META)) {
14759                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14760                         find_good_pkt_pointers(other_branch, src_reg,
14761                                                src_reg->type, true);
14762                         mark_pkt_end(this_branch, insn->src_reg, false);
14763                 } else {
14764                         return false;
14765                 }
14766                 break;
14767         case BPF_JLT:
14768                 if ((dst_reg->type == PTR_TO_PACKET &&
14769                      src_reg->type == PTR_TO_PACKET_END) ||
14770                     (dst_reg->type == PTR_TO_PACKET_META &&
14771                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14772                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14773                         find_good_pkt_pointers(other_branch, dst_reg,
14774                                                dst_reg->type, true);
14775                         mark_pkt_end(this_branch, insn->dst_reg, false);
14776                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14777                             src_reg->type == PTR_TO_PACKET) ||
14778                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14779                             src_reg->type == PTR_TO_PACKET_META)) {
14780                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14781                         find_good_pkt_pointers(this_branch, src_reg,
14782                                                src_reg->type, false);
14783                         mark_pkt_end(other_branch, insn->src_reg, true);
14784                 } else {
14785                         return false;
14786                 }
14787                 break;
14788         case BPF_JGE:
14789                 if ((dst_reg->type == PTR_TO_PACKET &&
14790                      src_reg->type == PTR_TO_PACKET_END) ||
14791                     (dst_reg->type == PTR_TO_PACKET_META &&
14792                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14793                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14794                         find_good_pkt_pointers(this_branch, dst_reg,
14795                                                dst_reg->type, true);
14796                         mark_pkt_end(other_branch, insn->dst_reg, false);
14797                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14798                             src_reg->type == PTR_TO_PACKET) ||
14799                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14800                             src_reg->type == PTR_TO_PACKET_META)) {
14801                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14802                         find_good_pkt_pointers(other_branch, src_reg,
14803                                                src_reg->type, false);
14804                         mark_pkt_end(this_branch, insn->src_reg, true);
14805                 } else {
14806                         return false;
14807                 }
14808                 break;
14809         case BPF_JLE:
14810                 if ((dst_reg->type == PTR_TO_PACKET &&
14811                      src_reg->type == PTR_TO_PACKET_END) ||
14812                     (dst_reg->type == PTR_TO_PACKET_META &&
14813                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14814                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14815                         find_good_pkt_pointers(other_branch, dst_reg,
14816                                                dst_reg->type, false);
14817                         mark_pkt_end(this_branch, insn->dst_reg, true);
14818                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14819                             src_reg->type == PTR_TO_PACKET) ||
14820                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14821                             src_reg->type == PTR_TO_PACKET_META)) {
14822                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14823                         find_good_pkt_pointers(this_branch, src_reg,
14824                                                src_reg->type, true);
14825                         mark_pkt_end(other_branch, insn->src_reg, false);
14826                 } else {
14827                         return false;
14828                 }
14829                 break;
14830         default:
14831                 return false;
14832         }
14833
14834         return true;
14835 }
14836
14837 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14838                                struct bpf_reg_state *known_reg)
14839 {
14840         struct bpf_func_state *state;
14841         struct bpf_reg_state *reg;
14842
14843         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14844                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14845                         copy_register_state(reg, known_reg);
14846         }));
14847 }
14848
14849 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14850                              struct bpf_insn *insn, int *insn_idx)
14851 {
14852         struct bpf_verifier_state *this_branch = env->cur_state;
14853         struct bpf_verifier_state *other_branch;
14854         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14855         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14856         struct bpf_reg_state *eq_branch_regs;
14857         struct bpf_reg_state fake_reg = {};
14858         u8 opcode = BPF_OP(insn->code);
14859         bool is_jmp32;
14860         int pred = -1;
14861         int err;
14862
14863         /* Only conditional jumps are expected to reach here. */
14864         if (opcode == BPF_JA || opcode > BPF_JSLE) {
14865                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14866                 return -EINVAL;
14867         }
14868
14869         /* check src2 operand */
14870         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14871         if (err)
14872                 return err;
14873
14874         dst_reg = &regs[insn->dst_reg];
14875         if (BPF_SRC(insn->code) == BPF_X) {
14876                 if (insn->imm != 0) {
14877                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14878                         return -EINVAL;
14879                 }
14880
14881                 /* check src1 operand */
14882                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14883                 if (err)
14884                         return err;
14885
14886                 src_reg = &regs[insn->src_reg];
14887                 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14888                     is_pointer_value(env, insn->src_reg)) {
14889                         verbose(env, "R%d pointer comparison prohibited\n",
14890                                 insn->src_reg);
14891                         return -EACCES;
14892                 }
14893         } else {
14894                 if (insn->src_reg != BPF_REG_0) {
14895                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14896                         return -EINVAL;
14897                 }
14898                 src_reg = &fake_reg;
14899                 src_reg->type = SCALAR_VALUE;
14900                 __mark_reg_known(src_reg, insn->imm);
14901         }
14902
14903         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14904         pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
14905         if (pred >= 0) {
14906                 /* If we get here with a dst_reg pointer type it is because
14907                  * above is_branch_taken() special cased the 0 comparison.
14908                  */
14909                 if (!__is_pointer_value(false, dst_reg))
14910                         err = mark_chain_precision(env, insn->dst_reg);
14911                 if (BPF_SRC(insn->code) == BPF_X && !err &&
14912                     !__is_pointer_value(false, src_reg))
14913                         err = mark_chain_precision(env, insn->src_reg);
14914                 if (err)
14915                         return err;
14916         }
14917
14918         if (pred == 1) {
14919                 /* Only follow the goto, ignore fall-through. If needed, push
14920                  * the fall-through branch for simulation under speculative
14921                  * execution.
14922                  */
14923                 if (!env->bypass_spec_v1 &&
14924                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
14925                                                *insn_idx))
14926                         return -EFAULT;
14927                 if (env->log.level & BPF_LOG_LEVEL)
14928                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14929                 *insn_idx += insn->off;
14930                 return 0;
14931         } else if (pred == 0) {
14932                 /* Only follow the fall-through branch, since that's where the
14933                  * program will go. If needed, push the goto branch for
14934                  * simulation under speculative execution.
14935                  */
14936                 if (!env->bypass_spec_v1 &&
14937                     !sanitize_speculative_path(env, insn,
14938                                                *insn_idx + insn->off + 1,
14939                                                *insn_idx))
14940                         return -EFAULT;
14941                 if (env->log.level & BPF_LOG_LEVEL)
14942                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14943                 return 0;
14944         }
14945
14946         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14947                                   false);
14948         if (!other_branch)
14949                 return -EFAULT;
14950         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14951
14952         if (BPF_SRC(insn->code) == BPF_X) {
14953                 err = reg_set_min_max(env,
14954                                       &other_branch_regs[insn->dst_reg],
14955                                       &other_branch_regs[insn->src_reg],
14956                                       dst_reg, src_reg, opcode, is_jmp32);
14957         } else /* BPF_SRC(insn->code) == BPF_K */ {
14958                 err = reg_set_min_max(env,
14959                                       &other_branch_regs[insn->dst_reg],
14960                                       src_reg /* fake one */,
14961                                       dst_reg, src_reg /* same fake one */,
14962                                       opcode, is_jmp32);
14963         }
14964         if (err)
14965                 return err;
14966
14967         if (BPF_SRC(insn->code) == BPF_X &&
14968             src_reg->type == SCALAR_VALUE && src_reg->id &&
14969             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14970                 find_equal_scalars(this_branch, src_reg);
14971                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14972         }
14973         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14974             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14975                 find_equal_scalars(this_branch, dst_reg);
14976                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14977         }
14978
14979         /* if one pointer register is compared to another pointer
14980          * register check if PTR_MAYBE_NULL could be lifted.
14981          * E.g. register A - maybe null
14982          *      register B - not null
14983          * for JNE A, B, ... - A is not null in the false branch;
14984          * for JEQ A, B, ... - A is not null in the true branch.
14985          *
14986          * Since PTR_TO_BTF_ID points to a kernel struct that does
14987          * not need to be null checked by the BPF program, i.e.,
14988          * could be null even without PTR_MAYBE_NULL marking, so
14989          * only propagate nullness when neither reg is that type.
14990          */
14991         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14992             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14993             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14994             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14995             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14996                 eq_branch_regs = NULL;
14997                 switch (opcode) {
14998                 case BPF_JEQ:
14999                         eq_branch_regs = other_branch_regs;
15000                         break;
15001                 case BPF_JNE:
15002                         eq_branch_regs = regs;
15003                         break;
15004                 default:
15005                         /* do nothing */
15006                         break;
15007                 }
15008                 if (eq_branch_regs) {
15009                         if (type_may_be_null(src_reg->type))
15010                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15011                         else
15012                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15013                 }
15014         }
15015
15016         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15017          * NOTE: these optimizations below are related with pointer comparison
15018          *       which will never be JMP32.
15019          */
15020         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15021             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15022             type_may_be_null(dst_reg->type)) {
15023                 /* Mark all identical registers in each branch as either
15024                  * safe or unknown depending R == 0 or R != 0 conditional.
15025                  */
15026                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15027                                       opcode == BPF_JNE);
15028                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15029                                       opcode == BPF_JEQ);
15030         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15031                                            this_branch, other_branch) &&
15032                    is_pointer_value(env, insn->dst_reg)) {
15033                 verbose(env, "R%d pointer comparison prohibited\n",
15034                         insn->dst_reg);
15035                 return -EACCES;
15036         }
15037         if (env->log.level & BPF_LOG_LEVEL)
15038                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15039         return 0;
15040 }
15041
15042 /* verify BPF_LD_IMM64 instruction */
15043 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15044 {
15045         struct bpf_insn_aux_data *aux = cur_aux(env);
15046         struct bpf_reg_state *regs = cur_regs(env);
15047         struct bpf_reg_state *dst_reg;
15048         struct bpf_map *map;
15049         int err;
15050
15051         if (BPF_SIZE(insn->code) != BPF_DW) {
15052                 verbose(env, "invalid BPF_LD_IMM insn\n");
15053                 return -EINVAL;
15054         }
15055         if (insn->off != 0) {
15056                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15057                 return -EINVAL;
15058         }
15059
15060         err = check_reg_arg(env, insn->dst_reg, DST_OP);
15061         if (err)
15062                 return err;
15063
15064         dst_reg = &regs[insn->dst_reg];
15065         if (insn->src_reg == 0) {
15066                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15067
15068                 dst_reg->type = SCALAR_VALUE;
15069                 __mark_reg_known(&regs[insn->dst_reg], imm);
15070                 return 0;
15071         }
15072
15073         /* All special src_reg cases are listed below. From this point onwards
15074          * we either succeed and assign a corresponding dst_reg->type after
15075          * zeroing the offset, or fail and reject the program.
15076          */
15077         mark_reg_known_zero(env, regs, insn->dst_reg);
15078
15079         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15080                 dst_reg->type = aux->btf_var.reg_type;
15081                 switch (base_type(dst_reg->type)) {
15082                 case PTR_TO_MEM:
15083                         dst_reg->mem_size = aux->btf_var.mem_size;
15084                         break;
15085                 case PTR_TO_BTF_ID:
15086                         dst_reg->btf = aux->btf_var.btf;
15087                         dst_reg->btf_id = aux->btf_var.btf_id;
15088                         break;
15089                 default:
15090                         verbose(env, "bpf verifier is misconfigured\n");
15091                         return -EFAULT;
15092                 }
15093                 return 0;
15094         }
15095
15096         if (insn->src_reg == BPF_PSEUDO_FUNC) {
15097                 struct bpf_prog_aux *aux = env->prog->aux;
15098                 u32 subprogno = find_subprog(env,
15099                                              env->insn_idx + insn->imm + 1);
15100
15101                 if (!aux->func_info) {
15102                         verbose(env, "missing btf func_info\n");
15103                         return -EINVAL;
15104                 }
15105                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15106                         verbose(env, "callback function not static\n");
15107                         return -EINVAL;
15108                 }
15109
15110                 dst_reg->type = PTR_TO_FUNC;
15111                 dst_reg->subprogno = subprogno;
15112                 return 0;
15113         }
15114
15115         map = env->used_maps[aux->map_index];
15116         dst_reg->map_ptr = map;
15117
15118         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15119             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15120                 dst_reg->type = PTR_TO_MAP_VALUE;
15121                 dst_reg->off = aux->map_off;
15122                 WARN_ON_ONCE(map->max_entries != 1);
15123                 /* We want reg->id to be same (0) as map_value is not distinct */
15124         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15125                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15126                 dst_reg->type = CONST_PTR_TO_MAP;
15127         } else {
15128                 verbose(env, "bpf verifier is misconfigured\n");
15129                 return -EINVAL;
15130         }
15131
15132         return 0;
15133 }
15134
15135 static bool may_access_skb(enum bpf_prog_type type)
15136 {
15137         switch (type) {
15138         case BPF_PROG_TYPE_SOCKET_FILTER:
15139         case BPF_PROG_TYPE_SCHED_CLS:
15140         case BPF_PROG_TYPE_SCHED_ACT:
15141                 return true;
15142         default:
15143                 return false;
15144         }
15145 }
15146
15147 /* verify safety of LD_ABS|LD_IND instructions:
15148  * - they can only appear in the programs where ctx == skb
15149  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15150  *   preserve R6-R9, and store return value into R0
15151  *
15152  * Implicit input:
15153  *   ctx == skb == R6 == CTX
15154  *
15155  * Explicit input:
15156  *   SRC == any register
15157  *   IMM == 32-bit immediate
15158  *
15159  * Output:
15160  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15161  */
15162 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15163 {
15164         struct bpf_reg_state *regs = cur_regs(env);
15165         static const int ctx_reg = BPF_REG_6;
15166         u8 mode = BPF_MODE(insn->code);
15167         int i, err;
15168
15169         if (!may_access_skb(resolve_prog_type(env->prog))) {
15170                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15171                 return -EINVAL;
15172         }
15173
15174         if (!env->ops->gen_ld_abs) {
15175                 verbose(env, "bpf verifier is misconfigured\n");
15176                 return -EINVAL;
15177         }
15178
15179         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15180             BPF_SIZE(insn->code) == BPF_DW ||
15181             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15182                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15183                 return -EINVAL;
15184         }
15185
15186         /* check whether implicit source operand (register R6) is readable */
15187         err = check_reg_arg(env, ctx_reg, SRC_OP);
15188         if (err)
15189                 return err;
15190
15191         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15192          * gen_ld_abs() may terminate the program at runtime, leading to
15193          * reference leak.
15194          */
15195         err = check_reference_leak(env, false);
15196         if (err) {
15197                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15198                 return err;
15199         }
15200
15201         if (env->cur_state->active_lock.ptr) {
15202                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15203                 return -EINVAL;
15204         }
15205
15206         if (env->cur_state->active_rcu_lock) {
15207                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15208                 return -EINVAL;
15209         }
15210
15211         if (regs[ctx_reg].type != PTR_TO_CTX) {
15212                 verbose(env,
15213                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15214                 return -EINVAL;
15215         }
15216
15217         if (mode == BPF_IND) {
15218                 /* check explicit source operand */
15219                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15220                 if (err)
15221                         return err;
15222         }
15223
15224         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15225         if (err < 0)
15226                 return err;
15227
15228         /* reset caller saved regs to unreadable */
15229         for (i = 0; i < CALLER_SAVED_REGS; i++) {
15230                 mark_reg_not_init(env, regs, caller_saved[i]);
15231                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15232         }
15233
15234         /* mark destination R0 register as readable, since it contains
15235          * the value fetched from the packet.
15236          * Already marked as written above.
15237          */
15238         mark_reg_unknown(env, regs, BPF_REG_0);
15239         /* ld_abs load up to 32-bit skb data. */
15240         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15241         return 0;
15242 }
15243
15244 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15245 {
15246         const char *exit_ctx = "At program exit";
15247         struct tnum enforce_attach_type_range = tnum_unknown;
15248         const struct bpf_prog *prog = env->prog;
15249         struct bpf_reg_state *reg;
15250         struct bpf_retval_range range = retval_range(0, 1);
15251         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15252         int err;
15253         struct bpf_func_state *frame = env->cur_state->frame[0];
15254         const bool is_subprog = frame->subprogno;
15255
15256         /* LSM and struct_ops func-ptr's return type could be "void" */
15257         if (!is_subprog || frame->in_exception_callback_fn) {
15258                 switch (prog_type) {
15259                 case BPF_PROG_TYPE_LSM:
15260                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
15261                                 /* See below, can be 0 or 0-1 depending on hook. */
15262                                 break;
15263                         fallthrough;
15264                 case BPF_PROG_TYPE_STRUCT_OPS:
15265                         if (!prog->aux->attach_func_proto->type)
15266                                 return 0;
15267                         break;
15268                 default:
15269                         break;
15270                 }
15271         }
15272
15273         /* eBPF calling convention is such that R0 is used
15274          * to return the value from eBPF program.
15275          * Make sure that it's readable at this time
15276          * of bpf_exit, which means that program wrote
15277          * something into it earlier
15278          */
15279         err = check_reg_arg(env, regno, SRC_OP);
15280         if (err)
15281                 return err;
15282
15283         if (is_pointer_value(env, regno)) {
15284                 verbose(env, "R%d leaks addr as return value\n", regno);
15285                 return -EACCES;
15286         }
15287
15288         reg = cur_regs(env) + regno;
15289
15290         if (frame->in_async_callback_fn) {
15291                 /* enforce return zero from async callbacks like timer */
15292                 exit_ctx = "At async callback return";
15293                 range = retval_range(0, 0);
15294                 goto enforce_retval;
15295         }
15296
15297         if (is_subprog && !frame->in_exception_callback_fn) {
15298                 if (reg->type != SCALAR_VALUE) {
15299                         verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15300                                 regno, reg_type_str(env, reg->type));
15301                         return -EINVAL;
15302                 }
15303                 return 0;
15304         }
15305
15306         switch (prog_type) {
15307         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15308                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15309                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15310                     env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15311                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15312                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15313                     env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15314                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15315                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15316                     env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15317                         range = retval_range(1, 1);
15318                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15319                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15320                         range = retval_range(0, 3);
15321                 break;
15322         case BPF_PROG_TYPE_CGROUP_SKB:
15323                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15324                         range = retval_range(0, 3);
15325                         enforce_attach_type_range = tnum_range(2, 3);
15326                 }
15327                 break;
15328         case BPF_PROG_TYPE_CGROUP_SOCK:
15329         case BPF_PROG_TYPE_SOCK_OPS:
15330         case BPF_PROG_TYPE_CGROUP_DEVICE:
15331         case BPF_PROG_TYPE_CGROUP_SYSCTL:
15332         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15333                 break;
15334         case BPF_PROG_TYPE_RAW_TRACEPOINT:
15335                 if (!env->prog->aux->attach_btf_id)
15336                         return 0;
15337                 range = retval_range(0, 0);
15338                 break;
15339         case BPF_PROG_TYPE_TRACING:
15340                 switch (env->prog->expected_attach_type) {
15341                 case BPF_TRACE_FENTRY:
15342                 case BPF_TRACE_FEXIT:
15343                         range = retval_range(0, 0);
15344                         break;
15345                 case BPF_TRACE_RAW_TP:
15346                 case BPF_MODIFY_RETURN:
15347                         return 0;
15348                 case BPF_TRACE_ITER:
15349                         break;
15350                 default:
15351                         return -ENOTSUPP;
15352                 }
15353                 break;
15354         case BPF_PROG_TYPE_SK_LOOKUP:
15355                 range = retval_range(SK_DROP, SK_PASS);
15356                 break;
15357
15358         case BPF_PROG_TYPE_LSM:
15359                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15360                         /* Regular BPF_PROG_TYPE_LSM programs can return
15361                          * any value.
15362                          */
15363                         return 0;
15364                 }
15365                 if (!env->prog->aux->attach_func_proto->type) {
15366                         /* Make sure programs that attach to void
15367                          * hooks don't try to modify return value.
15368                          */
15369                         range = retval_range(1, 1);
15370                 }
15371                 break;
15372
15373         case BPF_PROG_TYPE_NETFILTER:
15374                 range = retval_range(NF_DROP, NF_ACCEPT);
15375                 break;
15376         case BPF_PROG_TYPE_EXT:
15377                 /* freplace program can return anything as its return value
15378                  * depends on the to-be-replaced kernel func or bpf program.
15379                  */
15380         default:
15381                 return 0;
15382         }
15383
15384 enforce_retval:
15385         if (reg->type != SCALAR_VALUE) {
15386                 verbose(env, "%s the register R%d is not a known value (%s)\n",
15387                         exit_ctx, regno, reg_type_str(env, reg->type));
15388                 return -EINVAL;
15389         }
15390
15391         err = mark_chain_precision(env, regno);
15392         if (err)
15393                 return err;
15394
15395         if (!retval_range_within(range, reg)) {
15396                 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15397                 if (!is_subprog &&
15398                     prog->expected_attach_type == BPF_LSM_CGROUP &&
15399                     prog_type == BPF_PROG_TYPE_LSM &&
15400                     !prog->aux->attach_func_proto->type)
15401                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15402                 return -EINVAL;
15403         }
15404
15405         if (!tnum_is_unknown(enforce_attach_type_range) &&
15406             tnum_in(enforce_attach_type_range, reg->var_off))
15407                 env->prog->enforce_expected_attach_type = 1;
15408         return 0;
15409 }
15410
15411 /* non-recursive DFS pseudo code
15412  * 1  procedure DFS-iterative(G,v):
15413  * 2      label v as discovered
15414  * 3      let S be a stack
15415  * 4      S.push(v)
15416  * 5      while S is not empty
15417  * 6            t <- S.peek()
15418  * 7            if t is what we're looking for:
15419  * 8                return t
15420  * 9            for all edges e in G.adjacentEdges(t) do
15421  * 10               if edge e is already labelled
15422  * 11                   continue with the next edge
15423  * 12               w <- G.adjacentVertex(t,e)
15424  * 13               if vertex w is not discovered and not explored
15425  * 14                   label e as tree-edge
15426  * 15                   label w as discovered
15427  * 16                   S.push(w)
15428  * 17                   continue at 5
15429  * 18               else if vertex w is discovered
15430  * 19                   label e as back-edge
15431  * 20               else
15432  * 21                   // vertex w is explored
15433  * 22                   label e as forward- or cross-edge
15434  * 23           label t as explored
15435  * 24           S.pop()
15436  *
15437  * convention:
15438  * 0x10 - discovered
15439  * 0x11 - discovered and fall-through edge labelled
15440  * 0x12 - discovered and fall-through and branch edges labelled
15441  * 0x20 - explored
15442  */
15443
15444 enum {
15445         DISCOVERED = 0x10,
15446         EXPLORED = 0x20,
15447         FALLTHROUGH = 1,
15448         BRANCH = 2,
15449 };
15450
15451 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15452 {
15453         env->insn_aux_data[idx].prune_point = true;
15454 }
15455
15456 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15457 {
15458         return env->insn_aux_data[insn_idx].prune_point;
15459 }
15460
15461 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15462 {
15463         env->insn_aux_data[idx].force_checkpoint = true;
15464 }
15465
15466 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15467 {
15468         return env->insn_aux_data[insn_idx].force_checkpoint;
15469 }
15470
15471 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15472 {
15473         env->insn_aux_data[idx].calls_callback = true;
15474 }
15475
15476 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15477 {
15478         return env->insn_aux_data[insn_idx].calls_callback;
15479 }
15480
15481 enum {
15482         DONE_EXPLORING = 0,
15483         KEEP_EXPLORING = 1,
15484 };
15485
15486 /* t, w, e - match pseudo-code above:
15487  * t - index of current instruction
15488  * w - next instruction
15489  * e - edge
15490  */
15491 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15492 {
15493         int *insn_stack = env->cfg.insn_stack;
15494         int *insn_state = env->cfg.insn_state;
15495
15496         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15497                 return DONE_EXPLORING;
15498
15499         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15500                 return DONE_EXPLORING;
15501
15502         if (w < 0 || w >= env->prog->len) {
15503                 verbose_linfo(env, t, "%d: ", t);
15504                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15505                 return -EINVAL;
15506         }
15507
15508         if (e == BRANCH) {
15509                 /* mark branch target for state pruning */
15510                 mark_prune_point(env, w);
15511                 mark_jmp_point(env, w);
15512         }
15513
15514         if (insn_state[w] == 0) {
15515                 /* tree-edge */
15516                 insn_state[t] = DISCOVERED | e;
15517                 insn_state[w] = DISCOVERED;
15518                 if (env->cfg.cur_stack >= env->prog->len)
15519                         return -E2BIG;
15520                 insn_stack[env->cfg.cur_stack++] = w;
15521                 return KEEP_EXPLORING;
15522         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15523                 if (env->bpf_capable)
15524                         return DONE_EXPLORING;
15525                 verbose_linfo(env, t, "%d: ", t);
15526                 verbose_linfo(env, w, "%d: ", w);
15527                 verbose(env, "back-edge from insn %d to %d\n", t, w);
15528                 return -EINVAL;
15529         } else if (insn_state[w] == EXPLORED) {
15530                 /* forward- or cross-edge */
15531                 insn_state[t] = DISCOVERED | e;
15532         } else {
15533                 verbose(env, "insn state internal bug\n");
15534                 return -EFAULT;
15535         }
15536         return DONE_EXPLORING;
15537 }
15538
15539 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15540                                 struct bpf_verifier_env *env,
15541                                 bool visit_callee)
15542 {
15543         int ret, insn_sz;
15544
15545         insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15546         ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15547         if (ret)
15548                 return ret;
15549
15550         mark_prune_point(env, t + insn_sz);
15551         /* when we exit from subprog, we need to record non-linear history */
15552         mark_jmp_point(env, t + insn_sz);
15553
15554         if (visit_callee) {
15555                 mark_prune_point(env, t);
15556                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15557         }
15558         return ret;
15559 }
15560
15561 /* Visits the instruction at index t and returns one of the following:
15562  *  < 0 - an error occurred
15563  *  DONE_EXPLORING - the instruction was fully explored
15564  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15565  */
15566 static int visit_insn(int t, struct bpf_verifier_env *env)
15567 {
15568         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15569         int ret, off, insn_sz;
15570
15571         if (bpf_pseudo_func(insn))
15572                 return visit_func_call_insn(t, insns, env, true);
15573
15574         /* All non-branch instructions have a single fall-through edge. */
15575         if (BPF_CLASS(insn->code) != BPF_JMP &&
15576             BPF_CLASS(insn->code) != BPF_JMP32) {
15577                 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15578                 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15579         }
15580
15581         switch (BPF_OP(insn->code)) {
15582         case BPF_EXIT:
15583                 return DONE_EXPLORING;
15584
15585         case BPF_CALL:
15586                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15587                         /* Mark this call insn as a prune point to trigger
15588                          * is_state_visited() check before call itself is
15589                          * processed by __check_func_call(). Otherwise new
15590                          * async state will be pushed for further exploration.
15591                          */
15592                         mark_prune_point(env, t);
15593                 /* For functions that invoke callbacks it is not known how many times
15594                  * callback would be called. Verifier models callback calling functions
15595                  * by repeatedly visiting callback bodies and returning to origin call
15596                  * instruction.
15597                  * In order to stop such iteration verifier needs to identify when a
15598                  * state identical some state from a previous iteration is reached.
15599                  * Check below forces creation of checkpoint before callback calling
15600                  * instruction to allow search for such identical states.
15601                  */
15602                 if (is_sync_callback_calling_insn(insn)) {
15603                         mark_calls_callback(env, t);
15604                         mark_force_checkpoint(env, t);
15605                         mark_prune_point(env, t);
15606                         mark_jmp_point(env, t);
15607                 }
15608                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15609                         struct bpf_kfunc_call_arg_meta meta;
15610
15611                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15612                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
15613                                 mark_prune_point(env, t);
15614                                 /* Checking and saving state checkpoints at iter_next() call
15615                                  * is crucial for fast convergence of open-coded iterator loop
15616                                  * logic, so we need to force it. If we don't do that,
15617                                  * is_state_visited() might skip saving a checkpoint, causing
15618                                  * unnecessarily long sequence of not checkpointed
15619                                  * instructions and jumps, leading to exhaustion of jump
15620                                  * history buffer, and potentially other undesired outcomes.
15621                                  * It is expected that with correct open-coded iterators
15622                                  * convergence will happen quickly, so we don't run a risk of
15623                                  * exhausting memory.
15624                                  */
15625                                 mark_force_checkpoint(env, t);
15626                         }
15627                 }
15628                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15629
15630         case BPF_JA:
15631                 if (BPF_SRC(insn->code) != BPF_K)
15632                         return -EINVAL;
15633
15634                 if (BPF_CLASS(insn->code) == BPF_JMP)
15635                         off = insn->off;
15636                 else
15637                         off = insn->imm;
15638
15639                 /* unconditional jump with single edge */
15640                 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15641                 if (ret)
15642                         return ret;
15643
15644                 mark_prune_point(env, t + off + 1);
15645                 mark_jmp_point(env, t + off + 1);
15646
15647                 return ret;
15648
15649         default:
15650                 /* conditional jump with two edges */
15651                 mark_prune_point(env, t);
15652
15653                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
15654                 if (ret)
15655                         return ret;
15656
15657                 return push_insn(t, t + insn->off + 1, BRANCH, env);
15658         }
15659 }
15660
15661 /* non-recursive depth-first-search to detect loops in BPF program
15662  * loop == back-edge in directed graph
15663  */
15664 static int check_cfg(struct bpf_verifier_env *env)
15665 {
15666         int insn_cnt = env->prog->len;
15667         int *insn_stack, *insn_state;
15668         int ex_insn_beg, i, ret = 0;
15669         bool ex_done = false;
15670
15671         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15672         if (!insn_state)
15673                 return -ENOMEM;
15674
15675         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15676         if (!insn_stack) {
15677                 kvfree(insn_state);
15678                 return -ENOMEM;
15679         }
15680
15681         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15682         insn_stack[0] = 0; /* 0 is the first instruction */
15683         env->cfg.cur_stack = 1;
15684
15685 walk_cfg:
15686         while (env->cfg.cur_stack > 0) {
15687                 int t = insn_stack[env->cfg.cur_stack - 1];
15688
15689                 ret = visit_insn(t, env);
15690                 switch (ret) {
15691                 case DONE_EXPLORING:
15692                         insn_state[t] = EXPLORED;
15693                         env->cfg.cur_stack--;
15694                         break;
15695                 case KEEP_EXPLORING:
15696                         break;
15697                 default:
15698                         if (ret > 0) {
15699                                 verbose(env, "visit_insn internal bug\n");
15700                                 ret = -EFAULT;
15701                         }
15702                         goto err_free;
15703                 }
15704         }
15705
15706         if (env->cfg.cur_stack < 0) {
15707                 verbose(env, "pop stack internal bug\n");
15708                 ret = -EFAULT;
15709                 goto err_free;
15710         }
15711
15712         if (env->exception_callback_subprog && !ex_done) {
15713                 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15714
15715                 insn_state[ex_insn_beg] = DISCOVERED;
15716                 insn_stack[0] = ex_insn_beg;
15717                 env->cfg.cur_stack = 1;
15718                 ex_done = true;
15719                 goto walk_cfg;
15720         }
15721
15722         for (i = 0; i < insn_cnt; i++) {
15723                 struct bpf_insn *insn = &env->prog->insnsi[i];
15724
15725                 if (insn_state[i] != EXPLORED) {
15726                         verbose(env, "unreachable insn %d\n", i);
15727                         ret = -EINVAL;
15728                         goto err_free;
15729                 }
15730                 if (bpf_is_ldimm64(insn)) {
15731                         if (insn_state[i + 1] != 0) {
15732                                 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15733                                 ret = -EINVAL;
15734                                 goto err_free;
15735                         }
15736                         i++; /* skip second half of ldimm64 */
15737                 }
15738         }
15739         ret = 0; /* cfg looks good */
15740
15741 err_free:
15742         kvfree(insn_state);
15743         kvfree(insn_stack);
15744         env->cfg.insn_state = env->cfg.insn_stack = NULL;
15745         return ret;
15746 }
15747
15748 static int check_abnormal_return(struct bpf_verifier_env *env)
15749 {
15750         int i;
15751
15752         for (i = 1; i < env->subprog_cnt; i++) {
15753                 if (env->subprog_info[i].has_ld_abs) {
15754                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15755                         return -EINVAL;
15756                 }
15757                 if (env->subprog_info[i].has_tail_call) {
15758                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15759                         return -EINVAL;
15760                 }
15761         }
15762         return 0;
15763 }
15764
15765 /* The minimum supported BTF func info size */
15766 #define MIN_BPF_FUNCINFO_SIZE   8
15767 #define MAX_FUNCINFO_REC_SIZE   252
15768
15769 static int check_btf_func_early(struct bpf_verifier_env *env,
15770                                 const union bpf_attr *attr,
15771                                 bpfptr_t uattr)
15772 {
15773         u32 krec_size = sizeof(struct bpf_func_info);
15774         const struct btf_type *type, *func_proto;
15775         u32 i, nfuncs, urec_size, min_size;
15776         struct bpf_func_info *krecord;
15777         struct bpf_prog *prog;
15778         const struct btf *btf;
15779         u32 prev_offset = 0;
15780         bpfptr_t urecord;
15781         int ret = -ENOMEM;
15782
15783         nfuncs = attr->func_info_cnt;
15784         if (!nfuncs) {
15785                 if (check_abnormal_return(env))
15786                         return -EINVAL;
15787                 return 0;
15788         }
15789
15790         urec_size = attr->func_info_rec_size;
15791         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15792             urec_size > MAX_FUNCINFO_REC_SIZE ||
15793             urec_size % sizeof(u32)) {
15794                 verbose(env, "invalid func info rec size %u\n", urec_size);
15795                 return -EINVAL;
15796         }
15797
15798         prog = env->prog;
15799         btf = prog->aux->btf;
15800
15801         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15802         min_size = min_t(u32, krec_size, urec_size);
15803
15804         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15805         if (!krecord)
15806                 return -ENOMEM;
15807
15808         for (i = 0; i < nfuncs; i++) {
15809                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15810                 if (ret) {
15811                         if (ret == -E2BIG) {
15812                                 verbose(env, "nonzero tailing record in func info");
15813                                 /* set the size kernel expects so loader can zero
15814                                  * out the rest of the record.
15815                                  */
15816                                 if (copy_to_bpfptr_offset(uattr,
15817                                                           offsetof(union bpf_attr, func_info_rec_size),
15818                                                           &min_size, sizeof(min_size)))
15819                                         ret = -EFAULT;
15820                         }
15821                         goto err_free;
15822                 }
15823
15824                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15825                         ret = -EFAULT;
15826                         goto err_free;
15827                 }
15828
15829                 /* check insn_off */
15830                 ret = -EINVAL;
15831                 if (i == 0) {
15832                         if (krecord[i].insn_off) {
15833                                 verbose(env,
15834                                         "nonzero insn_off %u for the first func info record",
15835                                         krecord[i].insn_off);
15836                                 goto err_free;
15837                         }
15838                 } else if (krecord[i].insn_off <= prev_offset) {
15839                         verbose(env,
15840                                 "same or smaller insn offset (%u) than previous func info record (%u)",
15841                                 krecord[i].insn_off, prev_offset);
15842                         goto err_free;
15843                 }
15844
15845                 /* check type_id */
15846                 type = btf_type_by_id(btf, krecord[i].type_id);
15847                 if (!type || !btf_type_is_func(type)) {
15848                         verbose(env, "invalid type id %d in func info",
15849                                 krecord[i].type_id);
15850                         goto err_free;
15851                 }
15852
15853                 func_proto = btf_type_by_id(btf, type->type);
15854                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15855                         /* btf_func_check() already verified it during BTF load */
15856                         goto err_free;
15857
15858                 prev_offset = krecord[i].insn_off;
15859                 bpfptr_add(&urecord, urec_size);
15860         }
15861
15862         prog->aux->func_info = krecord;
15863         prog->aux->func_info_cnt = nfuncs;
15864         return 0;
15865
15866 err_free:
15867         kvfree(krecord);
15868         return ret;
15869 }
15870
15871 static int check_btf_func(struct bpf_verifier_env *env,
15872                           const union bpf_attr *attr,
15873                           bpfptr_t uattr)
15874 {
15875         const struct btf_type *type, *func_proto, *ret_type;
15876         u32 i, nfuncs, urec_size;
15877         struct bpf_func_info *krecord;
15878         struct bpf_func_info_aux *info_aux = NULL;
15879         struct bpf_prog *prog;
15880         const struct btf *btf;
15881         bpfptr_t urecord;
15882         bool scalar_return;
15883         int ret = -ENOMEM;
15884
15885         nfuncs = attr->func_info_cnt;
15886         if (!nfuncs) {
15887                 if (check_abnormal_return(env))
15888                         return -EINVAL;
15889                 return 0;
15890         }
15891         if (nfuncs != env->subprog_cnt) {
15892                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15893                 return -EINVAL;
15894         }
15895
15896         urec_size = attr->func_info_rec_size;
15897
15898         prog = env->prog;
15899         btf = prog->aux->btf;
15900
15901         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15902
15903         krecord = prog->aux->func_info;
15904         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15905         if (!info_aux)
15906                 return -ENOMEM;
15907
15908         for (i = 0; i < nfuncs; i++) {
15909                 /* check insn_off */
15910                 ret = -EINVAL;
15911
15912                 if (env->subprog_info[i].start != krecord[i].insn_off) {
15913                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15914                         goto err_free;
15915                 }
15916
15917                 /* Already checked type_id */
15918                 type = btf_type_by_id(btf, krecord[i].type_id);
15919                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15920                 /* Already checked func_proto */
15921                 func_proto = btf_type_by_id(btf, type->type);
15922
15923                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15924                 scalar_return =
15925                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15926                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15927                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15928                         goto err_free;
15929                 }
15930                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15931                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15932                         goto err_free;
15933                 }
15934
15935                 bpfptr_add(&urecord, urec_size);
15936         }
15937
15938         prog->aux->func_info_aux = info_aux;
15939         return 0;
15940
15941 err_free:
15942         kfree(info_aux);
15943         return ret;
15944 }
15945
15946 static void adjust_btf_func(struct bpf_verifier_env *env)
15947 {
15948         struct bpf_prog_aux *aux = env->prog->aux;
15949         int i;
15950
15951         if (!aux->func_info)
15952                 return;
15953
15954         /* func_info is not available for hidden subprogs */
15955         for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15956                 aux->func_info[i].insn_off = env->subprog_info[i].start;
15957 }
15958
15959 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
15960 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
15961
15962 static int check_btf_line(struct bpf_verifier_env *env,
15963                           const union bpf_attr *attr,
15964                           bpfptr_t uattr)
15965 {
15966         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15967         struct bpf_subprog_info *sub;
15968         struct bpf_line_info *linfo;
15969         struct bpf_prog *prog;
15970         const struct btf *btf;
15971         bpfptr_t ulinfo;
15972         int err;
15973
15974         nr_linfo = attr->line_info_cnt;
15975         if (!nr_linfo)
15976                 return 0;
15977         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15978                 return -EINVAL;
15979
15980         rec_size = attr->line_info_rec_size;
15981         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15982             rec_size > MAX_LINEINFO_REC_SIZE ||
15983             rec_size & (sizeof(u32) - 1))
15984                 return -EINVAL;
15985
15986         /* Need to zero it in case the userspace may
15987          * pass in a smaller bpf_line_info object.
15988          */
15989         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15990                          GFP_KERNEL | __GFP_NOWARN);
15991         if (!linfo)
15992                 return -ENOMEM;
15993
15994         prog = env->prog;
15995         btf = prog->aux->btf;
15996
15997         s = 0;
15998         sub = env->subprog_info;
15999         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16000         expected_size = sizeof(struct bpf_line_info);
16001         ncopy = min_t(u32, expected_size, rec_size);
16002         for (i = 0; i < nr_linfo; i++) {
16003                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16004                 if (err) {
16005                         if (err == -E2BIG) {
16006                                 verbose(env, "nonzero tailing record in line_info");
16007                                 if (copy_to_bpfptr_offset(uattr,
16008                                                           offsetof(union bpf_attr, line_info_rec_size),
16009                                                           &expected_size, sizeof(expected_size)))
16010                                         err = -EFAULT;
16011                         }
16012                         goto err_free;
16013                 }
16014
16015                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16016                         err = -EFAULT;
16017                         goto err_free;
16018                 }
16019
16020                 /*
16021                  * Check insn_off to ensure
16022                  * 1) strictly increasing AND
16023                  * 2) bounded by prog->len
16024                  *
16025                  * The linfo[0].insn_off == 0 check logically falls into
16026                  * the later "missing bpf_line_info for func..." case
16027                  * because the first linfo[0].insn_off must be the
16028                  * first sub also and the first sub must have
16029                  * subprog_info[0].start == 0.
16030                  */
16031                 if ((i && linfo[i].insn_off <= prev_offset) ||
16032                     linfo[i].insn_off >= prog->len) {
16033                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16034                                 i, linfo[i].insn_off, prev_offset,
16035                                 prog->len);
16036                         err = -EINVAL;
16037                         goto err_free;
16038                 }
16039
16040                 if (!prog->insnsi[linfo[i].insn_off].code) {
16041                         verbose(env,
16042                                 "Invalid insn code at line_info[%u].insn_off\n",
16043                                 i);
16044                         err = -EINVAL;
16045                         goto err_free;
16046                 }
16047
16048                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16049                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16050                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16051                         err = -EINVAL;
16052                         goto err_free;
16053                 }
16054
16055                 if (s != env->subprog_cnt) {
16056                         if (linfo[i].insn_off == sub[s].start) {
16057                                 sub[s].linfo_idx = i;
16058                                 s++;
16059                         } else if (sub[s].start < linfo[i].insn_off) {
16060                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
16061                                 err = -EINVAL;
16062                                 goto err_free;
16063                         }
16064                 }
16065
16066                 prev_offset = linfo[i].insn_off;
16067                 bpfptr_add(&ulinfo, rec_size);
16068         }
16069
16070         if (s != env->subprog_cnt) {
16071                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16072                         env->subprog_cnt - s, s);
16073                 err = -EINVAL;
16074                 goto err_free;
16075         }
16076
16077         prog->aux->linfo = linfo;
16078         prog->aux->nr_linfo = nr_linfo;
16079
16080         return 0;
16081
16082 err_free:
16083         kvfree(linfo);
16084         return err;
16085 }
16086
16087 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
16088 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
16089
16090 static int check_core_relo(struct bpf_verifier_env *env,
16091                            const union bpf_attr *attr,
16092                            bpfptr_t uattr)
16093 {
16094         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16095         struct bpf_core_relo core_relo = {};
16096         struct bpf_prog *prog = env->prog;
16097         const struct btf *btf = prog->aux->btf;
16098         struct bpf_core_ctx ctx = {
16099                 .log = &env->log,
16100                 .btf = btf,
16101         };
16102         bpfptr_t u_core_relo;
16103         int err;
16104
16105         nr_core_relo = attr->core_relo_cnt;
16106         if (!nr_core_relo)
16107                 return 0;
16108         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16109                 return -EINVAL;
16110
16111         rec_size = attr->core_relo_rec_size;
16112         if (rec_size < MIN_CORE_RELO_SIZE ||
16113             rec_size > MAX_CORE_RELO_SIZE ||
16114             rec_size % sizeof(u32))
16115                 return -EINVAL;
16116
16117         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16118         expected_size = sizeof(struct bpf_core_relo);
16119         ncopy = min_t(u32, expected_size, rec_size);
16120
16121         /* Unlike func_info and line_info, copy and apply each CO-RE
16122          * relocation record one at a time.
16123          */
16124         for (i = 0; i < nr_core_relo; i++) {
16125                 /* future proofing when sizeof(bpf_core_relo) changes */
16126                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16127                 if (err) {
16128                         if (err == -E2BIG) {
16129                                 verbose(env, "nonzero tailing record in core_relo");
16130                                 if (copy_to_bpfptr_offset(uattr,
16131                                                           offsetof(union bpf_attr, core_relo_rec_size),
16132                                                           &expected_size, sizeof(expected_size)))
16133                                         err = -EFAULT;
16134                         }
16135                         break;
16136                 }
16137
16138                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16139                         err = -EFAULT;
16140                         break;
16141                 }
16142
16143                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16144                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16145                                 i, core_relo.insn_off, prog->len);
16146                         err = -EINVAL;
16147                         break;
16148                 }
16149
16150                 err = bpf_core_apply(&ctx, &core_relo, i,
16151                                      &prog->insnsi[core_relo.insn_off / 8]);
16152                 if (err)
16153                         break;
16154                 bpfptr_add(&u_core_relo, rec_size);
16155         }
16156         return err;
16157 }
16158
16159 static int check_btf_info_early(struct bpf_verifier_env *env,
16160                                 const union bpf_attr *attr,
16161                                 bpfptr_t uattr)
16162 {
16163         struct btf *btf;
16164         int err;
16165
16166         if (!attr->func_info_cnt && !attr->line_info_cnt) {
16167                 if (check_abnormal_return(env))
16168                         return -EINVAL;
16169                 return 0;
16170         }
16171
16172         btf = btf_get_by_fd(attr->prog_btf_fd);
16173         if (IS_ERR(btf))
16174                 return PTR_ERR(btf);
16175         if (btf_is_kernel(btf)) {
16176                 btf_put(btf);
16177                 return -EACCES;
16178         }
16179         env->prog->aux->btf = btf;
16180
16181         err = check_btf_func_early(env, attr, uattr);
16182         if (err)
16183                 return err;
16184         return 0;
16185 }
16186
16187 static int check_btf_info(struct bpf_verifier_env *env,
16188                           const union bpf_attr *attr,
16189                           bpfptr_t uattr)
16190 {
16191         int err;
16192
16193         if (!attr->func_info_cnt && !attr->line_info_cnt) {
16194                 if (check_abnormal_return(env))
16195                         return -EINVAL;
16196                 return 0;
16197         }
16198
16199         err = check_btf_func(env, attr, uattr);
16200         if (err)
16201                 return err;
16202
16203         err = check_btf_line(env, attr, uattr);
16204         if (err)
16205                 return err;
16206
16207         err = check_core_relo(env, attr, uattr);
16208         if (err)
16209                 return err;
16210
16211         return 0;
16212 }
16213
16214 /* check %cur's range satisfies %old's */
16215 static bool range_within(struct bpf_reg_state *old,
16216                          struct bpf_reg_state *cur)
16217 {
16218         return old->umin_value <= cur->umin_value &&
16219                old->umax_value >= cur->umax_value &&
16220                old->smin_value <= cur->smin_value &&
16221                old->smax_value >= cur->smax_value &&
16222                old->u32_min_value <= cur->u32_min_value &&
16223                old->u32_max_value >= cur->u32_max_value &&
16224                old->s32_min_value <= cur->s32_min_value &&
16225                old->s32_max_value >= cur->s32_max_value;
16226 }
16227
16228 /* If in the old state two registers had the same id, then they need to have
16229  * the same id in the new state as well.  But that id could be different from
16230  * the old state, so we need to track the mapping from old to new ids.
16231  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16232  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16233  * regs with a different old id could still have new id 9, we don't care about
16234  * that.
16235  * So we look through our idmap to see if this old id has been seen before.  If
16236  * so, we require the new id to match; otherwise, we add the id pair to the map.
16237  */
16238 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16239 {
16240         struct bpf_id_pair *map = idmap->map;
16241         unsigned int i;
16242
16243         /* either both IDs should be set or both should be zero */
16244         if (!!old_id != !!cur_id)
16245                 return false;
16246
16247         if (old_id == 0) /* cur_id == 0 as well */
16248                 return true;
16249
16250         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16251                 if (!map[i].old) {
16252                         /* Reached an empty slot; haven't seen this id before */
16253                         map[i].old = old_id;
16254                         map[i].cur = cur_id;
16255                         return true;
16256                 }
16257                 if (map[i].old == old_id)
16258                         return map[i].cur == cur_id;
16259                 if (map[i].cur == cur_id)
16260                         return false;
16261         }
16262         /* We ran out of idmap slots, which should be impossible */
16263         WARN_ON_ONCE(1);
16264         return false;
16265 }
16266
16267 /* Similar to check_ids(), but allocate a unique temporary ID
16268  * for 'old_id' or 'cur_id' of zero.
16269  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16270  */
16271 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16272 {
16273         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16274         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16275
16276         return check_ids(old_id, cur_id, idmap);
16277 }
16278
16279 static void clean_func_state(struct bpf_verifier_env *env,
16280                              struct bpf_func_state *st)
16281 {
16282         enum bpf_reg_liveness live;
16283         int i, j;
16284
16285         for (i = 0; i < BPF_REG_FP; i++) {
16286                 live = st->regs[i].live;
16287                 /* liveness must not touch this register anymore */
16288                 st->regs[i].live |= REG_LIVE_DONE;
16289                 if (!(live & REG_LIVE_READ))
16290                         /* since the register is unused, clear its state
16291                          * to make further comparison simpler
16292                          */
16293                         __mark_reg_not_init(env, &st->regs[i]);
16294         }
16295
16296         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16297                 live = st->stack[i].spilled_ptr.live;
16298                 /* liveness must not touch this stack slot anymore */
16299                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16300                 if (!(live & REG_LIVE_READ)) {
16301                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16302                         for (j = 0; j < BPF_REG_SIZE; j++)
16303                                 st->stack[i].slot_type[j] = STACK_INVALID;
16304                 }
16305         }
16306 }
16307
16308 static void clean_verifier_state(struct bpf_verifier_env *env,
16309                                  struct bpf_verifier_state *st)
16310 {
16311         int i;
16312
16313         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16314                 /* all regs in this state in all frames were already marked */
16315                 return;
16316
16317         for (i = 0; i <= st->curframe; i++)
16318                 clean_func_state(env, st->frame[i]);
16319 }
16320
16321 /* the parentage chains form a tree.
16322  * the verifier states are added to state lists at given insn and
16323  * pushed into state stack for future exploration.
16324  * when the verifier reaches bpf_exit insn some of the verifer states
16325  * stored in the state lists have their final liveness state already,
16326  * but a lot of states will get revised from liveness point of view when
16327  * the verifier explores other branches.
16328  * Example:
16329  * 1: r0 = 1
16330  * 2: if r1 == 100 goto pc+1
16331  * 3: r0 = 2
16332  * 4: exit
16333  * when the verifier reaches exit insn the register r0 in the state list of
16334  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16335  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16336  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16337  *
16338  * Since the verifier pushes the branch states as it sees them while exploring
16339  * the program the condition of walking the branch instruction for the second
16340  * time means that all states below this branch were already explored and
16341  * their final liveness marks are already propagated.
16342  * Hence when the verifier completes the search of state list in is_state_visited()
16343  * we can call this clean_live_states() function to mark all liveness states
16344  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16345  * will not be used.
16346  * This function also clears the registers and stack for states that !READ
16347  * to simplify state merging.
16348  *
16349  * Important note here that walking the same branch instruction in the callee
16350  * doesn't meant that the states are DONE. The verifier has to compare
16351  * the callsites
16352  */
16353 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16354                               struct bpf_verifier_state *cur)
16355 {
16356         struct bpf_verifier_state_list *sl;
16357
16358         sl = *explored_state(env, insn);
16359         while (sl) {
16360                 if (sl->state.branches)
16361                         goto next;
16362                 if (sl->state.insn_idx != insn ||
16363                     !same_callsites(&sl->state, cur))
16364                         goto next;
16365                 clean_verifier_state(env, &sl->state);
16366 next:
16367                 sl = sl->next;
16368         }
16369 }
16370
16371 static bool regs_exact(const struct bpf_reg_state *rold,
16372                        const struct bpf_reg_state *rcur,
16373                        struct bpf_idmap *idmap)
16374 {
16375         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16376                check_ids(rold->id, rcur->id, idmap) &&
16377                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16378 }
16379
16380 /* Returns true if (rold safe implies rcur safe) */
16381 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16382                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16383 {
16384         if (exact)
16385                 return regs_exact(rold, rcur, idmap);
16386
16387         if (!(rold->live & REG_LIVE_READ))
16388                 /* explored state didn't use this */
16389                 return true;
16390         if (rold->type == NOT_INIT)
16391                 /* explored state can't have used this */
16392                 return true;
16393         if (rcur->type == NOT_INIT)
16394                 return false;
16395
16396         /* Enforce that register types have to match exactly, including their
16397          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16398          * rule.
16399          *
16400          * One can make a point that using a pointer register as unbounded
16401          * SCALAR would be technically acceptable, but this could lead to
16402          * pointer leaks because scalars are allowed to leak while pointers
16403          * are not. We could make this safe in special cases if root is
16404          * calling us, but it's probably not worth the hassle.
16405          *
16406          * Also, register types that are *not* MAYBE_NULL could technically be
16407          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16408          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16409          * to the same map).
16410          * However, if the old MAYBE_NULL register then got NULL checked,
16411          * doing so could have affected others with the same id, and we can't
16412          * check for that because we lost the id when we converted to
16413          * a non-MAYBE_NULL variant.
16414          * So, as a general rule we don't allow mixing MAYBE_NULL and
16415          * non-MAYBE_NULL registers as well.
16416          */
16417         if (rold->type != rcur->type)
16418                 return false;
16419
16420         switch (base_type(rold->type)) {
16421         case SCALAR_VALUE:
16422                 if (env->explore_alu_limits) {
16423                         /* explore_alu_limits disables tnum_in() and range_within()
16424                          * logic and requires everything to be strict
16425                          */
16426                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16427                                check_scalar_ids(rold->id, rcur->id, idmap);
16428                 }
16429                 if (!rold->precise)
16430                         return true;
16431                 /* Why check_ids() for scalar registers?
16432                  *
16433                  * Consider the following BPF code:
16434                  *   1: r6 = ... unbound scalar, ID=a ...
16435                  *   2: r7 = ... unbound scalar, ID=b ...
16436                  *   3: if (r6 > r7) goto +1
16437                  *   4: r6 = r7
16438                  *   5: if (r6 > X) goto ...
16439                  *   6: ... memory operation using r7 ...
16440                  *
16441                  * First verification path is [1-6]:
16442                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16443                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16444                  *   r7 <= X, because r6 and r7 share same id.
16445                  * Next verification path is [1-4, 6].
16446                  *
16447                  * Instruction (6) would be reached in two states:
16448                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16449                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16450                  *
16451                  * Use check_ids() to distinguish these states.
16452                  * ---
16453                  * Also verify that new value satisfies old value range knowledge.
16454                  */
16455                 return range_within(rold, rcur) &&
16456                        tnum_in(rold->var_off, rcur->var_off) &&
16457                        check_scalar_ids(rold->id, rcur->id, idmap);
16458         case PTR_TO_MAP_KEY:
16459         case PTR_TO_MAP_VALUE:
16460         case PTR_TO_MEM:
16461         case PTR_TO_BUF:
16462         case PTR_TO_TP_BUFFER:
16463                 /* If the new min/max/var_off satisfy the old ones and
16464                  * everything else matches, we are OK.
16465                  */
16466                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16467                        range_within(rold, rcur) &&
16468                        tnum_in(rold->var_off, rcur->var_off) &&
16469                        check_ids(rold->id, rcur->id, idmap) &&
16470                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16471         case PTR_TO_PACKET_META:
16472         case PTR_TO_PACKET:
16473                 /* We must have at least as much range as the old ptr
16474                  * did, so that any accesses which were safe before are
16475                  * still safe.  This is true even if old range < old off,
16476                  * since someone could have accessed through (ptr - k), or
16477                  * even done ptr -= k in a register, to get a safe access.
16478                  */
16479                 if (rold->range > rcur->range)
16480                         return false;
16481                 /* If the offsets don't match, we can't trust our alignment;
16482                  * nor can we be sure that we won't fall out of range.
16483                  */
16484                 if (rold->off != rcur->off)
16485                         return false;
16486                 /* id relations must be preserved */
16487                 if (!check_ids(rold->id, rcur->id, idmap))
16488                         return false;
16489                 /* new val must satisfy old val knowledge */
16490                 return range_within(rold, rcur) &&
16491                        tnum_in(rold->var_off, rcur->var_off);
16492         case PTR_TO_STACK:
16493                 /* two stack pointers are equal only if they're pointing to
16494                  * the same stack frame, since fp-8 in foo != fp-8 in bar
16495                  */
16496                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16497         default:
16498                 return regs_exact(rold, rcur, idmap);
16499         }
16500 }
16501
16502 static struct bpf_reg_state unbound_reg;
16503
16504 static __init int unbound_reg_init(void)
16505 {
16506         __mark_reg_unknown_imprecise(&unbound_reg);
16507         unbound_reg.live |= REG_LIVE_READ;
16508         return 0;
16509 }
16510 late_initcall(unbound_reg_init);
16511
16512 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16513                               struct bpf_stack_state *stack)
16514 {
16515         u32 i;
16516
16517         for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16518                 if ((stack->slot_type[i] == STACK_MISC) ||
16519                     (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16520                         continue;
16521                 return false;
16522         }
16523
16524         return true;
16525 }
16526
16527 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16528                                                   struct bpf_stack_state *stack)
16529 {
16530         if (is_spilled_scalar_reg64(stack))
16531                 return &stack->spilled_ptr;
16532
16533         if (is_stack_all_misc(env, stack))
16534                 return &unbound_reg;
16535
16536         return NULL;
16537 }
16538
16539 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16540                       struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16541 {
16542         int i, spi;
16543
16544         /* walk slots of the explored stack and ignore any additional
16545          * slots in the current stack, since explored(safe) state
16546          * didn't use them
16547          */
16548         for (i = 0; i < old->allocated_stack; i++) {
16549                 struct bpf_reg_state *old_reg, *cur_reg;
16550
16551                 spi = i / BPF_REG_SIZE;
16552
16553                 if (exact &&
16554                     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16555                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16556                         return false;
16557
16558                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16559                         i += BPF_REG_SIZE - 1;
16560                         /* explored state didn't use this */
16561                         continue;
16562                 }
16563
16564                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16565                         continue;
16566
16567                 if (env->allow_uninit_stack &&
16568                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16569                         continue;
16570
16571                 /* explored stack has more populated slots than current stack
16572                  * and these slots were used
16573                  */
16574                 if (i >= cur->allocated_stack)
16575                         return false;
16576
16577                 /* 64-bit scalar spill vs all slots MISC and vice versa.
16578                  * Load from all slots MISC produces unbound scalar.
16579                  * Construct a fake register for such stack and call
16580                  * regsafe() to ensure scalar ids are compared.
16581                  */
16582                 old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16583                 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16584                 if (old_reg && cur_reg) {
16585                         if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16586                                 return false;
16587                         i += BPF_REG_SIZE - 1;
16588                         continue;
16589                 }
16590
16591                 /* if old state was safe with misc data in the stack
16592                  * it will be safe with zero-initialized stack.
16593                  * The opposite is not true
16594                  */
16595                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16596                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16597                         continue;
16598                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16599                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16600                         /* Ex: old explored (safe) state has STACK_SPILL in
16601                          * this stack slot, but current has STACK_MISC ->
16602                          * this verifier states are not equivalent,
16603                          * return false to continue verification of this path
16604                          */
16605                         return false;
16606                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16607                         continue;
16608                 /* Both old and cur are having same slot_type */
16609                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16610                 case STACK_SPILL:
16611                         /* when explored and current stack slot are both storing
16612                          * spilled registers, check that stored pointers types
16613                          * are the same as well.
16614                          * Ex: explored safe path could have stored
16615                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16616                          * but current path has stored:
16617                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16618                          * such verifier states are not equivalent.
16619                          * return false to continue verification of this path
16620                          */
16621                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
16622                                      &cur->stack[spi].spilled_ptr, idmap, exact))
16623                                 return false;
16624                         break;
16625                 case STACK_DYNPTR:
16626                         old_reg = &old->stack[spi].spilled_ptr;
16627                         cur_reg = &cur->stack[spi].spilled_ptr;
16628                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16629                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16630                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16631                                 return false;
16632                         break;
16633                 case STACK_ITER:
16634                         old_reg = &old->stack[spi].spilled_ptr;
16635                         cur_reg = &cur->stack[spi].spilled_ptr;
16636                         /* iter.depth is not compared between states as it
16637                          * doesn't matter for correctness and would otherwise
16638                          * prevent convergence; we maintain it only to prevent
16639                          * infinite loop check triggering, see
16640                          * iter_active_depths_differ()
16641                          */
16642                         if (old_reg->iter.btf != cur_reg->iter.btf ||
16643                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16644                             old_reg->iter.state != cur_reg->iter.state ||
16645                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
16646                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16647                                 return false;
16648                         break;
16649                 case STACK_MISC:
16650                 case STACK_ZERO:
16651                 case STACK_INVALID:
16652                         continue;
16653                 /* Ensure that new unhandled slot types return false by default */
16654                 default:
16655                         return false;
16656                 }
16657         }
16658         return true;
16659 }
16660
16661 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16662                     struct bpf_idmap *idmap)
16663 {
16664         int i;
16665
16666         if (old->acquired_refs != cur->acquired_refs)
16667                 return false;
16668
16669         for (i = 0; i < old->acquired_refs; i++) {
16670                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16671                         return false;
16672         }
16673
16674         return true;
16675 }
16676
16677 /* compare two verifier states
16678  *
16679  * all states stored in state_list are known to be valid, since
16680  * verifier reached 'bpf_exit' instruction through them
16681  *
16682  * this function is called when verifier exploring different branches of
16683  * execution popped from the state stack. If it sees an old state that has
16684  * more strict register state and more strict stack state then this execution
16685  * branch doesn't need to be explored further, since verifier already
16686  * concluded that more strict state leads to valid finish.
16687  *
16688  * Therefore two states are equivalent if register state is more conservative
16689  * and explored stack state is more conservative than the current one.
16690  * Example:
16691  *       explored                   current
16692  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16693  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16694  *
16695  * In other words if current stack state (one being explored) has more
16696  * valid slots than old one that already passed validation, it means
16697  * the verifier can stop exploring and conclude that current state is valid too
16698  *
16699  * Similarly with registers. If explored state has register type as invalid
16700  * whereas register type in current state is meaningful, it means that
16701  * the current state will reach 'bpf_exit' instruction safely
16702  */
16703 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16704                               struct bpf_func_state *cur, bool exact)
16705 {
16706         int i;
16707
16708         for (i = 0; i < MAX_BPF_REG; i++)
16709                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16710                              &env->idmap_scratch, exact))
16711                         return false;
16712
16713         if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16714                 return false;
16715
16716         if (!refsafe(old, cur, &env->idmap_scratch))
16717                 return false;
16718
16719         return true;
16720 }
16721
16722 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16723 {
16724         env->idmap_scratch.tmp_id_gen = env->id_gen;
16725         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16726 }
16727
16728 static bool states_equal(struct bpf_verifier_env *env,
16729                          struct bpf_verifier_state *old,
16730                          struct bpf_verifier_state *cur,
16731                          bool exact)
16732 {
16733         int i;
16734
16735         if (old->curframe != cur->curframe)
16736                 return false;
16737
16738         reset_idmap_scratch(env);
16739
16740         /* Verification state from speculative execution simulation
16741          * must never prune a non-speculative execution one.
16742          */
16743         if (old->speculative && !cur->speculative)
16744                 return false;
16745
16746         if (old->active_lock.ptr != cur->active_lock.ptr)
16747                 return false;
16748
16749         /* Old and cur active_lock's have to be either both present
16750          * or both absent.
16751          */
16752         if (!!old->active_lock.id != !!cur->active_lock.id)
16753                 return false;
16754
16755         if (old->active_lock.id &&
16756             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16757                 return false;
16758
16759         if (old->active_rcu_lock != cur->active_rcu_lock)
16760                 return false;
16761
16762         /* for states to be equal callsites have to be the same
16763          * and all frame states need to be equivalent
16764          */
16765         for (i = 0; i <= old->curframe; i++) {
16766                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16767                         return false;
16768                 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16769                         return false;
16770         }
16771         return true;
16772 }
16773
16774 /* Return 0 if no propagation happened. Return negative error code if error
16775  * happened. Otherwise, return the propagated bit.
16776  */
16777 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16778                                   struct bpf_reg_state *reg,
16779                                   struct bpf_reg_state *parent_reg)
16780 {
16781         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16782         u8 flag = reg->live & REG_LIVE_READ;
16783         int err;
16784
16785         /* When comes here, read flags of PARENT_REG or REG could be any of
16786          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16787          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16788          */
16789         if (parent_flag == REG_LIVE_READ64 ||
16790             /* Or if there is no read flag from REG. */
16791             !flag ||
16792             /* Or if the read flag from REG is the same as PARENT_REG. */
16793             parent_flag == flag)
16794                 return 0;
16795
16796         err = mark_reg_read(env, reg, parent_reg, flag);
16797         if (err)
16798                 return err;
16799
16800         return flag;
16801 }
16802
16803 /* A write screens off any subsequent reads; but write marks come from the
16804  * straight-line code between a state and its parent.  When we arrive at an
16805  * equivalent state (jump target or such) we didn't arrive by the straight-line
16806  * code, so read marks in the state must propagate to the parent regardless
16807  * of the state's write marks. That's what 'parent == state->parent' comparison
16808  * in mark_reg_read() is for.
16809  */
16810 static int propagate_liveness(struct bpf_verifier_env *env,
16811                               const struct bpf_verifier_state *vstate,
16812                               struct bpf_verifier_state *vparent)
16813 {
16814         struct bpf_reg_state *state_reg, *parent_reg;
16815         struct bpf_func_state *state, *parent;
16816         int i, frame, err = 0;
16817
16818         if (vparent->curframe != vstate->curframe) {
16819                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16820                      vparent->curframe, vstate->curframe);
16821                 return -EFAULT;
16822         }
16823         /* Propagate read liveness of registers... */
16824         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16825         for (frame = 0; frame <= vstate->curframe; frame++) {
16826                 parent = vparent->frame[frame];
16827                 state = vstate->frame[frame];
16828                 parent_reg = parent->regs;
16829                 state_reg = state->regs;
16830                 /* We don't need to worry about FP liveness, it's read-only */
16831                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16832                         err = propagate_liveness_reg(env, &state_reg[i],
16833                                                      &parent_reg[i]);
16834                         if (err < 0)
16835                                 return err;
16836                         if (err == REG_LIVE_READ64)
16837                                 mark_insn_zext(env, &parent_reg[i]);
16838                 }
16839
16840                 /* Propagate stack slots. */
16841                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16842                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16843                         parent_reg = &parent->stack[i].spilled_ptr;
16844                         state_reg = &state->stack[i].spilled_ptr;
16845                         err = propagate_liveness_reg(env, state_reg,
16846                                                      parent_reg);
16847                         if (err < 0)
16848                                 return err;
16849                 }
16850         }
16851         return 0;
16852 }
16853
16854 /* find precise scalars in the previous equivalent state and
16855  * propagate them into the current state
16856  */
16857 static int propagate_precision(struct bpf_verifier_env *env,
16858                                const struct bpf_verifier_state *old)
16859 {
16860         struct bpf_reg_state *state_reg;
16861         struct bpf_func_state *state;
16862         int i, err = 0, fr;
16863         bool first;
16864
16865         for (fr = old->curframe; fr >= 0; fr--) {
16866                 state = old->frame[fr];
16867                 state_reg = state->regs;
16868                 first = true;
16869                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16870                         if (state_reg->type != SCALAR_VALUE ||
16871                             !state_reg->precise ||
16872                             !(state_reg->live & REG_LIVE_READ))
16873                                 continue;
16874                         if (env->log.level & BPF_LOG_LEVEL2) {
16875                                 if (first)
16876                                         verbose(env, "frame %d: propagating r%d", fr, i);
16877                                 else
16878                                         verbose(env, ",r%d", i);
16879                         }
16880                         bt_set_frame_reg(&env->bt, fr, i);
16881                         first = false;
16882                 }
16883
16884                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16885                         if (!is_spilled_reg(&state->stack[i]))
16886                                 continue;
16887                         state_reg = &state->stack[i].spilled_ptr;
16888                         if (state_reg->type != SCALAR_VALUE ||
16889                             !state_reg->precise ||
16890                             !(state_reg->live & REG_LIVE_READ))
16891                                 continue;
16892                         if (env->log.level & BPF_LOG_LEVEL2) {
16893                                 if (first)
16894                                         verbose(env, "frame %d: propagating fp%d",
16895                                                 fr, (-i - 1) * BPF_REG_SIZE);
16896                                 else
16897                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16898                         }
16899                         bt_set_frame_slot(&env->bt, fr, i);
16900                         first = false;
16901                 }
16902                 if (!first)
16903                         verbose(env, "\n");
16904         }
16905
16906         err = mark_chain_precision_batch(env);
16907         if (err < 0)
16908                 return err;
16909
16910         return 0;
16911 }
16912
16913 static bool states_maybe_looping(struct bpf_verifier_state *old,
16914                                  struct bpf_verifier_state *cur)
16915 {
16916         struct bpf_func_state *fold, *fcur;
16917         int i, fr = cur->curframe;
16918
16919         if (old->curframe != fr)
16920                 return false;
16921
16922         fold = old->frame[fr];
16923         fcur = cur->frame[fr];
16924         for (i = 0; i < MAX_BPF_REG; i++)
16925                 if (memcmp(&fold->regs[i], &fcur->regs[i],
16926                            offsetof(struct bpf_reg_state, parent)))
16927                         return false;
16928         return true;
16929 }
16930
16931 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16932 {
16933         return env->insn_aux_data[insn_idx].is_iter_next;
16934 }
16935
16936 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16937  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16938  * states to match, which otherwise would look like an infinite loop. So while
16939  * iter_next() calls are taken care of, we still need to be careful and
16940  * prevent erroneous and too eager declaration of "ininite loop", when
16941  * iterators are involved.
16942  *
16943  * Here's a situation in pseudo-BPF assembly form:
16944  *
16945  *   0: again:                          ; set up iter_next() call args
16946  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16947  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16948  *   3:   if r0 == 0 goto done
16949  *   4:   ... something useful here ...
16950  *   5:   goto again                    ; another iteration
16951  *   6: done:
16952  *   7:   r1 = &it
16953  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16954  *   9:   exit
16955  *
16956  * This is a typical loop. Let's assume that we have a prune point at 1:,
16957  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16958  * again`, assuming other heuristics don't get in a way).
16959  *
16960  * When we first time come to 1:, let's say we have some state X. We proceed
16961  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16962  * Now we come back to validate that forked ACTIVE state. We proceed through
16963  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16964  * are converging. But the problem is that we don't know that yet, as this
16965  * convergence has to happen at iter_next() call site only. So if nothing is
16966  * done, at 1: verifier will use bounded loop logic and declare infinite
16967  * looping (and would be *technically* correct, if not for iterator's
16968  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16969  * don't want that. So what we do in process_iter_next_call() when we go on
16970  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16971  * a different iteration. So when we suspect an infinite loop, we additionally
16972  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16973  * pretend we are not looping and wait for next iter_next() call.
16974  *
16975  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16976  * loop, because that would actually mean infinite loop, as DRAINED state is
16977  * "sticky", and so we'll keep returning into the same instruction with the
16978  * same state (at least in one of possible code paths).
16979  *
16980  * This approach allows to keep infinite loop heuristic even in the face of
16981  * active iterator. E.g., C snippet below is and will be detected as
16982  * inifintely looping:
16983  *
16984  *   struct bpf_iter_num it;
16985  *   int *p, x;
16986  *
16987  *   bpf_iter_num_new(&it, 0, 10);
16988  *   while ((p = bpf_iter_num_next(&t))) {
16989  *       x = p;
16990  *       while (x--) {} // <<-- infinite loop here
16991  *   }
16992  *
16993  */
16994 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16995 {
16996         struct bpf_reg_state *slot, *cur_slot;
16997         struct bpf_func_state *state;
16998         int i, fr;
16999
17000         for (fr = old->curframe; fr >= 0; fr--) {
17001                 state = old->frame[fr];
17002                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17003                         if (state->stack[i].slot_type[0] != STACK_ITER)
17004                                 continue;
17005
17006                         slot = &state->stack[i].spilled_ptr;
17007                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17008                                 continue;
17009
17010                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17011                         if (cur_slot->iter.depth != slot->iter.depth)
17012                                 return true;
17013                 }
17014         }
17015         return false;
17016 }
17017
17018 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17019 {
17020         struct bpf_verifier_state_list *new_sl;
17021         struct bpf_verifier_state_list *sl, **pprev;
17022         struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17023         int i, j, n, err, states_cnt = 0;
17024         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17025         bool add_new_state = force_new_state;
17026         bool force_exact;
17027
17028         /* bpf progs typically have pruning point every 4 instructions
17029          * http://vger.kernel.org/bpfconf2019.html#session-1
17030          * Do not add new state for future pruning if the verifier hasn't seen
17031          * at least 2 jumps and at least 8 instructions.
17032          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17033          * In tests that amounts to up to 50% reduction into total verifier
17034          * memory consumption and 20% verifier time speedup.
17035          */
17036         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17037             env->insn_processed - env->prev_insn_processed >= 8)
17038                 add_new_state = true;
17039
17040         pprev = explored_state(env, insn_idx);
17041         sl = *pprev;
17042
17043         clean_live_states(env, insn_idx, cur);
17044
17045         while (sl) {
17046                 states_cnt++;
17047                 if (sl->state.insn_idx != insn_idx)
17048                         goto next;
17049
17050                 if (sl->state.branches) {
17051                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17052
17053                         if (frame->in_async_callback_fn &&
17054                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17055                                 /* Different async_entry_cnt means that the verifier is
17056                                  * processing another entry into async callback.
17057                                  * Seeing the same state is not an indication of infinite
17058                                  * loop or infinite recursion.
17059                                  * But finding the same state doesn't mean that it's safe
17060                                  * to stop processing the current state. The previous state
17061                                  * hasn't yet reached bpf_exit, since state.branches > 0.
17062                                  * Checking in_async_callback_fn alone is not enough either.
17063                                  * Since the verifier still needs to catch infinite loops
17064                                  * inside async callbacks.
17065                                  */
17066                                 goto skip_inf_loop_check;
17067                         }
17068                         /* BPF open-coded iterators loop detection is special.
17069                          * states_maybe_looping() logic is too simplistic in detecting
17070                          * states that *might* be equivalent, because it doesn't know
17071                          * about ID remapping, so don't even perform it.
17072                          * See process_iter_next_call() and iter_active_depths_differ()
17073                          * for overview of the logic. When current and one of parent
17074                          * states are detected as equivalent, it's a good thing: we prove
17075                          * convergence and can stop simulating further iterations.
17076                          * It's safe to assume that iterator loop will finish, taking into
17077                          * account iter_next() contract of eventually returning
17078                          * sticky NULL result.
17079                          *
17080                          * Note, that states have to be compared exactly in this case because
17081                          * read and precision marks might not be finalized inside the loop.
17082                          * E.g. as in the program below:
17083                          *
17084                          *     1. r7 = -16
17085                          *     2. r6 = bpf_get_prandom_u32()
17086                          *     3. while (bpf_iter_num_next(&fp[-8])) {
17087                          *     4.   if (r6 != 42) {
17088                          *     5.     r7 = -32
17089                          *     6.     r6 = bpf_get_prandom_u32()
17090                          *     7.     continue
17091                          *     8.   }
17092                          *     9.   r0 = r10
17093                          *    10.   r0 += r7
17094                          *    11.   r8 = *(u64 *)(r0 + 0)
17095                          *    12.   r6 = bpf_get_prandom_u32()
17096                          *    13. }
17097                          *
17098                          * Here verifier would first visit path 1-3, create a checkpoint at 3
17099                          * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17100                          * not have read or precision mark for r7 yet, thus inexact states
17101                          * comparison would discard current state with r7=-32
17102                          * => unsafe memory access at 11 would not be caught.
17103                          */
17104                         if (is_iter_next_insn(env, insn_idx)) {
17105                                 if (states_equal(env, &sl->state, cur, true)) {
17106                                         struct bpf_func_state *cur_frame;
17107                                         struct bpf_reg_state *iter_state, *iter_reg;
17108                                         int spi;
17109
17110                                         cur_frame = cur->frame[cur->curframe];
17111                                         /* btf_check_iter_kfuncs() enforces that
17112                                          * iter state pointer is always the first arg
17113                                          */
17114                                         iter_reg = &cur_frame->regs[BPF_REG_1];
17115                                         /* current state is valid due to states_equal(),
17116                                          * so we can assume valid iter and reg state,
17117                                          * no need for extra (re-)validations
17118                                          */
17119                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17120                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17121                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17122                                                 update_loop_entry(cur, &sl->state);
17123                                                 goto hit;
17124                                         }
17125                                 }
17126                                 goto skip_inf_loop_check;
17127                         }
17128                         if (calls_callback(env, insn_idx)) {
17129                                 if (states_equal(env, &sl->state, cur, true))
17130                                         goto hit;
17131                                 goto skip_inf_loop_check;
17132                         }
17133                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
17134                         if (states_maybe_looping(&sl->state, cur) &&
17135                             states_equal(env, &sl->state, cur, true) &&
17136                             !iter_active_depths_differ(&sl->state, cur) &&
17137                             sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17138                                 verbose_linfo(env, insn_idx, "; ");
17139                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17140                                 verbose(env, "cur state:");
17141                                 print_verifier_state(env, cur->frame[cur->curframe], true);
17142                                 verbose(env, "old state:");
17143                                 print_verifier_state(env, sl->state.frame[cur->curframe], true);
17144                                 return -EINVAL;
17145                         }
17146                         /* if the verifier is processing a loop, avoid adding new state
17147                          * too often, since different loop iterations have distinct
17148                          * states and may not help future pruning.
17149                          * This threshold shouldn't be too low to make sure that
17150                          * a loop with large bound will be rejected quickly.
17151                          * The most abusive loop will be:
17152                          * r1 += 1
17153                          * if r1 < 1000000 goto pc-2
17154                          * 1M insn_procssed limit / 100 == 10k peak states.
17155                          * This threshold shouldn't be too high either, since states
17156                          * at the end of the loop are likely to be useful in pruning.
17157                          */
17158 skip_inf_loop_check:
17159                         if (!force_new_state &&
17160                             env->jmps_processed - env->prev_jmps_processed < 20 &&
17161                             env->insn_processed - env->prev_insn_processed < 100)
17162                                 add_new_state = false;
17163                         goto miss;
17164                 }
17165                 /* If sl->state is a part of a loop and this loop's entry is a part of
17166                  * current verification path then states have to be compared exactly.
17167                  * 'force_exact' is needed to catch the following case:
17168                  *
17169                  *                initial     Here state 'succ' was processed first,
17170                  *                  |         it was eventually tracked to produce a
17171                  *                  V         state identical to 'hdr'.
17172                  *     .---------> hdr        All branches from 'succ' had been explored
17173                  *     |            |         and thus 'succ' has its .branches == 0.
17174                  *     |            V
17175                  *     |    .------...        Suppose states 'cur' and 'succ' correspond
17176                  *     |    |       |         to the same instruction + callsites.
17177                  *     |    V       V         In such case it is necessary to check
17178                  *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17179                  *     |    |       |         If 'succ' and 'cur' are a part of the
17180                  *     |    V       V         same loop exact flag has to be set.
17181                  *     |   succ <- cur        To check if that is the case, verify
17182                  *     |    |                 if loop entry of 'succ' is in current
17183                  *     |    V                 DFS path.
17184                  *     |   ...
17185                  *     |    |
17186                  *     '----'
17187                  *
17188                  * Additional details are in the comment before get_loop_entry().
17189                  */
17190                 loop_entry = get_loop_entry(&sl->state);
17191                 force_exact = loop_entry && loop_entry->branches > 0;
17192                 if (states_equal(env, &sl->state, cur, force_exact)) {
17193                         if (force_exact)
17194                                 update_loop_entry(cur, loop_entry);
17195 hit:
17196                         sl->hit_cnt++;
17197                         /* reached equivalent register/stack state,
17198                          * prune the search.
17199                          * Registers read by the continuation are read by us.
17200                          * If we have any write marks in env->cur_state, they
17201                          * will prevent corresponding reads in the continuation
17202                          * from reaching our parent (an explored_state).  Our
17203                          * own state will get the read marks recorded, but
17204                          * they'll be immediately forgotten as we're pruning
17205                          * this state and will pop a new one.
17206                          */
17207                         err = propagate_liveness(env, &sl->state, cur);
17208
17209                         /* if previous state reached the exit with precision and
17210                          * current state is equivalent to it (except precsion marks)
17211                          * the precision needs to be propagated back in
17212                          * the current state.
17213                          */
17214                         if (is_jmp_point(env, env->insn_idx))
17215                                 err = err ? : push_jmp_history(env, cur, 0);
17216                         err = err ? : propagate_precision(env, &sl->state);
17217                         if (err)
17218                                 return err;
17219                         return 1;
17220                 }
17221 miss:
17222                 /* when new state is not going to be added do not increase miss count.
17223                  * Otherwise several loop iterations will remove the state
17224                  * recorded earlier. The goal of these heuristics is to have
17225                  * states from some iterations of the loop (some in the beginning
17226                  * and some at the end) to help pruning.
17227                  */
17228                 if (add_new_state)
17229                         sl->miss_cnt++;
17230                 /* heuristic to determine whether this state is beneficial
17231                  * to keep checking from state equivalence point of view.
17232                  * Higher numbers increase max_states_per_insn and verification time,
17233                  * but do not meaningfully decrease insn_processed.
17234                  * 'n' controls how many times state could miss before eviction.
17235                  * Use bigger 'n' for checkpoints because evicting checkpoint states
17236                  * too early would hinder iterator convergence.
17237                  */
17238                 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17239                 if (sl->miss_cnt > sl->hit_cnt * n + n) {
17240                         /* the state is unlikely to be useful. Remove it to
17241                          * speed up verification
17242                          */
17243                         *pprev = sl->next;
17244                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17245                             !sl->state.used_as_loop_entry) {
17246                                 u32 br = sl->state.branches;
17247
17248                                 WARN_ONCE(br,
17249                                           "BUG live_done but branches_to_explore %d\n",
17250                                           br);
17251                                 free_verifier_state(&sl->state, false);
17252                                 kfree(sl);
17253                                 env->peak_states--;
17254                         } else {
17255                                 /* cannot free this state, since parentage chain may
17256                                  * walk it later. Add it for free_list instead to
17257                                  * be freed at the end of verification
17258                                  */
17259                                 sl->next = env->free_list;
17260                                 env->free_list = sl;
17261                         }
17262                         sl = *pprev;
17263                         continue;
17264                 }
17265 next:
17266                 pprev = &sl->next;
17267                 sl = *pprev;
17268         }
17269
17270         if (env->max_states_per_insn < states_cnt)
17271                 env->max_states_per_insn = states_cnt;
17272
17273         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17274                 return 0;
17275
17276         if (!add_new_state)
17277                 return 0;
17278
17279         /* There were no equivalent states, remember the current one.
17280          * Technically the current state is not proven to be safe yet,
17281          * but it will either reach outer most bpf_exit (which means it's safe)
17282          * or it will be rejected. When there are no loops the verifier won't be
17283          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17284          * again on the way to bpf_exit.
17285          * When looping the sl->state.branches will be > 0 and this state
17286          * will not be considered for equivalence until branches == 0.
17287          */
17288         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17289         if (!new_sl)
17290                 return -ENOMEM;
17291         env->total_states++;
17292         env->peak_states++;
17293         env->prev_jmps_processed = env->jmps_processed;
17294         env->prev_insn_processed = env->insn_processed;
17295
17296         /* forget precise markings we inherited, see __mark_chain_precision */
17297         if (env->bpf_capable)
17298                 mark_all_scalars_imprecise(env, cur);
17299
17300         /* add new state to the head of linked list */
17301         new = &new_sl->state;
17302         err = copy_verifier_state(new, cur);
17303         if (err) {
17304                 free_verifier_state(new, false);
17305                 kfree(new_sl);
17306                 return err;
17307         }
17308         new->insn_idx = insn_idx;
17309         WARN_ONCE(new->branches != 1,
17310                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17311
17312         cur->parent = new;
17313         cur->first_insn_idx = insn_idx;
17314         cur->dfs_depth = new->dfs_depth + 1;
17315         clear_jmp_history(cur);
17316         new_sl->next = *explored_state(env, insn_idx);
17317         *explored_state(env, insn_idx) = new_sl;
17318         /* connect new state to parentage chain. Current frame needs all
17319          * registers connected. Only r6 - r9 of the callers are alive (pushed
17320          * to the stack implicitly by JITs) so in callers' frames connect just
17321          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17322          * the state of the call instruction (with WRITTEN set), and r0 comes
17323          * from callee with its full parentage chain, anyway.
17324          */
17325         /* clear write marks in current state: the writes we did are not writes
17326          * our child did, so they don't screen off its reads from us.
17327          * (There are no read marks in current state, because reads always mark
17328          * their parent and current state never has children yet.  Only
17329          * explored_states can get read marks.)
17330          */
17331         for (j = 0; j <= cur->curframe; j++) {
17332                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17333                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17334                 for (i = 0; i < BPF_REG_FP; i++)
17335                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17336         }
17337
17338         /* all stack frames are accessible from callee, clear them all */
17339         for (j = 0; j <= cur->curframe; j++) {
17340                 struct bpf_func_state *frame = cur->frame[j];
17341                 struct bpf_func_state *newframe = new->frame[j];
17342
17343                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17344                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17345                         frame->stack[i].spilled_ptr.parent =
17346                                                 &newframe->stack[i].spilled_ptr;
17347                 }
17348         }
17349         return 0;
17350 }
17351
17352 /* Return true if it's OK to have the same insn return a different type. */
17353 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17354 {
17355         switch (base_type(type)) {
17356         case PTR_TO_CTX:
17357         case PTR_TO_SOCKET:
17358         case PTR_TO_SOCK_COMMON:
17359         case PTR_TO_TCP_SOCK:
17360         case PTR_TO_XDP_SOCK:
17361         case PTR_TO_BTF_ID:
17362                 return false;
17363         default:
17364                 return true;
17365         }
17366 }
17367
17368 /* If an instruction was previously used with particular pointer types, then we
17369  * need to be careful to avoid cases such as the below, where it may be ok
17370  * for one branch accessing the pointer, but not ok for the other branch:
17371  *
17372  * R1 = sock_ptr
17373  * goto X;
17374  * ...
17375  * R1 = some_other_valid_ptr;
17376  * goto X;
17377  * ...
17378  * R2 = *(u32 *)(R1 + 0);
17379  */
17380 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17381 {
17382         return src != prev && (!reg_type_mismatch_ok(src) ||
17383                                !reg_type_mismatch_ok(prev));
17384 }
17385
17386 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17387                              bool allow_trust_missmatch)
17388 {
17389         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17390
17391         if (*prev_type == NOT_INIT) {
17392                 /* Saw a valid insn
17393                  * dst_reg = *(u32 *)(src_reg + off)
17394                  * save type to validate intersecting paths
17395                  */
17396                 *prev_type = type;
17397         } else if (reg_type_mismatch(type, *prev_type)) {
17398                 /* Abuser program is trying to use the same insn
17399                  * dst_reg = *(u32*) (src_reg + off)
17400                  * with different pointer types:
17401                  * src_reg == ctx in one branch and
17402                  * src_reg == stack|map in some other branch.
17403                  * Reject it.
17404                  */
17405                 if (allow_trust_missmatch &&
17406                     base_type(type) == PTR_TO_BTF_ID &&
17407                     base_type(*prev_type) == PTR_TO_BTF_ID) {
17408                         /*
17409                          * Have to support a use case when one path through
17410                          * the program yields TRUSTED pointer while another
17411                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
17412                          * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17413                          */
17414                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17415                 } else {
17416                         verbose(env, "same insn cannot be used with different pointers\n");
17417                         return -EINVAL;
17418                 }
17419         }
17420
17421         return 0;
17422 }
17423
17424 static int do_check(struct bpf_verifier_env *env)
17425 {
17426         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17427         struct bpf_verifier_state *state = env->cur_state;
17428         struct bpf_insn *insns = env->prog->insnsi;
17429         struct bpf_reg_state *regs;
17430         int insn_cnt = env->prog->len;
17431         bool do_print_state = false;
17432         int prev_insn_idx = -1;
17433
17434         for (;;) {
17435                 bool exception_exit = false;
17436                 struct bpf_insn *insn;
17437                 u8 class;
17438                 int err;
17439
17440                 /* reset current history entry on each new instruction */
17441                 env->cur_hist_ent = NULL;
17442
17443                 env->prev_insn_idx = prev_insn_idx;
17444                 if (env->insn_idx >= insn_cnt) {
17445                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
17446                                 env->insn_idx, insn_cnt);
17447                         return -EFAULT;
17448                 }
17449
17450                 insn = &insns[env->insn_idx];
17451                 class = BPF_CLASS(insn->code);
17452
17453                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17454                         verbose(env,
17455                                 "BPF program is too large. Processed %d insn\n",
17456                                 env->insn_processed);
17457                         return -E2BIG;
17458                 }
17459
17460                 state->last_insn_idx = env->prev_insn_idx;
17461
17462                 if (is_prune_point(env, env->insn_idx)) {
17463                         err = is_state_visited(env, env->insn_idx);
17464                         if (err < 0)
17465                                 return err;
17466                         if (err == 1) {
17467                                 /* found equivalent state, can prune the search */
17468                                 if (env->log.level & BPF_LOG_LEVEL) {
17469                                         if (do_print_state)
17470                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
17471                                                         env->prev_insn_idx, env->insn_idx,
17472                                                         env->cur_state->speculative ?
17473                                                         " (speculative execution)" : "");
17474                                         else
17475                                                 verbose(env, "%d: safe\n", env->insn_idx);
17476                                 }
17477                                 goto process_bpf_exit;
17478                         }
17479                 }
17480
17481                 if (is_jmp_point(env, env->insn_idx)) {
17482                         err = push_jmp_history(env, state, 0);
17483                         if (err)
17484                                 return err;
17485                 }
17486
17487                 if (signal_pending(current))
17488                         return -EAGAIN;
17489
17490                 if (need_resched())
17491                         cond_resched();
17492
17493                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17494                         verbose(env, "\nfrom %d to %d%s:",
17495                                 env->prev_insn_idx, env->insn_idx,
17496                                 env->cur_state->speculative ?
17497                                 " (speculative execution)" : "");
17498                         print_verifier_state(env, state->frame[state->curframe], true);
17499                         do_print_state = false;
17500                 }
17501
17502                 if (env->log.level & BPF_LOG_LEVEL) {
17503                         const struct bpf_insn_cbs cbs = {
17504                                 .cb_call        = disasm_kfunc_name,
17505                                 .cb_print       = verbose,
17506                                 .private_data   = env,
17507                         };
17508
17509                         if (verifier_state_scratched(env))
17510                                 print_insn_state(env, state->frame[state->curframe]);
17511
17512                         verbose_linfo(env, env->insn_idx, "; ");
17513                         env->prev_log_pos = env->log.end_pos;
17514                         verbose(env, "%d: ", env->insn_idx);
17515                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17516                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17517                         env->prev_log_pos = env->log.end_pos;
17518                 }
17519
17520                 if (bpf_prog_is_offloaded(env->prog->aux)) {
17521                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17522                                                            env->prev_insn_idx);
17523                         if (err)
17524                                 return err;
17525                 }
17526
17527                 regs = cur_regs(env);
17528                 sanitize_mark_insn_seen(env);
17529                 prev_insn_idx = env->insn_idx;
17530
17531                 if (class == BPF_ALU || class == BPF_ALU64) {
17532                         err = check_alu_op(env, insn);
17533                         if (err)
17534                                 return err;
17535
17536                 } else if (class == BPF_LDX) {
17537                         enum bpf_reg_type src_reg_type;
17538
17539                         /* check for reserved fields is already done */
17540
17541                         /* check src operand */
17542                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
17543                         if (err)
17544                                 return err;
17545
17546                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17547                         if (err)
17548                                 return err;
17549
17550                         src_reg_type = regs[insn->src_reg].type;
17551
17552                         /* check that memory (src_reg + off) is readable,
17553                          * the state of dst_reg will be updated by this func
17554                          */
17555                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
17556                                                insn->off, BPF_SIZE(insn->code),
17557                                                BPF_READ, insn->dst_reg, false,
17558                                                BPF_MODE(insn->code) == BPF_MEMSX);
17559                         err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17560                         err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17561                         if (err)
17562                                 return err;
17563                 } else if (class == BPF_STX) {
17564                         enum bpf_reg_type dst_reg_type;
17565
17566                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17567                                 err = check_atomic(env, env->insn_idx, insn);
17568                                 if (err)
17569                                         return err;
17570                                 env->insn_idx++;
17571                                 continue;
17572                         }
17573
17574                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17575                                 verbose(env, "BPF_STX uses reserved fields\n");
17576                                 return -EINVAL;
17577                         }
17578
17579                         /* check src1 operand */
17580                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
17581                         if (err)
17582                                 return err;
17583                         /* check src2 operand */
17584                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17585                         if (err)
17586                                 return err;
17587
17588                         dst_reg_type = regs[insn->dst_reg].type;
17589
17590                         /* check that memory (dst_reg + off) is writeable */
17591                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17592                                                insn->off, BPF_SIZE(insn->code),
17593                                                BPF_WRITE, insn->src_reg, false, false);
17594                         if (err)
17595                                 return err;
17596
17597                         err = save_aux_ptr_type(env, dst_reg_type, false);
17598                         if (err)
17599                                 return err;
17600                 } else if (class == BPF_ST) {
17601                         enum bpf_reg_type dst_reg_type;
17602
17603                         if (BPF_MODE(insn->code) != BPF_MEM ||
17604                             insn->src_reg != BPF_REG_0) {
17605                                 verbose(env, "BPF_ST uses reserved fields\n");
17606                                 return -EINVAL;
17607                         }
17608                         /* check src operand */
17609                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17610                         if (err)
17611                                 return err;
17612
17613                         dst_reg_type = regs[insn->dst_reg].type;
17614
17615                         /* check that memory (dst_reg + off) is writeable */
17616                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17617                                                insn->off, BPF_SIZE(insn->code),
17618                                                BPF_WRITE, -1, false, false);
17619                         if (err)
17620                                 return err;
17621
17622                         err = save_aux_ptr_type(env, dst_reg_type, false);
17623                         if (err)
17624                                 return err;
17625                 } else if (class == BPF_JMP || class == BPF_JMP32) {
17626                         u8 opcode = BPF_OP(insn->code);
17627
17628                         env->jmps_processed++;
17629                         if (opcode == BPF_CALL) {
17630                                 if (BPF_SRC(insn->code) != BPF_K ||
17631                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17632                                      && insn->off != 0) ||
17633                                     (insn->src_reg != BPF_REG_0 &&
17634                                      insn->src_reg != BPF_PSEUDO_CALL &&
17635                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17636                                     insn->dst_reg != BPF_REG_0 ||
17637                                     class == BPF_JMP32) {
17638                                         verbose(env, "BPF_CALL uses reserved fields\n");
17639                                         return -EINVAL;
17640                                 }
17641
17642                                 if (env->cur_state->active_lock.ptr) {
17643                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17644                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17645                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17646                                                 verbose(env, "function calls are not allowed while holding a lock\n");
17647                                                 return -EINVAL;
17648                                         }
17649                                 }
17650                                 if (insn->src_reg == BPF_PSEUDO_CALL) {
17651                                         err = check_func_call(env, insn, &env->insn_idx);
17652                                 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17653                                         err = check_kfunc_call(env, insn, &env->insn_idx);
17654                                         if (!err && is_bpf_throw_kfunc(insn)) {
17655                                                 exception_exit = true;
17656                                                 goto process_bpf_exit_full;
17657                                         }
17658                                 } else {
17659                                         err = check_helper_call(env, insn, &env->insn_idx);
17660                                 }
17661                                 if (err)
17662                                         return err;
17663
17664                                 mark_reg_scratched(env, BPF_REG_0);
17665                         } else if (opcode == BPF_JA) {
17666                                 if (BPF_SRC(insn->code) != BPF_K ||
17667                                     insn->src_reg != BPF_REG_0 ||
17668                                     insn->dst_reg != BPF_REG_0 ||
17669                                     (class == BPF_JMP && insn->imm != 0) ||
17670                                     (class == BPF_JMP32 && insn->off != 0)) {
17671                                         verbose(env, "BPF_JA uses reserved fields\n");
17672                                         return -EINVAL;
17673                                 }
17674
17675                                 if (class == BPF_JMP)
17676                                         env->insn_idx += insn->off + 1;
17677                                 else
17678                                         env->insn_idx += insn->imm + 1;
17679                                 continue;
17680
17681                         } else if (opcode == BPF_EXIT) {
17682                                 if (BPF_SRC(insn->code) != BPF_K ||
17683                                     insn->imm != 0 ||
17684                                     insn->src_reg != BPF_REG_0 ||
17685                                     insn->dst_reg != BPF_REG_0 ||
17686                                     class == BPF_JMP32) {
17687                                         verbose(env, "BPF_EXIT uses reserved fields\n");
17688                                         return -EINVAL;
17689                                 }
17690 process_bpf_exit_full:
17691                                 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
17692                                         verbose(env, "bpf_spin_unlock is missing\n");
17693                                         return -EINVAL;
17694                                 }
17695
17696                                 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
17697                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
17698                                         return -EINVAL;
17699                                 }
17700
17701                                 /* We must do check_reference_leak here before
17702                                  * prepare_func_exit to handle the case when
17703                                  * state->curframe > 0, it may be a callback
17704                                  * function, for which reference_state must
17705                                  * match caller reference state when it exits.
17706                                  */
17707                                 err = check_reference_leak(env, exception_exit);
17708                                 if (err)
17709                                         return err;
17710
17711                                 /* The side effect of the prepare_func_exit
17712                                  * which is being skipped is that it frees
17713                                  * bpf_func_state. Typically, process_bpf_exit
17714                                  * will only be hit with outermost exit.
17715                                  * copy_verifier_state in pop_stack will handle
17716                                  * freeing of any extra bpf_func_state left over
17717                                  * from not processing all nested function
17718                                  * exits. We also skip return code checks as
17719                                  * they are not needed for exceptional exits.
17720                                  */
17721                                 if (exception_exit)
17722                                         goto process_bpf_exit;
17723
17724                                 if (state->curframe) {
17725                                         /* exit from nested function */
17726                                         err = prepare_func_exit(env, &env->insn_idx);
17727                                         if (err)
17728                                                 return err;
17729                                         do_print_state = true;
17730                                         continue;
17731                                 }
17732
17733                                 err = check_return_code(env, BPF_REG_0, "R0");
17734                                 if (err)
17735                                         return err;
17736 process_bpf_exit:
17737                                 mark_verifier_state_scratched(env);
17738                                 update_branch_counts(env, env->cur_state);
17739                                 err = pop_stack(env, &prev_insn_idx,
17740                                                 &env->insn_idx, pop_log);
17741                                 if (err < 0) {
17742                                         if (err != -ENOENT)
17743                                                 return err;
17744                                         break;
17745                                 } else {
17746                                         do_print_state = true;
17747                                         continue;
17748                                 }
17749                         } else {
17750                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17751                                 if (err)
17752                                         return err;
17753                         }
17754                 } else if (class == BPF_LD) {
17755                         u8 mode = BPF_MODE(insn->code);
17756
17757                         if (mode == BPF_ABS || mode == BPF_IND) {
17758                                 err = check_ld_abs(env, insn);
17759                                 if (err)
17760                                         return err;
17761
17762                         } else if (mode == BPF_IMM) {
17763                                 err = check_ld_imm(env, insn);
17764                                 if (err)
17765                                         return err;
17766
17767                                 env->insn_idx++;
17768                                 sanitize_mark_insn_seen(env);
17769                         } else {
17770                                 verbose(env, "invalid BPF_LD mode\n");
17771                                 return -EINVAL;
17772                         }
17773                 } else {
17774                         verbose(env, "unknown insn class %d\n", class);
17775                         return -EINVAL;
17776                 }
17777
17778                 env->insn_idx++;
17779         }
17780
17781         return 0;
17782 }
17783
17784 static int find_btf_percpu_datasec(struct btf *btf)
17785 {
17786         const struct btf_type *t;
17787         const char *tname;
17788         int i, n;
17789
17790         /*
17791          * Both vmlinux and module each have their own ".data..percpu"
17792          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17793          * types to look at only module's own BTF types.
17794          */
17795         n = btf_nr_types(btf);
17796         if (btf_is_module(btf))
17797                 i = btf_nr_types(btf_vmlinux);
17798         else
17799                 i = 1;
17800
17801         for(; i < n; i++) {
17802                 t = btf_type_by_id(btf, i);
17803                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17804                         continue;
17805
17806                 tname = btf_name_by_offset(btf, t->name_off);
17807                 if (!strcmp(tname, ".data..percpu"))
17808                         return i;
17809         }
17810
17811         return -ENOENT;
17812 }
17813
17814 /* replace pseudo btf_id with kernel symbol address */
17815 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17816                                struct bpf_insn *insn,
17817                                struct bpf_insn_aux_data *aux)
17818 {
17819         const struct btf_var_secinfo *vsi;
17820         const struct btf_type *datasec;
17821         struct btf_mod_pair *btf_mod;
17822         const struct btf_type *t;
17823         const char *sym_name;
17824         bool percpu = false;
17825         u32 type, id = insn->imm;
17826         struct btf *btf;
17827         s32 datasec_id;
17828         u64 addr;
17829         int i, btf_fd, err;
17830
17831         btf_fd = insn[1].imm;
17832         if (btf_fd) {
17833                 btf = btf_get_by_fd(btf_fd);
17834                 if (IS_ERR(btf)) {
17835                         verbose(env, "invalid module BTF object FD specified.\n");
17836                         return -EINVAL;
17837                 }
17838         } else {
17839                 if (!btf_vmlinux) {
17840                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17841                         return -EINVAL;
17842                 }
17843                 btf = btf_vmlinux;
17844                 btf_get(btf);
17845         }
17846
17847         t = btf_type_by_id(btf, id);
17848         if (!t) {
17849                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17850                 err = -ENOENT;
17851                 goto err_put;
17852         }
17853
17854         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17855                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17856                 err = -EINVAL;
17857                 goto err_put;
17858         }
17859
17860         sym_name = btf_name_by_offset(btf, t->name_off);
17861         addr = kallsyms_lookup_name(sym_name);
17862         if (!addr) {
17863                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17864                         sym_name);
17865                 err = -ENOENT;
17866                 goto err_put;
17867         }
17868         insn[0].imm = (u32)addr;
17869         insn[1].imm = addr >> 32;
17870
17871         if (btf_type_is_func(t)) {
17872                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17873                 aux->btf_var.mem_size = 0;
17874                 goto check_btf;
17875         }
17876
17877         datasec_id = find_btf_percpu_datasec(btf);
17878         if (datasec_id > 0) {
17879                 datasec = btf_type_by_id(btf, datasec_id);
17880                 for_each_vsi(i, datasec, vsi) {
17881                         if (vsi->type == id) {
17882                                 percpu = true;
17883                                 break;
17884                         }
17885                 }
17886         }
17887
17888         type = t->type;
17889         t = btf_type_skip_modifiers(btf, type, NULL);
17890         if (percpu) {
17891                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17892                 aux->btf_var.btf = btf;
17893                 aux->btf_var.btf_id = type;
17894         } else if (!btf_type_is_struct(t)) {
17895                 const struct btf_type *ret;
17896                 const char *tname;
17897                 u32 tsize;
17898
17899                 /* resolve the type size of ksym. */
17900                 ret = btf_resolve_size(btf, t, &tsize);
17901                 if (IS_ERR(ret)) {
17902                         tname = btf_name_by_offset(btf, t->name_off);
17903                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17904                                 tname, PTR_ERR(ret));
17905                         err = -EINVAL;
17906                         goto err_put;
17907                 }
17908                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17909                 aux->btf_var.mem_size = tsize;
17910         } else {
17911                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
17912                 aux->btf_var.btf = btf;
17913                 aux->btf_var.btf_id = type;
17914         }
17915 check_btf:
17916         /* check whether we recorded this BTF (and maybe module) already */
17917         for (i = 0; i < env->used_btf_cnt; i++) {
17918                 if (env->used_btfs[i].btf == btf) {
17919                         btf_put(btf);
17920                         return 0;
17921                 }
17922         }
17923
17924         if (env->used_btf_cnt >= MAX_USED_BTFS) {
17925                 err = -E2BIG;
17926                 goto err_put;
17927         }
17928
17929         btf_mod = &env->used_btfs[env->used_btf_cnt];
17930         btf_mod->btf = btf;
17931         btf_mod->module = NULL;
17932
17933         /* if we reference variables from kernel module, bump its refcount */
17934         if (btf_is_module(btf)) {
17935                 btf_mod->module = btf_try_get_module(btf);
17936                 if (!btf_mod->module) {
17937                         err = -ENXIO;
17938                         goto err_put;
17939                 }
17940         }
17941
17942         env->used_btf_cnt++;
17943
17944         return 0;
17945 err_put:
17946         btf_put(btf);
17947         return err;
17948 }
17949
17950 static bool is_tracing_prog_type(enum bpf_prog_type type)
17951 {
17952         switch (type) {
17953         case BPF_PROG_TYPE_KPROBE:
17954         case BPF_PROG_TYPE_TRACEPOINT:
17955         case BPF_PROG_TYPE_PERF_EVENT:
17956         case BPF_PROG_TYPE_RAW_TRACEPOINT:
17957         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17958                 return true;
17959         default:
17960                 return false;
17961         }
17962 }
17963
17964 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17965                                         struct bpf_map *map,
17966                                         struct bpf_prog *prog)
17967
17968 {
17969         enum bpf_prog_type prog_type = resolve_prog_type(prog);
17970
17971         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17972             btf_record_has_field(map->record, BPF_RB_ROOT)) {
17973                 if (is_tracing_prog_type(prog_type)) {
17974                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17975                         return -EINVAL;
17976                 }
17977         }
17978
17979         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17980                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17981                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17982                         return -EINVAL;
17983                 }
17984
17985                 if (is_tracing_prog_type(prog_type)) {
17986                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17987                         return -EINVAL;
17988                 }
17989         }
17990
17991         if (btf_record_has_field(map->record, BPF_TIMER)) {
17992                 if (is_tracing_prog_type(prog_type)) {
17993                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
17994                         return -EINVAL;
17995                 }
17996         }
17997
17998         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17999             !bpf_offload_prog_map_match(prog, map)) {
18000                 verbose(env, "offload device mismatch between prog and map\n");
18001                 return -EINVAL;
18002         }
18003
18004         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18005                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18006                 return -EINVAL;
18007         }
18008
18009         if (prog->aux->sleepable)
18010                 switch (map->map_type) {
18011                 case BPF_MAP_TYPE_HASH:
18012                 case BPF_MAP_TYPE_LRU_HASH:
18013                 case BPF_MAP_TYPE_ARRAY:
18014                 case BPF_MAP_TYPE_PERCPU_HASH:
18015                 case BPF_MAP_TYPE_PERCPU_ARRAY:
18016                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18017                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18018                 case BPF_MAP_TYPE_HASH_OF_MAPS:
18019                 case BPF_MAP_TYPE_RINGBUF:
18020                 case BPF_MAP_TYPE_USER_RINGBUF:
18021                 case BPF_MAP_TYPE_INODE_STORAGE:
18022                 case BPF_MAP_TYPE_SK_STORAGE:
18023                 case BPF_MAP_TYPE_TASK_STORAGE:
18024                 case BPF_MAP_TYPE_CGRP_STORAGE:
18025                 case BPF_MAP_TYPE_QUEUE:
18026                 case BPF_MAP_TYPE_STACK:
18027                         break;
18028                 default:
18029                         verbose(env,
18030                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18031                         return -EINVAL;
18032                 }
18033
18034         return 0;
18035 }
18036
18037 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18038 {
18039         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18040                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18041 }
18042
18043 /* find and rewrite pseudo imm in ld_imm64 instructions:
18044  *
18045  * 1. if it accesses map FD, replace it with actual map pointer.
18046  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18047  *
18048  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18049  */
18050 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18051 {
18052         struct bpf_insn *insn = env->prog->insnsi;
18053         int insn_cnt = env->prog->len;
18054         int i, j, err;
18055
18056         err = bpf_prog_calc_tag(env->prog);
18057         if (err)
18058                 return err;
18059
18060         for (i = 0; i < insn_cnt; i++, insn++) {
18061                 if (BPF_CLASS(insn->code) == BPF_LDX &&
18062                     ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18063                     insn->imm != 0)) {
18064                         verbose(env, "BPF_LDX uses reserved fields\n");
18065                         return -EINVAL;
18066                 }
18067
18068                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18069                         struct bpf_insn_aux_data *aux;
18070                         struct bpf_map *map;
18071                         struct fd f;
18072                         u64 addr;
18073                         u32 fd;
18074
18075                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
18076                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18077                             insn[1].off != 0) {
18078                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
18079                                 return -EINVAL;
18080                         }
18081
18082                         if (insn[0].src_reg == 0)
18083                                 /* valid generic load 64-bit imm */
18084                                 goto next_insn;
18085
18086                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18087                                 aux = &env->insn_aux_data[i];
18088                                 err = check_pseudo_btf_id(env, insn, aux);
18089                                 if (err)
18090                                         return err;
18091                                 goto next_insn;
18092                         }
18093
18094                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18095                                 aux = &env->insn_aux_data[i];
18096                                 aux->ptr_type = PTR_TO_FUNC;
18097                                 goto next_insn;
18098                         }
18099
18100                         /* In final convert_pseudo_ld_imm64() step, this is
18101                          * converted into regular 64-bit imm load insn.
18102                          */
18103                         switch (insn[0].src_reg) {
18104                         case BPF_PSEUDO_MAP_VALUE:
18105                         case BPF_PSEUDO_MAP_IDX_VALUE:
18106                                 break;
18107                         case BPF_PSEUDO_MAP_FD:
18108                         case BPF_PSEUDO_MAP_IDX:
18109                                 if (insn[1].imm == 0)
18110                                         break;
18111                                 fallthrough;
18112                         default:
18113                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18114                                 return -EINVAL;
18115                         }
18116
18117                         switch (insn[0].src_reg) {
18118                         case BPF_PSEUDO_MAP_IDX_VALUE:
18119                         case BPF_PSEUDO_MAP_IDX:
18120                                 if (bpfptr_is_null(env->fd_array)) {
18121                                         verbose(env, "fd_idx without fd_array is invalid\n");
18122                                         return -EPROTO;
18123                                 }
18124                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
18125                                                             insn[0].imm * sizeof(fd),
18126                                                             sizeof(fd)))
18127                                         return -EFAULT;
18128                                 break;
18129                         default:
18130                                 fd = insn[0].imm;
18131                                 break;
18132                         }
18133
18134                         f = fdget(fd);
18135                         map = __bpf_map_get(f);
18136                         if (IS_ERR(map)) {
18137                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
18138                                         insn[0].imm);
18139                                 return PTR_ERR(map);
18140                         }
18141
18142                         err = check_map_prog_compatibility(env, map, env->prog);
18143                         if (err) {
18144                                 fdput(f);
18145                                 return err;
18146                         }
18147
18148                         aux = &env->insn_aux_data[i];
18149                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18150                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18151                                 addr = (unsigned long)map;
18152                         } else {
18153                                 u32 off = insn[1].imm;
18154
18155                                 if (off >= BPF_MAX_VAR_OFF) {
18156                                         verbose(env, "direct value offset of %u is not allowed\n", off);
18157                                         fdput(f);
18158                                         return -EINVAL;
18159                                 }
18160
18161                                 if (!map->ops->map_direct_value_addr) {
18162                                         verbose(env, "no direct value access support for this map type\n");
18163                                         fdput(f);
18164                                         return -EINVAL;
18165                                 }
18166
18167                                 err = map->ops->map_direct_value_addr(map, &addr, off);
18168                                 if (err) {
18169                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18170                                                 map->value_size, off);
18171                                         fdput(f);
18172                                         return err;
18173                                 }
18174
18175                                 aux->map_off = off;
18176                                 addr += off;
18177                         }
18178
18179                         insn[0].imm = (u32)addr;
18180                         insn[1].imm = addr >> 32;
18181
18182                         /* check whether we recorded this map already */
18183                         for (j = 0; j < env->used_map_cnt; j++) {
18184                                 if (env->used_maps[j] == map) {
18185                                         aux->map_index = j;
18186                                         fdput(f);
18187                                         goto next_insn;
18188                                 }
18189                         }
18190
18191                         if (env->used_map_cnt >= MAX_USED_MAPS) {
18192                                 fdput(f);
18193                                 return -E2BIG;
18194                         }
18195
18196                         if (env->prog->aux->sleepable)
18197                                 atomic64_inc(&map->sleepable_refcnt);
18198                         /* hold the map. If the program is rejected by verifier,
18199                          * the map will be released by release_maps() or it
18200                          * will be used by the valid program until it's unloaded
18201                          * and all maps are released in bpf_free_used_maps()
18202                          */
18203                         bpf_map_inc(map);
18204
18205                         aux->map_index = env->used_map_cnt;
18206                         env->used_maps[env->used_map_cnt++] = map;
18207
18208                         if (bpf_map_is_cgroup_storage(map) &&
18209                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
18210                                 verbose(env, "only one cgroup storage of each type is allowed\n");
18211                                 fdput(f);
18212                                 return -EBUSY;
18213                         }
18214
18215                         fdput(f);
18216 next_insn:
18217                         insn++;
18218                         i++;
18219                         continue;
18220                 }
18221
18222                 /* Basic sanity check before we invest more work here. */
18223                 if (!bpf_opcode_in_insntable(insn->code)) {
18224                         verbose(env, "unknown opcode %02x\n", insn->code);
18225                         return -EINVAL;
18226                 }
18227         }
18228
18229         /* now all pseudo BPF_LD_IMM64 instructions load valid
18230          * 'struct bpf_map *' into a register instead of user map_fd.
18231          * These pointers will be used later by verifier to validate map access.
18232          */
18233         return 0;
18234 }
18235
18236 /* drop refcnt of maps used by the rejected program */
18237 static void release_maps(struct bpf_verifier_env *env)
18238 {
18239         __bpf_free_used_maps(env->prog->aux, env->used_maps,
18240                              env->used_map_cnt);
18241 }
18242
18243 /* drop refcnt of maps used by the rejected program */
18244 static void release_btfs(struct bpf_verifier_env *env)
18245 {
18246         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18247                              env->used_btf_cnt);
18248 }
18249
18250 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18251 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18252 {
18253         struct bpf_insn *insn = env->prog->insnsi;
18254         int insn_cnt = env->prog->len;
18255         int i;
18256
18257         for (i = 0; i < insn_cnt; i++, insn++) {
18258                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18259                         continue;
18260                 if (insn->src_reg == BPF_PSEUDO_FUNC)
18261                         continue;
18262                 insn->src_reg = 0;
18263         }
18264 }
18265
18266 /* single env->prog->insni[off] instruction was replaced with the range
18267  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18268  * [0, off) and [off, end) to new locations, so the patched range stays zero
18269  */
18270 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18271                                  struct bpf_insn_aux_data *new_data,
18272                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
18273 {
18274         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18275         struct bpf_insn *insn = new_prog->insnsi;
18276         u32 old_seen = old_data[off].seen;
18277         u32 prog_len;
18278         int i;
18279
18280         /* aux info at OFF always needs adjustment, no matter fast path
18281          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18282          * original insn at old prog.
18283          */
18284         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18285
18286         if (cnt == 1)
18287                 return;
18288         prog_len = new_prog->len;
18289
18290         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18291         memcpy(new_data + off + cnt - 1, old_data + off,
18292                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18293         for (i = off; i < off + cnt - 1; i++) {
18294                 /* Expand insni[off]'s seen count to the patched range. */
18295                 new_data[i].seen = old_seen;
18296                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18297         }
18298         env->insn_aux_data = new_data;
18299         vfree(old_data);
18300 }
18301
18302 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18303 {
18304         int i;
18305
18306         if (len == 1)
18307                 return;
18308         /* NOTE: fake 'exit' subprog should be updated as well. */
18309         for (i = 0; i <= env->subprog_cnt; i++) {
18310                 if (env->subprog_info[i].start <= off)
18311                         continue;
18312                 env->subprog_info[i].start += len - 1;
18313         }
18314 }
18315
18316 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18317 {
18318         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18319         int i, sz = prog->aux->size_poke_tab;
18320         struct bpf_jit_poke_descriptor *desc;
18321
18322         for (i = 0; i < sz; i++) {
18323                 desc = &tab[i];
18324                 if (desc->insn_idx <= off)
18325                         continue;
18326                 desc->insn_idx += len - 1;
18327         }
18328 }
18329
18330 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18331                                             const struct bpf_insn *patch, u32 len)
18332 {
18333         struct bpf_prog *new_prog;
18334         struct bpf_insn_aux_data *new_data = NULL;
18335
18336         if (len > 1) {
18337                 new_data = vzalloc(array_size(env->prog->len + len - 1,
18338                                               sizeof(struct bpf_insn_aux_data)));
18339                 if (!new_data)
18340                         return NULL;
18341         }
18342
18343         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18344         if (IS_ERR(new_prog)) {
18345                 if (PTR_ERR(new_prog) == -ERANGE)
18346                         verbose(env,
18347                                 "insn %d cannot be patched due to 16-bit range\n",
18348                                 env->insn_aux_data[off].orig_idx);
18349                 vfree(new_data);
18350                 return NULL;
18351         }
18352         adjust_insn_aux_data(env, new_data, new_prog, off, len);
18353         adjust_subprog_starts(env, off, len);
18354         adjust_poke_descs(new_prog, off, len);
18355         return new_prog;
18356 }
18357
18358 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18359                                               u32 off, u32 cnt)
18360 {
18361         int i, j;
18362
18363         /* find first prog starting at or after off (first to remove) */
18364         for (i = 0; i < env->subprog_cnt; i++)
18365                 if (env->subprog_info[i].start >= off)
18366                         break;
18367         /* find first prog starting at or after off + cnt (first to stay) */
18368         for (j = i; j < env->subprog_cnt; j++)
18369                 if (env->subprog_info[j].start >= off + cnt)
18370                         break;
18371         /* if j doesn't start exactly at off + cnt, we are just removing
18372          * the front of previous prog
18373          */
18374         if (env->subprog_info[j].start != off + cnt)
18375                 j--;
18376
18377         if (j > i) {
18378                 struct bpf_prog_aux *aux = env->prog->aux;
18379                 int move;
18380
18381                 /* move fake 'exit' subprog as well */
18382                 move = env->subprog_cnt + 1 - j;
18383
18384                 memmove(env->subprog_info + i,
18385                         env->subprog_info + j,
18386                         sizeof(*env->subprog_info) * move);
18387                 env->subprog_cnt -= j - i;
18388
18389                 /* remove func_info */
18390                 if (aux->func_info) {
18391                         move = aux->func_info_cnt - j;
18392
18393                         memmove(aux->func_info + i,
18394                                 aux->func_info + j,
18395                                 sizeof(*aux->func_info) * move);
18396                         aux->func_info_cnt -= j - i;
18397                         /* func_info->insn_off is set after all code rewrites,
18398                          * in adjust_btf_func() - no need to adjust
18399                          */
18400                 }
18401         } else {
18402                 /* convert i from "first prog to remove" to "first to adjust" */
18403                 if (env->subprog_info[i].start == off)
18404                         i++;
18405         }
18406
18407         /* update fake 'exit' subprog as well */
18408         for (; i <= env->subprog_cnt; i++)
18409                 env->subprog_info[i].start -= cnt;
18410
18411         return 0;
18412 }
18413
18414 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18415                                       u32 cnt)
18416 {
18417         struct bpf_prog *prog = env->prog;
18418         u32 i, l_off, l_cnt, nr_linfo;
18419         struct bpf_line_info *linfo;
18420
18421         nr_linfo = prog->aux->nr_linfo;
18422         if (!nr_linfo)
18423                 return 0;
18424
18425         linfo = prog->aux->linfo;
18426
18427         /* find first line info to remove, count lines to be removed */
18428         for (i = 0; i < nr_linfo; i++)
18429                 if (linfo[i].insn_off >= off)
18430                         break;
18431
18432         l_off = i;
18433         l_cnt = 0;
18434         for (; i < nr_linfo; i++)
18435                 if (linfo[i].insn_off < off + cnt)
18436                         l_cnt++;
18437                 else
18438                         break;
18439
18440         /* First live insn doesn't match first live linfo, it needs to "inherit"
18441          * last removed linfo.  prog is already modified, so prog->len == off
18442          * means no live instructions after (tail of the program was removed).
18443          */
18444         if (prog->len != off && l_cnt &&
18445             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18446                 l_cnt--;
18447                 linfo[--i].insn_off = off + cnt;
18448         }
18449
18450         /* remove the line info which refer to the removed instructions */
18451         if (l_cnt) {
18452                 memmove(linfo + l_off, linfo + i,
18453                         sizeof(*linfo) * (nr_linfo - i));
18454
18455                 prog->aux->nr_linfo -= l_cnt;
18456                 nr_linfo = prog->aux->nr_linfo;
18457         }
18458
18459         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18460         for (i = l_off; i < nr_linfo; i++)
18461                 linfo[i].insn_off -= cnt;
18462
18463         /* fix up all subprogs (incl. 'exit') which start >= off */
18464         for (i = 0; i <= env->subprog_cnt; i++)
18465                 if (env->subprog_info[i].linfo_idx > l_off) {
18466                         /* program may have started in the removed region but
18467                          * may not be fully removed
18468                          */
18469                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18470                                 env->subprog_info[i].linfo_idx -= l_cnt;
18471                         else
18472                                 env->subprog_info[i].linfo_idx = l_off;
18473                 }
18474
18475         return 0;
18476 }
18477
18478 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18479 {
18480         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18481         unsigned int orig_prog_len = env->prog->len;
18482         int err;
18483
18484         if (bpf_prog_is_offloaded(env->prog->aux))
18485                 bpf_prog_offload_remove_insns(env, off, cnt);
18486
18487         err = bpf_remove_insns(env->prog, off, cnt);
18488         if (err)
18489                 return err;
18490
18491         err = adjust_subprog_starts_after_remove(env, off, cnt);
18492         if (err)
18493                 return err;
18494
18495         err = bpf_adj_linfo_after_remove(env, off, cnt);
18496         if (err)
18497                 return err;
18498
18499         memmove(aux_data + off, aux_data + off + cnt,
18500                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18501
18502         return 0;
18503 }
18504
18505 /* The verifier does more data flow analysis than llvm and will not
18506  * explore branches that are dead at run time. Malicious programs can
18507  * have dead code too. Therefore replace all dead at-run-time code
18508  * with 'ja -1'.
18509  *
18510  * Just nops are not optimal, e.g. if they would sit at the end of the
18511  * program and through another bug we would manage to jump there, then
18512  * we'd execute beyond program memory otherwise. Returning exception
18513  * code also wouldn't work since we can have subprogs where the dead
18514  * code could be located.
18515  */
18516 static void sanitize_dead_code(struct bpf_verifier_env *env)
18517 {
18518         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18519         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18520         struct bpf_insn *insn = env->prog->insnsi;
18521         const int insn_cnt = env->prog->len;
18522         int i;
18523
18524         for (i = 0; i < insn_cnt; i++) {
18525                 if (aux_data[i].seen)
18526                         continue;
18527                 memcpy(insn + i, &trap, sizeof(trap));
18528                 aux_data[i].zext_dst = false;
18529         }
18530 }
18531
18532 static bool insn_is_cond_jump(u8 code)
18533 {
18534         u8 op;
18535
18536         op = BPF_OP(code);
18537         if (BPF_CLASS(code) == BPF_JMP32)
18538                 return op != BPF_JA;
18539
18540         if (BPF_CLASS(code) != BPF_JMP)
18541                 return false;
18542
18543         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18544 }
18545
18546 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18547 {
18548         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18549         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18550         struct bpf_insn *insn = env->prog->insnsi;
18551         const int insn_cnt = env->prog->len;
18552         int i;
18553
18554         for (i = 0; i < insn_cnt; i++, insn++) {
18555                 if (!insn_is_cond_jump(insn->code))
18556                         continue;
18557
18558                 if (!aux_data[i + 1].seen)
18559                         ja.off = insn->off;
18560                 else if (!aux_data[i + 1 + insn->off].seen)
18561                         ja.off = 0;
18562                 else
18563                         continue;
18564
18565                 if (bpf_prog_is_offloaded(env->prog->aux))
18566                         bpf_prog_offload_replace_insn(env, i, &ja);
18567
18568                 memcpy(insn, &ja, sizeof(ja));
18569         }
18570 }
18571
18572 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18573 {
18574         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18575         int insn_cnt = env->prog->len;
18576         int i, err;
18577
18578         for (i = 0; i < insn_cnt; i++) {
18579                 int j;
18580
18581                 j = 0;
18582                 while (i + j < insn_cnt && !aux_data[i + j].seen)
18583                         j++;
18584                 if (!j)
18585                         continue;
18586
18587                 err = verifier_remove_insns(env, i, j);
18588                 if (err)
18589                         return err;
18590                 insn_cnt = env->prog->len;
18591         }
18592
18593         return 0;
18594 }
18595
18596 static int opt_remove_nops(struct bpf_verifier_env *env)
18597 {
18598         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18599         struct bpf_insn *insn = env->prog->insnsi;
18600         int insn_cnt = env->prog->len;
18601         int i, err;
18602
18603         for (i = 0; i < insn_cnt; i++) {
18604                 if (memcmp(&insn[i], &ja, sizeof(ja)))
18605                         continue;
18606
18607                 err = verifier_remove_insns(env, i, 1);
18608                 if (err)
18609                         return err;
18610                 insn_cnt--;
18611                 i--;
18612         }
18613
18614         return 0;
18615 }
18616
18617 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18618                                          const union bpf_attr *attr)
18619 {
18620         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18621         struct bpf_insn_aux_data *aux = env->insn_aux_data;
18622         int i, patch_len, delta = 0, len = env->prog->len;
18623         struct bpf_insn *insns = env->prog->insnsi;
18624         struct bpf_prog *new_prog;
18625         bool rnd_hi32;
18626
18627         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18628         zext_patch[1] = BPF_ZEXT_REG(0);
18629         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18630         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18631         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18632         for (i = 0; i < len; i++) {
18633                 int adj_idx = i + delta;
18634                 struct bpf_insn insn;
18635                 int load_reg;
18636
18637                 insn = insns[adj_idx];
18638                 load_reg = insn_def_regno(&insn);
18639                 if (!aux[adj_idx].zext_dst) {
18640                         u8 code, class;
18641                         u32 imm_rnd;
18642
18643                         if (!rnd_hi32)
18644                                 continue;
18645
18646                         code = insn.code;
18647                         class = BPF_CLASS(code);
18648                         if (load_reg == -1)
18649                                 continue;
18650
18651                         /* NOTE: arg "reg" (the fourth one) is only used for
18652                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
18653                          *       here.
18654                          */
18655                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18656                                 if (class == BPF_LD &&
18657                                     BPF_MODE(code) == BPF_IMM)
18658                                         i++;
18659                                 continue;
18660                         }
18661
18662                         /* ctx load could be transformed into wider load. */
18663                         if (class == BPF_LDX &&
18664                             aux[adj_idx].ptr_type == PTR_TO_CTX)
18665                                 continue;
18666
18667                         imm_rnd = get_random_u32();
18668                         rnd_hi32_patch[0] = insn;
18669                         rnd_hi32_patch[1].imm = imm_rnd;
18670                         rnd_hi32_patch[3].dst_reg = load_reg;
18671                         patch = rnd_hi32_patch;
18672                         patch_len = 4;
18673                         goto apply_patch_buffer;
18674                 }
18675
18676                 /* Add in an zero-extend instruction if a) the JIT has requested
18677                  * it or b) it's a CMPXCHG.
18678                  *
18679                  * The latter is because: BPF_CMPXCHG always loads a value into
18680                  * R0, therefore always zero-extends. However some archs'
18681                  * equivalent instruction only does this load when the
18682                  * comparison is successful. This detail of CMPXCHG is
18683                  * orthogonal to the general zero-extension behaviour of the
18684                  * CPU, so it's treated independently of bpf_jit_needs_zext.
18685                  */
18686                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18687                         continue;
18688
18689                 /* Zero-extension is done by the caller. */
18690                 if (bpf_pseudo_kfunc_call(&insn))
18691                         continue;
18692
18693                 if (WARN_ON(load_reg == -1)) {
18694                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18695                         return -EFAULT;
18696                 }
18697
18698                 zext_patch[0] = insn;
18699                 zext_patch[1].dst_reg = load_reg;
18700                 zext_patch[1].src_reg = load_reg;
18701                 patch = zext_patch;
18702                 patch_len = 2;
18703 apply_patch_buffer:
18704                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18705                 if (!new_prog)
18706                         return -ENOMEM;
18707                 env->prog = new_prog;
18708                 insns = new_prog->insnsi;
18709                 aux = env->insn_aux_data;
18710                 delta += patch_len - 1;
18711         }
18712
18713         return 0;
18714 }
18715
18716 /* convert load instructions that access fields of a context type into a
18717  * sequence of instructions that access fields of the underlying structure:
18718  *     struct __sk_buff    -> struct sk_buff
18719  *     struct bpf_sock_ops -> struct sock
18720  */
18721 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18722 {
18723         const struct bpf_verifier_ops *ops = env->ops;
18724         int i, cnt, size, ctx_field_size, delta = 0;
18725         const int insn_cnt = env->prog->len;
18726         struct bpf_insn insn_buf[16], *insn;
18727         u32 target_size, size_default, off;
18728         struct bpf_prog *new_prog;
18729         enum bpf_access_type type;
18730         bool is_narrower_load;
18731
18732         if (ops->gen_prologue || env->seen_direct_write) {
18733                 if (!ops->gen_prologue) {
18734                         verbose(env, "bpf verifier is misconfigured\n");
18735                         return -EINVAL;
18736                 }
18737                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18738                                         env->prog);
18739                 if (cnt >= ARRAY_SIZE(insn_buf)) {
18740                         verbose(env, "bpf verifier is misconfigured\n");
18741                         return -EINVAL;
18742                 } else if (cnt) {
18743                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18744                         if (!new_prog)
18745                                 return -ENOMEM;
18746
18747                         env->prog = new_prog;
18748                         delta += cnt - 1;
18749                 }
18750         }
18751
18752         if (bpf_prog_is_offloaded(env->prog->aux))
18753                 return 0;
18754
18755         insn = env->prog->insnsi + delta;
18756
18757         for (i = 0; i < insn_cnt; i++, insn++) {
18758                 bpf_convert_ctx_access_t convert_ctx_access;
18759                 u8 mode;
18760
18761                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18762                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18763                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18764                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18765                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18766                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18767                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18768                         type = BPF_READ;
18769                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18770                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18771                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18772                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18773                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18774                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18775                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18776                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18777                         type = BPF_WRITE;
18778                 } else {
18779                         continue;
18780                 }
18781
18782                 if (type == BPF_WRITE &&
18783                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
18784                         struct bpf_insn patch[] = {
18785                                 *insn,
18786                                 BPF_ST_NOSPEC(),
18787                         };
18788
18789                         cnt = ARRAY_SIZE(patch);
18790                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18791                         if (!new_prog)
18792                                 return -ENOMEM;
18793
18794                         delta    += cnt - 1;
18795                         env->prog = new_prog;
18796                         insn      = new_prog->insnsi + i + delta;
18797                         continue;
18798                 }
18799
18800                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18801                 case PTR_TO_CTX:
18802                         if (!ops->convert_ctx_access)
18803                                 continue;
18804                         convert_ctx_access = ops->convert_ctx_access;
18805                         break;
18806                 case PTR_TO_SOCKET:
18807                 case PTR_TO_SOCK_COMMON:
18808                         convert_ctx_access = bpf_sock_convert_ctx_access;
18809                         break;
18810                 case PTR_TO_TCP_SOCK:
18811                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18812                         break;
18813                 case PTR_TO_XDP_SOCK:
18814                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18815                         break;
18816                 case PTR_TO_BTF_ID:
18817                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18818                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18819                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18820                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
18821                  * any faults for loads into such types. BPF_WRITE is disallowed
18822                  * for this case.
18823                  */
18824                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18825                         if (type == BPF_READ) {
18826                                 if (BPF_MODE(insn->code) == BPF_MEM)
18827                                         insn->code = BPF_LDX | BPF_PROBE_MEM |
18828                                                      BPF_SIZE((insn)->code);
18829                                 else
18830                                         insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18831                                                      BPF_SIZE((insn)->code);
18832                                 env->prog->aux->num_exentries++;
18833                         }
18834                         continue;
18835                 default:
18836                         continue;
18837                 }
18838
18839                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18840                 size = BPF_LDST_BYTES(insn);
18841                 mode = BPF_MODE(insn->code);
18842
18843                 /* If the read access is a narrower load of the field,
18844                  * convert to a 4/8-byte load, to minimum program type specific
18845                  * convert_ctx_access changes. If conversion is successful,
18846                  * we will apply proper mask to the result.
18847                  */
18848                 is_narrower_load = size < ctx_field_size;
18849                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18850                 off = insn->off;
18851                 if (is_narrower_load) {
18852                         u8 size_code;
18853
18854                         if (type == BPF_WRITE) {
18855                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18856                                 return -EINVAL;
18857                         }
18858
18859                         size_code = BPF_H;
18860                         if (ctx_field_size == 4)
18861                                 size_code = BPF_W;
18862                         else if (ctx_field_size == 8)
18863                                 size_code = BPF_DW;
18864
18865                         insn->off = off & ~(size_default - 1);
18866                         insn->code = BPF_LDX | BPF_MEM | size_code;
18867                 }
18868
18869                 target_size = 0;
18870                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18871                                          &target_size);
18872                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18873                     (ctx_field_size && !target_size)) {
18874                         verbose(env, "bpf verifier is misconfigured\n");
18875                         return -EINVAL;
18876                 }
18877
18878                 if (is_narrower_load && size < target_size) {
18879                         u8 shift = bpf_ctx_narrow_access_offset(
18880                                 off, size, size_default) * 8;
18881                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18882                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18883                                 return -EINVAL;
18884                         }
18885                         if (ctx_field_size <= 4) {
18886                                 if (shift)
18887                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18888                                                                         insn->dst_reg,
18889                                                                         shift);
18890                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18891                                                                 (1 << size * 8) - 1);
18892                         } else {
18893                                 if (shift)
18894                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18895                                                                         insn->dst_reg,
18896                                                                         shift);
18897                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18898                                                                 (1ULL << size * 8) - 1);
18899                         }
18900                 }
18901                 if (mode == BPF_MEMSX)
18902                         insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18903                                                        insn->dst_reg, insn->dst_reg,
18904                                                        size * 8, 0);
18905
18906                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18907                 if (!new_prog)
18908                         return -ENOMEM;
18909
18910                 delta += cnt - 1;
18911
18912                 /* keep walking new program and skip insns we just inserted */
18913                 env->prog = new_prog;
18914                 insn      = new_prog->insnsi + i + delta;
18915         }
18916
18917         return 0;
18918 }
18919
18920 static int jit_subprogs(struct bpf_verifier_env *env)
18921 {
18922         struct bpf_prog *prog = env->prog, **func, *tmp;
18923         int i, j, subprog_start, subprog_end = 0, len, subprog;
18924         struct bpf_map *map_ptr;
18925         struct bpf_insn *insn;
18926         void *old_bpf_func;
18927         int err, num_exentries;
18928
18929         if (env->subprog_cnt <= 1)
18930                 return 0;
18931
18932         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18933                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18934                         continue;
18935
18936                 /* Upon error here we cannot fall back to interpreter but
18937                  * need a hard reject of the program. Thus -EFAULT is
18938                  * propagated in any case.
18939                  */
18940                 subprog = find_subprog(env, i + insn->imm + 1);
18941                 if (subprog < 0) {
18942                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18943                                   i + insn->imm + 1);
18944                         return -EFAULT;
18945                 }
18946                 /* temporarily remember subprog id inside insn instead of
18947                  * aux_data, since next loop will split up all insns into funcs
18948                  */
18949                 insn->off = subprog;
18950                 /* remember original imm in case JIT fails and fallback
18951                  * to interpreter will be needed
18952                  */
18953                 env->insn_aux_data[i].call_imm = insn->imm;
18954                 /* point imm to __bpf_call_base+1 from JITs point of view */
18955                 insn->imm = 1;
18956                 if (bpf_pseudo_func(insn))
18957                         /* jit (e.g. x86_64) may emit fewer instructions
18958                          * if it learns a u32 imm is the same as a u64 imm.
18959                          * Force a non zero here.
18960                          */
18961                         insn[1].imm = 1;
18962         }
18963
18964         err = bpf_prog_alloc_jited_linfo(prog);
18965         if (err)
18966                 goto out_undo_insn;
18967
18968         err = -ENOMEM;
18969         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18970         if (!func)
18971                 goto out_undo_insn;
18972
18973         for (i = 0; i < env->subprog_cnt; i++) {
18974                 subprog_start = subprog_end;
18975                 subprog_end = env->subprog_info[i + 1].start;
18976
18977                 len = subprog_end - subprog_start;
18978                 /* bpf_prog_run() doesn't call subprogs directly,
18979                  * hence main prog stats include the runtime of subprogs.
18980                  * subprogs don't have IDs and not reachable via prog_get_next_id
18981                  * func[i]->stats will never be accessed and stays NULL
18982                  */
18983                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18984                 if (!func[i])
18985                         goto out_free;
18986                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18987                        len * sizeof(struct bpf_insn));
18988                 func[i]->type = prog->type;
18989                 func[i]->len = len;
18990                 if (bpf_prog_calc_tag(func[i]))
18991                         goto out_free;
18992                 func[i]->is_func = 1;
18993                 func[i]->aux->func_idx = i;
18994                 /* Below members will be freed only at prog->aux */
18995                 func[i]->aux->btf = prog->aux->btf;
18996                 func[i]->aux->func_info = prog->aux->func_info;
18997                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18998                 func[i]->aux->poke_tab = prog->aux->poke_tab;
18999                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19000
19001                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
19002                         struct bpf_jit_poke_descriptor *poke;
19003
19004                         poke = &prog->aux->poke_tab[j];
19005                         if (poke->insn_idx < subprog_end &&
19006                             poke->insn_idx >= subprog_start)
19007                                 poke->aux = func[i]->aux;
19008                 }
19009
19010                 func[i]->aux->name[0] = 'F';
19011                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19012                 func[i]->jit_requested = 1;
19013                 func[i]->blinding_requested = prog->blinding_requested;
19014                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19015                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19016                 func[i]->aux->linfo = prog->aux->linfo;
19017                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19018                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19019                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19020                 num_exentries = 0;
19021                 insn = func[i]->insnsi;
19022                 for (j = 0; j < func[i]->len; j++, insn++) {
19023                         if (BPF_CLASS(insn->code) == BPF_LDX &&
19024                             (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19025                              BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19026                                 num_exentries++;
19027                 }
19028                 func[i]->aux->num_exentries = num_exentries;
19029                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19030                 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19031                 if (!i)
19032                         func[i]->aux->exception_boundary = env->seen_exception;
19033                 func[i] = bpf_int_jit_compile(func[i]);
19034                 if (!func[i]->jited) {
19035                         err = -ENOTSUPP;
19036                         goto out_free;
19037                 }
19038                 cond_resched();
19039         }
19040
19041         /* at this point all bpf functions were successfully JITed
19042          * now populate all bpf_calls with correct addresses and
19043          * run last pass of JIT
19044          */
19045         for (i = 0; i < env->subprog_cnt; i++) {
19046                 insn = func[i]->insnsi;
19047                 for (j = 0; j < func[i]->len; j++, insn++) {
19048                         if (bpf_pseudo_func(insn)) {
19049                                 subprog = insn->off;
19050                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19051                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19052                                 continue;
19053                         }
19054                         if (!bpf_pseudo_call(insn))
19055                                 continue;
19056                         subprog = insn->off;
19057                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19058                 }
19059
19060                 /* we use the aux data to keep a list of the start addresses
19061                  * of the JITed images for each function in the program
19062                  *
19063                  * for some architectures, such as powerpc64, the imm field
19064                  * might not be large enough to hold the offset of the start
19065                  * address of the callee's JITed image from __bpf_call_base
19066                  *
19067                  * in such cases, we can lookup the start address of a callee
19068                  * by using its subprog id, available from the off field of
19069                  * the call instruction, as an index for this list
19070                  */
19071                 func[i]->aux->func = func;
19072                 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19073                 func[i]->aux->real_func_cnt = env->subprog_cnt;
19074         }
19075         for (i = 0; i < env->subprog_cnt; i++) {
19076                 old_bpf_func = func[i]->bpf_func;
19077                 tmp = bpf_int_jit_compile(func[i]);
19078                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19079                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19080                         err = -ENOTSUPP;
19081                         goto out_free;
19082                 }
19083                 cond_resched();
19084         }
19085
19086         /* finally lock prog and jit images for all functions and
19087          * populate kallsysm. Begin at the first subprogram, since
19088          * bpf_prog_load will add the kallsyms for the main program.
19089          */
19090         for (i = 1; i < env->subprog_cnt; i++) {
19091                 bpf_prog_lock_ro(func[i]);
19092                 bpf_prog_kallsyms_add(func[i]);
19093         }
19094
19095         /* Last step: make now unused interpreter insns from main
19096          * prog consistent for later dump requests, so they can
19097          * later look the same as if they were interpreted only.
19098          */
19099         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19100                 if (bpf_pseudo_func(insn)) {
19101                         insn[0].imm = env->insn_aux_data[i].call_imm;
19102                         insn[1].imm = insn->off;
19103                         insn->off = 0;
19104                         continue;
19105                 }
19106                 if (!bpf_pseudo_call(insn))
19107                         continue;
19108                 insn->off = env->insn_aux_data[i].call_imm;
19109                 subprog = find_subprog(env, i + insn->off + 1);
19110                 insn->imm = subprog;
19111         }
19112
19113         prog->jited = 1;
19114         prog->bpf_func = func[0]->bpf_func;
19115         prog->jited_len = func[0]->jited_len;
19116         prog->aux->extable = func[0]->aux->extable;
19117         prog->aux->num_exentries = func[0]->aux->num_exentries;
19118         prog->aux->func = func;
19119         prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19120         prog->aux->real_func_cnt = env->subprog_cnt;
19121         prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19122         prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19123         bpf_prog_jit_attempt_done(prog);
19124         return 0;
19125 out_free:
19126         /* We failed JIT'ing, so at this point we need to unregister poke
19127          * descriptors from subprogs, so that kernel is not attempting to
19128          * patch it anymore as we're freeing the subprog JIT memory.
19129          */
19130         for (i = 0; i < prog->aux->size_poke_tab; i++) {
19131                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19132                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19133         }
19134         /* At this point we're guaranteed that poke descriptors are not
19135          * live anymore. We can just unlink its descriptor table as it's
19136          * released with the main prog.
19137          */
19138         for (i = 0; i < env->subprog_cnt; i++) {
19139                 if (!func[i])
19140                         continue;
19141                 func[i]->aux->poke_tab = NULL;
19142                 bpf_jit_free(func[i]);
19143         }
19144         kfree(func);
19145 out_undo_insn:
19146         /* cleanup main prog to be interpreted */
19147         prog->jit_requested = 0;
19148         prog->blinding_requested = 0;
19149         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19150                 if (!bpf_pseudo_call(insn))
19151                         continue;
19152                 insn->off = 0;
19153                 insn->imm = env->insn_aux_data[i].call_imm;
19154         }
19155         bpf_prog_jit_attempt_done(prog);
19156         return err;
19157 }
19158
19159 static int fixup_call_args(struct bpf_verifier_env *env)
19160 {
19161 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19162         struct bpf_prog *prog = env->prog;
19163         struct bpf_insn *insn = prog->insnsi;
19164         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19165         int i, depth;
19166 #endif
19167         int err = 0;
19168
19169         if (env->prog->jit_requested &&
19170             !bpf_prog_is_offloaded(env->prog->aux)) {
19171                 err = jit_subprogs(env);
19172                 if (err == 0)
19173                         return 0;
19174                 if (err == -EFAULT)
19175                         return err;
19176         }
19177 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19178         if (has_kfunc_call) {
19179                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19180                 return -EINVAL;
19181         }
19182         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19183                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
19184                  * have to be rejected, since interpreter doesn't support them yet.
19185                  */
19186                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19187                 return -EINVAL;
19188         }
19189         for (i = 0; i < prog->len; i++, insn++) {
19190                 if (bpf_pseudo_func(insn)) {
19191                         /* When JIT fails the progs with callback calls
19192                          * have to be rejected, since interpreter doesn't support them yet.
19193                          */
19194                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
19195                         return -EINVAL;
19196                 }
19197
19198                 if (!bpf_pseudo_call(insn))
19199                         continue;
19200                 depth = get_callee_stack_depth(env, insn, i);
19201                 if (depth < 0)
19202                         return depth;
19203                 bpf_patch_call_args(insn, depth);
19204         }
19205         err = 0;
19206 #endif
19207         return err;
19208 }
19209
19210 /* replace a generic kfunc with a specialized version if necessary */
19211 static void specialize_kfunc(struct bpf_verifier_env *env,
19212                              u32 func_id, u16 offset, unsigned long *addr)
19213 {
19214         struct bpf_prog *prog = env->prog;
19215         bool seen_direct_write;
19216         void *xdp_kfunc;
19217         bool is_rdonly;
19218
19219         if (bpf_dev_bound_kfunc_id(func_id)) {
19220                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19221                 if (xdp_kfunc) {
19222                         *addr = (unsigned long)xdp_kfunc;
19223                         return;
19224                 }
19225                 /* fallback to default kfunc when not supported by netdev */
19226         }
19227
19228         if (offset)
19229                 return;
19230
19231         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19232                 seen_direct_write = env->seen_direct_write;
19233                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19234
19235                 if (is_rdonly)
19236                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19237
19238                 /* restore env->seen_direct_write to its original value, since
19239                  * may_access_direct_pkt_data mutates it
19240                  */
19241                 env->seen_direct_write = seen_direct_write;
19242         }
19243 }
19244
19245 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19246                                             u16 struct_meta_reg,
19247                                             u16 node_offset_reg,
19248                                             struct bpf_insn *insn,
19249                                             struct bpf_insn *insn_buf,
19250                                             int *cnt)
19251 {
19252         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19253         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19254
19255         insn_buf[0] = addr[0];
19256         insn_buf[1] = addr[1];
19257         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19258         insn_buf[3] = *insn;
19259         *cnt = 4;
19260 }
19261
19262 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19263                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19264 {
19265         const struct bpf_kfunc_desc *desc;
19266
19267         if (!insn->imm) {
19268                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19269                 return -EINVAL;
19270         }
19271
19272         *cnt = 0;
19273
19274         /* insn->imm has the btf func_id. Replace it with an offset relative to
19275          * __bpf_call_base, unless the JIT needs to call functions that are
19276          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19277          */
19278         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19279         if (!desc) {
19280                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19281                         insn->imm);
19282                 return -EFAULT;
19283         }
19284
19285         if (!bpf_jit_supports_far_kfunc_call())
19286                 insn->imm = BPF_CALL_IMM(desc->addr);
19287         if (insn->off)
19288                 return 0;
19289         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19290             desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19291                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19292                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19293                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19294
19295                 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19296                         verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19297                                 insn_idx);
19298                         return -EFAULT;
19299                 }
19300
19301                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19302                 insn_buf[1] = addr[0];
19303                 insn_buf[2] = addr[1];
19304                 insn_buf[3] = *insn;
19305                 *cnt = 4;
19306         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19307                    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19308                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19309                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19310                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19311
19312                 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19313                         verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19314                                 insn_idx);
19315                         return -EFAULT;
19316                 }
19317
19318                 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19319                     !kptr_struct_meta) {
19320                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19321                                 insn_idx);
19322                         return -EFAULT;
19323                 }
19324
19325                 insn_buf[0] = addr[0];
19326                 insn_buf[1] = addr[1];
19327                 insn_buf[2] = *insn;
19328                 *cnt = 3;
19329         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19330                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19331                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19332                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19333                 int struct_meta_reg = BPF_REG_3;
19334                 int node_offset_reg = BPF_REG_4;
19335
19336                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19337                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19338                         struct_meta_reg = BPF_REG_4;
19339                         node_offset_reg = BPF_REG_5;
19340                 }
19341
19342                 if (!kptr_struct_meta) {
19343                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19344                                 insn_idx);
19345                         return -EFAULT;
19346                 }
19347
19348                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19349                                                 node_offset_reg, insn, insn_buf, cnt);
19350         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19351                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19352                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19353                 *cnt = 1;
19354         }
19355         return 0;
19356 }
19357
19358 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19359 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19360 {
19361         struct bpf_subprog_info *info = env->subprog_info;
19362         int cnt = env->subprog_cnt;
19363         struct bpf_prog *prog;
19364
19365         /* We only reserve one slot for hidden subprogs in subprog_info. */
19366         if (env->hidden_subprog_cnt) {
19367                 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19368                 return -EFAULT;
19369         }
19370         /* We're not patching any existing instruction, just appending the new
19371          * ones for the hidden subprog. Hence all of the adjustment operations
19372          * in bpf_patch_insn_data are no-ops.
19373          */
19374         prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19375         if (!prog)
19376                 return -ENOMEM;
19377         env->prog = prog;
19378         info[cnt + 1].start = info[cnt].start;
19379         info[cnt].start = prog->len - len + 1;
19380         env->subprog_cnt++;
19381         env->hidden_subprog_cnt++;
19382         return 0;
19383 }
19384
19385 /* Do various post-verification rewrites in a single program pass.
19386  * These rewrites simplify JIT and interpreter implementations.
19387  */
19388 static int do_misc_fixups(struct bpf_verifier_env *env)
19389 {
19390         struct bpf_prog *prog = env->prog;
19391         enum bpf_attach_type eatype = prog->expected_attach_type;
19392         enum bpf_prog_type prog_type = resolve_prog_type(prog);
19393         struct bpf_insn *insn = prog->insnsi;
19394         const struct bpf_func_proto *fn;
19395         const int insn_cnt = prog->len;
19396         const struct bpf_map_ops *ops;
19397         struct bpf_insn_aux_data *aux;
19398         struct bpf_insn insn_buf[16];
19399         struct bpf_prog *new_prog;
19400         struct bpf_map *map_ptr;
19401         int i, ret, cnt, delta = 0;
19402
19403         if (env->seen_exception && !env->exception_callback_subprog) {
19404                 struct bpf_insn patch[] = {
19405                         env->prog->insnsi[insn_cnt - 1],
19406                         BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19407                         BPF_EXIT_INSN(),
19408                 };
19409
19410                 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19411                 if (ret < 0)
19412                         return ret;
19413                 prog = env->prog;
19414                 insn = prog->insnsi;
19415
19416                 env->exception_callback_subprog = env->subprog_cnt - 1;
19417                 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19418                 mark_subprog_exc_cb(env, env->exception_callback_subprog);
19419         }
19420
19421         for (i = 0; i < insn_cnt; i++, insn++) {
19422                 /* Make divide-by-zero exceptions impossible. */
19423                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19424                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19425                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19426                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19427                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19428                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19429                         struct bpf_insn *patchlet;
19430                         struct bpf_insn chk_and_div[] = {
19431                                 /* [R,W]x div 0 -> 0 */
19432                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19433                                              BPF_JNE | BPF_K, insn->src_reg,
19434                                              0, 2, 0),
19435                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19436                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19437                                 *insn,
19438                         };
19439                         struct bpf_insn chk_and_mod[] = {
19440                                 /* [R,W]x mod 0 -> [R,W]x */
19441                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19442                                              BPF_JEQ | BPF_K, insn->src_reg,
19443                                              0, 1 + (is64 ? 0 : 1), 0),
19444                                 *insn,
19445                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19446                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19447                         };
19448
19449                         patchlet = isdiv ? chk_and_div : chk_and_mod;
19450                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19451                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19452
19453                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19454                         if (!new_prog)
19455                                 return -ENOMEM;
19456
19457                         delta    += cnt - 1;
19458                         env->prog = prog = new_prog;
19459                         insn      = new_prog->insnsi + i + delta;
19460                         continue;
19461                 }
19462
19463                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19464                 if (BPF_CLASS(insn->code) == BPF_LD &&
19465                     (BPF_MODE(insn->code) == BPF_ABS ||
19466                      BPF_MODE(insn->code) == BPF_IND)) {
19467                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
19468                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19469                                 verbose(env, "bpf verifier is misconfigured\n");
19470                                 return -EINVAL;
19471                         }
19472
19473                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19474                         if (!new_prog)
19475                                 return -ENOMEM;
19476
19477                         delta    += cnt - 1;
19478                         env->prog = prog = new_prog;
19479                         insn      = new_prog->insnsi + i + delta;
19480                         continue;
19481                 }
19482
19483                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
19484                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19485                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19486                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19487                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19488                         struct bpf_insn *patch = &insn_buf[0];
19489                         bool issrc, isneg, isimm;
19490                         u32 off_reg;
19491
19492                         aux = &env->insn_aux_data[i + delta];
19493                         if (!aux->alu_state ||
19494                             aux->alu_state == BPF_ALU_NON_POINTER)
19495                                 continue;
19496
19497                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19498                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19499                                 BPF_ALU_SANITIZE_SRC;
19500                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19501
19502                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
19503                         if (isimm) {
19504                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19505                         } else {
19506                                 if (isneg)
19507                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19508                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19509                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19510                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19511                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19512                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19513                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19514                         }
19515                         if (!issrc)
19516                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19517                         insn->src_reg = BPF_REG_AX;
19518                         if (isneg)
19519                                 insn->code = insn->code == code_add ?
19520                                              code_sub : code_add;
19521                         *patch++ = *insn;
19522                         if (issrc && isneg && !isimm)
19523                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19524                         cnt = patch - insn_buf;
19525
19526                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19527                         if (!new_prog)
19528                                 return -ENOMEM;
19529
19530                         delta    += cnt - 1;
19531                         env->prog = prog = new_prog;
19532                         insn      = new_prog->insnsi + i + delta;
19533                         continue;
19534                 }
19535
19536                 if (insn->code != (BPF_JMP | BPF_CALL))
19537                         continue;
19538                 if (insn->src_reg == BPF_PSEUDO_CALL)
19539                         continue;
19540                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19541                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19542                         if (ret)
19543                                 return ret;
19544                         if (cnt == 0)
19545                                 continue;
19546
19547                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19548                         if (!new_prog)
19549                                 return -ENOMEM;
19550
19551                         delta    += cnt - 1;
19552                         env->prog = prog = new_prog;
19553                         insn      = new_prog->insnsi + i + delta;
19554                         continue;
19555                 }
19556
19557                 if (insn->imm == BPF_FUNC_get_route_realm)
19558                         prog->dst_needed = 1;
19559                 if (insn->imm == BPF_FUNC_get_prandom_u32)
19560                         bpf_user_rnd_init_once();
19561                 if (insn->imm == BPF_FUNC_override_return)
19562                         prog->kprobe_override = 1;
19563                 if (insn->imm == BPF_FUNC_tail_call) {
19564                         /* If we tail call into other programs, we
19565                          * cannot make any assumptions since they can
19566                          * be replaced dynamically during runtime in
19567                          * the program array.
19568                          */
19569                         prog->cb_access = 1;
19570                         if (!allow_tail_call_in_subprogs(env))
19571                                 prog->aux->stack_depth = MAX_BPF_STACK;
19572                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19573
19574                         /* mark bpf_tail_call as different opcode to avoid
19575                          * conditional branch in the interpreter for every normal
19576                          * call and to prevent accidental JITing by JIT compiler
19577                          * that doesn't support bpf_tail_call yet
19578                          */
19579                         insn->imm = 0;
19580                         insn->code = BPF_JMP | BPF_TAIL_CALL;
19581
19582                         aux = &env->insn_aux_data[i + delta];
19583                         if (env->bpf_capable && !prog->blinding_requested &&
19584                             prog->jit_requested &&
19585                             !bpf_map_key_poisoned(aux) &&
19586                             !bpf_map_ptr_poisoned(aux) &&
19587                             !bpf_map_ptr_unpriv(aux)) {
19588                                 struct bpf_jit_poke_descriptor desc = {
19589                                         .reason = BPF_POKE_REASON_TAIL_CALL,
19590                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19591                                         .tail_call.key = bpf_map_key_immediate(aux),
19592                                         .insn_idx = i + delta,
19593                                 };
19594
19595                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19596                                 if (ret < 0) {
19597                                         verbose(env, "adding tail call poke descriptor failed\n");
19598                                         return ret;
19599                                 }
19600
19601                                 insn->imm = ret + 1;
19602                                 continue;
19603                         }
19604
19605                         if (!bpf_map_ptr_unpriv(aux))
19606                                 continue;
19607
19608                         /* instead of changing every JIT dealing with tail_call
19609                          * emit two extra insns:
19610                          * if (index >= max_entries) goto out;
19611                          * index &= array->index_mask;
19612                          * to avoid out-of-bounds cpu speculation
19613                          */
19614                         if (bpf_map_ptr_poisoned(aux)) {
19615                                 verbose(env, "tail_call abusing map_ptr\n");
19616                                 return -EINVAL;
19617                         }
19618
19619                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19620                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19621                                                   map_ptr->max_entries, 2);
19622                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19623                                                     container_of(map_ptr,
19624                                                                  struct bpf_array,
19625                                                                  map)->index_mask);
19626                         insn_buf[2] = *insn;
19627                         cnt = 3;
19628                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19629                         if (!new_prog)
19630                                 return -ENOMEM;
19631
19632                         delta    += cnt - 1;
19633                         env->prog = prog = new_prog;
19634                         insn      = new_prog->insnsi + i + delta;
19635                         continue;
19636                 }
19637
19638                 if (insn->imm == BPF_FUNC_timer_set_callback) {
19639                         /* The verifier will process callback_fn as many times as necessary
19640                          * with different maps and the register states prepared by
19641                          * set_timer_callback_state will be accurate.
19642                          *
19643                          * The following use case is valid:
19644                          *   map1 is shared by prog1, prog2, prog3.
19645                          *   prog1 calls bpf_timer_init for some map1 elements
19646                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
19647                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
19648                          *   prog3 calls bpf_timer_start for some map1 elements.
19649                          *     Those that were not both bpf_timer_init-ed and
19650                          *     bpf_timer_set_callback-ed will return -EINVAL.
19651                          */
19652                         struct bpf_insn ld_addrs[2] = {
19653                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19654                         };
19655
19656                         insn_buf[0] = ld_addrs[0];
19657                         insn_buf[1] = ld_addrs[1];
19658                         insn_buf[2] = *insn;
19659                         cnt = 3;
19660
19661                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19662                         if (!new_prog)
19663                                 return -ENOMEM;
19664
19665                         delta    += cnt - 1;
19666                         env->prog = prog = new_prog;
19667                         insn      = new_prog->insnsi + i + delta;
19668                         goto patch_call_imm;
19669                 }
19670
19671                 if (is_storage_get_function(insn->imm)) {
19672                         if (!env->prog->aux->sleepable ||
19673                             env->insn_aux_data[i + delta].storage_get_func_atomic)
19674                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19675                         else
19676                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19677                         insn_buf[1] = *insn;
19678                         cnt = 2;
19679
19680                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19681                         if (!new_prog)
19682                                 return -ENOMEM;
19683
19684                         delta += cnt - 1;
19685                         env->prog = prog = new_prog;
19686                         insn = new_prog->insnsi + i + delta;
19687                         goto patch_call_imm;
19688                 }
19689
19690                 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19691                 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19692                         /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19693                          * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19694                          */
19695                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19696                         insn_buf[1] = *insn;
19697                         cnt = 2;
19698
19699                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19700                         if (!new_prog)
19701                                 return -ENOMEM;
19702
19703                         delta += cnt - 1;
19704                         env->prog = prog = new_prog;
19705                         insn = new_prog->insnsi + i + delta;
19706                         goto patch_call_imm;
19707                 }
19708
19709                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19710                  * and other inlining handlers are currently limited to 64 bit
19711                  * only.
19712                  */
19713                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19714                     (insn->imm == BPF_FUNC_map_lookup_elem ||
19715                      insn->imm == BPF_FUNC_map_update_elem ||
19716                      insn->imm == BPF_FUNC_map_delete_elem ||
19717                      insn->imm == BPF_FUNC_map_push_elem   ||
19718                      insn->imm == BPF_FUNC_map_pop_elem    ||
19719                      insn->imm == BPF_FUNC_map_peek_elem   ||
19720                      insn->imm == BPF_FUNC_redirect_map    ||
19721                      insn->imm == BPF_FUNC_for_each_map_elem ||
19722                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19723                         aux = &env->insn_aux_data[i + delta];
19724                         if (bpf_map_ptr_poisoned(aux))
19725                                 goto patch_call_imm;
19726
19727                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19728                         ops = map_ptr->ops;
19729                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
19730                             ops->map_gen_lookup) {
19731                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19732                                 if (cnt == -EOPNOTSUPP)
19733                                         goto patch_map_ops_generic;
19734                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19735                                         verbose(env, "bpf verifier is misconfigured\n");
19736                                         return -EINVAL;
19737                                 }
19738
19739                                 new_prog = bpf_patch_insn_data(env, i + delta,
19740                                                                insn_buf, cnt);
19741                                 if (!new_prog)
19742                                         return -ENOMEM;
19743
19744                                 delta    += cnt - 1;
19745                                 env->prog = prog = new_prog;
19746                                 insn      = new_prog->insnsi + i + delta;
19747                                 continue;
19748                         }
19749
19750                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19751                                      (void *(*)(struct bpf_map *map, void *key))NULL));
19752                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19753                                      (long (*)(struct bpf_map *map, void *key))NULL));
19754                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19755                                      (long (*)(struct bpf_map *map, void *key, void *value,
19756                                               u64 flags))NULL));
19757                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19758                                      (long (*)(struct bpf_map *map, void *value,
19759                                               u64 flags))NULL));
19760                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19761                                      (long (*)(struct bpf_map *map, void *value))NULL));
19762                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19763                                      (long (*)(struct bpf_map *map, void *value))NULL));
19764                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
19765                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19766                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19767                                      (long (*)(struct bpf_map *map,
19768                                               bpf_callback_t callback_fn,
19769                                               void *callback_ctx,
19770                                               u64 flags))NULL));
19771                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19772                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19773
19774 patch_map_ops_generic:
19775                         switch (insn->imm) {
19776                         case BPF_FUNC_map_lookup_elem:
19777                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19778                                 continue;
19779                         case BPF_FUNC_map_update_elem:
19780                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19781                                 continue;
19782                         case BPF_FUNC_map_delete_elem:
19783                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19784                                 continue;
19785                         case BPF_FUNC_map_push_elem:
19786                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19787                                 continue;
19788                         case BPF_FUNC_map_pop_elem:
19789                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19790                                 continue;
19791                         case BPF_FUNC_map_peek_elem:
19792                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19793                                 continue;
19794                         case BPF_FUNC_redirect_map:
19795                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
19796                                 continue;
19797                         case BPF_FUNC_for_each_map_elem:
19798                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19799                                 continue;
19800                         case BPF_FUNC_map_lookup_percpu_elem:
19801                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19802                                 continue;
19803                         }
19804
19805                         goto patch_call_imm;
19806                 }
19807
19808                 /* Implement bpf_jiffies64 inline. */
19809                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19810                     insn->imm == BPF_FUNC_jiffies64) {
19811                         struct bpf_insn ld_jiffies_addr[2] = {
19812                                 BPF_LD_IMM64(BPF_REG_0,
19813                                              (unsigned long)&jiffies),
19814                         };
19815
19816                         insn_buf[0] = ld_jiffies_addr[0];
19817                         insn_buf[1] = ld_jiffies_addr[1];
19818                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19819                                                   BPF_REG_0, 0);
19820                         cnt = 3;
19821
19822                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19823                                                        cnt);
19824                         if (!new_prog)
19825                                 return -ENOMEM;
19826
19827                         delta    += cnt - 1;
19828                         env->prog = prog = new_prog;
19829                         insn      = new_prog->insnsi + i + delta;
19830                         continue;
19831                 }
19832
19833                 /* Implement bpf_get_func_arg inline. */
19834                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19835                     insn->imm == BPF_FUNC_get_func_arg) {
19836                         /* Load nr_args from ctx - 8 */
19837                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19838                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19839                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19840                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19841                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19842                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19843                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19844                         insn_buf[7] = BPF_JMP_A(1);
19845                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19846                         cnt = 9;
19847
19848                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19849                         if (!new_prog)
19850                                 return -ENOMEM;
19851
19852                         delta    += cnt - 1;
19853                         env->prog = prog = new_prog;
19854                         insn      = new_prog->insnsi + i + delta;
19855                         continue;
19856                 }
19857
19858                 /* Implement bpf_get_func_ret inline. */
19859                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19860                     insn->imm == BPF_FUNC_get_func_ret) {
19861                         if (eatype == BPF_TRACE_FEXIT ||
19862                             eatype == BPF_MODIFY_RETURN) {
19863                                 /* Load nr_args from ctx - 8 */
19864                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19865                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19866                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19867                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19868                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19869                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19870                                 cnt = 6;
19871                         } else {
19872                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19873                                 cnt = 1;
19874                         }
19875
19876                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19877                         if (!new_prog)
19878                                 return -ENOMEM;
19879
19880                         delta    += cnt - 1;
19881                         env->prog = prog = new_prog;
19882                         insn      = new_prog->insnsi + i + delta;
19883                         continue;
19884                 }
19885
19886                 /* Implement get_func_arg_cnt inline. */
19887                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19888                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
19889                         /* Load nr_args from ctx - 8 */
19890                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19891
19892                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19893                         if (!new_prog)
19894                                 return -ENOMEM;
19895
19896                         env->prog = prog = new_prog;
19897                         insn      = new_prog->insnsi + i + delta;
19898                         continue;
19899                 }
19900
19901                 /* Implement bpf_get_func_ip inline. */
19902                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19903                     insn->imm == BPF_FUNC_get_func_ip) {
19904                         /* Load IP address from ctx - 16 */
19905                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19906
19907                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19908                         if (!new_prog)
19909                                 return -ENOMEM;
19910
19911                         env->prog = prog = new_prog;
19912                         insn      = new_prog->insnsi + i + delta;
19913                         continue;
19914                 }
19915
19916                 /* Implement bpf_kptr_xchg inline */
19917                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19918                     insn->imm == BPF_FUNC_kptr_xchg &&
19919                     bpf_jit_supports_ptr_xchg()) {
19920                         insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
19921                         insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
19922                         cnt = 2;
19923
19924                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19925                         if (!new_prog)
19926                                 return -ENOMEM;
19927
19928                         delta    += cnt - 1;
19929                         env->prog = prog = new_prog;
19930                         insn      = new_prog->insnsi + i + delta;
19931                         continue;
19932                 }
19933 patch_call_imm:
19934                 fn = env->ops->get_func_proto(insn->imm, env->prog);
19935                 /* all functions that have prototype and verifier allowed
19936                  * programs to call them, must be real in-kernel functions
19937                  */
19938                 if (!fn->func) {
19939                         verbose(env,
19940                                 "kernel subsystem misconfigured func %s#%d\n",
19941                                 func_id_name(insn->imm), insn->imm);
19942                         return -EFAULT;
19943                 }
19944                 insn->imm = fn->func - __bpf_call_base;
19945         }
19946
19947         /* Since poke tab is now finalized, publish aux to tracker. */
19948         for (i = 0; i < prog->aux->size_poke_tab; i++) {
19949                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19950                 if (!map_ptr->ops->map_poke_track ||
19951                     !map_ptr->ops->map_poke_untrack ||
19952                     !map_ptr->ops->map_poke_run) {
19953                         verbose(env, "bpf verifier is misconfigured\n");
19954                         return -EINVAL;
19955                 }
19956
19957                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19958                 if (ret < 0) {
19959                         verbose(env, "tracking tail call prog failed\n");
19960                         return ret;
19961                 }
19962         }
19963
19964         sort_kfunc_descs_by_imm_off(env->prog);
19965
19966         return 0;
19967 }
19968
19969 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19970                                         int position,
19971                                         s32 stack_base,
19972                                         u32 callback_subprogno,
19973                                         u32 *cnt)
19974 {
19975         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19976         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19977         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19978         int reg_loop_max = BPF_REG_6;
19979         int reg_loop_cnt = BPF_REG_7;
19980         int reg_loop_ctx = BPF_REG_8;
19981
19982         struct bpf_prog *new_prog;
19983         u32 callback_start;
19984         u32 call_insn_offset;
19985         s32 callback_offset;
19986
19987         /* This represents an inlined version of bpf_iter.c:bpf_loop,
19988          * be careful to modify this code in sync.
19989          */
19990         struct bpf_insn insn_buf[] = {
19991                 /* Return error and jump to the end of the patch if
19992                  * expected number of iterations is too big.
19993                  */
19994                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19995                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19996                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19997                 /* spill R6, R7, R8 to use these as loop vars */
19998                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19999                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20000                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20001                 /* initialize loop vars */
20002                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20003                 BPF_MOV32_IMM(reg_loop_cnt, 0),
20004                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20005                 /* loop header,
20006                  * if reg_loop_cnt >= reg_loop_max skip the loop body
20007                  */
20008                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20009                 /* callback call,
20010                  * correct callback offset would be set after patching
20011                  */
20012                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20013                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20014                 BPF_CALL_REL(0),
20015                 /* increment loop counter */
20016                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20017                 /* jump to loop header if callback returned 0 */
20018                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20019                 /* return value of bpf_loop,
20020                  * set R0 to the number of iterations
20021                  */
20022                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20023                 /* restore original values of R6, R7, R8 */
20024                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20025                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20026                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20027         };
20028
20029         *cnt = ARRAY_SIZE(insn_buf);
20030         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20031         if (!new_prog)
20032                 return new_prog;
20033
20034         /* callback start is known only after patching */
20035         callback_start = env->subprog_info[callback_subprogno].start;
20036         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20037         call_insn_offset = position + 12;
20038         callback_offset = callback_start - call_insn_offset - 1;
20039         new_prog->insnsi[call_insn_offset].imm = callback_offset;
20040
20041         return new_prog;
20042 }
20043
20044 static bool is_bpf_loop_call(struct bpf_insn *insn)
20045 {
20046         return insn->code == (BPF_JMP | BPF_CALL) &&
20047                 insn->src_reg == 0 &&
20048                 insn->imm == BPF_FUNC_loop;
20049 }
20050
20051 /* For all sub-programs in the program (including main) check
20052  * insn_aux_data to see if there are bpf_loop calls that require
20053  * inlining. If such calls are found the calls are replaced with a
20054  * sequence of instructions produced by `inline_bpf_loop` function and
20055  * subprog stack_depth is increased by the size of 3 registers.
20056  * This stack space is used to spill values of the R6, R7, R8.  These
20057  * registers are used to store the loop bound, counter and context
20058  * variables.
20059  */
20060 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20061 {
20062         struct bpf_subprog_info *subprogs = env->subprog_info;
20063         int i, cur_subprog = 0, cnt, delta = 0;
20064         struct bpf_insn *insn = env->prog->insnsi;
20065         int insn_cnt = env->prog->len;
20066         u16 stack_depth = subprogs[cur_subprog].stack_depth;
20067         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20068         u16 stack_depth_extra = 0;
20069
20070         for (i = 0; i < insn_cnt; i++, insn++) {
20071                 struct bpf_loop_inline_state *inline_state =
20072                         &env->insn_aux_data[i + delta].loop_inline_state;
20073
20074                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20075                         struct bpf_prog *new_prog;
20076
20077                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20078                         new_prog = inline_bpf_loop(env,
20079                                                    i + delta,
20080                                                    -(stack_depth + stack_depth_extra),
20081                                                    inline_state->callback_subprogno,
20082                                                    &cnt);
20083                         if (!new_prog)
20084                                 return -ENOMEM;
20085
20086                         delta     += cnt - 1;
20087                         env->prog  = new_prog;
20088                         insn       = new_prog->insnsi + i + delta;
20089                 }
20090
20091                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20092                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
20093                         cur_subprog++;
20094                         stack_depth = subprogs[cur_subprog].stack_depth;
20095                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20096                         stack_depth_extra = 0;
20097                 }
20098         }
20099
20100         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20101
20102         return 0;
20103 }
20104
20105 static void free_states(struct bpf_verifier_env *env)
20106 {
20107         struct bpf_verifier_state_list *sl, *sln;
20108         int i;
20109
20110         sl = env->free_list;
20111         while (sl) {
20112                 sln = sl->next;
20113                 free_verifier_state(&sl->state, false);
20114                 kfree(sl);
20115                 sl = sln;
20116         }
20117         env->free_list = NULL;
20118
20119         if (!env->explored_states)
20120                 return;
20121
20122         for (i = 0; i < state_htab_size(env); i++) {
20123                 sl = env->explored_states[i];
20124
20125                 while (sl) {
20126                         sln = sl->next;
20127                         free_verifier_state(&sl->state, false);
20128                         kfree(sl);
20129                         sl = sln;
20130                 }
20131                 env->explored_states[i] = NULL;
20132         }
20133 }
20134
20135 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20136 {
20137         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20138         struct bpf_subprog_info *sub = subprog_info(env, subprog);
20139         struct bpf_verifier_state *state;
20140         struct bpf_reg_state *regs;
20141         int ret, i;
20142
20143         env->prev_linfo = NULL;
20144         env->pass_cnt++;
20145
20146         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20147         if (!state)
20148                 return -ENOMEM;
20149         state->curframe = 0;
20150         state->speculative = false;
20151         state->branches = 1;
20152         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20153         if (!state->frame[0]) {
20154                 kfree(state);
20155                 return -ENOMEM;
20156         }
20157         env->cur_state = state;
20158         init_func_state(env, state->frame[0],
20159                         BPF_MAIN_FUNC /* callsite */,
20160                         0 /* frameno */,
20161                         subprog);
20162         state->first_insn_idx = env->subprog_info[subprog].start;
20163         state->last_insn_idx = -1;
20164
20165         regs = state->frame[state->curframe]->regs;
20166         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20167                 const char *sub_name = subprog_name(env, subprog);
20168                 struct bpf_subprog_arg_info *arg;
20169                 struct bpf_reg_state *reg;
20170
20171                 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20172                 ret = btf_prepare_func_args(env, subprog);
20173                 if (ret)
20174                         goto out;
20175
20176                 if (subprog_is_exc_cb(env, subprog)) {
20177                         state->frame[0]->in_exception_callback_fn = true;
20178                         /* We have already ensured that the callback returns an integer, just
20179                          * like all global subprogs. We need to determine it only has a single
20180                          * scalar argument.
20181                          */
20182                         if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20183                                 verbose(env, "exception cb only supports single integer argument\n");
20184                                 ret = -EINVAL;
20185                                 goto out;
20186                         }
20187                 }
20188                 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20189                         arg = &sub->args[i - BPF_REG_1];
20190                         reg = &regs[i];
20191
20192                         if (arg->arg_type == ARG_PTR_TO_CTX) {
20193                                 reg->type = PTR_TO_CTX;
20194                                 mark_reg_known_zero(env, regs, i);
20195                         } else if (arg->arg_type == ARG_ANYTHING) {
20196                                 reg->type = SCALAR_VALUE;
20197                                 mark_reg_unknown(env, regs, i);
20198                         } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20199                                 /* assume unspecial LOCAL dynptr type */
20200                                 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20201                         } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20202                                 reg->type = PTR_TO_MEM;
20203                                 if (arg->arg_type & PTR_MAYBE_NULL)
20204                                         reg->type |= PTR_MAYBE_NULL;
20205                                 mark_reg_known_zero(env, regs, i);
20206                                 reg->mem_size = arg->mem_size;
20207                                 reg->id = ++env->id_gen;
20208                         } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20209                                 reg->type = PTR_TO_BTF_ID;
20210                                 if (arg->arg_type & PTR_MAYBE_NULL)
20211                                         reg->type |= PTR_MAYBE_NULL;
20212                                 if (arg->arg_type & PTR_UNTRUSTED)
20213                                         reg->type |= PTR_UNTRUSTED;
20214                                 if (arg->arg_type & PTR_TRUSTED)
20215                                         reg->type |= PTR_TRUSTED;
20216                                 mark_reg_known_zero(env, regs, i);
20217                                 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20218                                 reg->btf_id = arg->btf_id;
20219                                 reg->id = ++env->id_gen;
20220                         } else {
20221                                 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20222                                           i - BPF_REG_1, arg->arg_type);
20223                                 ret = -EFAULT;
20224                                 goto out;
20225                         }
20226                 }
20227         } else {
20228                 /* if main BPF program has associated BTF info, validate that
20229                  * it's matching expected signature, and otherwise mark BTF
20230                  * info for main program as unreliable
20231                  */
20232                 if (env->prog->aux->func_info_aux) {
20233                         ret = btf_prepare_func_args(env, 0);
20234                         if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20235                                 env->prog->aux->func_info_aux[0].unreliable = true;
20236                 }
20237
20238                 /* 1st arg to a function */
20239                 regs[BPF_REG_1].type = PTR_TO_CTX;
20240                 mark_reg_known_zero(env, regs, BPF_REG_1);
20241         }
20242
20243         ret = do_check(env);
20244 out:
20245         /* check for NULL is necessary, since cur_state can be freed inside
20246          * do_check() under memory pressure.
20247          */
20248         if (env->cur_state) {
20249                 free_verifier_state(env->cur_state, true);
20250                 env->cur_state = NULL;
20251         }
20252         while (!pop_stack(env, NULL, NULL, false));
20253         if (!ret && pop_log)
20254                 bpf_vlog_reset(&env->log, 0);
20255         free_states(env);
20256         return ret;
20257 }
20258
20259 /* Lazily verify all global functions based on their BTF, if they are called
20260  * from main BPF program or any of subprograms transitively.
20261  * BPF global subprogs called from dead code are not validated.
20262  * All callable global functions must pass verification.
20263  * Otherwise the whole program is rejected.
20264  * Consider:
20265  * int bar(int);
20266  * int foo(int f)
20267  * {
20268  *    return bar(f);
20269  * }
20270  * int bar(int b)
20271  * {
20272  *    ...
20273  * }
20274  * foo() will be verified first for R1=any_scalar_value. During verification it
20275  * will be assumed that bar() already verified successfully and call to bar()
20276  * from foo() will be checked for type match only. Later bar() will be verified
20277  * independently to check that it's safe for R1=any_scalar_value.
20278  */
20279 static int do_check_subprogs(struct bpf_verifier_env *env)
20280 {
20281         struct bpf_prog_aux *aux = env->prog->aux;
20282         struct bpf_func_info_aux *sub_aux;
20283         int i, ret, new_cnt;
20284
20285         if (!aux->func_info)
20286                 return 0;
20287
20288         /* exception callback is presumed to be always called */
20289         if (env->exception_callback_subprog)
20290                 subprog_aux(env, env->exception_callback_subprog)->called = true;
20291
20292 again:
20293         new_cnt = 0;
20294         for (i = 1; i < env->subprog_cnt; i++) {
20295                 if (!subprog_is_global(env, i))
20296                         continue;
20297
20298                 sub_aux = subprog_aux(env, i);
20299                 if (!sub_aux->called || sub_aux->verified)
20300                         continue;
20301
20302                 env->insn_idx = env->subprog_info[i].start;
20303                 WARN_ON_ONCE(env->insn_idx == 0);
20304                 ret = do_check_common(env, i);
20305                 if (ret) {
20306                         return ret;
20307                 } else if (env->log.level & BPF_LOG_LEVEL) {
20308                         verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20309                                 i, subprog_name(env, i));
20310                 }
20311
20312                 /* We verified new global subprog, it might have called some
20313                  * more global subprogs that we haven't verified yet, so we
20314                  * need to do another pass over subprogs to verify those.
20315                  */
20316                 sub_aux->verified = true;
20317                 new_cnt++;
20318         }
20319
20320         /* We can't loop forever as we verify at least one global subprog on
20321          * each pass.
20322          */
20323         if (new_cnt)
20324                 goto again;
20325
20326         return 0;
20327 }
20328
20329 static int do_check_main(struct bpf_verifier_env *env)
20330 {
20331         int ret;
20332
20333         env->insn_idx = 0;
20334         ret = do_check_common(env, 0);
20335         if (!ret)
20336                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20337         return ret;
20338 }
20339
20340
20341 static void print_verification_stats(struct bpf_verifier_env *env)
20342 {
20343         int i;
20344
20345         if (env->log.level & BPF_LOG_STATS) {
20346                 verbose(env, "verification time %lld usec\n",
20347                         div_u64(env->verification_time, 1000));
20348                 verbose(env, "stack depth ");
20349                 for (i = 0; i < env->subprog_cnt; i++) {
20350                         u32 depth = env->subprog_info[i].stack_depth;
20351
20352                         verbose(env, "%d", depth);
20353                         if (i + 1 < env->subprog_cnt)
20354                                 verbose(env, "+");
20355                 }
20356                 verbose(env, "\n");
20357         }
20358         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20359                 "total_states %d peak_states %d mark_read %d\n",
20360                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20361                 env->max_states_per_insn, env->total_states,
20362                 env->peak_states, env->longest_mark_read_walk);
20363 }
20364
20365 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20366 {
20367         const struct btf_type *t, *func_proto;
20368         const struct bpf_struct_ops_desc *st_ops_desc;
20369         const struct bpf_struct_ops *st_ops;
20370         const struct btf_member *member;
20371         struct bpf_prog *prog = env->prog;
20372         u32 btf_id, member_idx;
20373         struct btf *btf;
20374         const char *mname;
20375
20376         if (!prog->gpl_compatible) {
20377                 verbose(env, "struct ops programs must have a GPL compatible license\n");
20378                 return -EINVAL;
20379         }
20380
20381         if (!prog->aux->attach_btf_id)
20382                 return -ENOTSUPP;
20383
20384         btf = prog->aux->attach_btf;
20385         if (btf_is_module(btf)) {
20386                 /* Make sure st_ops is valid through the lifetime of env */
20387                 env->attach_btf_mod = btf_try_get_module(btf);
20388                 if (!env->attach_btf_mod) {
20389                         verbose(env, "struct_ops module %s is not found\n",
20390                                 btf_get_name(btf));
20391                         return -ENOTSUPP;
20392                 }
20393         }
20394
20395         btf_id = prog->aux->attach_btf_id;
20396         st_ops_desc = bpf_struct_ops_find(btf, btf_id);
20397         if (!st_ops_desc) {
20398                 verbose(env, "attach_btf_id %u is not a supported struct\n",
20399                         btf_id);
20400                 return -ENOTSUPP;
20401         }
20402         st_ops = st_ops_desc->st_ops;
20403
20404         t = st_ops_desc->type;
20405         member_idx = prog->expected_attach_type;
20406         if (member_idx >= btf_type_vlen(t)) {
20407                 verbose(env, "attach to invalid member idx %u of struct %s\n",
20408                         member_idx, st_ops->name);
20409                 return -EINVAL;
20410         }
20411
20412         member = &btf_type_member(t)[member_idx];
20413         mname = btf_name_by_offset(btf, member->name_off);
20414         func_proto = btf_type_resolve_func_ptr(btf, member->type,
20415                                                NULL);
20416         if (!func_proto) {
20417                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20418                         mname, member_idx, st_ops->name);
20419                 return -EINVAL;
20420         }
20421
20422         if (st_ops->check_member) {
20423                 int err = st_ops->check_member(t, member, prog);
20424
20425                 if (err) {
20426                         verbose(env, "attach to unsupported member %s of struct %s\n",
20427                                 mname, st_ops->name);
20428                         return err;
20429                 }
20430         }
20431
20432         /* btf_ctx_access() used this to provide argument type info */
20433         prog->aux->ctx_arg_info =
20434                 st_ops_desc->arg_info[member_idx].info;
20435         prog->aux->ctx_arg_info_size =
20436                 st_ops_desc->arg_info[member_idx].cnt;
20437
20438         prog->aux->attach_func_proto = func_proto;
20439         prog->aux->attach_func_name = mname;
20440         env->ops = st_ops->verifier_ops;
20441
20442         return 0;
20443 }
20444 #define SECURITY_PREFIX "security_"
20445
20446 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20447 {
20448         if (within_error_injection_list(addr) ||
20449             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20450                 return 0;
20451
20452         return -EINVAL;
20453 }
20454
20455 /* list of non-sleepable functions that are otherwise on
20456  * ALLOW_ERROR_INJECTION list
20457  */
20458 BTF_SET_START(btf_non_sleepable_error_inject)
20459 /* Three functions below can be called from sleepable and non-sleepable context.
20460  * Assume non-sleepable from bpf safety point of view.
20461  */
20462 BTF_ID(func, __filemap_add_folio)
20463 BTF_ID(func, should_fail_alloc_page)
20464 BTF_ID(func, should_failslab)
20465 BTF_SET_END(btf_non_sleepable_error_inject)
20466
20467 static int check_non_sleepable_error_inject(u32 btf_id)
20468 {
20469         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20470 }
20471
20472 int bpf_check_attach_target(struct bpf_verifier_log *log,
20473                             const struct bpf_prog *prog,
20474                             const struct bpf_prog *tgt_prog,
20475                             u32 btf_id,
20476                             struct bpf_attach_target_info *tgt_info)
20477 {
20478         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20479         bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20480         const char prefix[] = "btf_trace_";
20481         int ret = 0, subprog = -1, i;
20482         const struct btf_type *t;
20483         bool conservative = true;
20484         const char *tname;
20485         struct btf *btf;
20486         long addr = 0;
20487         struct module *mod = NULL;
20488
20489         if (!btf_id) {
20490                 bpf_log(log, "Tracing programs must provide btf_id\n");
20491                 return -EINVAL;
20492         }
20493         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20494         if (!btf) {
20495                 bpf_log(log,
20496                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20497                 return -EINVAL;
20498         }
20499         t = btf_type_by_id(btf, btf_id);
20500         if (!t) {
20501                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20502                 return -EINVAL;
20503         }
20504         tname = btf_name_by_offset(btf, t->name_off);
20505         if (!tname) {
20506                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20507                 return -EINVAL;
20508         }
20509         if (tgt_prog) {
20510                 struct bpf_prog_aux *aux = tgt_prog->aux;
20511
20512                 if (bpf_prog_is_dev_bound(prog->aux) &&
20513                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20514                         bpf_log(log, "Target program bound device mismatch");
20515                         return -EINVAL;
20516                 }
20517
20518                 for (i = 0; i < aux->func_info_cnt; i++)
20519                         if (aux->func_info[i].type_id == btf_id) {
20520                                 subprog = i;
20521                                 break;
20522                         }
20523                 if (subprog == -1) {
20524                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
20525                         return -EINVAL;
20526                 }
20527                 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20528                         bpf_log(log,
20529                                 "%s programs cannot attach to exception callback\n",
20530                                 prog_extension ? "Extension" : "FENTRY/FEXIT");
20531                         return -EINVAL;
20532                 }
20533                 conservative = aux->func_info_aux[subprog].unreliable;
20534                 if (prog_extension) {
20535                         if (conservative) {
20536                                 bpf_log(log,
20537                                         "Cannot replace static functions\n");
20538                                 return -EINVAL;
20539                         }
20540                         if (!prog->jit_requested) {
20541                                 bpf_log(log,
20542                                         "Extension programs should be JITed\n");
20543                                 return -EINVAL;
20544                         }
20545                 }
20546                 if (!tgt_prog->jited) {
20547                         bpf_log(log, "Can attach to only JITed progs\n");
20548                         return -EINVAL;
20549                 }
20550                 if (prog_tracing) {
20551                         if (aux->attach_tracing_prog) {
20552                                 /*
20553                                  * Target program is an fentry/fexit which is already attached
20554                                  * to another tracing program. More levels of nesting
20555                                  * attachment are not allowed.
20556                                  */
20557                                 bpf_log(log, "Cannot nest tracing program attach more than once\n");
20558                                 return -EINVAL;
20559                         }
20560                 } else if (tgt_prog->type == prog->type) {
20561                         /*
20562                          * To avoid potential call chain cycles, prevent attaching of a
20563                          * program extension to another extension. It's ok to attach
20564                          * fentry/fexit to extension program.
20565                          */
20566                         bpf_log(log, "Cannot recursively attach\n");
20567                         return -EINVAL;
20568                 }
20569                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20570                     prog_extension &&
20571                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20572                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20573                         /* Program extensions can extend all program types
20574                          * except fentry/fexit. The reason is the following.
20575                          * The fentry/fexit programs are used for performance
20576                          * analysis, stats and can be attached to any program
20577                          * type. When extension program is replacing XDP function
20578                          * it is necessary to allow performance analysis of all
20579                          * functions. Both original XDP program and its program
20580                          * extension. Hence attaching fentry/fexit to
20581                          * BPF_PROG_TYPE_EXT is allowed. If extending of
20582                          * fentry/fexit was allowed it would be possible to create
20583                          * long call chain fentry->extension->fentry->extension
20584                          * beyond reasonable stack size. Hence extending fentry
20585                          * is not allowed.
20586                          */
20587                         bpf_log(log, "Cannot extend fentry/fexit\n");
20588                         return -EINVAL;
20589                 }
20590         } else {
20591                 if (prog_extension) {
20592                         bpf_log(log, "Cannot replace kernel functions\n");
20593                         return -EINVAL;
20594                 }
20595         }
20596
20597         switch (prog->expected_attach_type) {
20598         case BPF_TRACE_RAW_TP:
20599                 if (tgt_prog) {
20600                         bpf_log(log,
20601                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20602                         return -EINVAL;
20603                 }
20604                 if (!btf_type_is_typedef(t)) {
20605                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
20606                                 btf_id);
20607                         return -EINVAL;
20608                 }
20609                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20610                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20611                                 btf_id, tname);
20612                         return -EINVAL;
20613                 }
20614                 tname += sizeof(prefix) - 1;
20615                 t = btf_type_by_id(btf, t->type);
20616                 if (!btf_type_is_ptr(t))
20617                         /* should never happen in valid vmlinux build */
20618                         return -EINVAL;
20619                 t = btf_type_by_id(btf, t->type);
20620                 if (!btf_type_is_func_proto(t))
20621                         /* should never happen in valid vmlinux build */
20622                         return -EINVAL;
20623
20624                 break;
20625         case BPF_TRACE_ITER:
20626                 if (!btf_type_is_func(t)) {
20627                         bpf_log(log, "attach_btf_id %u is not a function\n",
20628                                 btf_id);
20629                         return -EINVAL;
20630                 }
20631                 t = btf_type_by_id(btf, t->type);
20632                 if (!btf_type_is_func_proto(t))
20633                         return -EINVAL;
20634                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20635                 if (ret)
20636                         return ret;
20637                 break;
20638         default:
20639                 if (!prog_extension)
20640                         return -EINVAL;
20641                 fallthrough;
20642         case BPF_MODIFY_RETURN:
20643         case BPF_LSM_MAC:
20644         case BPF_LSM_CGROUP:
20645         case BPF_TRACE_FENTRY:
20646         case BPF_TRACE_FEXIT:
20647                 if (!btf_type_is_func(t)) {
20648                         bpf_log(log, "attach_btf_id %u is not a function\n",
20649                                 btf_id);
20650                         return -EINVAL;
20651                 }
20652                 if (prog_extension &&
20653                     btf_check_type_match(log, prog, btf, t))
20654                         return -EINVAL;
20655                 t = btf_type_by_id(btf, t->type);
20656                 if (!btf_type_is_func_proto(t))
20657                         return -EINVAL;
20658
20659                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20660                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20661                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20662                         return -EINVAL;
20663
20664                 if (tgt_prog && conservative)
20665                         t = NULL;
20666
20667                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20668                 if (ret < 0)
20669                         return ret;
20670
20671                 if (tgt_prog) {
20672                         if (subprog == 0)
20673                                 addr = (long) tgt_prog->bpf_func;
20674                         else
20675                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20676                 } else {
20677                         if (btf_is_module(btf)) {
20678                                 mod = btf_try_get_module(btf);
20679                                 if (mod)
20680                                         addr = find_kallsyms_symbol_value(mod, tname);
20681                                 else
20682                                         addr = 0;
20683                         } else {
20684                                 addr = kallsyms_lookup_name(tname);
20685                         }
20686                         if (!addr) {
20687                                 module_put(mod);
20688                                 bpf_log(log,
20689                                         "The address of function %s cannot be found\n",
20690                                         tname);
20691                                 return -ENOENT;
20692                         }
20693                 }
20694
20695                 if (prog->aux->sleepable) {
20696                         ret = -EINVAL;
20697                         switch (prog->type) {
20698                         case BPF_PROG_TYPE_TRACING:
20699
20700                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
20701                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20702                                  */
20703                                 if (!check_non_sleepable_error_inject(btf_id) &&
20704                                     within_error_injection_list(addr))
20705                                         ret = 0;
20706                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20707                                  * in the fmodret id set with the KF_SLEEPABLE flag.
20708                                  */
20709                                 else {
20710                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20711                                                                                 prog);
20712
20713                                         if (flags && (*flags & KF_SLEEPABLE))
20714                                                 ret = 0;
20715                                 }
20716                                 break;
20717                         case BPF_PROG_TYPE_LSM:
20718                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20719                                  * Only some of them are sleepable.
20720                                  */
20721                                 if (bpf_lsm_is_sleepable_hook(btf_id))
20722                                         ret = 0;
20723                                 break;
20724                         default:
20725                                 break;
20726                         }
20727                         if (ret) {
20728                                 module_put(mod);
20729                                 bpf_log(log, "%s is not sleepable\n", tname);
20730                                 return ret;
20731                         }
20732                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20733                         if (tgt_prog) {
20734                                 module_put(mod);
20735                                 bpf_log(log, "can't modify return codes of BPF programs\n");
20736                                 return -EINVAL;
20737                         }
20738                         ret = -EINVAL;
20739                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20740                             !check_attach_modify_return(addr, tname))
20741                                 ret = 0;
20742                         if (ret) {
20743                                 module_put(mod);
20744                                 bpf_log(log, "%s() is not modifiable\n", tname);
20745                                 return ret;
20746                         }
20747                 }
20748
20749                 break;
20750         }
20751         tgt_info->tgt_addr = addr;
20752         tgt_info->tgt_name = tname;
20753         tgt_info->tgt_type = t;
20754         tgt_info->tgt_mod = mod;
20755         return 0;
20756 }
20757
20758 BTF_SET_START(btf_id_deny)
20759 BTF_ID_UNUSED
20760 #ifdef CONFIG_SMP
20761 BTF_ID(func, migrate_disable)
20762 BTF_ID(func, migrate_enable)
20763 #endif
20764 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20765 BTF_ID(func, rcu_read_unlock_strict)
20766 #endif
20767 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20768 BTF_ID(func, preempt_count_add)
20769 BTF_ID(func, preempt_count_sub)
20770 #endif
20771 #ifdef CONFIG_PREEMPT_RCU
20772 BTF_ID(func, __rcu_read_lock)
20773 BTF_ID(func, __rcu_read_unlock)
20774 #endif
20775 BTF_SET_END(btf_id_deny)
20776
20777 static bool can_be_sleepable(struct bpf_prog *prog)
20778 {
20779         if (prog->type == BPF_PROG_TYPE_TRACING) {
20780                 switch (prog->expected_attach_type) {
20781                 case BPF_TRACE_FENTRY:
20782                 case BPF_TRACE_FEXIT:
20783                 case BPF_MODIFY_RETURN:
20784                 case BPF_TRACE_ITER:
20785                         return true;
20786                 default:
20787                         return false;
20788                 }
20789         }
20790         return prog->type == BPF_PROG_TYPE_LSM ||
20791                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20792                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20793 }
20794
20795 static int check_attach_btf_id(struct bpf_verifier_env *env)
20796 {
20797         struct bpf_prog *prog = env->prog;
20798         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20799         struct bpf_attach_target_info tgt_info = {};
20800         u32 btf_id = prog->aux->attach_btf_id;
20801         struct bpf_trampoline *tr;
20802         int ret;
20803         u64 key;
20804
20805         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20806                 if (prog->aux->sleepable)
20807                         /* attach_btf_id checked to be zero already */
20808                         return 0;
20809                 verbose(env, "Syscall programs can only be sleepable\n");
20810                 return -EINVAL;
20811         }
20812
20813         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20814                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20815                 return -EINVAL;
20816         }
20817
20818         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20819                 return check_struct_ops_btf_id(env);
20820
20821         if (prog->type != BPF_PROG_TYPE_TRACING &&
20822             prog->type != BPF_PROG_TYPE_LSM &&
20823             prog->type != BPF_PROG_TYPE_EXT)
20824                 return 0;
20825
20826         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20827         if (ret)
20828                 return ret;
20829
20830         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20831                 /* to make freplace equivalent to their targets, they need to
20832                  * inherit env->ops and expected_attach_type for the rest of the
20833                  * verification
20834                  */
20835                 env->ops = bpf_verifier_ops[tgt_prog->type];
20836                 prog->expected_attach_type = tgt_prog->expected_attach_type;
20837         }
20838
20839         /* store info about the attachment target that will be used later */
20840         prog->aux->attach_func_proto = tgt_info.tgt_type;
20841         prog->aux->attach_func_name = tgt_info.tgt_name;
20842         prog->aux->mod = tgt_info.tgt_mod;
20843
20844         if (tgt_prog) {
20845                 prog->aux->saved_dst_prog_type = tgt_prog->type;
20846                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20847         }
20848
20849         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20850                 prog->aux->attach_btf_trace = true;
20851                 return 0;
20852         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20853                 if (!bpf_iter_prog_supported(prog))
20854                         return -EINVAL;
20855                 return 0;
20856         }
20857
20858         if (prog->type == BPF_PROG_TYPE_LSM) {
20859                 ret = bpf_lsm_verify_prog(&env->log, prog);
20860                 if (ret < 0)
20861                         return ret;
20862         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20863                    btf_id_set_contains(&btf_id_deny, btf_id)) {
20864                 return -EINVAL;
20865         }
20866
20867         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20868         tr = bpf_trampoline_get(key, &tgt_info);
20869         if (!tr)
20870                 return -ENOMEM;
20871
20872         if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20873                 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20874
20875         prog->aux->dst_trampoline = tr;
20876         return 0;
20877 }
20878
20879 struct btf *bpf_get_btf_vmlinux(void)
20880 {
20881         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20882                 mutex_lock(&bpf_verifier_lock);
20883                 if (!btf_vmlinux)
20884                         btf_vmlinux = btf_parse_vmlinux();
20885                 mutex_unlock(&bpf_verifier_lock);
20886         }
20887         return btf_vmlinux;
20888 }
20889
20890 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20891 {
20892         u64 start_time = ktime_get_ns();
20893         struct bpf_verifier_env *env;
20894         int i, len, ret = -EINVAL, err;
20895         u32 log_true_size;
20896         bool is_priv;
20897
20898         /* no program is valid */
20899         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20900                 return -EINVAL;
20901
20902         /* 'struct bpf_verifier_env' can be global, but since it's not small,
20903          * allocate/free it every time bpf_check() is called
20904          */
20905         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20906         if (!env)
20907                 return -ENOMEM;
20908
20909         env->bt.env = env;
20910
20911         len = (*prog)->len;
20912         env->insn_aux_data =
20913                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20914         ret = -ENOMEM;
20915         if (!env->insn_aux_data)
20916                 goto err_free_env;
20917         for (i = 0; i < len; i++)
20918                 env->insn_aux_data[i].orig_idx = i;
20919         env->prog = *prog;
20920         env->ops = bpf_verifier_ops[env->prog->type];
20921         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20922
20923         env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
20924         env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
20925         env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
20926         env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
20927         env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
20928
20929         bpf_get_btf_vmlinux();
20930
20931         /* grab the mutex to protect few globals used by verifier */
20932         if (!is_priv)
20933                 mutex_lock(&bpf_verifier_lock);
20934
20935         /* user could have requested verbose verifier output
20936          * and supplied buffer to store the verification trace
20937          */
20938         ret = bpf_vlog_init(&env->log, attr->log_level,
20939                             (char __user *) (unsigned long) attr->log_buf,
20940                             attr->log_size);
20941         if (ret)
20942                 goto err_unlock;
20943
20944         mark_verifier_state_clean(env);
20945
20946         if (IS_ERR(btf_vmlinux)) {
20947                 /* Either gcc or pahole or kernel are broken. */
20948                 verbose(env, "in-kernel BTF is malformed\n");
20949                 ret = PTR_ERR(btf_vmlinux);
20950                 goto skip_full_check;
20951         }
20952
20953         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20954         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20955                 env->strict_alignment = true;
20956         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20957                 env->strict_alignment = false;
20958
20959         if (is_priv)
20960                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20961         env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
20962
20963         env->explored_states = kvcalloc(state_htab_size(env),
20964                                        sizeof(struct bpf_verifier_state_list *),
20965                                        GFP_USER);
20966         ret = -ENOMEM;
20967         if (!env->explored_states)
20968                 goto skip_full_check;
20969
20970         ret = check_btf_info_early(env, attr, uattr);
20971         if (ret < 0)
20972                 goto skip_full_check;
20973
20974         ret = add_subprog_and_kfunc(env);
20975         if (ret < 0)
20976                 goto skip_full_check;
20977
20978         ret = check_subprogs(env);
20979         if (ret < 0)
20980                 goto skip_full_check;
20981
20982         ret = check_btf_info(env, attr, uattr);
20983         if (ret < 0)
20984                 goto skip_full_check;
20985
20986         ret = check_attach_btf_id(env);
20987         if (ret)
20988                 goto skip_full_check;
20989
20990         ret = resolve_pseudo_ldimm64(env);
20991         if (ret < 0)
20992                 goto skip_full_check;
20993
20994         if (bpf_prog_is_offloaded(env->prog->aux)) {
20995                 ret = bpf_prog_offload_verifier_prep(env->prog);
20996                 if (ret)
20997                         goto skip_full_check;
20998         }
20999
21000         ret = check_cfg(env);
21001         if (ret < 0)
21002                 goto skip_full_check;
21003
21004         ret = do_check_main(env);
21005         ret = ret ?: do_check_subprogs(env);
21006
21007         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21008                 ret = bpf_prog_offload_finalize(env);
21009
21010 skip_full_check:
21011         kvfree(env->explored_states);
21012
21013         if (ret == 0)
21014                 ret = check_max_stack_depth(env);
21015
21016         /* instruction rewrites happen after this point */
21017         if (ret == 0)
21018                 ret = optimize_bpf_loop(env);
21019
21020         if (is_priv) {
21021                 if (ret == 0)
21022                         opt_hard_wire_dead_code_branches(env);
21023                 if (ret == 0)
21024                         ret = opt_remove_dead_code(env);
21025                 if (ret == 0)
21026                         ret = opt_remove_nops(env);
21027         } else {
21028                 if (ret == 0)
21029                         sanitize_dead_code(env);
21030         }
21031
21032         if (ret == 0)
21033                 /* program is valid, convert *(u32*)(ctx + off) accesses */
21034                 ret = convert_ctx_accesses(env);
21035
21036         if (ret == 0)
21037                 ret = do_misc_fixups(env);
21038
21039         /* do 32-bit optimization after insn patching has done so those patched
21040          * insns could be handled correctly.
21041          */
21042         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21043                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21044                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21045                                                                      : false;
21046         }
21047
21048         if (ret == 0)
21049                 ret = fixup_call_args(env);
21050
21051         env->verification_time = ktime_get_ns() - start_time;
21052         print_verification_stats(env);
21053         env->prog->aux->verified_insns = env->insn_processed;
21054
21055         /* preserve original error even if log finalization is successful */
21056         err = bpf_vlog_finalize(&env->log, &log_true_size);
21057         if (err)
21058                 ret = err;
21059
21060         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21061             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21062                                   &log_true_size, sizeof(log_true_size))) {
21063                 ret = -EFAULT;
21064                 goto err_release_maps;
21065         }
21066
21067         if (ret)
21068                 goto err_release_maps;
21069
21070         if (env->used_map_cnt) {
21071                 /* if program passed verifier, update used_maps in bpf_prog_info */
21072                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21073                                                           sizeof(env->used_maps[0]),
21074                                                           GFP_KERNEL);
21075
21076                 if (!env->prog->aux->used_maps) {
21077                         ret = -ENOMEM;
21078                         goto err_release_maps;
21079                 }
21080
21081                 memcpy(env->prog->aux->used_maps, env->used_maps,
21082                        sizeof(env->used_maps[0]) * env->used_map_cnt);
21083                 env->prog->aux->used_map_cnt = env->used_map_cnt;
21084         }
21085         if (env->used_btf_cnt) {
21086                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
21087                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21088                                                           sizeof(env->used_btfs[0]),
21089                                                           GFP_KERNEL);
21090                 if (!env->prog->aux->used_btfs) {
21091                         ret = -ENOMEM;
21092                         goto err_release_maps;
21093                 }
21094
21095                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
21096                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21097                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21098         }
21099         if (env->used_map_cnt || env->used_btf_cnt) {
21100                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
21101                  * bpf_ld_imm64 instructions
21102                  */
21103                 convert_pseudo_ld_imm64(env);
21104         }
21105
21106         adjust_btf_func(env);
21107
21108 err_release_maps:
21109         if (!env->prog->aux->used_maps)
21110                 /* if we didn't copy map pointers into bpf_prog_info, release
21111                  * them now. Otherwise free_used_maps() will release them.
21112                  */
21113                 release_maps(env);
21114         if (!env->prog->aux->used_btfs)
21115                 release_btfs(env);
21116
21117         /* extension progs temporarily inherit the attach_type of their targets
21118            for verification purposes, so set it back to zero before returning
21119          */
21120         if (env->prog->type == BPF_PROG_TYPE_EXT)
21121                 env->prog->expected_attach_type = 0;
21122
21123         *prog = env->prog;
21124
21125         module_put(env->attach_btf_mod);
21126 err_unlock:
21127         if (!is_priv)
21128                 mutex_unlock(&bpf_verifier_lock);
21129         vfree(env->insn_aux_data);
21130 err_free_env:
21131         kfree(env);
21132         return ret;
21133 }