bpf: consider CONST_PTR_TO_MAP as trusted pointer to struct bpf_map
[linux-2.6-microblaze.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
30 #include "disasm.h"
31
32 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
33 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
34         [_id] = & _name ## _verifier_ops,
35 #define BPF_MAP_TYPE(_id, _ops)
36 #define BPF_LINK_TYPE(_id, _name)
37 #include <linux/bpf_types.h>
38 #undef BPF_PROG_TYPE
39 #undef BPF_MAP_TYPE
40 #undef BPF_LINK_TYPE
41 };
42
43 /* bpf_check() is a static code analyzer that walks eBPF program
44  * instruction by instruction and updates register/stack state.
45  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46  *
47  * The first pass is depth-first-search to check that the program is a DAG.
48  * It rejects the following programs:
49  * - larger than BPF_MAXINSNS insns
50  * - if loop is present (detected via back-edge)
51  * - unreachable insns exist (shouldn't be a forest. program = one function)
52  * - out of bounds or malformed jumps
53  * The second pass is all possible path descent from the 1st insn.
54  * Since it's analyzing all paths through the program, the length of the
55  * analysis is limited to 64k insn, which may be hit even if total number of
56  * insn is less then 4K, but there are too many branches that change stack/regs.
57  * Number of 'branches to be analyzed' is limited to 1k
58  *
59  * On entry to each instruction, each register has a type, and the instruction
60  * changes the types of the registers depending on instruction semantics.
61  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
62  * copied to R1.
63  *
64  * All registers are 64-bit.
65  * R0 - return register
66  * R1-R5 argument passing registers
67  * R6-R9 callee saved registers
68  * R10 - frame pointer read-only
69  *
70  * At the start of BPF program the register R1 contains a pointer to bpf_context
71  * and has type PTR_TO_CTX.
72  *
73  * Verifier tracks arithmetic operations on pointers in case:
74  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
75  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
76  * 1st insn copies R10 (which has FRAME_PTR) type into R1
77  * and 2nd arithmetic instruction is pattern matched to recognize
78  * that it wants to construct a pointer to some element within stack.
79  * So after 2nd insn, the register R1 has type PTR_TO_STACK
80  * (and -20 constant is saved for further stack bounds checking).
81  * Meaning that this reg is a pointer to stack plus known immediate constant.
82  *
83  * Most of the time the registers have SCALAR_VALUE type, which
84  * means the register has some value, but it's not a valid pointer.
85  * (like pointer plus pointer becomes SCALAR_VALUE type)
86  *
87  * When verifier sees load or store instructions the type of base register
88  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
89  * four pointer types recognized by check_mem_access() function.
90  *
91  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
92  * and the range of [ptr, ptr + map's value_size) is accessible.
93  *
94  * registers used to pass values to function calls are checked against
95  * function argument constraints.
96  *
97  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
98  * It means that the register type passed to this function must be
99  * PTR_TO_STACK and it will be used inside the function as
100  * 'pointer to map element key'
101  *
102  * For example the argument constraints for bpf_map_lookup_elem():
103  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
104  *   .arg1_type = ARG_CONST_MAP_PTR,
105  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
106  *
107  * ret_type says that this function returns 'pointer to map elem value or null'
108  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
109  * 2nd argument should be a pointer to stack, which will be used inside
110  * the helper function as a pointer to map element key.
111  *
112  * On the kernel side the helper function looks like:
113  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114  * {
115  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
116  *    void *key = (void *) (unsigned long) r2;
117  *    void *value;
118  *
119  *    here kernel can access 'key' and 'map' pointers safely, knowing that
120  *    [key, key + map->key_size) bytes are valid and were initialized on
121  *    the stack of eBPF program.
122  * }
123  *
124  * Corresponding eBPF program may look like:
125  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
126  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
127  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
128  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
129  * here verifier looks at prototype of map_lookup_elem() and sees:
130  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
131  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132  *
133  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
134  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
135  * and were initialized prior to this call.
136  * If it's ok, then verifier allows this BPF_CALL insn and looks at
137  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
138  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
139  * returns either pointer to map value or NULL.
140  *
141  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
142  * insn, the register holding that pointer in the true branch changes state to
143  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
144  * branch. See check_cond_jmp_op().
145  *
146  * After the call R0 is set to return type of the function and registers R1-R5
147  * are set to NOT_INIT to indicate that they are no longer readable.
148  *
149  * The following reference types represent a potential reference to a kernel
150  * resource which, after first being allocated, must be checked and freed by
151  * the BPF program:
152  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153  *
154  * When the verifier sees a helper call return a reference type, it allocates a
155  * pointer id for the reference and stores it in the current function state.
156  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
157  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
158  * passes through a NULL-check conditional. For the branch wherein the state is
159  * changed to CONST_IMM, the verifier releases the reference.
160  *
161  * For each helper function that allocates a reference, such as
162  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
163  * bpf_sk_release(). When a reference type passes into the release function,
164  * the verifier also releases the reference. If any unchecked or unreleased
165  * reference remains at the end of the program, the verifier rejects it.
166  */
167
168 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
169 struct bpf_verifier_stack_elem {
170         /* verifer state is 'st'
171          * before processing instruction 'insn_idx'
172          * and after processing instruction 'prev_insn_idx'
173          */
174         struct bpf_verifier_state st;
175         int insn_idx;
176         int prev_insn_idx;
177         struct bpf_verifier_stack_elem *next;
178         /* length of verifier log at the time this state was pushed on stack */
179         u32 log_pos;
180 };
181
182 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
183 #define BPF_COMPLEXITY_LIMIT_STATES     64
184
185 #define BPF_MAP_KEY_POISON      (1ULL << 63)
186 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
187
188 #define BPF_MAP_PTR_UNPRIV      1UL
189 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
190                                           POISON_POINTER_DELTA))
191 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
192
193 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
194 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
195 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
196 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
197 static int ref_set_non_owning(struct bpf_verifier_env *env,
198                               struct bpf_reg_state *reg);
199 static void specialize_kfunc(struct bpf_verifier_env *env,
200                              u32 func_id, u16 offset, unsigned long *addr);
201 static bool is_trusted_reg(const struct bpf_reg_state *reg);
202
203 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
204 {
205         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
206 }
207
208 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
209 {
210         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
211 }
212
213 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
214                               const struct bpf_map *map, bool unpriv)
215 {
216         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
217         unpriv |= bpf_map_ptr_unpriv(aux);
218         aux->map_ptr_state = (unsigned long)map |
219                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
220 }
221
222 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
223 {
224         return aux->map_key_state & BPF_MAP_KEY_POISON;
225 }
226
227 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
228 {
229         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
230 }
231
232 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
233 {
234         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
235 }
236
237 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
238 {
239         bool poisoned = bpf_map_key_poisoned(aux);
240
241         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
242                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
243 }
244
245 static bool bpf_helper_call(const struct bpf_insn *insn)
246 {
247         return insn->code == (BPF_JMP | BPF_CALL) &&
248                insn->src_reg == 0;
249 }
250
251 static bool bpf_pseudo_call(const struct bpf_insn *insn)
252 {
253         return insn->code == (BPF_JMP | BPF_CALL) &&
254                insn->src_reg == BPF_PSEUDO_CALL;
255 }
256
257 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
258 {
259         return insn->code == (BPF_JMP | BPF_CALL) &&
260                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
261 }
262
263 struct bpf_call_arg_meta {
264         struct bpf_map *map_ptr;
265         bool raw_mode;
266         bool pkt_access;
267         u8 release_regno;
268         int regno;
269         int access_size;
270         int mem_size;
271         u64 msize_max_value;
272         int ref_obj_id;
273         int dynptr_id;
274         int map_uid;
275         int func_id;
276         struct btf *btf;
277         u32 btf_id;
278         struct btf *ret_btf;
279         u32 ret_btf_id;
280         u32 subprogno;
281         struct btf_field *kptr_field;
282 };
283
284 struct bpf_kfunc_call_arg_meta {
285         /* In parameters */
286         struct btf *btf;
287         u32 func_id;
288         u32 kfunc_flags;
289         const struct btf_type *func_proto;
290         const char *func_name;
291         /* Out parameters */
292         u32 ref_obj_id;
293         u8 release_regno;
294         bool r0_rdonly;
295         u32 ret_btf_id;
296         u64 r0_size;
297         u32 subprogno;
298         struct {
299                 u64 value;
300                 bool found;
301         } arg_constant;
302
303         /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
304          * generally to pass info about user-defined local kptr types to later
305          * verification logic
306          *   bpf_obj_drop
307          *     Record the local kptr type to be drop'd
308          *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
309          *     Record the local kptr type to be refcount_incr'd and use
310          *     arg_owning_ref to determine whether refcount_acquire should be
311          *     fallible
312          */
313         struct btf *arg_btf;
314         u32 arg_btf_id;
315         bool arg_owning_ref;
316
317         struct {
318                 struct btf_field *field;
319         } arg_list_head;
320         struct {
321                 struct btf_field *field;
322         } arg_rbtree_root;
323         struct {
324                 enum bpf_dynptr_type type;
325                 u32 id;
326                 u32 ref_obj_id;
327         } initialized_dynptr;
328         struct {
329                 u8 spi;
330                 u8 frameno;
331         } iter;
332         u64 mem_size;
333 };
334
335 struct btf *btf_vmlinux;
336
337 static DEFINE_MUTEX(bpf_verifier_lock);
338
339 static const struct bpf_line_info *
340 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
341 {
342         const struct bpf_line_info *linfo;
343         const struct bpf_prog *prog;
344         u32 i, nr_linfo;
345
346         prog = env->prog;
347         nr_linfo = prog->aux->nr_linfo;
348
349         if (!nr_linfo || insn_off >= prog->len)
350                 return NULL;
351
352         linfo = prog->aux->linfo;
353         for (i = 1; i < nr_linfo; i++)
354                 if (insn_off < linfo[i].insn_off)
355                         break;
356
357         return &linfo[i - 1];
358 }
359
360 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
361 {
362         struct bpf_verifier_env *env = private_data;
363         va_list args;
364
365         if (!bpf_verifier_log_needed(&env->log))
366                 return;
367
368         va_start(args, fmt);
369         bpf_verifier_vlog(&env->log, fmt, args);
370         va_end(args);
371 }
372
373 static const char *ltrim(const char *s)
374 {
375         while (isspace(*s))
376                 s++;
377
378         return s;
379 }
380
381 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
382                                          u32 insn_off,
383                                          const char *prefix_fmt, ...)
384 {
385         const struct bpf_line_info *linfo;
386
387         if (!bpf_verifier_log_needed(&env->log))
388                 return;
389
390         linfo = find_linfo(env, insn_off);
391         if (!linfo || linfo == env->prev_linfo)
392                 return;
393
394         if (prefix_fmt) {
395                 va_list args;
396
397                 va_start(args, prefix_fmt);
398                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
399                 va_end(args);
400         }
401
402         verbose(env, "%s\n",
403                 ltrim(btf_name_by_offset(env->prog->aux->btf,
404                                          linfo->line_off)));
405
406         env->prev_linfo = linfo;
407 }
408
409 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
410                                    struct bpf_reg_state *reg,
411                                    struct tnum *range, const char *ctx,
412                                    const char *reg_name)
413 {
414         char tn_buf[48];
415
416         verbose(env, "At %s the register %s ", ctx, reg_name);
417         if (!tnum_is_unknown(reg->var_off)) {
418                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
419                 verbose(env, "has value %s", tn_buf);
420         } else {
421                 verbose(env, "has unknown scalar value");
422         }
423         tnum_strn(tn_buf, sizeof(tn_buf), *range);
424         verbose(env, " should have been in %s\n", tn_buf);
425 }
426
427 static bool type_is_pkt_pointer(enum bpf_reg_type type)
428 {
429         type = base_type(type);
430         return type == PTR_TO_PACKET ||
431                type == PTR_TO_PACKET_META;
432 }
433
434 static bool type_is_sk_pointer(enum bpf_reg_type type)
435 {
436         return type == PTR_TO_SOCKET ||
437                 type == PTR_TO_SOCK_COMMON ||
438                 type == PTR_TO_TCP_SOCK ||
439                 type == PTR_TO_XDP_SOCK;
440 }
441
442 static bool type_may_be_null(u32 type)
443 {
444         return type & PTR_MAYBE_NULL;
445 }
446
447 static bool reg_not_null(const struct bpf_reg_state *reg)
448 {
449         enum bpf_reg_type type;
450
451         type = reg->type;
452         if (type_may_be_null(type))
453                 return false;
454
455         type = base_type(type);
456         return type == PTR_TO_SOCKET ||
457                 type == PTR_TO_TCP_SOCK ||
458                 type == PTR_TO_MAP_VALUE ||
459                 type == PTR_TO_MAP_KEY ||
460                 type == PTR_TO_SOCK_COMMON ||
461                 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
462                 type == PTR_TO_MEM;
463 }
464
465 static bool type_is_ptr_alloc_obj(u32 type)
466 {
467         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
468 }
469
470 static bool type_is_non_owning_ref(u32 type)
471 {
472         return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
473 }
474
475 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
476 {
477         struct btf_record *rec = NULL;
478         struct btf_struct_meta *meta;
479
480         if (reg->type == PTR_TO_MAP_VALUE) {
481                 rec = reg->map_ptr->record;
482         } else if (type_is_ptr_alloc_obj(reg->type)) {
483                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
484                 if (meta)
485                         rec = meta->record;
486         }
487         return rec;
488 }
489
490 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
491 {
492         struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
493
494         return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
495 }
496
497 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
498 {
499         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
500 }
501
502 static bool type_is_rdonly_mem(u32 type)
503 {
504         return type & MEM_RDONLY;
505 }
506
507 static bool is_acquire_function(enum bpf_func_id func_id,
508                                 const struct bpf_map *map)
509 {
510         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
511
512         if (func_id == BPF_FUNC_sk_lookup_tcp ||
513             func_id == BPF_FUNC_sk_lookup_udp ||
514             func_id == BPF_FUNC_skc_lookup_tcp ||
515             func_id == BPF_FUNC_ringbuf_reserve ||
516             func_id == BPF_FUNC_kptr_xchg)
517                 return true;
518
519         if (func_id == BPF_FUNC_map_lookup_elem &&
520             (map_type == BPF_MAP_TYPE_SOCKMAP ||
521              map_type == BPF_MAP_TYPE_SOCKHASH))
522                 return true;
523
524         return false;
525 }
526
527 static bool is_ptr_cast_function(enum bpf_func_id func_id)
528 {
529         return func_id == BPF_FUNC_tcp_sock ||
530                 func_id == BPF_FUNC_sk_fullsock ||
531                 func_id == BPF_FUNC_skc_to_tcp_sock ||
532                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
533                 func_id == BPF_FUNC_skc_to_udp6_sock ||
534                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
535                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
536                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
537 }
538
539 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
540 {
541         return func_id == BPF_FUNC_dynptr_data;
542 }
543
544 static bool is_callback_calling_kfunc(u32 btf_id);
545
546 static bool is_callback_calling_function(enum bpf_func_id func_id)
547 {
548         return func_id == BPF_FUNC_for_each_map_elem ||
549                func_id == BPF_FUNC_timer_set_callback ||
550                func_id == BPF_FUNC_find_vma ||
551                func_id == BPF_FUNC_loop ||
552                func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557         return func_id == BPF_FUNC_timer_set_callback;
558 }
559
560 static bool is_storage_get_function(enum bpf_func_id func_id)
561 {
562         return func_id == BPF_FUNC_sk_storage_get ||
563                func_id == BPF_FUNC_inode_storage_get ||
564                func_id == BPF_FUNC_task_storage_get ||
565                func_id == BPF_FUNC_cgrp_storage_get;
566 }
567
568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569                                         const struct bpf_map *map)
570 {
571         int ref_obj_uses = 0;
572
573         if (is_ptr_cast_function(func_id))
574                 ref_obj_uses++;
575         if (is_acquire_function(func_id, map))
576                 ref_obj_uses++;
577         if (is_dynptr_ref_function(func_id))
578                 ref_obj_uses++;
579
580         return ref_obj_uses > 1;
581 }
582
583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 {
585         return BPF_CLASS(insn->code) == BPF_STX &&
586                BPF_MODE(insn->code) == BPF_ATOMIC &&
587                insn->imm == BPF_CMPXCHG;
588 }
589
590 /* string representation of 'enum bpf_reg_type'
591  *
592  * Note that reg_type_str() can not appear more than once in a single verbose()
593  * statement.
594  */
595 static const char *reg_type_str(struct bpf_verifier_env *env,
596                                 enum bpf_reg_type type)
597 {
598         char postfix[16] = {0}, prefix[64] = {0};
599         static const char * const str[] = {
600                 [NOT_INIT]              = "?",
601                 [SCALAR_VALUE]          = "scalar",
602                 [PTR_TO_CTX]            = "ctx",
603                 [CONST_PTR_TO_MAP]      = "map_ptr",
604                 [PTR_TO_MAP_VALUE]      = "map_value",
605                 [PTR_TO_STACK]          = "fp",
606                 [PTR_TO_PACKET]         = "pkt",
607                 [PTR_TO_PACKET_META]    = "pkt_meta",
608                 [PTR_TO_PACKET_END]     = "pkt_end",
609                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
610                 [PTR_TO_SOCKET]         = "sock",
611                 [PTR_TO_SOCK_COMMON]    = "sock_common",
612                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
613                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
614                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
615                 [PTR_TO_BTF_ID]         = "ptr_",
616                 [PTR_TO_MEM]            = "mem",
617                 [PTR_TO_BUF]            = "buf",
618                 [PTR_TO_FUNC]           = "func",
619                 [PTR_TO_MAP_KEY]        = "map_key",
620                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
621         };
622
623         if (type & PTR_MAYBE_NULL) {
624                 if (base_type(type) == PTR_TO_BTF_ID)
625                         strncpy(postfix, "or_null_", 16);
626                 else
627                         strncpy(postfix, "_or_null", 16);
628         }
629
630         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
631                  type & MEM_RDONLY ? "rdonly_" : "",
632                  type & MEM_RINGBUF ? "ringbuf_" : "",
633                  type & MEM_USER ? "user_" : "",
634                  type & MEM_PERCPU ? "percpu_" : "",
635                  type & MEM_RCU ? "rcu_" : "",
636                  type & PTR_UNTRUSTED ? "untrusted_" : "",
637                  type & PTR_TRUSTED ? "trusted_" : ""
638         );
639
640         snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
641                  prefix, str[base_type(type)], postfix);
642         return env->tmp_str_buf;
643 }
644
645 static char slot_type_char[] = {
646         [STACK_INVALID] = '?',
647         [STACK_SPILL]   = 'r',
648         [STACK_MISC]    = 'm',
649         [STACK_ZERO]    = '0',
650         [STACK_DYNPTR]  = 'd',
651         [STACK_ITER]    = 'i',
652 };
653
654 static void print_liveness(struct bpf_verifier_env *env,
655                            enum bpf_reg_liveness live)
656 {
657         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
658             verbose(env, "_");
659         if (live & REG_LIVE_READ)
660                 verbose(env, "r");
661         if (live & REG_LIVE_WRITTEN)
662                 verbose(env, "w");
663         if (live & REG_LIVE_DONE)
664                 verbose(env, "D");
665 }
666
667 static int __get_spi(s32 off)
668 {
669         return (-off - 1) / BPF_REG_SIZE;
670 }
671
672 static struct bpf_func_state *func(struct bpf_verifier_env *env,
673                                    const struct bpf_reg_state *reg)
674 {
675         struct bpf_verifier_state *cur = env->cur_state;
676
677         return cur->frame[reg->frameno];
678 }
679
680 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
681 {
682        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
683
684        /* We need to check that slots between [spi - nr_slots + 1, spi] are
685         * within [0, allocated_stack).
686         *
687         * Please note that the spi grows downwards. For example, a dynptr
688         * takes the size of two stack slots; the first slot will be at
689         * spi and the second slot will be at spi - 1.
690         */
691        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
692 }
693
694 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
695                                   const char *obj_kind, int nr_slots)
696 {
697         int off, spi;
698
699         if (!tnum_is_const(reg->var_off)) {
700                 verbose(env, "%s has to be at a constant offset\n", obj_kind);
701                 return -EINVAL;
702         }
703
704         off = reg->off + reg->var_off.value;
705         if (off % BPF_REG_SIZE) {
706                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
707                 return -EINVAL;
708         }
709
710         spi = __get_spi(off);
711         if (spi + 1 < nr_slots) {
712                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
713                 return -EINVAL;
714         }
715
716         if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
717                 return -ERANGE;
718         return spi;
719 }
720
721 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
722 {
723         return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
724 }
725
726 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
727 {
728         return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
729 }
730
731 static const char *btf_type_name(const struct btf *btf, u32 id)
732 {
733         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
734 }
735
736 static const char *dynptr_type_str(enum bpf_dynptr_type type)
737 {
738         switch (type) {
739         case BPF_DYNPTR_TYPE_LOCAL:
740                 return "local";
741         case BPF_DYNPTR_TYPE_RINGBUF:
742                 return "ringbuf";
743         case BPF_DYNPTR_TYPE_SKB:
744                 return "skb";
745         case BPF_DYNPTR_TYPE_XDP:
746                 return "xdp";
747         case BPF_DYNPTR_TYPE_INVALID:
748                 return "<invalid>";
749         default:
750                 WARN_ONCE(1, "unknown dynptr type %d\n", type);
751                 return "<unknown>";
752         }
753 }
754
755 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
756 {
757         if (!btf || btf_id == 0)
758                 return "<invalid>";
759
760         /* we already validated that type is valid and has conforming name */
761         return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
762 }
763
764 static const char *iter_state_str(enum bpf_iter_state state)
765 {
766         switch (state) {
767         case BPF_ITER_STATE_ACTIVE:
768                 return "active";
769         case BPF_ITER_STATE_DRAINED:
770                 return "drained";
771         case BPF_ITER_STATE_INVALID:
772                 return "<invalid>";
773         default:
774                 WARN_ONCE(1, "unknown iter state %d\n", state);
775                 return "<unknown>";
776         }
777 }
778
779 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
780 {
781         env->scratched_regs |= 1U << regno;
782 }
783
784 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
785 {
786         env->scratched_stack_slots |= 1ULL << spi;
787 }
788
789 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
790 {
791         return (env->scratched_regs >> regno) & 1;
792 }
793
794 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
795 {
796         return (env->scratched_stack_slots >> regno) & 1;
797 }
798
799 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
800 {
801         return env->scratched_regs || env->scratched_stack_slots;
802 }
803
804 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
805 {
806         env->scratched_regs = 0U;
807         env->scratched_stack_slots = 0ULL;
808 }
809
810 /* Used for printing the entire verifier state. */
811 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
812 {
813         env->scratched_regs = ~0U;
814         env->scratched_stack_slots = ~0ULL;
815 }
816
817 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
818 {
819         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
820         case DYNPTR_TYPE_LOCAL:
821                 return BPF_DYNPTR_TYPE_LOCAL;
822         case DYNPTR_TYPE_RINGBUF:
823                 return BPF_DYNPTR_TYPE_RINGBUF;
824         case DYNPTR_TYPE_SKB:
825                 return BPF_DYNPTR_TYPE_SKB;
826         case DYNPTR_TYPE_XDP:
827                 return BPF_DYNPTR_TYPE_XDP;
828         default:
829                 return BPF_DYNPTR_TYPE_INVALID;
830         }
831 }
832
833 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
834 {
835         switch (type) {
836         case BPF_DYNPTR_TYPE_LOCAL:
837                 return DYNPTR_TYPE_LOCAL;
838         case BPF_DYNPTR_TYPE_RINGBUF:
839                 return DYNPTR_TYPE_RINGBUF;
840         case BPF_DYNPTR_TYPE_SKB:
841                 return DYNPTR_TYPE_SKB;
842         case BPF_DYNPTR_TYPE_XDP:
843                 return DYNPTR_TYPE_XDP;
844         default:
845                 return 0;
846         }
847 }
848
849 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
850 {
851         return type == BPF_DYNPTR_TYPE_RINGBUF;
852 }
853
854 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
855                               enum bpf_dynptr_type type,
856                               bool first_slot, int dynptr_id);
857
858 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
859                                 struct bpf_reg_state *reg);
860
861 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
862                                    struct bpf_reg_state *sreg1,
863                                    struct bpf_reg_state *sreg2,
864                                    enum bpf_dynptr_type type)
865 {
866         int id = ++env->id_gen;
867
868         __mark_dynptr_reg(sreg1, type, true, id);
869         __mark_dynptr_reg(sreg2, type, false, id);
870 }
871
872 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
873                                struct bpf_reg_state *reg,
874                                enum bpf_dynptr_type type)
875 {
876         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
877 }
878
879 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
880                                         struct bpf_func_state *state, int spi);
881
882 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
883                                    enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
884 {
885         struct bpf_func_state *state = func(env, reg);
886         enum bpf_dynptr_type type;
887         int spi, i, err;
888
889         spi = dynptr_get_spi(env, reg);
890         if (spi < 0)
891                 return spi;
892
893         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
894          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
895          * to ensure that for the following example:
896          *      [d1][d1][d2][d2]
897          * spi    3   2   1   0
898          * So marking spi = 2 should lead to destruction of both d1 and d2. In
899          * case they do belong to same dynptr, second call won't see slot_type
900          * as STACK_DYNPTR and will simply skip destruction.
901          */
902         err = destroy_if_dynptr_stack_slot(env, state, spi);
903         if (err)
904                 return err;
905         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
906         if (err)
907                 return err;
908
909         for (i = 0; i < BPF_REG_SIZE; i++) {
910                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
911                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
912         }
913
914         type = arg_to_dynptr_type(arg_type);
915         if (type == BPF_DYNPTR_TYPE_INVALID)
916                 return -EINVAL;
917
918         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
919                                &state->stack[spi - 1].spilled_ptr, type);
920
921         if (dynptr_type_refcounted(type)) {
922                 /* The id is used to track proper releasing */
923                 int id;
924
925                 if (clone_ref_obj_id)
926                         id = clone_ref_obj_id;
927                 else
928                         id = acquire_reference_state(env, insn_idx);
929
930                 if (id < 0)
931                         return id;
932
933                 state->stack[spi].spilled_ptr.ref_obj_id = id;
934                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
935         }
936
937         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
938         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
939
940         return 0;
941 }
942
943 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
944 {
945         int i;
946
947         for (i = 0; i < BPF_REG_SIZE; i++) {
948                 state->stack[spi].slot_type[i] = STACK_INVALID;
949                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
950         }
951
952         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
953         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
954
955         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
956          *
957          * While we don't allow reading STACK_INVALID, it is still possible to
958          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
959          * helpers or insns can do partial read of that part without failing,
960          * but check_stack_range_initialized, check_stack_read_var_off, and
961          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
962          * the slot conservatively. Hence we need to prevent those liveness
963          * marking walks.
964          *
965          * This was not a problem before because STACK_INVALID is only set by
966          * default (where the default reg state has its reg->parent as NULL), or
967          * in clean_live_states after REG_LIVE_DONE (at which point
968          * mark_reg_read won't walk reg->parent chain), but not randomly during
969          * verifier state exploration (like we did above). Hence, for our case
970          * parentage chain will still be live (i.e. reg->parent may be
971          * non-NULL), while earlier reg->parent was NULL, so we need
972          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
973          * done later on reads or by mark_dynptr_read as well to unnecessary
974          * mark registers in verifier state.
975          */
976         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
977         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
978 }
979
980 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
981 {
982         struct bpf_func_state *state = func(env, reg);
983         int spi, ref_obj_id, i;
984
985         spi = dynptr_get_spi(env, reg);
986         if (spi < 0)
987                 return spi;
988
989         if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
990                 invalidate_dynptr(env, state, spi);
991                 return 0;
992         }
993
994         ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
995
996         /* If the dynptr has a ref_obj_id, then we need to invalidate
997          * two things:
998          *
999          * 1) Any dynptrs with a matching ref_obj_id (clones)
1000          * 2) Any slices derived from this dynptr.
1001          */
1002
1003         /* Invalidate any slices associated with this dynptr */
1004         WARN_ON_ONCE(release_reference(env, ref_obj_id));
1005
1006         /* Invalidate any dynptr clones */
1007         for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1008                 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1009                         continue;
1010
1011                 /* it should always be the case that if the ref obj id
1012                  * matches then the stack slot also belongs to a
1013                  * dynptr
1014                  */
1015                 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1016                         verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1017                         return -EFAULT;
1018                 }
1019                 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1020                         invalidate_dynptr(env, state, i);
1021         }
1022
1023         return 0;
1024 }
1025
1026 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1027                                struct bpf_reg_state *reg);
1028
1029 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1030 {
1031         if (!env->allow_ptr_leaks)
1032                 __mark_reg_not_init(env, reg);
1033         else
1034                 __mark_reg_unknown(env, reg);
1035 }
1036
1037 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1038                                         struct bpf_func_state *state, int spi)
1039 {
1040         struct bpf_func_state *fstate;
1041         struct bpf_reg_state *dreg;
1042         int i, dynptr_id;
1043
1044         /* We always ensure that STACK_DYNPTR is never set partially,
1045          * hence just checking for slot_type[0] is enough. This is
1046          * different for STACK_SPILL, where it may be only set for
1047          * 1 byte, so code has to use is_spilled_reg.
1048          */
1049         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1050                 return 0;
1051
1052         /* Reposition spi to first slot */
1053         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1054                 spi = spi + 1;
1055
1056         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1057                 verbose(env, "cannot overwrite referenced dynptr\n");
1058                 return -EINVAL;
1059         }
1060
1061         mark_stack_slot_scratched(env, spi);
1062         mark_stack_slot_scratched(env, spi - 1);
1063
1064         /* Writing partially to one dynptr stack slot destroys both. */
1065         for (i = 0; i < BPF_REG_SIZE; i++) {
1066                 state->stack[spi].slot_type[i] = STACK_INVALID;
1067                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1068         }
1069
1070         dynptr_id = state->stack[spi].spilled_ptr.id;
1071         /* Invalidate any slices associated with this dynptr */
1072         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1073                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1074                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1075                         continue;
1076                 if (dreg->dynptr_id == dynptr_id)
1077                         mark_reg_invalid(env, dreg);
1078         }));
1079
1080         /* Do not release reference state, we are destroying dynptr on stack,
1081          * not using some helper to release it. Just reset register.
1082          */
1083         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1084         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1085
1086         /* Same reason as unmark_stack_slots_dynptr above */
1087         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1088         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089
1090         return 0;
1091 }
1092
1093 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1094 {
1095         int spi;
1096
1097         if (reg->type == CONST_PTR_TO_DYNPTR)
1098                 return false;
1099
1100         spi = dynptr_get_spi(env, reg);
1101
1102         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1103          * error because this just means the stack state hasn't been updated yet.
1104          * We will do check_mem_access to check and update stack bounds later.
1105          */
1106         if (spi < 0 && spi != -ERANGE)
1107                 return false;
1108
1109         /* We don't need to check if the stack slots are marked by previous
1110          * dynptr initializations because we allow overwriting existing unreferenced
1111          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1112          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1113          * touching are completely destructed before we reinitialize them for a new
1114          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1115          * instead of delaying it until the end where the user will get "Unreleased
1116          * reference" error.
1117          */
1118         return true;
1119 }
1120
1121 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1122 {
1123         struct bpf_func_state *state = func(env, reg);
1124         int i, spi;
1125
1126         /* This already represents first slot of initialized bpf_dynptr.
1127          *
1128          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1129          * check_func_arg_reg_off's logic, so we don't need to check its
1130          * offset and alignment.
1131          */
1132         if (reg->type == CONST_PTR_TO_DYNPTR)
1133                 return true;
1134
1135         spi = dynptr_get_spi(env, reg);
1136         if (spi < 0)
1137                 return false;
1138         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1139                 return false;
1140
1141         for (i = 0; i < BPF_REG_SIZE; i++) {
1142                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1143                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1144                         return false;
1145         }
1146
1147         return true;
1148 }
1149
1150 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1151                                     enum bpf_arg_type arg_type)
1152 {
1153         struct bpf_func_state *state = func(env, reg);
1154         enum bpf_dynptr_type dynptr_type;
1155         int spi;
1156
1157         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1158         if (arg_type == ARG_PTR_TO_DYNPTR)
1159                 return true;
1160
1161         dynptr_type = arg_to_dynptr_type(arg_type);
1162         if (reg->type == CONST_PTR_TO_DYNPTR) {
1163                 return reg->dynptr.type == dynptr_type;
1164         } else {
1165                 spi = dynptr_get_spi(env, reg);
1166                 if (spi < 0)
1167                         return false;
1168                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1169         }
1170 }
1171
1172 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1173
1174 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1175                                  struct bpf_reg_state *reg, int insn_idx,
1176                                  struct btf *btf, u32 btf_id, int nr_slots)
1177 {
1178         struct bpf_func_state *state = func(env, reg);
1179         int spi, i, j, id;
1180
1181         spi = iter_get_spi(env, reg, nr_slots);
1182         if (spi < 0)
1183                 return spi;
1184
1185         id = acquire_reference_state(env, insn_idx);
1186         if (id < 0)
1187                 return id;
1188
1189         for (i = 0; i < nr_slots; i++) {
1190                 struct bpf_stack_state *slot = &state->stack[spi - i];
1191                 struct bpf_reg_state *st = &slot->spilled_ptr;
1192
1193                 __mark_reg_known_zero(st);
1194                 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1195                 st->live |= REG_LIVE_WRITTEN;
1196                 st->ref_obj_id = i == 0 ? id : 0;
1197                 st->iter.btf = btf;
1198                 st->iter.btf_id = btf_id;
1199                 st->iter.state = BPF_ITER_STATE_ACTIVE;
1200                 st->iter.depth = 0;
1201
1202                 for (j = 0; j < BPF_REG_SIZE; j++)
1203                         slot->slot_type[j] = STACK_ITER;
1204
1205                 mark_stack_slot_scratched(env, spi - i);
1206         }
1207
1208         return 0;
1209 }
1210
1211 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1212                                    struct bpf_reg_state *reg, int nr_slots)
1213 {
1214         struct bpf_func_state *state = func(env, reg);
1215         int spi, i, j;
1216
1217         spi = iter_get_spi(env, reg, nr_slots);
1218         if (spi < 0)
1219                 return spi;
1220
1221         for (i = 0; i < nr_slots; i++) {
1222                 struct bpf_stack_state *slot = &state->stack[spi - i];
1223                 struct bpf_reg_state *st = &slot->spilled_ptr;
1224
1225                 if (i == 0)
1226                         WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1227
1228                 __mark_reg_not_init(env, st);
1229
1230                 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1231                 st->live |= REG_LIVE_WRITTEN;
1232
1233                 for (j = 0; j < BPF_REG_SIZE; j++)
1234                         slot->slot_type[j] = STACK_INVALID;
1235
1236                 mark_stack_slot_scratched(env, spi - i);
1237         }
1238
1239         return 0;
1240 }
1241
1242 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1243                                      struct bpf_reg_state *reg, int nr_slots)
1244 {
1245         struct bpf_func_state *state = func(env, reg);
1246         int spi, i, j;
1247
1248         /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1249          * will do check_mem_access to check and update stack bounds later, so
1250          * return true for that case.
1251          */
1252         spi = iter_get_spi(env, reg, nr_slots);
1253         if (spi == -ERANGE)
1254                 return true;
1255         if (spi < 0)
1256                 return false;
1257
1258         for (i = 0; i < nr_slots; i++) {
1259                 struct bpf_stack_state *slot = &state->stack[spi - i];
1260
1261                 for (j = 0; j < BPF_REG_SIZE; j++)
1262                         if (slot->slot_type[j] == STACK_ITER)
1263                                 return false;
1264         }
1265
1266         return true;
1267 }
1268
1269 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1270                                    struct btf *btf, u32 btf_id, int nr_slots)
1271 {
1272         struct bpf_func_state *state = func(env, reg);
1273         int spi, i, j;
1274
1275         spi = iter_get_spi(env, reg, nr_slots);
1276         if (spi < 0)
1277                 return false;
1278
1279         for (i = 0; i < nr_slots; i++) {
1280                 struct bpf_stack_state *slot = &state->stack[spi - i];
1281                 struct bpf_reg_state *st = &slot->spilled_ptr;
1282
1283                 /* only main (first) slot has ref_obj_id set */
1284                 if (i == 0 && !st->ref_obj_id)
1285                         return false;
1286                 if (i != 0 && st->ref_obj_id)
1287                         return false;
1288                 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1289                         return false;
1290
1291                 for (j = 0; j < BPF_REG_SIZE; j++)
1292                         if (slot->slot_type[j] != STACK_ITER)
1293                                 return false;
1294         }
1295
1296         return true;
1297 }
1298
1299 /* Check if given stack slot is "special":
1300  *   - spilled register state (STACK_SPILL);
1301  *   - dynptr state (STACK_DYNPTR);
1302  *   - iter state (STACK_ITER).
1303  */
1304 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1305 {
1306         enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1307
1308         switch (type) {
1309         case STACK_SPILL:
1310         case STACK_DYNPTR:
1311         case STACK_ITER:
1312                 return true;
1313         case STACK_INVALID:
1314         case STACK_MISC:
1315         case STACK_ZERO:
1316                 return false;
1317         default:
1318                 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1319                 return true;
1320         }
1321 }
1322
1323 /* The reg state of a pointer or a bounded scalar was saved when
1324  * it was spilled to the stack.
1325  */
1326 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1327 {
1328         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1329 }
1330
1331 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1332 {
1333         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1334                stack->spilled_ptr.type == SCALAR_VALUE;
1335 }
1336
1337 static void scrub_spilled_slot(u8 *stype)
1338 {
1339         if (*stype != STACK_INVALID)
1340                 *stype = STACK_MISC;
1341 }
1342
1343 static void print_verifier_state(struct bpf_verifier_env *env,
1344                                  const struct bpf_func_state *state,
1345                                  bool print_all)
1346 {
1347         const struct bpf_reg_state *reg;
1348         enum bpf_reg_type t;
1349         int i;
1350
1351         if (state->frameno)
1352                 verbose(env, " frame%d:", state->frameno);
1353         for (i = 0; i < MAX_BPF_REG; i++) {
1354                 reg = &state->regs[i];
1355                 t = reg->type;
1356                 if (t == NOT_INIT)
1357                         continue;
1358                 if (!print_all && !reg_scratched(env, i))
1359                         continue;
1360                 verbose(env, " R%d", i);
1361                 print_liveness(env, reg->live);
1362                 verbose(env, "=");
1363                 if (t == SCALAR_VALUE && reg->precise)
1364                         verbose(env, "P");
1365                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1366                     tnum_is_const(reg->var_off)) {
1367                         /* reg->off should be 0 for SCALAR_VALUE */
1368                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1369                         verbose(env, "%lld", reg->var_off.value + reg->off);
1370                 } else {
1371                         const char *sep = "";
1372
1373                         verbose(env, "%s", reg_type_str(env, t));
1374                         if (base_type(t) == PTR_TO_BTF_ID)
1375                                 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1376                         verbose(env, "(");
1377 /*
1378  * _a stands for append, was shortened to avoid multiline statements below.
1379  * This macro is used to output a comma separated list of attributes.
1380  */
1381 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1382
1383                         if (reg->id)
1384                                 verbose_a("id=%d", reg->id);
1385                         if (reg->ref_obj_id)
1386                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1387                         if (type_is_non_owning_ref(reg->type))
1388                                 verbose_a("%s", "non_own_ref");
1389                         if (t != SCALAR_VALUE)
1390                                 verbose_a("off=%d", reg->off);
1391                         if (type_is_pkt_pointer(t))
1392                                 verbose_a("r=%d", reg->range);
1393                         else if (base_type(t) == CONST_PTR_TO_MAP ||
1394                                  base_type(t) == PTR_TO_MAP_KEY ||
1395                                  base_type(t) == PTR_TO_MAP_VALUE)
1396                                 verbose_a("ks=%d,vs=%d",
1397                                           reg->map_ptr->key_size,
1398                                           reg->map_ptr->value_size);
1399                         if (tnum_is_const(reg->var_off)) {
1400                                 /* Typically an immediate SCALAR_VALUE, but
1401                                  * could be a pointer whose offset is too big
1402                                  * for reg->off
1403                                  */
1404                                 verbose_a("imm=%llx", reg->var_off.value);
1405                         } else {
1406                                 if (reg->smin_value != reg->umin_value &&
1407                                     reg->smin_value != S64_MIN)
1408                                         verbose_a("smin=%lld", (long long)reg->smin_value);
1409                                 if (reg->smax_value != reg->umax_value &&
1410                                     reg->smax_value != S64_MAX)
1411                                         verbose_a("smax=%lld", (long long)reg->smax_value);
1412                                 if (reg->umin_value != 0)
1413                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1414                                 if (reg->umax_value != U64_MAX)
1415                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1416                                 if (!tnum_is_unknown(reg->var_off)) {
1417                                         char tn_buf[48];
1418
1419                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1420                                         verbose_a("var_off=%s", tn_buf);
1421                                 }
1422                                 if (reg->s32_min_value != reg->smin_value &&
1423                                     reg->s32_min_value != S32_MIN)
1424                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1425                                 if (reg->s32_max_value != reg->smax_value &&
1426                                     reg->s32_max_value != S32_MAX)
1427                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1428                                 if (reg->u32_min_value != reg->umin_value &&
1429                                     reg->u32_min_value != U32_MIN)
1430                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1431                                 if (reg->u32_max_value != reg->umax_value &&
1432                                     reg->u32_max_value != U32_MAX)
1433                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1434                         }
1435 #undef verbose_a
1436
1437                         verbose(env, ")");
1438                 }
1439         }
1440         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1441                 char types_buf[BPF_REG_SIZE + 1];
1442                 bool valid = false;
1443                 int j;
1444
1445                 for (j = 0; j < BPF_REG_SIZE; j++) {
1446                         if (state->stack[i].slot_type[j] != STACK_INVALID)
1447                                 valid = true;
1448                         types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1449                 }
1450                 types_buf[BPF_REG_SIZE] = 0;
1451                 if (!valid)
1452                         continue;
1453                 if (!print_all && !stack_slot_scratched(env, i))
1454                         continue;
1455                 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1456                 case STACK_SPILL:
1457                         reg = &state->stack[i].spilled_ptr;
1458                         t = reg->type;
1459
1460                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1461                         print_liveness(env, reg->live);
1462                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1463                         if (t == SCALAR_VALUE && reg->precise)
1464                                 verbose(env, "P");
1465                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1466                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1467                         break;
1468                 case STACK_DYNPTR:
1469                         i += BPF_DYNPTR_NR_SLOTS - 1;
1470                         reg = &state->stack[i].spilled_ptr;
1471
1472                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473                         print_liveness(env, reg->live);
1474                         verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1475                         if (reg->ref_obj_id)
1476                                 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1477                         break;
1478                 case STACK_ITER:
1479                         /* only main slot has ref_obj_id set; skip others */
1480                         reg = &state->stack[i].spilled_ptr;
1481                         if (!reg->ref_obj_id)
1482                                 continue;
1483
1484                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485                         print_liveness(env, reg->live);
1486                         verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1487                                 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1488                                 reg->ref_obj_id, iter_state_str(reg->iter.state),
1489                                 reg->iter.depth);
1490                         break;
1491                 case STACK_MISC:
1492                 case STACK_ZERO:
1493                 default:
1494                         reg = &state->stack[i].spilled_ptr;
1495
1496                         for (j = 0; j < BPF_REG_SIZE; j++)
1497                                 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1498                         types_buf[BPF_REG_SIZE] = 0;
1499
1500                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1501                         print_liveness(env, reg->live);
1502                         verbose(env, "=%s", types_buf);
1503                         break;
1504                 }
1505         }
1506         if (state->acquired_refs && state->refs[0].id) {
1507                 verbose(env, " refs=%d", state->refs[0].id);
1508                 for (i = 1; i < state->acquired_refs; i++)
1509                         if (state->refs[i].id)
1510                                 verbose(env, ",%d", state->refs[i].id);
1511         }
1512         if (state->in_callback_fn)
1513                 verbose(env, " cb");
1514         if (state->in_async_callback_fn)
1515                 verbose(env, " async_cb");
1516         verbose(env, "\n");
1517         mark_verifier_state_clean(env);
1518 }
1519
1520 static inline u32 vlog_alignment(u32 pos)
1521 {
1522         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1523                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1524 }
1525
1526 static void print_insn_state(struct bpf_verifier_env *env,
1527                              const struct bpf_func_state *state)
1528 {
1529         if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1530                 /* remove new line character */
1531                 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1532                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1533         } else {
1534                 verbose(env, "%d:", env->insn_idx);
1535         }
1536         print_verifier_state(env, state, false);
1537 }
1538
1539 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1540  * small to hold src. This is different from krealloc since we don't want to preserve
1541  * the contents of dst.
1542  *
1543  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1544  * not be allocated.
1545  */
1546 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1547 {
1548         size_t alloc_bytes;
1549         void *orig = dst;
1550         size_t bytes;
1551
1552         if (ZERO_OR_NULL_PTR(src))
1553                 goto out;
1554
1555         if (unlikely(check_mul_overflow(n, size, &bytes)))
1556                 return NULL;
1557
1558         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1559         dst = krealloc(orig, alloc_bytes, flags);
1560         if (!dst) {
1561                 kfree(orig);
1562                 return NULL;
1563         }
1564
1565         memcpy(dst, src, bytes);
1566 out:
1567         return dst ? dst : ZERO_SIZE_PTR;
1568 }
1569
1570 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1571  * small to hold new_n items. new items are zeroed out if the array grows.
1572  *
1573  * Contrary to krealloc_array, does not free arr if new_n is zero.
1574  */
1575 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1576 {
1577         size_t alloc_size;
1578         void *new_arr;
1579
1580         if (!new_n || old_n == new_n)
1581                 goto out;
1582
1583         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1584         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1585         if (!new_arr) {
1586                 kfree(arr);
1587                 return NULL;
1588         }
1589         arr = new_arr;
1590
1591         if (new_n > old_n)
1592                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1593
1594 out:
1595         return arr ? arr : ZERO_SIZE_PTR;
1596 }
1597
1598 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1599 {
1600         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1601                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1602         if (!dst->refs)
1603                 return -ENOMEM;
1604
1605         dst->acquired_refs = src->acquired_refs;
1606         return 0;
1607 }
1608
1609 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1610 {
1611         size_t n = src->allocated_stack / BPF_REG_SIZE;
1612
1613         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1614                                 GFP_KERNEL);
1615         if (!dst->stack)
1616                 return -ENOMEM;
1617
1618         dst->allocated_stack = src->allocated_stack;
1619         return 0;
1620 }
1621
1622 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1623 {
1624         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1625                                     sizeof(struct bpf_reference_state));
1626         if (!state->refs)
1627                 return -ENOMEM;
1628
1629         state->acquired_refs = n;
1630         return 0;
1631 }
1632
1633 static int grow_stack_state(struct bpf_func_state *state, int size)
1634 {
1635         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1636
1637         if (old_n >= n)
1638                 return 0;
1639
1640         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1641         if (!state->stack)
1642                 return -ENOMEM;
1643
1644         state->allocated_stack = size;
1645         return 0;
1646 }
1647
1648 /* Acquire a pointer id from the env and update the state->refs to include
1649  * this new pointer reference.
1650  * On success, returns a valid pointer id to associate with the register
1651  * On failure, returns a negative errno.
1652  */
1653 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1654 {
1655         struct bpf_func_state *state = cur_func(env);
1656         int new_ofs = state->acquired_refs;
1657         int id, err;
1658
1659         err = resize_reference_state(state, state->acquired_refs + 1);
1660         if (err)
1661                 return err;
1662         id = ++env->id_gen;
1663         state->refs[new_ofs].id = id;
1664         state->refs[new_ofs].insn_idx = insn_idx;
1665         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1666
1667         return id;
1668 }
1669
1670 /* release function corresponding to acquire_reference_state(). Idempotent. */
1671 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1672 {
1673         int i, last_idx;
1674
1675         last_idx = state->acquired_refs - 1;
1676         for (i = 0; i < state->acquired_refs; i++) {
1677                 if (state->refs[i].id == ptr_id) {
1678                         /* Cannot release caller references in callbacks */
1679                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1680                                 return -EINVAL;
1681                         if (last_idx && i != last_idx)
1682                                 memcpy(&state->refs[i], &state->refs[last_idx],
1683                                        sizeof(*state->refs));
1684                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1685                         state->acquired_refs--;
1686                         return 0;
1687                 }
1688         }
1689         return -EINVAL;
1690 }
1691
1692 static void free_func_state(struct bpf_func_state *state)
1693 {
1694         if (!state)
1695                 return;
1696         kfree(state->refs);
1697         kfree(state->stack);
1698         kfree(state);
1699 }
1700
1701 static void clear_jmp_history(struct bpf_verifier_state *state)
1702 {
1703         kfree(state->jmp_history);
1704         state->jmp_history = NULL;
1705         state->jmp_history_cnt = 0;
1706 }
1707
1708 static void free_verifier_state(struct bpf_verifier_state *state,
1709                                 bool free_self)
1710 {
1711         int i;
1712
1713         for (i = 0; i <= state->curframe; i++) {
1714                 free_func_state(state->frame[i]);
1715                 state->frame[i] = NULL;
1716         }
1717         clear_jmp_history(state);
1718         if (free_self)
1719                 kfree(state);
1720 }
1721
1722 /* copy verifier state from src to dst growing dst stack space
1723  * when necessary to accommodate larger src stack
1724  */
1725 static int copy_func_state(struct bpf_func_state *dst,
1726                            const struct bpf_func_state *src)
1727 {
1728         int err;
1729
1730         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1731         err = copy_reference_state(dst, src);
1732         if (err)
1733                 return err;
1734         return copy_stack_state(dst, src);
1735 }
1736
1737 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1738                                const struct bpf_verifier_state *src)
1739 {
1740         struct bpf_func_state *dst;
1741         int i, err;
1742
1743         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1744                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1745                                             GFP_USER);
1746         if (!dst_state->jmp_history)
1747                 return -ENOMEM;
1748         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1749
1750         /* if dst has more stack frames then src frame, free them */
1751         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752                 free_func_state(dst_state->frame[i]);
1753                 dst_state->frame[i] = NULL;
1754         }
1755         dst_state->speculative = src->speculative;
1756         dst_state->active_rcu_lock = src->active_rcu_lock;
1757         dst_state->curframe = src->curframe;
1758         dst_state->active_lock.ptr = src->active_lock.ptr;
1759         dst_state->active_lock.id = src->active_lock.id;
1760         dst_state->branches = src->branches;
1761         dst_state->parent = src->parent;
1762         dst_state->first_insn_idx = src->first_insn_idx;
1763         dst_state->last_insn_idx = src->last_insn_idx;
1764         for (i = 0; i <= src->curframe; i++) {
1765                 dst = dst_state->frame[i];
1766                 if (!dst) {
1767                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1768                         if (!dst)
1769                                 return -ENOMEM;
1770                         dst_state->frame[i] = dst;
1771                 }
1772                 err = copy_func_state(dst, src->frame[i]);
1773                 if (err)
1774                         return err;
1775         }
1776         return 0;
1777 }
1778
1779 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1780 {
1781         while (st) {
1782                 u32 br = --st->branches;
1783
1784                 /* WARN_ON(br > 1) technically makes sense here,
1785                  * but see comment in push_stack(), hence:
1786                  */
1787                 WARN_ONCE((int)br < 0,
1788                           "BUG update_branch_counts:branches_to_explore=%d\n",
1789                           br);
1790                 if (br)
1791                         break;
1792                 st = st->parent;
1793         }
1794 }
1795
1796 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1797                      int *insn_idx, bool pop_log)
1798 {
1799         struct bpf_verifier_state *cur = env->cur_state;
1800         struct bpf_verifier_stack_elem *elem, *head = env->head;
1801         int err;
1802
1803         if (env->head == NULL)
1804                 return -ENOENT;
1805
1806         if (cur) {
1807                 err = copy_verifier_state(cur, &head->st);
1808                 if (err)
1809                         return err;
1810         }
1811         if (pop_log)
1812                 bpf_vlog_reset(&env->log, head->log_pos);
1813         if (insn_idx)
1814                 *insn_idx = head->insn_idx;
1815         if (prev_insn_idx)
1816                 *prev_insn_idx = head->prev_insn_idx;
1817         elem = head->next;
1818         free_verifier_state(&head->st, false);
1819         kfree(head);
1820         env->head = elem;
1821         env->stack_size--;
1822         return 0;
1823 }
1824
1825 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1826                                              int insn_idx, int prev_insn_idx,
1827                                              bool speculative)
1828 {
1829         struct bpf_verifier_state *cur = env->cur_state;
1830         struct bpf_verifier_stack_elem *elem;
1831         int err;
1832
1833         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1834         if (!elem)
1835                 goto err;
1836
1837         elem->insn_idx = insn_idx;
1838         elem->prev_insn_idx = prev_insn_idx;
1839         elem->next = env->head;
1840         elem->log_pos = env->log.end_pos;
1841         env->head = elem;
1842         env->stack_size++;
1843         err = copy_verifier_state(&elem->st, cur);
1844         if (err)
1845                 goto err;
1846         elem->st.speculative |= speculative;
1847         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1848                 verbose(env, "The sequence of %d jumps is too complex.\n",
1849                         env->stack_size);
1850                 goto err;
1851         }
1852         if (elem->st.parent) {
1853                 ++elem->st.parent->branches;
1854                 /* WARN_ON(branches > 2) technically makes sense here,
1855                  * but
1856                  * 1. speculative states will bump 'branches' for non-branch
1857                  * instructions
1858                  * 2. is_state_visited() heuristics may decide not to create
1859                  * a new state for a sequence of branches and all such current
1860                  * and cloned states will be pointing to a single parent state
1861                  * which might have large 'branches' count.
1862                  */
1863         }
1864         return &elem->st;
1865 err:
1866         free_verifier_state(env->cur_state, true);
1867         env->cur_state = NULL;
1868         /* pop all elements and return */
1869         while (!pop_stack(env, NULL, NULL, false));
1870         return NULL;
1871 }
1872
1873 #define CALLER_SAVED_REGS 6
1874 static const int caller_saved[CALLER_SAVED_REGS] = {
1875         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1876 };
1877
1878 /* This helper doesn't clear reg->id */
1879 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1880 {
1881         reg->var_off = tnum_const(imm);
1882         reg->smin_value = (s64)imm;
1883         reg->smax_value = (s64)imm;
1884         reg->umin_value = imm;
1885         reg->umax_value = imm;
1886
1887         reg->s32_min_value = (s32)imm;
1888         reg->s32_max_value = (s32)imm;
1889         reg->u32_min_value = (u32)imm;
1890         reg->u32_max_value = (u32)imm;
1891 }
1892
1893 /* Mark the unknown part of a register (variable offset or scalar value) as
1894  * known to have the value @imm.
1895  */
1896 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1897 {
1898         /* Clear off and union(map_ptr, range) */
1899         memset(((u8 *)reg) + sizeof(reg->type), 0,
1900                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1901         reg->id = 0;
1902         reg->ref_obj_id = 0;
1903         ___mark_reg_known(reg, imm);
1904 }
1905
1906 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1907 {
1908         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1909         reg->s32_min_value = (s32)imm;
1910         reg->s32_max_value = (s32)imm;
1911         reg->u32_min_value = (u32)imm;
1912         reg->u32_max_value = (u32)imm;
1913 }
1914
1915 /* Mark the 'variable offset' part of a register as zero.  This should be
1916  * used only on registers holding a pointer type.
1917  */
1918 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1919 {
1920         __mark_reg_known(reg, 0);
1921 }
1922
1923 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1924 {
1925         __mark_reg_known(reg, 0);
1926         reg->type = SCALAR_VALUE;
1927 }
1928
1929 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1930                                 struct bpf_reg_state *regs, u32 regno)
1931 {
1932         if (WARN_ON(regno >= MAX_BPF_REG)) {
1933                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1934                 /* Something bad happened, let's kill all regs */
1935                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1936                         __mark_reg_not_init(env, regs + regno);
1937                 return;
1938         }
1939         __mark_reg_known_zero(regs + regno);
1940 }
1941
1942 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1943                               bool first_slot, int dynptr_id)
1944 {
1945         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1946          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1947          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1948          */
1949         __mark_reg_known_zero(reg);
1950         reg->type = CONST_PTR_TO_DYNPTR;
1951         /* Give each dynptr a unique id to uniquely associate slices to it. */
1952         reg->id = dynptr_id;
1953         reg->dynptr.type = type;
1954         reg->dynptr.first_slot = first_slot;
1955 }
1956
1957 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1958 {
1959         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1960                 const struct bpf_map *map = reg->map_ptr;
1961
1962                 if (map->inner_map_meta) {
1963                         reg->type = CONST_PTR_TO_MAP;
1964                         reg->map_ptr = map->inner_map_meta;
1965                         /* transfer reg's id which is unique for every map_lookup_elem
1966                          * as UID of the inner map.
1967                          */
1968                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1969                                 reg->map_uid = reg->id;
1970                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1971                         reg->type = PTR_TO_XDP_SOCK;
1972                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1973                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1974                         reg->type = PTR_TO_SOCKET;
1975                 } else {
1976                         reg->type = PTR_TO_MAP_VALUE;
1977                 }
1978                 return;
1979         }
1980
1981         reg->type &= ~PTR_MAYBE_NULL;
1982 }
1983
1984 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1985                                 struct btf_field_graph_root *ds_head)
1986 {
1987         __mark_reg_known_zero(&regs[regno]);
1988         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1989         regs[regno].btf = ds_head->btf;
1990         regs[regno].btf_id = ds_head->value_btf_id;
1991         regs[regno].off = ds_head->node_offset;
1992 }
1993
1994 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1995 {
1996         return type_is_pkt_pointer(reg->type);
1997 }
1998
1999 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2000 {
2001         return reg_is_pkt_pointer(reg) ||
2002                reg->type == PTR_TO_PACKET_END;
2003 }
2004
2005 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2006 {
2007         return base_type(reg->type) == PTR_TO_MEM &&
2008                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2009 }
2010
2011 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2012 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2013                                     enum bpf_reg_type which)
2014 {
2015         /* The register can already have a range from prior markings.
2016          * This is fine as long as it hasn't been advanced from its
2017          * origin.
2018          */
2019         return reg->type == which &&
2020                reg->id == 0 &&
2021                reg->off == 0 &&
2022                tnum_equals_const(reg->var_off, 0);
2023 }
2024
2025 /* Reset the min/max bounds of a register */
2026 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2027 {
2028         reg->smin_value = S64_MIN;
2029         reg->smax_value = S64_MAX;
2030         reg->umin_value = 0;
2031         reg->umax_value = U64_MAX;
2032
2033         reg->s32_min_value = S32_MIN;
2034         reg->s32_max_value = S32_MAX;
2035         reg->u32_min_value = 0;
2036         reg->u32_max_value = U32_MAX;
2037 }
2038
2039 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2040 {
2041         reg->smin_value = S64_MIN;
2042         reg->smax_value = S64_MAX;
2043         reg->umin_value = 0;
2044         reg->umax_value = U64_MAX;
2045 }
2046
2047 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2048 {
2049         reg->s32_min_value = S32_MIN;
2050         reg->s32_max_value = S32_MAX;
2051         reg->u32_min_value = 0;
2052         reg->u32_max_value = U32_MAX;
2053 }
2054
2055 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2056 {
2057         struct tnum var32_off = tnum_subreg(reg->var_off);
2058
2059         /* min signed is max(sign bit) | min(other bits) */
2060         reg->s32_min_value = max_t(s32, reg->s32_min_value,
2061                         var32_off.value | (var32_off.mask & S32_MIN));
2062         /* max signed is min(sign bit) | max(other bits) */
2063         reg->s32_max_value = min_t(s32, reg->s32_max_value,
2064                         var32_off.value | (var32_off.mask & S32_MAX));
2065         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2066         reg->u32_max_value = min(reg->u32_max_value,
2067                                  (u32)(var32_off.value | var32_off.mask));
2068 }
2069
2070 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2071 {
2072         /* min signed is max(sign bit) | min(other bits) */
2073         reg->smin_value = max_t(s64, reg->smin_value,
2074                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2075         /* max signed is min(sign bit) | max(other bits) */
2076         reg->smax_value = min_t(s64, reg->smax_value,
2077                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2078         reg->umin_value = max(reg->umin_value, reg->var_off.value);
2079         reg->umax_value = min(reg->umax_value,
2080                               reg->var_off.value | reg->var_off.mask);
2081 }
2082
2083 static void __update_reg_bounds(struct bpf_reg_state *reg)
2084 {
2085         __update_reg32_bounds(reg);
2086         __update_reg64_bounds(reg);
2087 }
2088
2089 /* Uses signed min/max values to inform unsigned, and vice-versa */
2090 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2091 {
2092         /* Learn sign from signed bounds.
2093          * If we cannot cross the sign boundary, then signed and unsigned bounds
2094          * are the same, so combine.  This works even in the negative case, e.g.
2095          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2096          */
2097         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2098                 reg->s32_min_value = reg->u32_min_value =
2099                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2100                 reg->s32_max_value = reg->u32_max_value =
2101                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2102                 return;
2103         }
2104         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2105          * boundary, so we must be careful.
2106          */
2107         if ((s32)reg->u32_max_value >= 0) {
2108                 /* Positive.  We can't learn anything from the smin, but smax
2109                  * is positive, hence safe.
2110                  */
2111                 reg->s32_min_value = reg->u32_min_value;
2112                 reg->s32_max_value = reg->u32_max_value =
2113                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2114         } else if ((s32)reg->u32_min_value < 0) {
2115                 /* Negative.  We can't learn anything from the smax, but smin
2116                  * is negative, hence safe.
2117                  */
2118                 reg->s32_min_value = reg->u32_min_value =
2119                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2120                 reg->s32_max_value = reg->u32_max_value;
2121         }
2122 }
2123
2124 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2125 {
2126         /* Learn sign from signed bounds.
2127          * If we cannot cross the sign boundary, then signed and unsigned bounds
2128          * are the same, so combine.  This works even in the negative case, e.g.
2129          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2130          */
2131         if (reg->smin_value >= 0 || reg->smax_value < 0) {
2132                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2133                                                           reg->umin_value);
2134                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2135                                                           reg->umax_value);
2136                 return;
2137         }
2138         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2139          * boundary, so we must be careful.
2140          */
2141         if ((s64)reg->umax_value >= 0) {
2142                 /* Positive.  We can't learn anything from the smin, but smax
2143                  * is positive, hence safe.
2144                  */
2145                 reg->smin_value = reg->umin_value;
2146                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2147                                                           reg->umax_value);
2148         } else if ((s64)reg->umin_value < 0) {
2149                 /* Negative.  We can't learn anything from the smax, but smin
2150                  * is negative, hence safe.
2151                  */
2152                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2153                                                           reg->umin_value);
2154                 reg->smax_value = reg->umax_value;
2155         }
2156 }
2157
2158 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2159 {
2160         __reg32_deduce_bounds(reg);
2161         __reg64_deduce_bounds(reg);
2162 }
2163
2164 /* Attempts to improve var_off based on unsigned min/max information */
2165 static void __reg_bound_offset(struct bpf_reg_state *reg)
2166 {
2167         struct tnum var64_off = tnum_intersect(reg->var_off,
2168                                                tnum_range(reg->umin_value,
2169                                                           reg->umax_value));
2170         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2171                                                tnum_range(reg->u32_min_value,
2172                                                           reg->u32_max_value));
2173
2174         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2175 }
2176
2177 static void reg_bounds_sync(struct bpf_reg_state *reg)
2178 {
2179         /* We might have learned new bounds from the var_off. */
2180         __update_reg_bounds(reg);
2181         /* We might have learned something about the sign bit. */
2182         __reg_deduce_bounds(reg);
2183         /* We might have learned some bits from the bounds. */
2184         __reg_bound_offset(reg);
2185         /* Intersecting with the old var_off might have improved our bounds
2186          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187          * then new var_off is (0; 0x7f...fc) which improves our umax.
2188          */
2189         __update_reg_bounds(reg);
2190 }
2191
2192 static bool __reg32_bound_s64(s32 a)
2193 {
2194         return a >= 0 && a <= S32_MAX;
2195 }
2196
2197 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2198 {
2199         reg->umin_value = reg->u32_min_value;
2200         reg->umax_value = reg->u32_max_value;
2201
2202         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2203          * be positive otherwise set to worse case bounds and refine later
2204          * from tnum.
2205          */
2206         if (__reg32_bound_s64(reg->s32_min_value) &&
2207             __reg32_bound_s64(reg->s32_max_value)) {
2208                 reg->smin_value = reg->s32_min_value;
2209                 reg->smax_value = reg->s32_max_value;
2210         } else {
2211                 reg->smin_value = 0;
2212                 reg->smax_value = U32_MAX;
2213         }
2214 }
2215
2216 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2217 {
2218         /* special case when 64-bit register has upper 32-bit register
2219          * zeroed. Typically happens after zext or <<32, >>32 sequence
2220          * allowing us to use 32-bit bounds directly,
2221          */
2222         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2223                 __reg_assign_32_into_64(reg);
2224         } else {
2225                 /* Otherwise the best we can do is push lower 32bit known and
2226                  * unknown bits into register (var_off set from jmp logic)
2227                  * then learn as much as possible from the 64-bit tnum
2228                  * known and unknown bits. The previous smin/smax bounds are
2229                  * invalid here because of jmp32 compare so mark them unknown
2230                  * so they do not impact tnum bounds calculation.
2231                  */
2232                 __mark_reg64_unbounded(reg);
2233         }
2234         reg_bounds_sync(reg);
2235 }
2236
2237 static bool __reg64_bound_s32(s64 a)
2238 {
2239         return a >= S32_MIN && a <= S32_MAX;
2240 }
2241
2242 static bool __reg64_bound_u32(u64 a)
2243 {
2244         return a >= U32_MIN && a <= U32_MAX;
2245 }
2246
2247 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2248 {
2249         __mark_reg32_unbounded(reg);
2250         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2251                 reg->s32_min_value = (s32)reg->smin_value;
2252                 reg->s32_max_value = (s32)reg->smax_value;
2253         }
2254         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2255                 reg->u32_min_value = (u32)reg->umin_value;
2256                 reg->u32_max_value = (u32)reg->umax_value;
2257         }
2258         reg_bounds_sync(reg);
2259 }
2260
2261 /* Mark a register as having a completely unknown (scalar) value. */
2262 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2263                                struct bpf_reg_state *reg)
2264 {
2265         /*
2266          * Clear type, off, and union(map_ptr, range) and
2267          * padding between 'type' and union
2268          */
2269         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2270         reg->type = SCALAR_VALUE;
2271         reg->id = 0;
2272         reg->ref_obj_id = 0;
2273         reg->var_off = tnum_unknown;
2274         reg->frameno = 0;
2275         reg->precise = !env->bpf_capable;
2276         __mark_reg_unbounded(reg);
2277 }
2278
2279 static void mark_reg_unknown(struct bpf_verifier_env *env,
2280                              struct bpf_reg_state *regs, u32 regno)
2281 {
2282         if (WARN_ON(regno >= MAX_BPF_REG)) {
2283                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2284                 /* Something bad happened, let's kill all regs except FP */
2285                 for (regno = 0; regno < BPF_REG_FP; regno++)
2286                         __mark_reg_not_init(env, regs + regno);
2287                 return;
2288         }
2289         __mark_reg_unknown(env, regs + regno);
2290 }
2291
2292 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2293                                 struct bpf_reg_state *reg)
2294 {
2295         __mark_reg_unknown(env, reg);
2296         reg->type = NOT_INIT;
2297 }
2298
2299 static void mark_reg_not_init(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_not_init(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_not_init(env, regs + regno);
2310 }
2311
2312 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2313                             struct bpf_reg_state *regs, u32 regno,
2314                             enum bpf_reg_type reg_type,
2315                             struct btf *btf, u32 btf_id,
2316                             enum bpf_type_flag flag)
2317 {
2318         if (reg_type == SCALAR_VALUE) {
2319                 mark_reg_unknown(env, regs, regno);
2320                 return;
2321         }
2322         mark_reg_known_zero(env, regs, regno);
2323         regs[regno].type = PTR_TO_BTF_ID | flag;
2324         regs[regno].btf = btf;
2325         regs[regno].btf_id = btf_id;
2326 }
2327
2328 #define DEF_NOT_SUBREG  (0)
2329 static void init_reg_state(struct bpf_verifier_env *env,
2330                            struct bpf_func_state *state)
2331 {
2332         struct bpf_reg_state *regs = state->regs;
2333         int i;
2334
2335         for (i = 0; i < MAX_BPF_REG; i++) {
2336                 mark_reg_not_init(env, regs, i);
2337                 regs[i].live = REG_LIVE_NONE;
2338                 regs[i].parent = NULL;
2339                 regs[i].subreg_def = DEF_NOT_SUBREG;
2340         }
2341
2342         /* frame pointer */
2343         regs[BPF_REG_FP].type = PTR_TO_STACK;
2344         mark_reg_known_zero(env, regs, BPF_REG_FP);
2345         regs[BPF_REG_FP].frameno = state->frameno;
2346 }
2347
2348 #define BPF_MAIN_FUNC (-1)
2349 static void init_func_state(struct bpf_verifier_env *env,
2350                             struct bpf_func_state *state,
2351                             int callsite, int frameno, int subprogno)
2352 {
2353         state->callsite = callsite;
2354         state->frameno = frameno;
2355         state->subprogno = subprogno;
2356         state->callback_ret_range = tnum_range(0, 0);
2357         init_reg_state(env, state);
2358         mark_verifier_state_scratched(env);
2359 }
2360
2361 /* Similar to push_stack(), but for async callbacks */
2362 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2363                                                 int insn_idx, int prev_insn_idx,
2364                                                 int subprog)
2365 {
2366         struct bpf_verifier_stack_elem *elem;
2367         struct bpf_func_state *frame;
2368
2369         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2370         if (!elem)
2371                 goto err;
2372
2373         elem->insn_idx = insn_idx;
2374         elem->prev_insn_idx = prev_insn_idx;
2375         elem->next = env->head;
2376         elem->log_pos = env->log.end_pos;
2377         env->head = elem;
2378         env->stack_size++;
2379         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2380                 verbose(env,
2381                         "The sequence of %d jumps is too complex for async cb.\n",
2382                         env->stack_size);
2383                 goto err;
2384         }
2385         /* Unlike push_stack() do not copy_verifier_state().
2386          * The caller state doesn't matter.
2387          * This is async callback. It starts in a fresh stack.
2388          * Initialize it similar to do_check_common().
2389          */
2390         elem->st.branches = 1;
2391         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2392         if (!frame)
2393                 goto err;
2394         init_func_state(env, frame,
2395                         BPF_MAIN_FUNC /* callsite */,
2396                         0 /* frameno within this callchain */,
2397                         subprog /* subprog number within this prog */);
2398         elem->st.frame[0] = frame;
2399         return &elem->st;
2400 err:
2401         free_verifier_state(env->cur_state, true);
2402         env->cur_state = NULL;
2403         /* pop all elements and return */
2404         while (!pop_stack(env, NULL, NULL, false));
2405         return NULL;
2406 }
2407
2408
2409 enum reg_arg_type {
2410         SRC_OP,         /* register is used as source operand */
2411         DST_OP,         /* register is used as destination operand */
2412         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2413 };
2414
2415 static int cmp_subprogs(const void *a, const void *b)
2416 {
2417         return ((struct bpf_subprog_info *)a)->start -
2418                ((struct bpf_subprog_info *)b)->start;
2419 }
2420
2421 static int find_subprog(struct bpf_verifier_env *env, int off)
2422 {
2423         struct bpf_subprog_info *p;
2424
2425         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2426                     sizeof(env->subprog_info[0]), cmp_subprogs);
2427         if (!p)
2428                 return -ENOENT;
2429         return p - env->subprog_info;
2430
2431 }
2432
2433 static int add_subprog(struct bpf_verifier_env *env, int off)
2434 {
2435         int insn_cnt = env->prog->len;
2436         int ret;
2437
2438         if (off >= insn_cnt || off < 0) {
2439                 verbose(env, "call to invalid destination\n");
2440                 return -EINVAL;
2441         }
2442         ret = find_subprog(env, off);
2443         if (ret >= 0)
2444                 return ret;
2445         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2446                 verbose(env, "too many subprograms\n");
2447                 return -E2BIG;
2448         }
2449         /* determine subprog starts. The end is one before the next starts */
2450         env->subprog_info[env->subprog_cnt++].start = off;
2451         sort(env->subprog_info, env->subprog_cnt,
2452              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2453         return env->subprog_cnt - 1;
2454 }
2455
2456 #define MAX_KFUNC_DESCS 256
2457 #define MAX_KFUNC_BTFS  256
2458
2459 struct bpf_kfunc_desc {
2460         struct btf_func_model func_model;
2461         u32 func_id;
2462         s32 imm;
2463         u16 offset;
2464         unsigned long addr;
2465 };
2466
2467 struct bpf_kfunc_btf {
2468         struct btf *btf;
2469         struct module *module;
2470         u16 offset;
2471 };
2472
2473 struct bpf_kfunc_desc_tab {
2474         /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2475          * verification. JITs do lookups by bpf_insn, where func_id may not be
2476          * available, therefore at the end of verification do_misc_fixups()
2477          * sorts this by imm and offset.
2478          */
2479         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2480         u32 nr_descs;
2481 };
2482
2483 struct bpf_kfunc_btf_tab {
2484         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2485         u32 nr_descs;
2486 };
2487
2488 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2489 {
2490         const struct bpf_kfunc_desc *d0 = a;
2491         const struct bpf_kfunc_desc *d1 = b;
2492
2493         /* func_id is not greater than BTF_MAX_TYPE */
2494         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2495 }
2496
2497 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2498 {
2499         const struct bpf_kfunc_btf *d0 = a;
2500         const struct bpf_kfunc_btf *d1 = b;
2501
2502         return d0->offset - d1->offset;
2503 }
2504
2505 static const struct bpf_kfunc_desc *
2506 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2507 {
2508         struct bpf_kfunc_desc desc = {
2509                 .func_id = func_id,
2510                 .offset = offset,
2511         };
2512         struct bpf_kfunc_desc_tab *tab;
2513
2514         tab = prog->aux->kfunc_tab;
2515         return bsearch(&desc, tab->descs, tab->nr_descs,
2516                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2517 }
2518
2519 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2520                        u16 btf_fd_idx, u8 **func_addr)
2521 {
2522         const struct bpf_kfunc_desc *desc;
2523
2524         desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2525         if (!desc)
2526                 return -EFAULT;
2527
2528         *func_addr = (u8 *)desc->addr;
2529         return 0;
2530 }
2531
2532 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2533                                          s16 offset)
2534 {
2535         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2536         struct bpf_kfunc_btf_tab *tab;
2537         struct bpf_kfunc_btf *b;
2538         struct module *mod;
2539         struct btf *btf;
2540         int btf_fd;
2541
2542         tab = env->prog->aux->kfunc_btf_tab;
2543         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2544                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2545         if (!b) {
2546                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2547                         verbose(env, "too many different module BTFs\n");
2548                         return ERR_PTR(-E2BIG);
2549                 }
2550
2551                 if (bpfptr_is_null(env->fd_array)) {
2552                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2553                         return ERR_PTR(-EPROTO);
2554                 }
2555
2556                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2557                                             offset * sizeof(btf_fd),
2558                                             sizeof(btf_fd)))
2559                         return ERR_PTR(-EFAULT);
2560
2561                 btf = btf_get_by_fd(btf_fd);
2562                 if (IS_ERR(btf)) {
2563                         verbose(env, "invalid module BTF fd specified\n");
2564                         return btf;
2565                 }
2566
2567                 if (!btf_is_module(btf)) {
2568                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2569                         btf_put(btf);
2570                         return ERR_PTR(-EINVAL);
2571                 }
2572
2573                 mod = btf_try_get_module(btf);
2574                 if (!mod) {
2575                         btf_put(btf);
2576                         return ERR_PTR(-ENXIO);
2577                 }
2578
2579                 b = &tab->descs[tab->nr_descs++];
2580                 b->btf = btf;
2581                 b->module = mod;
2582                 b->offset = offset;
2583
2584                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2585                      kfunc_btf_cmp_by_off, NULL);
2586         }
2587         return b->btf;
2588 }
2589
2590 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2591 {
2592         if (!tab)
2593                 return;
2594
2595         while (tab->nr_descs--) {
2596                 module_put(tab->descs[tab->nr_descs].module);
2597                 btf_put(tab->descs[tab->nr_descs].btf);
2598         }
2599         kfree(tab);
2600 }
2601
2602 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2603 {
2604         if (offset) {
2605                 if (offset < 0) {
2606                         /* In the future, this can be allowed to increase limit
2607                          * of fd index into fd_array, interpreted as u16.
2608                          */
2609                         verbose(env, "negative offset disallowed for kernel module function call\n");
2610                         return ERR_PTR(-EINVAL);
2611                 }
2612
2613                 return __find_kfunc_desc_btf(env, offset);
2614         }
2615         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2616 }
2617
2618 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2619 {
2620         const struct btf_type *func, *func_proto;
2621         struct bpf_kfunc_btf_tab *btf_tab;
2622         struct bpf_kfunc_desc_tab *tab;
2623         struct bpf_prog_aux *prog_aux;
2624         struct bpf_kfunc_desc *desc;
2625         const char *func_name;
2626         struct btf *desc_btf;
2627         unsigned long call_imm;
2628         unsigned long addr;
2629         int err;
2630
2631         prog_aux = env->prog->aux;
2632         tab = prog_aux->kfunc_tab;
2633         btf_tab = prog_aux->kfunc_btf_tab;
2634         if (!tab) {
2635                 if (!btf_vmlinux) {
2636                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2637                         return -ENOTSUPP;
2638                 }
2639
2640                 if (!env->prog->jit_requested) {
2641                         verbose(env, "JIT is required for calling kernel function\n");
2642                         return -ENOTSUPP;
2643                 }
2644
2645                 if (!bpf_jit_supports_kfunc_call()) {
2646                         verbose(env, "JIT does not support calling kernel function\n");
2647                         return -ENOTSUPP;
2648                 }
2649
2650                 if (!env->prog->gpl_compatible) {
2651                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2652                         return -EINVAL;
2653                 }
2654
2655                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2656                 if (!tab)
2657                         return -ENOMEM;
2658                 prog_aux->kfunc_tab = tab;
2659         }
2660
2661         /* func_id == 0 is always invalid, but instead of returning an error, be
2662          * conservative and wait until the code elimination pass before returning
2663          * error, so that invalid calls that get pruned out can be in BPF programs
2664          * loaded from userspace.  It is also required that offset be untouched
2665          * for such calls.
2666          */
2667         if (!func_id && !offset)
2668                 return 0;
2669
2670         if (!btf_tab && offset) {
2671                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2672                 if (!btf_tab)
2673                         return -ENOMEM;
2674                 prog_aux->kfunc_btf_tab = btf_tab;
2675         }
2676
2677         desc_btf = find_kfunc_desc_btf(env, offset);
2678         if (IS_ERR(desc_btf)) {
2679                 verbose(env, "failed to find BTF for kernel function\n");
2680                 return PTR_ERR(desc_btf);
2681         }
2682
2683         if (find_kfunc_desc(env->prog, func_id, offset))
2684                 return 0;
2685
2686         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2687                 verbose(env, "too many different kernel function calls\n");
2688                 return -E2BIG;
2689         }
2690
2691         func = btf_type_by_id(desc_btf, func_id);
2692         if (!func || !btf_type_is_func(func)) {
2693                 verbose(env, "kernel btf_id %u is not a function\n",
2694                         func_id);
2695                 return -EINVAL;
2696         }
2697         func_proto = btf_type_by_id(desc_btf, func->type);
2698         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2699                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2700                         func_id);
2701                 return -EINVAL;
2702         }
2703
2704         func_name = btf_name_by_offset(desc_btf, func->name_off);
2705         addr = kallsyms_lookup_name(func_name);
2706         if (!addr) {
2707                 verbose(env, "cannot find address for kernel function %s\n",
2708                         func_name);
2709                 return -EINVAL;
2710         }
2711         specialize_kfunc(env, func_id, offset, &addr);
2712
2713         if (bpf_jit_supports_far_kfunc_call()) {
2714                 call_imm = func_id;
2715         } else {
2716                 call_imm = BPF_CALL_IMM(addr);
2717                 /* Check whether the relative offset overflows desc->imm */
2718                 if ((unsigned long)(s32)call_imm != call_imm) {
2719                         verbose(env, "address of kernel function %s is out of range\n",
2720                                 func_name);
2721                         return -EINVAL;
2722                 }
2723         }
2724
2725         if (bpf_dev_bound_kfunc_id(func_id)) {
2726                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2727                 if (err)
2728                         return err;
2729         }
2730
2731         desc = &tab->descs[tab->nr_descs++];
2732         desc->func_id = func_id;
2733         desc->imm = call_imm;
2734         desc->offset = offset;
2735         desc->addr = addr;
2736         err = btf_distill_func_proto(&env->log, desc_btf,
2737                                      func_proto, func_name,
2738                                      &desc->func_model);
2739         if (!err)
2740                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2741                      kfunc_desc_cmp_by_id_off, NULL);
2742         return err;
2743 }
2744
2745 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2746 {
2747         const struct bpf_kfunc_desc *d0 = a;
2748         const struct bpf_kfunc_desc *d1 = b;
2749
2750         if (d0->imm != d1->imm)
2751                 return d0->imm < d1->imm ? -1 : 1;
2752         if (d0->offset != d1->offset)
2753                 return d0->offset < d1->offset ? -1 : 1;
2754         return 0;
2755 }
2756
2757 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2758 {
2759         struct bpf_kfunc_desc_tab *tab;
2760
2761         tab = prog->aux->kfunc_tab;
2762         if (!tab)
2763                 return;
2764
2765         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2766              kfunc_desc_cmp_by_imm_off, NULL);
2767 }
2768
2769 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2770 {
2771         return !!prog->aux->kfunc_tab;
2772 }
2773
2774 const struct btf_func_model *
2775 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2776                          const struct bpf_insn *insn)
2777 {
2778         const struct bpf_kfunc_desc desc = {
2779                 .imm = insn->imm,
2780                 .offset = insn->off,
2781         };
2782         const struct bpf_kfunc_desc *res;
2783         struct bpf_kfunc_desc_tab *tab;
2784
2785         tab = prog->aux->kfunc_tab;
2786         res = bsearch(&desc, tab->descs, tab->nr_descs,
2787                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2788
2789         return res ? &res->func_model : NULL;
2790 }
2791
2792 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2793 {
2794         struct bpf_subprog_info *subprog = env->subprog_info;
2795         struct bpf_insn *insn = env->prog->insnsi;
2796         int i, ret, insn_cnt = env->prog->len;
2797
2798         /* Add entry function. */
2799         ret = add_subprog(env, 0);
2800         if (ret)
2801                 return ret;
2802
2803         for (i = 0; i < insn_cnt; i++, insn++) {
2804                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2805                     !bpf_pseudo_kfunc_call(insn))
2806                         continue;
2807
2808                 if (!env->bpf_capable) {
2809                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2810                         return -EPERM;
2811                 }
2812
2813                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2814                         ret = add_subprog(env, i + insn->imm + 1);
2815                 else
2816                         ret = add_kfunc_call(env, insn->imm, insn->off);
2817
2818                 if (ret < 0)
2819                         return ret;
2820         }
2821
2822         /* Add a fake 'exit' subprog which could simplify subprog iteration
2823          * logic. 'subprog_cnt' should not be increased.
2824          */
2825         subprog[env->subprog_cnt].start = insn_cnt;
2826
2827         if (env->log.level & BPF_LOG_LEVEL2)
2828                 for (i = 0; i < env->subprog_cnt; i++)
2829                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2830
2831         return 0;
2832 }
2833
2834 static int check_subprogs(struct bpf_verifier_env *env)
2835 {
2836         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2837         struct bpf_subprog_info *subprog = env->subprog_info;
2838         struct bpf_insn *insn = env->prog->insnsi;
2839         int insn_cnt = env->prog->len;
2840
2841         /* now check that all jumps are within the same subprog */
2842         subprog_start = subprog[cur_subprog].start;
2843         subprog_end = subprog[cur_subprog + 1].start;
2844         for (i = 0; i < insn_cnt; i++) {
2845                 u8 code = insn[i].code;
2846
2847                 if (code == (BPF_JMP | BPF_CALL) &&
2848                     insn[i].src_reg == 0 &&
2849                     insn[i].imm == BPF_FUNC_tail_call)
2850                         subprog[cur_subprog].has_tail_call = true;
2851                 if (BPF_CLASS(code) == BPF_LD &&
2852                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2853                         subprog[cur_subprog].has_ld_abs = true;
2854                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2855                         goto next;
2856                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2857                         goto next;
2858                 off = i + insn[i].off + 1;
2859                 if (off < subprog_start || off >= subprog_end) {
2860                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2861                         return -EINVAL;
2862                 }
2863 next:
2864                 if (i == subprog_end - 1) {
2865                         /* to avoid fall-through from one subprog into another
2866                          * the last insn of the subprog should be either exit
2867                          * or unconditional jump back
2868                          */
2869                         if (code != (BPF_JMP | BPF_EXIT) &&
2870                             code != (BPF_JMP | BPF_JA)) {
2871                                 verbose(env, "last insn is not an exit or jmp\n");
2872                                 return -EINVAL;
2873                         }
2874                         subprog_start = subprog_end;
2875                         cur_subprog++;
2876                         if (cur_subprog < env->subprog_cnt)
2877                                 subprog_end = subprog[cur_subprog + 1].start;
2878                 }
2879         }
2880         return 0;
2881 }
2882
2883 /* Parentage chain of this register (or stack slot) should take care of all
2884  * issues like callee-saved registers, stack slot allocation time, etc.
2885  */
2886 static int mark_reg_read(struct bpf_verifier_env *env,
2887                          const struct bpf_reg_state *state,
2888                          struct bpf_reg_state *parent, u8 flag)
2889 {
2890         bool writes = parent == state->parent; /* Observe write marks */
2891         int cnt = 0;
2892
2893         while (parent) {
2894                 /* if read wasn't screened by an earlier write ... */
2895                 if (writes && state->live & REG_LIVE_WRITTEN)
2896                         break;
2897                 if (parent->live & REG_LIVE_DONE) {
2898                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2899                                 reg_type_str(env, parent->type),
2900                                 parent->var_off.value, parent->off);
2901                         return -EFAULT;
2902                 }
2903                 /* The first condition is more likely to be true than the
2904                  * second, checked it first.
2905                  */
2906                 if ((parent->live & REG_LIVE_READ) == flag ||
2907                     parent->live & REG_LIVE_READ64)
2908                         /* The parentage chain never changes and
2909                          * this parent was already marked as LIVE_READ.
2910                          * There is no need to keep walking the chain again and
2911                          * keep re-marking all parents as LIVE_READ.
2912                          * This case happens when the same register is read
2913                          * multiple times without writes into it in-between.
2914                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2915                          * then no need to set the weak REG_LIVE_READ32.
2916                          */
2917                         break;
2918                 /* ... then we depend on parent's value */
2919                 parent->live |= flag;
2920                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2921                 if (flag == REG_LIVE_READ64)
2922                         parent->live &= ~REG_LIVE_READ32;
2923                 state = parent;
2924                 parent = state->parent;
2925                 writes = true;
2926                 cnt++;
2927         }
2928
2929         if (env->longest_mark_read_walk < cnt)
2930                 env->longest_mark_read_walk = cnt;
2931         return 0;
2932 }
2933
2934 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2935 {
2936         struct bpf_func_state *state = func(env, reg);
2937         int spi, ret;
2938
2939         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2940          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2941          * check_kfunc_call.
2942          */
2943         if (reg->type == CONST_PTR_TO_DYNPTR)
2944                 return 0;
2945         spi = dynptr_get_spi(env, reg);
2946         if (spi < 0)
2947                 return spi;
2948         /* Caller ensures dynptr is valid and initialized, which means spi is in
2949          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2950          * read.
2951          */
2952         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2953                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2954         if (ret)
2955                 return ret;
2956         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2957                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2958 }
2959
2960 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2961                           int spi, int nr_slots)
2962 {
2963         struct bpf_func_state *state = func(env, reg);
2964         int err, i;
2965
2966         for (i = 0; i < nr_slots; i++) {
2967                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2968
2969                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2970                 if (err)
2971                         return err;
2972
2973                 mark_stack_slot_scratched(env, spi - i);
2974         }
2975
2976         return 0;
2977 }
2978
2979 /* This function is supposed to be used by the following 32-bit optimization
2980  * code only. It returns TRUE if the source or destination register operates
2981  * on 64-bit, otherwise return FALSE.
2982  */
2983 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2984                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2985 {
2986         u8 code, class, op;
2987
2988         code = insn->code;
2989         class = BPF_CLASS(code);
2990         op = BPF_OP(code);
2991         if (class == BPF_JMP) {
2992                 /* BPF_EXIT for "main" will reach here. Return TRUE
2993                  * conservatively.
2994                  */
2995                 if (op == BPF_EXIT)
2996                         return true;
2997                 if (op == BPF_CALL) {
2998                         /* BPF to BPF call will reach here because of marking
2999                          * caller saved clobber with DST_OP_NO_MARK for which we
3000                          * don't care the register def because they are anyway
3001                          * marked as NOT_INIT already.
3002                          */
3003                         if (insn->src_reg == BPF_PSEUDO_CALL)
3004                                 return false;
3005                         /* Helper call will reach here because of arg type
3006                          * check, conservatively return TRUE.
3007                          */
3008                         if (t == SRC_OP)
3009                                 return true;
3010
3011                         return false;
3012                 }
3013         }
3014
3015         if (class == BPF_ALU64 || class == BPF_JMP ||
3016             /* BPF_END always use BPF_ALU class. */
3017             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3018                 return true;
3019
3020         if (class == BPF_ALU || class == BPF_JMP32)
3021                 return false;
3022
3023         if (class == BPF_LDX) {
3024                 if (t != SRC_OP)
3025                         return BPF_SIZE(code) == BPF_DW;
3026                 /* LDX source must be ptr. */
3027                 return true;
3028         }
3029
3030         if (class == BPF_STX) {
3031                 /* BPF_STX (including atomic variants) has multiple source
3032                  * operands, one of which is a ptr. Check whether the caller is
3033                  * asking about it.
3034                  */
3035                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3036                         return true;
3037                 return BPF_SIZE(code) == BPF_DW;
3038         }
3039
3040         if (class == BPF_LD) {
3041                 u8 mode = BPF_MODE(code);
3042
3043                 /* LD_IMM64 */
3044                 if (mode == BPF_IMM)
3045                         return true;
3046
3047                 /* Both LD_IND and LD_ABS return 32-bit data. */
3048                 if (t != SRC_OP)
3049                         return  false;
3050
3051                 /* Implicit ctx ptr. */
3052                 if (regno == BPF_REG_6)
3053                         return true;
3054
3055                 /* Explicit source could be any width. */
3056                 return true;
3057         }
3058
3059         if (class == BPF_ST)
3060                 /* The only source register for BPF_ST is a ptr. */
3061                 return true;
3062
3063         /* Conservatively return true at default. */
3064         return true;
3065 }
3066
3067 /* Return the regno defined by the insn, or -1. */
3068 static int insn_def_regno(const struct bpf_insn *insn)
3069 {
3070         switch (BPF_CLASS(insn->code)) {
3071         case BPF_JMP:
3072         case BPF_JMP32:
3073         case BPF_ST:
3074                 return -1;
3075         case BPF_STX:
3076                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3077                     (insn->imm & BPF_FETCH)) {
3078                         if (insn->imm == BPF_CMPXCHG)
3079                                 return BPF_REG_0;
3080                         else
3081                                 return insn->src_reg;
3082                 } else {
3083                         return -1;
3084                 }
3085         default:
3086                 return insn->dst_reg;
3087         }
3088 }
3089
3090 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3091 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3092 {
3093         int dst_reg = insn_def_regno(insn);
3094
3095         if (dst_reg == -1)
3096                 return false;
3097
3098         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3099 }
3100
3101 static void mark_insn_zext(struct bpf_verifier_env *env,
3102                            struct bpf_reg_state *reg)
3103 {
3104         s32 def_idx = reg->subreg_def;
3105
3106         if (def_idx == DEF_NOT_SUBREG)
3107                 return;
3108
3109         env->insn_aux_data[def_idx - 1].zext_dst = true;
3110         /* The dst will be zero extended, so won't be sub-register anymore. */
3111         reg->subreg_def = DEF_NOT_SUBREG;
3112 }
3113
3114 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3115                          enum reg_arg_type t)
3116 {
3117         struct bpf_verifier_state *vstate = env->cur_state;
3118         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3119         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3120         struct bpf_reg_state *reg, *regs = state->regs;
3121         bool rw64;
3122
3123         if (regno >= MAX_BPF_REG) {
3124                 verbose(env, "R%d is invalid\n", regno);
3125                 return -EINVAL;
3126         }
3127
3128         mark_reg_scratched(env, regno);
3129
3130         reg = &regs[regno];
3131         rw64 = is_reg64(env, insn, regno, reg, t);
3132         if (t == SRC_OP) {
3133                 /* check whether register used as source operand can be read */
3134                 if (reg->type == NOT_INIT) {
3135                         verbose(env, "R%d !read_ok\n", regno);
3136                         return -EACCES;
3137                 }
3138                 /* We don't need to worry about FP liveness because it's read-only */
3139                 if (regno == BPF_REG_FP)
3140                         return 0;
3141
3142                 if (rw64)
3143                         mark_insn_zext(env, reg);
3144
3145                 return mark_reg_read(env, reg, reg->parent,
3146                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3147         } else {
3148                 /* check whether register used as dest operand can be written to */
3149                 if (regno == BPF_REG_FP) {
3150                         verbose(env, "frame pointer is read only\n");
3151                         return -EACCES;
3152                 }
3153                 reg->live |= REG_LIVE_WRITTEN;
3154                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3155                 if (t == DST_OP)
3156                         mark_reg_unknown(env, regs, regno);
3157         }
3158         return 0;
3159 }
3160
3161 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3162 {
3163         env->insn_aux_data[idx].jmp_point = true;
3164 }
3165
3166 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3167 {
3168         return env->insn_aux_data[insn_idx].jmp_point;
3169 }
3170
3171 /* for any branch, call, exit record the history of jmps in the given state */
3172 static int push_jmp_history(struct bpf_verifier_env *env,
3173                             struct bpf_verifier_state *cur)
3174 {
3175         u32 cnt = cur->jmp_history_cnt;
3176         struct bpf_idx_pair *p;
3177         size_t alloc_size;
3178
3179         if (!is_jmp_point(env, env->insn_idx))
3180                 return 0;
3181
3182         cnt++;
3183         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3184         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3185         if (!p)
3186                 return -ENOMEM;
3187         p[cnt - 1].idx = env->insn_idx;
3188         p[cnt - 1].prev_idx = env->prev_insn_idx;
3189         cur->jmp_history = p;
3190         cur->jmp_history_cnt = cnt;
3191         return 0;
3192 }
3193
3194 /* Backtrack one insn at a time. If idx is not at the top of recorded
3195  * history then previous instruction came from straight line execution.
3196  */
3197 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3198                              u32 *history)
3199 {
3200         u32 cnt = *history;
3201
3202         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3203                 i = st->jmp_history[cnt - 1].prev_idx;
3204                 (*history)--;
3205         } else {
3206                 i--;
3207         }
3208         return i;
3209 }
3210
3211 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3212 {
3213         const struct btf_type *func;
3214         struct btf *desc_btf;
3215
3216         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3217                 return NULL;
3218
3219         desc_btf = find_kfunc_desc_btf(data, insn->off);
3220         if (IS_ERR(desc_btf))
3221                 return "<error>";
3222
3223         func = btf_type_by_id(desc_btf, insn->imm);
3224         return btf_name_by_offset(desc_btf, func->name_off);
3225 }
3226
3227 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3228 {
3229         bt->frame = frame;
3230 }
3231
3232 static inline void bt_reset(struct backtrack_state *bt)
3233 {
3234         struct bpf_verifier_env *env = bt->env;
3235
3236         memset(bt, 0, sizeof(*bt));
3237         bt->env = env;
3238 }
3239
3240 static inline u32 bt_empty(struct backtrack_state *bt)
3241 {
3242         u64 mask = 0;
3243         int i;
3244
3245         for (i = 0; i <= bt->frame; i++)
3246                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3247
3248         return mask == 0;
3249 }
3250
3251 static inline int bt_subprog_enter(struct backtrack_state *bt)
3252 {
3253         if (bt->frame == MAX_CALL_FRAMES - 1) {
3254                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3255                 WARN_ONCE(1, "verifier backtracking bug");
3256                 return -EFAULT;
3257         }
3258         bt->frame++;
3259         return 0;
3260 }
3261
3262 static inline int bt_subprog_exit(struct backtrack_state *bt)
3263 {
3264         if (bt->frame == 0) {
3265                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3266                 WARN_ONCE(1, "verifier backtracking bug");
3267                 return -EFAULT;
3268         }
3269         bt->frame--;
3270         return 0;
3271 }
3272
3273 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3274 {
3275         bt->reg_masks[frame] |= 1 << reg;
3276 }
3277
3278 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3279 {
3280         bt->reg_masks[frame] &= ~(1 << reg);
3281 }
3282
3283 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3284 {
3285         bt_set_frame_reg(bt, bt->frame, reg);
3286 }
3287
3288 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3289 {
3290         bt_clear_frame_reg(bt, bt->frame, reg);
3291 }
3292
3293 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3294 {
3295         bt->stack_masks[frame] |= 1ull << slot;
3296 }
3297
3298 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3299 {
3300         bt->stack_masks[frame] &= ~(1ull << slot);
3301 }
3302
3303 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3304 {
3305         bt_set_frame_slot(bt, bt->frame, slot);
3306 }
3307
3308 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3309 {
3310         bt_clear_frame_slot(bt, bt->frame, slot);
3311 }
3312
3313 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3314 {
3315         return bt->reg_masks[frame];
3316 }
3317
3318 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3319 {
3320         return bt->reg_masks[bt->frame];
3321 }
3322
3323 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3324 {
3325         return bt->stack_masks[frame];
3326 }
3327
3328 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3329 {
3330         return bt->stack_masks[bt->frame];
3331 }
3332
3333 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3334 {
3335         return bt->reg_masks[bt->frame] & (1 << reg);
3336 }
3337
3338 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3339 {
3340         return bt->stack_masks[bt->frame] & (1ull << slot);
3341 }
3342
3343 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3344 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3345 {
3346         DECLARE_BITMAP(mask, 64);
3347         bool first = true;
3348         int i, n;
3349
3350         buf[0] = '\0';
3351
3352         bitmap_from_u64(mask, reg_mask);
3353         for_each_set_bit(i, mask, 32) {
3354                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3355                 first = false;
3356                 buf += n;
3357                 buf_sz -= n;
3358                 if (buf_sz < 0)
3359                         break;
3360         }
3361 }
3362 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3363 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3364 {
3365         DECLARE_BITMAP(mask, 64);
3366         bool first = true;
3367         int i, n;
3368
3369         buf[0] = '\0';
3370
3371         bitmap_from_u64(mask, stack_mask);
3372         for_each_set_bit(i, mask, 64) {
3373                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3374                 first = false;
3375                 buf += n;
3376                 buf_sz -= n;
3377                 if (buf_sz < 0)
3378                         break;
3379         }
3380 }
3381
3382 /* For given verifier state backtrack_insn() is called from the last insn to
3383  * the first insn. Its purpose is to compute a bitmask of registers and
3384  * stack slots that needs precision in the parent verifier state.
3385  *
3386  * @idx is an index of the instruction we are currently processing;
3387  * @subseq_idx is an index of the subsequent instruction that:
3388  *   - *would be* executed next, if jump history is viewed in forward order;
3389  *   - *was* processed previously during backtracking.
3390  */
3391 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3392                           struct backtrack_state *bt)
3393 {
3394         const struct bpf_insn_cbs cbs = {
3395                 .cb_call        = disasm_kfunc_name,
3396                 .cb_print       = verbose,
3397                 .private_data   = env,
3398         };
3399         struct bpf_insn *insn = env->prog->insnsi + idx;
3400         u8 class = BPF_CLASS(insn->code);
3401         u8 opcode = BPF_OP(insn->code);
3402         u8 mode = BPF_MODE(insn->code);
3403         u32 dreg = insn->dst_reg;
3404         u32 sreg = insn->src_reg;
3405         u32 spi, i;
3406
3407         if (insn->code == 0)
3408                 return 0;
3409         if (env->log.level & BPF_LOG_LEVEL2) {
3410                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3411                 verbose(env, "mark_precise: frame%d: regs=%s ",
3412                         bt->frame, env->tmp_str_buf);
3413                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3414                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3415                 verbose(env, "%d: ", idx);
3416                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3417         }
3418
3419         if (class == BPF_ALU || class == BPF_ALU64) {
3420                 if (!bt_is_reg_set(bt, dreg))
3421                         return 0;
3422                 if (opcode == BPF_MOV) {
3423                         if (BPF_SRC(insn->code) == BPF_X) {
3424                                 /* dreg = sreg
3425                                  * dreg needs precision after this insn
3426                                  * sreg needs precision before this insn
3427                                  */
3428                                 bt_clear_reg(bt, dreg);
3429                                 bt_set_reg(bt, sreg);
3430                         } else {
3431                                 /* dreg = K
3432                                  * dreg needs precision after this insn.
3433                                  * Corresponding register is already marked
3434                                  * as precise=true in this verifier state.
3435                                  * No further markings in parent are necessary
3436                                  */
3437                                 bt_clear_reg(bt, dreg);
3438                         }
3439                 } else {
3440                         if (BPF_SRC(insn->code) == BPF_X) {
3441                                 /* dreg += sreg
3442                                  * both dreg and sreg need precision
3443                                  * before this insn
3444                                  */
3445                                 bt_set_reg(bt, sreg);
3446                         } /* else dreg += K
3447                            * dreg still needs precision before this insn
3448                            */
3449                 }
3450         } else if (class == BPF_LDX) {
3451                 if (!bt_is_reg_set(bt, dreg))
3452                         return 0;
3453                 bt_clear_reg(bt, dreg);
3454
3455                 /* scalars can only be spilled into stack w/o losing precision.
3456                  * Load from any other memory can be zero extended.
3457                  * The desire to keep that precision is already indicated
3458                  * by 'precise' mark in corresponding register of this state.
3459                  * No further tracking necessary.
3460                  */
3461                 if (insn->src_reg != BPF_REG_FP)
3462                         return 0;
3463
3464                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3465                  * that [fp - off] slot contains scalar that needs to be
3466                  * tracked with precision
3467                  */
3468                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3469                 if (spi >= 64) {
3470                         verbose(env, "BUG spi %d\n", spi);
3471                         WARN_ONCE(1, "verifier backtracking bug");
3472                         return -EFAULT;
3473                 }
3474                 bt_set_slot(bt, spi);
3475         } else if (class == BPF_STX || class == BPF_ST) {
3476                 if (bt_is_reg_set(bt, dreg))
3477                         /* stx & st shouldn't be using _scalar_ dst_reg
3478                          * to access memory. It means backtracking
3479                          * encountered a case of pointer subtraction.
3480                          */
3481                         return -ENOTSUPP;
3482                 /* scalars can only be spilled into stack */
3483                 if (insn->dst_reg != BPF_REG_FP)
3484                         return 0;
3485                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3486                 if (spi >= 64) {
3487                         verbose(env, "BUG spi %d\n", spi);
3488                         WARN_ONCE(1, "verifier backtracking bug");
3489                         return -EFAULT;
3490                 }
3491                 if (!bt_is_slot_set(bt, spi))
3492                         return 0;
3493                 bt_clear_slot(bt, spi);
3494                 if (class == BPF_STX)
3495                         bt_set_reg(bt, sreg);
3496         } else if (class == BPF_JMP || class == BPF_JMP32) {
3497                 if (bpf_pseudo_call(insn)) {
3498                         int subprog_insn_idx, subprog;
3499
3500                         subprog_insn_idx = idx + insn->imm + 1;
3501                         subprog = find_subprog(env, subprog_insn_idx);
3502                         if (subprog < 0)
3503                                 return -EFAULT;
3504
3505                         if (subprog_is_global(env, subprog)) {
3506                                 /* check that jump history doesn't have any
3507                                  * extra instructions from subprog; the next
3508                                  * instruction after call to global subprog
3509                                  * should be literally next instruction in
3510                                  * caller program
3511                                  */
3512                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3513                                 /* r1-r5 are invalidated after subprog call,
3514                                  * so for global func call it shouldn't be set
3515                                  * anymore
3516                                  */
3517                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3518                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3519                                         WARN_ONCE(1, "verifier backtracking bug");
3520                                         return -EFAULT;
3521                                 }
3522                                 /* global subprog always sets R0 */
3523                                 bt_clear_reg(bt, BPF_REG_0);
3524                                 return 0;
3525                         } else {
3526                                 /* static subprog call instruction, which
3527                                  * means that we are exiting current subprog,
3528                                  * so only r1-r5 could be still requested as
3529                                  * precise, r0 and r6-r10 or any stack slot in
3530                                  * the current frame should be zero by now
3531                                  */
3532                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3533                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3534                                         WARN_ONCE(1, "verifier backtracking bug");
3535                                         return -EFAULT;
3536                                 }
3537                                 /* we don't track register spills perfectly,
3538                                  * so fallback to force-precise instead of failing */
3539                                 if (bt_stack_mask(bt) != 0)
3540                                         return -ENOTSUPP;
3541                                 /* propagate r1-r5 to the caller */
3542                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3543                                         if (bt_is_reg_set(bt, i)) {
3544                                                 bt_clear_reg(bt, i);
3545                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3546                                         }
3547                                 }
3548                                 if (bt_subprog_exit(bt))
3549                                         return -EFAULT;
3550                                 return 0;
3551                         }
3552                 } else if ((bpf_helper_call(insn) &&
3553                             is_callback_calling_function(insn->imm) &&
3554                             !is_async_callback_calling_function(insn->imm)) ||
3555                            (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3556                         /* callback-calling helper or kfunc call, which means
3557                          * we are exiting from subprog, but unlike the subprog
3558                          * call handling above, we shouldn't propagate
3559                          * precision of r1-r5 (if any requested), as they are
3560                          * not actually arguments passed directly to callback
3561                          * subprogs
3562                          */
3563                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3564                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3565                                 WARN_ONCE(1, "verifier backtracking bug");
3566                                 return -EFAULT;
3567                         }
3568                         if (bt_stack_mask(bt) != 0)
3569                                 return -ENOTSUPP;
3570                         /* clear r1-r5 in callback subprog's mask */
3571                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3572                                 bt_clear_reg(bt, i);
3573                         if (bt_subprog_exit(bt))
3574                                 return -EFAULT;
3575                         return 0;
3576                 } else if (opcode == BPF_CALL) {
3577                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3578                          * catch this error later. Make backtracking conservative
3579                          * with ENOTSUPP.
3580                          */
3581                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3582                                 return -ENOTSUPP;
3583                         /* regular helper call sets R0 */
3584                         bt_clear_reg(bt, BPF_REG_0);
3585                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3586                                 /* if backtracing was looking for registers R1-R5
3587                                  * they should have been found already.
3588                                  */
3589                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3590                                 WARN_ONCE(1, "verifier backtracking bug");
3591                                 return -EFAULT;
3592                         }
3593                 } else if (opcode == BPF_EXIT) {
3594                         bool r0_precise;
3595
3596                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3597                                 /* if backtracing was looking for registers R1-R5
3598                                  * they should have been found already.
3599                                  */
3600                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3601                                 WARN_ONCE(1, "verifier backtracking bug");
3602                                 return -EFAULT;
3603                         }
3604
3605                         /* BPF_EXIT in subprog or callback always returns
3606                          * right after the call instruction, so by checking
3607                          * whether the instruction at subseq_idx-1 is subprog
3608                          * call or not we can distinguish actual exit from
3609                          * *subprog* from exit from *callback*. In the former
3610                          * case, we need to propagate r0 precision, if
3611                          * necessary. In the former we never do that.
3612                          */
3613                         r0_precise = subseq_idx - 1 >= 0 &&
3614                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3615                                      bt_is_reg_set(bt, BPF_REG_0);
3616
3617                         bt_clear_reg(bt, BPF_REG_0);
3618                         if (bt_subprog_enter(bt))
3619                                 return -EFAULT;
3620
3621                         if (r0_precise)
3622                                 bt_set_reg(bt, BPF_REG_0);
3623                         /* r6-r9 and stack slots will stay set in caller frame
3624                          * bitmasks until we return back from callee(s)
3625                          */
3626                         return 0;
3627                 } else if (BPF_SRC(insn->code) == BPF_X) {
3628                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3629                                 return 0;
3630                         /* dreg <cond> sreg
3631                          * Both dreg and sreg need precision before
3632                          * this insn. If only sreg was marked precise
3633                          * before it would be equally necessary to
3634                          * propagate it to dreg.
3635                          */
3636                         bt_set_reg(bt, dreg);
3637                         bt_set_reg(bt, sreg);
3638                          /* else dreg <cond> K
3639                           * Only dreg still needs precision before
3640                           * this insn, so for the K-based conditional
3641                           * there is nothing new to be marked.
3642                           */
3643                 }
3644         } else if (class == BPF_LD) {
3645                 if (!bt_is_reg_set(bt, dreg))
3646                         return 0;
3647                 bt_clear_reg(bt, dreg);
3648                 /* It's ld_imm64 or ld_abs or ld_ind.
3649                  * For ld_imm64 no further tracking of precision
3650                  * into parent is necessary
3651                  */
3652                 if (mode == BPF_IND || mode == BPF_ABS)
3653                         /* to be analyzed */
3654                         return -ENOTSUPP;
3655         }
3656         return 0;
3657 }
3658
3659 /* the scalar precision tracking algorithm:
3660  * . at the start all registers have precise=false.
3661  * . scalar ranges are tracked as normal through alu and jmp insns.
3662  * . once precise value of the scalar register is used in:
3663  *   .  ptr + scalar alu
3664  *   . if (scalar cond K|scalar)
3665  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3666  *   backtrack through the verifier states and mark all registers and
3667  *   stack slots with spilled constants that these scalar regisers
3668  *   should be precise.
3669  * . during state pruning two registers (or spilled stack slots)
3670  *   are equivalent if both are not precise.
3671  *
3672  * Note the verifier cannot simply walk register parentage chain,
3673  * since many different registers and stack slots could have been
3674  * used to compute single precise scalar.
3675  *
3676  * The approach of starting with precise=true for all registers and then
3677  * backtrack to mark a register as not precise when the verifier detects
3678  * that program doesn't care about specific value (e.g., when helper
3679  * takes register as ARG_ANYTHING parameter) is not safe.
3680  *
3681  * It's ok to walk single parentage chain of the verifier states.
3682  * It's possible that this backtracking will go all the way till 1st insn.
3683  * All other branches will be explored for needing precision later.
3684  *
3685  * The backtracking needs to deal with cases like:
3686  *   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)
3687  * r9 -= r8
3688  * r5 = r9
3689  * if r5 > 0x79f goto pc+7
3690  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3691  * r5 += 1
3692  * ...
3693  * call bpf_perf_event_output#25
3694  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3695  *
3696  * and this case:
3697  * r6 = 1
3698  * call foo // uses callee's r6 inside to compute r0
3699  * r0 += r6
3700  * if r0 == 0 goto
3701  *
3702  * to track above reg_mask/stack_mask needs to be independent for each frame.
3703  *
3704  * Also if parent's curframe > frame where backtracking started,
3705  * the verifier need to mark registers in both frames, otherwise callees
3706  * may incorrectly prune callers. This is similar to
3707  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3708  *
3709  * For now backtracking falls back into conservative marking.
3710  */
3711 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3712                                      struct bpf_verifier_state *st)
3713 {
3714         struct bpf_func_state *func;
3715         struct bpf_reg_state *reg;
3716         int i, j;
3717
3718         if (env->log.level & BPF_LOG_LEVEL2) {
3719                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3720                         st->curframe);
3721         }
3722
3723         /* big hammer: mark all scalars precise in this path.
3724          * pop_stack may still get !precise scalars.
3725          * We also skip current state and go straight to first parent state,
3726          * because precision markings in current non-checkpointed state are
3727          * not needed. See why in the comment in __mark_chain_precision below.
3728          */
3729         for (st = st->parent; st; st = st->parent) {
3730                 for (i = 0; i <= st->curframe; i++) {
3731                         func = st->frame[i];
3732                         for (j = 0; j < BPF_REG_FP; j++) {
3733                                 reg = &func->regs[j];
3734                                 if (reg->type != SCALAR_VALUE || reg->precise)
3735                                         continue;
3736                                 reg->precise = true;
3737                                 if (env->log.level & BPF_LOG_LEVEL2) {
3738                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3739                                                 i, j);
3740                                 }
3741                         }
3742                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3743                                 if (!is_spilled_reg(&func->stack[j]))
3744                                         continue;
3745                                 reg = &func->stack[j].spilled_ptr;
3746                                 if (reg->type != SCALAR_VALUE || reg->precise)
3747                                         continue;
3748                                 reg->precise = true;
3749                                 if (env->log.level & BPF_LOG_LEVEL2) {
3750                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3751                                                 i, -(j + 1) * 8);
3752                                 }
3753                         }
3754                 }
3755         }
3756 }
3757
3758 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3759 {
3760         struct bpf_func_state *func;
3761         struct bpf_reg_state *reg;
3762         int i, j;
3763
3764         for (i = 0; i <= st->curframe; i++) {
3765                 func = st->frame[i];
3766                 for (j = 0; j < BPF_REG_FP; j++) {
3767                         reg = &func->regs[j];
3768                         if (reg->type != SCALAR_VALUE)
3769                                 continue;
3770                         reg->precise = false;
3771                 }
3772                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3773                         if (!is_spilled_reg(&func->stack[j]))
3774                                 continue;
3775                         reg = &func->stack[j].spilled_ptr;
3776                         if (reg->type != SCALAR_VALUE)
3777                                 continue;
3778                         reg->precise = false;
3779                 }
3780         }
3781 }
3782
3783 static bool idset_contains(struct bpf_idset *s, u32 id)
3784 {
3785         u32 i;
3786
3787         for (i = 0; i < s->count; ++i)
3788                 if (s->ids[i] == id)
3789                         return true;
3790
3791         return false;
3792 }
3793
3794 static int idset_push(struct bpf_idset *s, u32 id)
3795 {
3796         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3797                 return -EFAULT;
3798         s->ids[s->count++] = id;
3799         return 0;
3800 }
3801
3802 static void idset_reset(struct bpf_idset *s)
3803 {
3804         s->count = 0;
3805 }
3806
3807 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3808  * Mark all registers with these IDs as precise.
3809  */
3810 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3811 {
3812         struct bpf_idset *precise_ids = &env->idset_scratch;
3813         struct backtrack_state *bt = &env->bt;
3814         struct bpf_func_state *func;
3815         struct bpf_reg_state *reg;
3816         DECLARE_BITMAP(mask, 64);
3817         int i, fr;
3818
3819         idset_reset(precise_ids);
3820
3821         for (fr = bt->frame; fr >= 0; fr--) {
3822                 func = st->frame[fr];
3823
3824                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3825                 for_each_set_bit(i, mask, 32) {
3826                         reg = &func->regs[i];
3827                         if (!reg->id || reg->type != SCALAR_VALUE)
3828                                 continue;
3829                         if (idset_push(precise_ids, reg->id))
3830                                 return -EFAULT;
3831                 }
3832
3833                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3834                 for_each_set_bit(i, mask, 64) {
3835                         if (i >= func->allocated_stack / BPF_REG_SIZE)
3836                                 break;
3837                         if (!is_spilled_scalar_reg(&func->stack[i]))
3838                                 continue;
3839                         reg = &func->stack[i].spilled_ptr;
3840                         if (!reg->id)
3841                                 continue;
3842                         if (idset_push(precise_ids, reg->id))
3843                                 return -EFAULT;
3844                 }
3845         }
3846
3847         for (fr = 0; fr <= st->curframe; ++fr) {
3848                 func = st->frame[fr];
3849
3850                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3851                         reg = &func->regs[i];
3852                         if (!reg->id)
3853                                 continue;
3854                         if (!idset_contains(precise_ids, reg->id))
3855                                 continue;
3856                         bt_set_frame_reg(bt, fr, i);
3857                 }
3858                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3859                         if (!is_spilled_scalar_reg(&func->stack[i]))
3860                                 continue;
3861                         reg = &func->stack[i].spilled_ptr;
3862                         if (!reg->id)
3863                                 continue;
3864                         if (!idset_contains(precise_ids, reg->id))
3865                                 continue;
3866                         bt_set_frame_slot(bt, fr, i);
3867                 }
3868         }
3869
3870         return 0;
3871 }
3872
3873 /*
3874  * __mark_chain_precision() backtracks BPF program instruction sequence and
3875  * chain of verifier states making sure that register *regno* (if regno >= 0)
3876  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3877  * SCALARS, as well as any other registers and slots that contribute to
3878  * a tracked state of given registers/stack slots, depending on specific BPF
3879  * assembly instructions (see backtrack_insns() for exact instruction handling
3880  * logic). This backtracking relies on recorded jmp_history and is able to
3881  * traverse entire chain of parent states. This process ends only when all the
3882  * necessary registers/slots and their transitive dependencies are marked as
3883  * precise.
3884  *
3885  * One important and subtle aspect is that precise marks *do not matter* in
3886  * the currently verified state (current state). It is important to understand
3887  * why this is the case.
3888  *
3889  * First, note that current state is the state that is not yet "checkpointed",
3890  * i.e., it is not yet put into env->explored_states, and it has no children
3891  * states as well. It's ephemeral, and can end up either a) being discarded if
3892  * compatible explored state is found at some point or BPF_EXIT instruction is
3893  * reached or b) checkpointed and put into env->explored_states, branching out
3894  * into one or more children states.
3895  *
3896  * In the former case, precise markings in current state are completely
3897  * ignored by state comparison code (see regsafe() for details). Only
3898  * checkpointed ("old") state precise markings are important, and if old
3899  * state's register/slot is precise, regsafe() assumes current state's
3900  * register/slot as precise and checks value ranges exactly and precisely. If
3901  * states turn out to be compatible, current state's necessary precise
3902  * markings and any required parent states' precise markings are enforced
3903  * after the fact with propagate_precision() logic, after the fact. But it's
3904  * important to realize that in this case, even after marking current state
3905  * registers/slots as precise, we immediately discard current state. So what
3906  * actually matters is any of the precise markings propagated into current
3907  * state's parent states, which are always checkpointed (due to b) case above).
3908  * As such, for scenario a) it doesn't matter if current state has precise
3909  * markings set or not.
3910  *
3911  * Now, for the scenario b), checkpointing and forking into child(ren)
3912  * state(s). Note that before current state gets to checkpointing step, any
3913  * processed instruction always assumes precise SCALAR register/slot
3914  * knowledge: if precise value or range is useful to prune jump branch, BPF
3915  * verifier takes this opportunity enthusiastically. Similarly, when
3916  * register's value is used to calculate offset or memory address, exact
3917  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3918  * what we mentioned above about state comparison ignoring precise markings
3919  * during state comparison, BPF verifier ignores and also assumes precise
3920  * markings *at will* during instruction verification process. But as verifier
3921  * assumes precision, it also propagates any precision dependencies across
3922  * parent states, which are not yet finalized, so can be further restricted
3923  * based on new knowledge gained from restrictions enforced by their children
3924  * states. This is so that once those parent states are finalized, i.e., when
3925  * they have no more active children state, state comparison logic in
3926  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3927  * required for correctness.
3928  *
3929  * To build a bit more intuition, note also that once a state is checkpointed,
3930  * the path we took to get to that state is not important. This is crucial
3931  * property for state pruning. When state is checkpointed and finalized at
3932  * some instruction index, it can be correctly and safely used to "short
3933  * circuit" any *compatible* state that reaches exactly the same instruction
3934  * index. I.e., if we jumped to that instruction from a completely different
3935  * code path than original finalized state was derived from, it doesn't
3936  * matter, current state can be discarded because from that instruction
3937  * forward having a compatible state will ensure we will safely reach the
3938  * exit. States describe preconditions for further exploration, but completely
3939  * forget the history of how we got here.
3940  *
3941  * This also means that even if we needed precise SCALAR range to get to
3942  * finalized state, but from that point forward *that same* SCALAR register is
3943  * never used in a precise context (i.e., it's precise value is not needed for
3944  * correctness), it's correct and safe to mark such register as "imprecise"
3945  * (i.e., precise marking set to false). This is what we rely on when we do
3946  * not set precise marking in current state. If no child state requires
3947  * precision for any given SCALAR register, it's safe to dictate that it can
3948  * be imprecise. If any child state does require this register to be precise,
3949  * we'll mark it precise later retroactively during precise markings
3950  * propagation from child state to parent states.
3951  *
3952  * Skipping precise marking setting in current state is a mild version of
3953  * relying on the above observation. But we can utilize this property even
3954  * more aggressively by proactively forgetting any precise marking in the
3955  * current state (which we inherited from the parent state), right before we
3956  * checkpoint it and branch off into new child state. This is done by
3957  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3958  * finalized states which help in short circuiting more future states.
3959  */
3960 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3961 {
3962         struct backtrack_state *bt = &env->bt;
3963         struct bpf_verifier_state *st = env->cur_state;
3964         int first_idx = st->first_insn_idx;
3965         int last_idx = env->insn_idx;
3966         int subseq_idx = -1;
3967         struct bpf_func_state *func;
3968         struct bpf_reg_state *reg;
3969         bool skip_first = true;
3970         int i, fr, err;
3971
3972         if (!env->bpf_capable)
3973                 return 0;
3974
3975         /* set frame number from which we are starting to backtrack */
3976         bt_init(bt, env->cur_state->curframe);
3977
3978         /* Do sanity checks against current state of register and/or stack
3979          * slot, but don't set precise flag in current state, as precision
3980          * tracking in the current state is unnecessary.
3981          */
3982         func = st->frame[bt->frame];
3983         if (regno >= 0) {
3984                 reg = &func->regs[regno];
3985                 if (reg->type != SCALAR_VALUE) {
3986                         WARN_ONCE(1, "backtracing misuse");
3987                         return -EFAULT;
3988                 }
3989                 bt_set_reg(bt, regno);
3990         }
3991
3992         if (bt_empty(bt))
3993                 return 0;
3994
3995         for (;;) {
3996                 DECLARE_BITMAP(mask, 64);
3997                 u32 history = st->jmp_history_cnt;
3998
3999                 if (env->log.level & BPF_LOG_LEVEL2) {
4000                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4001                                 bt->frame, last_idx, first_idx, subseq_idx);
4002                 }
4003
4004                 /* If some register with scalar ID is marked as precise,
4005                  * make sure that all registers sharing this ID are also precise.
4006                  * This is needed to estimate effect of find_equal_scalars().
4007                  * Do this at the last instruction of each state,
4008                  * bpf_reg_state::id fields are valid for these instructions.
4009                  *
4010                  * Allows to track precision in situation like below:
4011                  *
4012                  *     r2 = unknown value
4013                  *     ...
4014                  *   --- state #0 ---
4015                  *     ...
4016                  *     r1 = r2                 // r1 and r2 now share the same ID
4017                  *     ...
4018                  *   --- state #1 {r1.id = A, r2.id = A} ---
4019                  *     ...
4020                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4021                  *     ...
4022                  *   --- state #2 {r1.id = A, r2.id = A} ---
4023                  *     r3 = r10
4024                  *     r3 += r1                // need to mark both r1 and r2
4025                  */
4026                 if (mark_precise_scalar_ids(env, st))
4027                         return -EFAULT;
4028
4029                 if (last_idx < 0) {
4030                         /* we are at the entry into subprog, which
4031                          * is expected for global funcs, but only if
4032                          * requested precise registers are R1-R5
4033                          * (which are global func's input arguments)
4034                          */
4035                         if (st->curframe == 0 &&
4036                             st->frame[0]->subprogno > 0 &&
4037                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4038                             bt_stack_mask(bt) == 0 &&
4039                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4040                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4041                                 for_each_set_bit(i, mask, 32) {
4042                                         reg = &st->frame[0]->regs[i];
4043                                         if (reg->type != SCALAR_VALUE) {
4044                                                 bt_clear_reg(bt, i);
4045                                                 continue;
4046                                         }
4047                                         reg->precise = true;
4048                                 }
4049                                 return 0;
4050                         }
4051
4052                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4053                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4054                         WARN_ONCE(1, "verifier backtracking bug");
4055                         return -EFAULT;
4056                 }
4057
4058                 for (i = last_idx;;) {
4059                         if (skip_first) {
4060                                 err = 0;
4061                                 skip_first = false;
4062                         } else {
4063                                 err = backtrack_insn(env, i, subseq_idx, bt);
4064                         }
4065                         if (err == -ENOTSUPP) {
4066                                 mark_all_scalars_precise(env, env->cur_state);
4067                                 bt_reset(bt);
4068                                 return 0;
4069                         } else if (err) {
4070                                 return err;
4071                         }
4072                         if (bt_empty(bt))
4073                                 /* Found assignment(s) into tracked register in this state.
4074                                  * Since this state is already marked, just return.
4075                                  * Nothing to be tracked further in the parent state.
4076                                  */
4077                                 return 0;
4078                         if (i == first_idx)
4079                                 break;
4080                         subseq_idx = i;
4081                         i = get_prev_insn_idx(st, i, &history);
4082                         if (i >= env->prog->len) {
4083                                 /* This can happen if backtracking reached insn 0
4084                                  * and there are still reg_mask or stack_mask
4085                                  * to backtrack.
4086                                  * It means the backtracking missed the spot where
4087                                  * particular register was initialized with a constant.
4088                                  */
4089                                 verbose(env, "BUG backtracking idx %d\n", i);
4090                                 WARN_ONCE(1, "verifier backtracking bug");
4091                                 return -EFAULT;
4092                         }
4093                 }
4094                 st = st->parent;
4095                 if (!st)
4096                         break;
4097
4098                 for (fr = bt->frame; fr >= 0; fr--) {
4099                         func = st->frame[fr];
4100                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4101                         for_each_set_bit(i, mask, 32) {
4102                                 reg = &func->regs[i];
4103                                 if (reg->type != SCALAR_VALUE) {
4104                                         bt_clear_frame_reg(bt, fr, i);
4105                                         continue;
4106                                 }
4107                                 if (reg->precise)
4108                                         bt_clear_frame_reg(bt, fr, i);
4109                                 else
4110                                         reg->precise = true;
4111                         }
4112
4113                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4114                         for_each_set_bit(i, mask, 64) {
4115                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4116                                         /* the sequence of instructions:
4117                                          * 2: (bf) r3 = r10
4118                                          * 3: (7b) *(u64 *)(r3 -8) = r0
4119                                          * 4: (79) r4 = *(u64 *)(r10 -8)
4120                                          * doesn't contain jmps. It's backtracked
4121                                          * as a single block.
4122                                          * During backtracking insn 3 is not recognized as
4123                                          * stack access, so at the end of backtracking
4124                                          * stack slot fp-8 is still marked in stack_mask.
4125                                          * However the parent state may not have accessed
4126                                          * fp-8 and it's "unallocated" stack space.
4127                                          * In such case fallback to conservative.
4128                                          */
4129                                         mark_all_scalars_precise(env, env->cur_state);
4130                                         bt_reset(bt);
4131                                         return 0;
4132                                 }
4133
4134                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4135                                         bt_clear_frame_slot(bt, fr, i);
4136                                         continue;
4137                                 }
4138                                 reg = &func->stack[i].spilled_ptr;
4139                                 if (reg->precise)
4140                                         bt_clear_frame_slot(bt, fr, i);
4141                                 else
4142                                         reg->precise = true;
4143                         }
4144                         if (env->log.level & BPF_LOG_LEVEL2) {
4145                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4146                                              bt_frame_reg_mask(bt, fr));
4147                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4148                                         fr, env->tmp_str_buf);
4149                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4150                                                bt_frame_stack_mask(bt, fr));
4151                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4152                                 print_verifier_state(env, func, true);
4153                         }
4154                 }
4155
4156                 if (bt_empty(bt))
4157                         return 0;
4158
4159                 subseq_idx = first_idx;
4160                 last_idx = st->last_insn_idx;
4161                 first_idx = st->first_insn_idx;
4162         }
4163
4164         /* if we still have requested precise regs or slots, we missed
4165          * something (e.g., stack access through non-r10 register), so
4166          * fallback to marking all precise
4167          */
4168         if (!bt_empty(bt)) {
4169                 mark_all_scalars_precise(env, env->cur_state);
4170                 bt_reset(bt);
4171         }
4172
4173         return 0;
4174 }
4175
4176 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4177 {
4178         return __mark_chain_precision(env, regno);
4179 }
4180
4181 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4182  * desired reg and stack masks across all relevant frames
4183  */
4184 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4185 {
4186         return __mark_chain_precision(env, -1);
4187 }
4188
4189 static bool is_spillable_regtype(enum bpf_reg_type type)
4190 {
4191         switch (base_type(type)) {
4192         case PTR_TO_MAP_VALUE:
4193         case PTR_TO_STACK:
4194         case PTR_TO_CTX:
4195         case PTR_TO_PACKET:
4196         case PTR_TO_PACKET_META:
4197         case PTR_TO_PACKET_END:
4198         case PTR_TO_FLOW_KEYS:
4199         case CONST_PTR_TO_MAP:
4200         case PTR_TO_SOCKET:
4201         case PTR_TO_SOCK_COMMON:
4202         case PTR_TO_TCP_SOCK:
4203         case PTR_TO_XDP_SOCK:
4204         case PTR_TO_BTF_ID:
4205         case PTR_TO_BUF:
4206         case PTR_TO_MEM:
4207         case PTR_TO_FUNC:
4208         case PTR_TO_MAP_KEY:
4209                 return true;
4210         default:
4211                 return false;
4212         }
4213 }
4214
4215 /* Does this register contain a constant zero? */
4216 static bool register_is_null(struct bpf_reg_state *reg)
4217 {
4218         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4219 }
4220
4221 static bool register_is_const(struct bpf_reg_state *reg)
4222 {
4223         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4224 }
4225
4226 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4227 {
4228         return tnum_is_unknown(reg->var_off) &&
4229                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4230                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4231                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4232                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4233 }
4234
4235 static bool register_is_bounded(struct bpf_reg_state *reg)
4236 {
4237         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4238 }
4239
4240 static bool __is_pointer_value(bool allow_ptr_leaks,
4241                                const struct bpf_reg_state *reg)
4242 {
4243         if (allow_ptr_leaks)
4244                 return false;
4245
4246         return reg->type != SCALAR_VALUE;
4247 }
4248
4249 /* Copy src state preserving dst->parent and dst->live fields */
4250 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4251 {
4252         struct bpf_reg_state *parent = dst->parent;
4253         enum bpf_reg_liveness live = dst->live;
4254
4255         *dst = *src;
4256         dst->parent = parent;
4257         dst->live = live;
4258 }
4259
4260 static void save_register_state(struct bpf_func_state *state,
4261                                 int spi, struct bpf_reg_state *reg,
4262                                 int size)
4263 {
4264         int i;
4265
4266         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4267         if (size == BPF_REG_SIZE)
4268                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4269
4270         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4271                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4272
4273         /* size < 8 bytes spill */
4274         for (; i; i--)
4275                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4276 }
4277
4278 static bool is_bpf_st_mem(struct bpf_insn *insn)
4279 {
4280         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4281 }
4282
4283 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4284  * stack boundary and alignment are checked in check_mem_access()
4285  */
4286 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4287                                        /* stack frame we're writing to */
4288                                        struct bpf_func_state *state,
4289                                        int off, int size, int value_regno,
4290                                        int insn_idx)
4291 {
4292         struct bpf_func_state *cur; /* state of the current function */
4293         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4294         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4295         struct bpf_reg_state *reg = NULL;
4296         u32 dst_reg = insn->dst_reg;
4297
4298         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4299         if (err)
4300                 return err;
4301         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4302          * so it's aligned access and [off, off + size) are within stack limits
4303          */
4304         if (!env->allow_ptr_leaks &&
4305             state->stack[spi].slot_type[0] == STACK_SPILL &&
4306             size != BPF_REG_SIZE) {
4307                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4308                 return -EACCES;
4309         }
4310
4311         cur = env->cur_state->frame[env->cur_state->curframe];
4312         if (value_regno >= 0)
4313                 reg = &cur->regs[value_regno];
4314         if (!env->bypass_spec_v4) {
4315                 bool sanitize = reg && is_spillable_regtype(reg->type);
4316
4317                 for (i = 0; i < size; i++) {
4318                         u8 type = state->stack[spi].slot_type[i];
4319
4320                         if (type != STACK_MISC && type != STACK_ZERO) {
4321                                 sanitize = true;
4322                                 break;
4323                         }
4324                 }
4325
4326                 if (sanitize)
4327                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4328         }
4329
4330         err = destroy_if_dynptr_stack_slot(env, state, spi);
4331         if (err)
4332                 return err;
4333
4334         mark_stack_slot_scratched(env, spi);
4335         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4336             !register_is_null(reg) && env->bpf_capable) {
4337                 if (dst_reg != BPF_REG_FP) {
4338                         /* The backtracking logic can only recognize explicit
4339                          * stack slot address like [fp - 8]. Other spill of
4340                          * scalar via different register has to be conservative.
4341                          * Backtrack from here and mark all registers as precise
4342                          * that contributed into 'reg' being a constant.
4343                          */
4344                         err = mark_chain_precision(env, value_regno);
4345                         if (err)
4346                                 return err;
4347                 }
4348                 save_register_state(state, spi, reg, size);
4349                 /* Break the relation on a narrowing spill. */
4350                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4351                         state->stack[spi].spilled_ptr.id = 0;
4352         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4353                    insn->imm != 0 && env->bpf_capable) {
4354                 struct bpf_reg_state fake_reg = {};
4355
4356                 __mark_reg_known(&fake_reg, (u32)insn->imm);
4357                 fake_reg.type = SCALAR_VALUE;
4358                 save_register_state(state, spi, &fake_reg, size);
4359         } else if (reg && is_spillable_regtype(reg->type)) {
4360                 /* register containing pointer is being spilled into stack */
4361                 if (size != BPF_REG_SIZE) {
4362                         verbose_linfo(env, insn_idx, "; ");
4363                         verbose(env, "invalid size of register spill\n");
4364                         return -EACCES;
4365                 }
4366                 if (state != cur && reg->type == PTR_TO_STACK) {
4367                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4368                         return -EINVAL;
4369                 }
4370                 save_register_state(state, spi, reg, size);
4371         } else {
4372                 u8 type = STACK_MISC;
4373
4374                 /* regular write of data into stack destroys any spilled ptr */
4375                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4376                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4377                 if (is_stack_slot_special(&state->stack[spi]))
4378                         for (i = 0; i < BPF_REG_SIZE; i++)
4379                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4380
4381                 /* only mark the slot as written if all 8 bytes were written
4382                  * otherwise read propagation may incorrectly stop too soon
4383                  * when stack slots are partially written.
4384                  * This heuristic means that read propagation will be
4385                  * conservative, since it will add reg_live_read marks
4386                  * to stack slots all the way to first state when programs
4387                  * writes+reads less than 8 bytes
4388                  */
4389                 if (size == BPF_REG_SIZE)
4390                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4391
4392                 /* when we zero initialize stack slots mark them as such */
4393                 if ((reg && register_is_null(reg)) ||
4394                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4395                         /* backtracking doesn't work for STACK_ZERO yet. */
4396                         err = mark_chain_precision(env, value_regno);
4397                         if (err)
4398                                 return err;
4399                         type = STACK_ZERO;
4400                 }
4401
4402                 /* Mark slots affected by this stack write. */
4403                 for (i = 0; i < size; i++)
4404                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4405                                 type;
4406         }
4407         return 0;
4408 }
4409
4410 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4411  * known to contain a variable offset.
4412  * This function checks whether the write is permitted and conservatively
4413  * tracks the effects of the write, considering that each stack slot in the
4414  * dynamic range is potentially written to.
4415  *
4416  * 'off' includes 'regno->off'.
4417  * 'value_regno' can be -1, meaning that an unknown value is being written to
4418  * the stack.
4419  *
4420  * Spilled pointers in range are not marked as written because we don't know
4421  * what's going to be actually written. This means that read propagation for
4422  * future reads cannot be terminated by this write.
4423  *
4424  * For privileged programs, uninitialized stack slots are considered
4425  * initialized by this write (even though we don't know exactly what offsets
4426  * are going to be written to). The idea is that we don't want the verifier to
4427  * reject future reads that access slots written to through variable offsets.
4428  */
4429 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4430                                      /* func where register points to */
4431                                      struct bpf_func_state *state,
4432                                      int ptr_regno, int off, int size,
4433                                      int value_regno, int insn_idx)
4434 {
4435         struct bpf_func_state *cur; /* state of the current function */
4436         int min_off, max_off;
4437         int i, err;
4438         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4439         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4440         bool writing_zero = false;
4441         /* set if the fact that we're writing a zero is used to let any
4442          * stack slots remain STACK_ZERO
4443          */
4444         bool zero_used = false;
4445
4446         cur = env->cur_state->frame[env->cur_state->curframe];
4447         ptr_reg = &cur->regs[ptr_regno];
4448         min_off = ptr_reg->smin_value + off;
4449         max_off = ptr_reg->smax_value + off + size;
4450         if (value_regno >= 0)
4451                 value_reg = &cur->regs[value_regno];
4452         if ((value_reg && register_is_null(value_reg)) ||
4453             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4454                 writing_zero = true;
4455
4456         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4457         if (err)
4458                 return err;
4459
4460         for (i = min_off; i < max_off; i++) {
4461                 int spi;
4462
4463                 spi = __get_spi(i);
4464                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4465                 if (err)
4466                         return err;
4467         }
4468
4469         /* Variable offset writes destroy any spilled pointers in range. */
4470         for (i = min_off; i < max_off; i++) {
4471                 u8 new_type, *stype;
4472                 int slot, spi;
4473
4474                 slot = -i - 1;
4475                 spi = slot / BPF_REG_SIZE;
4476                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4477                 mark_stack_slot_scratched(env, spi);
4478
4479                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4480                         /* Reject the write if range we may write to has not
4481                          * been initialized beforehand. If we didn't reject
4482                          * here, the ptr status would be erased below (even
4483                          * though not all slots are actually overwritten),
4484                          * possibly opening the door to leaks.
4485                          *
4486                          * We do however catch STACK_INVALID case below, and
4487                          * only allow reading possibly uninitialized memory
4488                          * later for CAP_PERFMON, as the write may not happen to
4489                          * that slot.
4490                          */
4491                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4492                                 insn_idx, i);
4493                         return -EINVAL;
4494                 }
4495
4496                 /* Erase all spilled pointers. */
4497                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4498
4499                 /* Update the slot type. */
4500                 new_type = STACK_MISC;
4501                 if (writing_zero && *stype == STACK_ZERO) {
4502                         new_type = STACK_ZERO;
4503                         zero_used = true;
4504                 }
4505                 /* If the slot is STACK_INVALID, we check whether it's OK to
4506                  * pretend that it will be initialized by this write. The slot
4507                  * might not actually be written to, and so if we mark it as
4508                  * initialized future reads might leak uninitialized memory.
4509                  * For privileged programs, we will accept such reads to slots
4510                  * that may or may not be written because, if we're reject
4511                  * them, the error would be too confusing.
4512                  */
4513                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4514                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4515                                         insn_idx, i);
4516                         return -EINVAL;
4517                 }
4518                 *stype = new_type;
4519         }
4520         if (zero_used) {
4521                 /* backtracking doesn't work for STACK_ZERO yet. */
4522                 err = mark_chain_precision(env, value_regno);
4523                 if (err)
4524                         return err;
4525         }
4526         return 0;
4527 }
4528
4529 /* When register 'dst_regno' is assigned some values from stack[min_off,
4530  * max_off), we set the register's type according to the types of the
4531  * respective stack slots. If all the stack values are known to be zeros, then
4532  * so is the destination reg. Otherwise, the register is considered to be
4533  * SCALAR. This function does not deal with register filling; the caller must
4534  * ensure that all spilled registers in the stack range have been marked as
4535  * read.
4536  */
4537 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4538                                 /* func where src register points to */
4539                                 struct bpf_func_state *ptr_state,
4540                                 int min_off, int max_off, int dst_regno)
4541 {
4542         struct bpf_verifier_state *vstate = env->cur_state;
4543         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4544         int i, slot, spi;
4545         u8 *stype;
4546         int zeros = 0;
4547
4548         for (i = min_off; i < max_off; i++) {
4549                 slot = -i - 1;
4550                 spi = slot / BPF_REG_SIZE;
4551                 mark_stack_slot_scratched(env, spi);
4552                 stype = ptr_state->stack[spi].slot_type;
4553                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4554                         break;
4555                 zeros++;
4556         }
4557         if (zeros == max_off - min_off) {
4558                 /* any access_size read into register is zero extended,
4559                  * so the whole register == const_zero
4560                  */
4561                 __mark_reg_const_zero(&state->regs[dst_regno]);
4562                 /* backtracking doesn't support STACK_ZERO yet,
4563                  * so mark it precise here, so that later
4564                  * backtracking can stop here.
4565                  * Backtracking may not need this if this register
4566                  * doesn't participate in pointer adjustment.
4567                  * Forward propagation of precise flag is not
4568                  * necessary either. This mark is only to stop
4569                  * backtracking. Any register that contributed
4570                  * to const 0 was marked precise before spill.
4571                  */
4572                 state->regs[dst_regno].precise = true;
4573         } else {
4574                 /* have read misc data from the stack */
4575                 mark_reg_unknown(env, state->regs, dst_regno);
4576         }
4577         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4578 }
4579
4580 /* Read the stack at 'off' and put the results into the register indicated by
4581  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4582  * spilled reg.
4583  *
4584  * 'dst_regno' can be -1, meaning that the read value is not going to a
4585  * register.
4586  *
4587  * The access is assumed to be within the current stack bounds.
4588  */
4589 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4590                                       /* func where src register points to */
4591                                       struct bpf_func_state *reg_state,
4592                                       int off, int size, int dst_regno)
4593 {
4594         struct bpf_verifier_state *vstate = env->cur_state;
4595         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4596         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4597         struct bpf_reg_state *reg;
4598         u8 *stype, type;
4599
4600         stype = reg_state->stack[spi].slot_type;
4601         reg = &reg_state->stack[spi].spilled_ptr;
4602
4603         mark_stack_slot_scratched(env, spi);
4604
4605         if (is_spilled_reg(&reg_state->stack[spi])) {
4606                 u8 spill_size = 1;
4607
4608                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4609                         spill_size++;
4610
4611                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4612                         if (reg->type != SCALAR_VALUE) {
4613                                 verbose_linfo(env, env->insn_idx, "; ");
4614                                 verbose(env, "invalid size of register fill\n");
4615                                 return -EACCES;
4616                         }
4617
4618                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4619                         if (dst_regno < 0)
4620                                 return 0;
4621
4622                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4623                                 /* The earlier check_reg_arg() has decided the
4624                                  * subreg_def for this insn.  Save it first.
4625                                  */
4626                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4627
4628                                 copy_register_state(&state->regs[dst_regno], reg);
4629                                 state->regs[dst_regno].subreg_def = subreg_def;
4630                         } else {
4631                                 for (i = 0; i < size; i++) {
4632                                         type = stype[(slot - i) % BPF_REG_SIZE];
4633                                         if (type == STACK_SPILL)
4634                                                 continue;
4635                                         if (type == STACK_MISC)
4636                                                 continue;
4637                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4638                                                 continue;
4639                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4640                                                 off, i, size);
4641                                         return -EACCES;
4642                                 }
4643                                 mark_reg_unknown(env, state->regs, dst_regno);
4644                         }
4645                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4646                         return 0;
4647                 }
4648
4649                 if (dst_regno >= 0) {
4650                         /* restore register state from stack */
4651                         copy_register_state(&state->regs[dst_regno], reg);
4652                         /* mark reg as written since spilled pointer state likely
4653                          * has its liveness marks cleared by is_state_visited()
4654                          * which resets stack/reg liveness for state transitions
4655                          */
4656                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4657                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4658                         /* If dst_regno==-1, the caller is asking us whether
4659                          * it is acceptable to use this value as a SCALAR_VALUE
4660                          * (e.g. for XADD).
4661                          * We must not allow unprivileged callers to do that
4662                          * with spilled pointers.
4663                          */
4664                         verbose(env, "leaking pointer from stack off %d\n",
4665                                 off);
4666                         return -EACCES;
4667                 }
4668                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4669         } else {
4670                 for (i = 0; i < size; i++) {
4671                         type = stype[(slot - i) % BPF_REG_SIZE];
4672                         if (type == STACK_MISC)
4673                                 continue;
4674                         if (type == STACK_ZERO)
4675                                 continue;
4676                         if (type == STACK_INVALID && env->allow_uninit_stack)
4677                                 continue;
4678                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4679                                 off, i, size);
4680                         return -EACCES;
4681                 }
4682                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4683                 if (dst_regno >= 0)
4684                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4685         }
4686         return 0;
4687 }
4688
4689 enum bpf_access_src {
4690         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4691         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4692 };
4693
4694 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4695                                          int regno, int off, int access_size,
4696                                          bool zero_size_allowed,
4697                                          enum bpf_access_src type,
4698                                          struct bpf_call_arg_meta *meta);
4699
4700 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4701 {
4702         return cur_regs(env) + regno;
4703 }
4704
4705 /* Read the stack at 'ptr_regno + off' and put the result into the register
4706  * 'dst_regno'.
4707  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4708  * but not its variable offset.
4709  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4710  *
4711  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4712  * filling registers (i.e. reads of spilled register cannot be detected when
4713  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4714  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4715  * offset; for a fixed offset check_stack_read_fixed_off should be used
4716  * instead.
4717  */
4718 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4719                                     int ptr_regno, int off, int size, int dst_regno)
4720 {
4721         /* The state of the source register. */
4722         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4723         struct bpf_func_state *ptr_state = func(env, reg);
4724         int err;
4725         int min_off, max_off;
4726
4727         /* Note that we pass a NULL meta, so raw access will not be permitted.
4728          */
4729         err = check_stack_range_initialized(env, ptr_regno, off, size,
4730                                             false, ACCESS_DIRECT, NULL);
4731         if (err)
4732                 return err;
4733
4734         min_off = reg->smin_value + off;
4735         max_off = reg->smax_value + off;
4736         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4737         return 0;
4738 }
4739
4740 /* check_stack_read dispatches to check_stack_read_fixed_off or
4741  * check_stack_read_var_off.
4742  *
4743  * The caller must ensure that the offset falls within the allocated stack
4744  * bounds.
4745  *
4746  * 'dst_regno' is a register which will receive the value from the stack. It
4747  * can be -1, meaning that the read value is not going to a register.
4748  */
4749 static int check_stack_read(struct bpf_verifier_env *env,
4750                             int ptr_regno, int off, int size,
4751                             int dst_regno)
4752 {
4753         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4754         struct bpf_func_state *state = func(env, reg);
4755         int err;
4756         /* Some accesses are only permitted with a static offset. */
4757         bool var_off = !tnum_is_const(reg->var_off);
4758
4759         /* The offset is required to be static when reads don't go to a
4760          * register, in order to not leak pointers (see
4761          * check_stack_read_fixed_off).
4762          */
4763         if (dst_regno < 0 && var_off) {
4764                 char tn_buf[48];
4765
4766                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4767                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4768                         tn_buf, off, size);
4769                 return -EACCES;
4770         }
4771         /* Variable offset is prohibited for unprivileged mode for simplicity
4772          * since it requires corresponding support in Spectre masking for stack
4773          * ALU. See also retrieve_ptr_limit(). The check in
4774          * check_stack_access_for_ptr_arithmetic() called by
4775          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4776          * with variable offsets, therefore no check is required here. Further,
4777          * just checking it here would be insufficient as speculative stack
4778          * writes could still lead to unsafe speculative behaviour.
4779          */
4780         if (!var_off) {
4781                 off += reg->var_off.value;
4782                 err = check_stack_read_fixed_off(env, state, off, size,
4783                                                  dst_regno);
4784         } else {
4785                 /* Variable offset stack reads need more conservative handling
4786                  * than fixed offset ones. Note that dst_regno >= 0 on this
4787                  * branch.
4788                  */
4789                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4790                                                dst_regno);
4791         }
4792         return err;
4793 }
4794
4795
4796 /* check_stack_write dispatches to check_stack_write_fixed_off or
4797  * check_stack_write_var_off.
4798  *
4799  * 'ptr_regno' is the register used as a pointer into the stack.
4800  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4801  * 'value_regno' is the register whose value we're writing to the stack. It can
4802  * be -1, meaning that we're not writing from a register.
4803  *
4804  * The caller must ensure that the offset falls within the maximum stack size.
4805  */
4806 static int check_stack_write(struct bpf_verifier_env *env,
4807                              int ptr_regno, int off, int size,
4808                              int value_regno, int insn_idx)
4809 {
4810         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4811         struct bpf_func_state *state = func(env, reg);
4812         int err;
4813
4814         if (tnum_is_const(reg->var_off)) {
4815                 off += reg->var_off.value;
4816                 err = check_stack_write_fixed_off(env, state, off, size,
4817                                                   value_regno, insn_idx);
4818         } else {
4819                 /* Variable offset stack reads need more conservative handling
4820                  * than fixed offset ones.
4821                  */
4822                 err = check_stack_write_var_off(env, state,
4823                                                 ptr_regno, off, size,
4824                                                 value_regno, insn_idx);
4825         }
4826         return err;
4827 }
4828
4829 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4830                                  int off, int size, enum bpf_access_type type)
4831 {
4832         struct bpf_reg_state *regs = cur_regs(env);
4833         struct bpf_map *map = regs[regno].map_ptr;
4834         u32 cap = bpf_map_flags_to_cap(map);
4835
4836         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4837                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4838                         map->value_size, off, size);
4839                 return -EACCES;
4840         }
4841
4842         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4843                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4844                         map->value_size, off, size);
4845                 return -EACCES;
4846         }
4847
4848         return 0;
4849 }
4850
4851 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4852 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4853                               int off, int size, u32 mem_size,
4854                               bool zero_size_allowed)
4855 {
4856         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4857         struct bpf_reg_state *reg;
4858
4859         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4860                 return 0;
4861
4862         reg = &cur_regs(env)[regno];
4863         switch (reg->type) {
4864         case PTR_TO_MAP_KEY:
4865                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4866                         mem_size, off, size);
4867                 break;
4868         case PTR_TO_MAP_VALUE:
4869                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4870                         mem_size, off, size);
4871                 break;
4872         case PTR_TO_PACKET:
4873         case PTR_TO_PACKET_META:
4874         case PTR_TO_PACKET_END:
4875                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4876                         off, size, regno, reg->id, off, mem_size);
4877                 break;
4878         case PTR_TO_MEM:
4879         default:
4880                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4881                         mem_size, off, size);
4882         }
4883
4884         return -EACCES;
4885 }
4886
4887 /* check read/write into a memory region with possible variable offset */
4888 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4889                                    int off, int size, u32 mem_size,
4890                                    bool zero_size_allowed)
4891 {
4892         struct bpf_verifier_state *vstate = env->cur_state;
4893         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4894         struct bpf_reg_state *reg = &state->regs[regno];
4895         int err;
4896
4897         /* We may have adjusted the register pointing to memory region, so we
4898          * need to try adding each of min_value and max_value to off
4899          * to make sure our theoretical access will be safe.
4900          *
4901          * The minimum value is only important with signed
4902          * comparisons where we can't assume the floor of a
4903          * value is 0.  If we are using signed variables for our
4904          * index'es we need to make sure that whatever we use
4905          * will have a set floor within our range.
4906          */
4907         if (reg->smin_value < 0 &&
4908             (reg->smin_value == S64_MIN ||
4909              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4910               reg->smin_value + off < 0)) {
4911                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4912                         regno);
4913                 return -EACCES;
4914         }
4915         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4916                                  mem_size, zero_size_allowed);
4917         if (err) {
4918                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4919                         regno);
4920                 return err;
4921         }
4922
4923         /* If we haven't set a max value then we need to bail since we can't be
4924          * sure we won't do bad things.
4925          * If reg->umax_value + off could overflow, treat that as unbounded too.
4926          */
4927         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4928                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4929                         regno);
4930                 return -EACCES;
4931         }
4932         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4933                                  mem_size, zero_size_allowed);
4934         if (err) {
4935                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4936                         regno);
4937                 return err;
4938         }
4939
4940         return 0;
4941 }
4942
4943 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4944                                const struct bpf_reg_state *reg, int regno,
4945                                bool fixed_off_ok)
4946 {
4947         /* Access to this pointer-typed register or passing it to a helper
4948          * is only allowed in its original, unmodified form.
4949          */
4950
4951         if (reg->off < 0) {
4952                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4953                         reg_type_str(env, reg->type), regno, reg->off);
4954                 return -EACCES;
4955         }
4956
4957         if (!fixed_off_ok && reg->off) {
4958                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4959                         reg_type_str(env, reg->type), regno, reg->off);
4960                 return -EACCES;
4961         }
4962
4963         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4964                 char tn_buf[48];
4965
4966                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4967                 verbose(env, "variable %s access var_off=%s disallowed\n",
4968                         reg_type_str(env, reg->type), tn_buf);
4969                 return -EACCES;
4970         }
4971
4972         return 0;
4973 }
4974
4975 int check_ptr_off_reg(struct bpf_verifier_env *env,
4976                       const struct bpf_reg_state *reg, int regno)
4977 {
4978         return __check_ptr_off_reg(env, reg, regno, false);
4979 }
4980
4981 static int map_kptr_match_type(struct bpf_verifier_env *env,
4982                                struct btf_field *kptr_field,
4983                                struct bpf_reg_state *reg, u32 regno)
4984 {
4985         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4986         int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4987         const char *reg_name = "";
4988
4989         /* Only unreferenced case accepts untrusted pointers */
4990         if (kptr_field->type == BPF_KPTR_UNREF)
4991                 perm_flags |= PTR_UNTRUSTED;
4992
4993         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4994                 goto bad_type;
4995
4996         if (!btf_is_kernel(reg->btf)) {
4997                 verbose(env, "R%d must point to kernel BTF\n", regno);
4998                 return -EINVAL;
4999         }
5000         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5001         reg_name = btf_type_name(reg->btf, reg->btf_id);
5002
5003         /* For ref_ptr case, release function check should ensure we get one
5004          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5005          * normal store of unreferenced kptr, we must ensure var_off is zero.
5006          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5007          * reg->off and reg->ref_obj_id are not needed here.
5008          */
5009         if (__check_ptr_off_reg(env, reg, regno, true))
5010                 return -EACCES;
5011
5012         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5013          * we also need to take into account the reg->off.
5014          *
5015          * We want to support cases like:
5016          *
5017          * struct foo {
5018          *         struct bar br;
5019          *         struct baz bz;
5020          * };
5021          *
5022          * struct foo *v;
5023          * v = func();        // PTR_TO_BTF_ID
5024          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5025          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5026          *                    // first member type of struct after comparison fails
5027          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5028          *                    // to match type
5029          *
5030          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5031          * is zero. We must also ensure that btf_struct_ids_match does not walk
5032          * the struct to match type against first member of struct, i.e. reject
5033          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5034          * strict mode to true for type match.
5035          */
5036         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5037                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5038                                   kptr_field->type == BPF_KPTR_REF))
5039                 goto bad_type;
5040         return 0;
5041 bad_type:
5042         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5043                 reg_type_str(env, reg->type), reg_name);
5044         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5045         if (kptr_field->type == BPF_KPTR_UNREF)
5046                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5047                         targ_name);
5048         else
5049                 verbose(env, "\n");
5050         return -EINVAL;
5051 }
5052
5053 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5054  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5055  */
5056 static bool in_rcu_cs(struct bpf_verifier_env *env)
5057 {
5058         return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5059 }
5060
5061 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5062 BTF_SET_START(rcu_protected_types)
5063 BTF_ID(struct, prog_test_ref_kfunc)
5064 BTF_ID(struct, cgroup)
5065 BTF_ID(struct, bpf_cpumask)
5066 BTF_ID(struct, task_struct)
5067 BTF_SET_END(rcu_protected_types)
5068
5069 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5070 {
5071         if (!btf_is_kernel(btf))
5072                 return false;
5073         return btf_id_set_contains(&rcu_protected_types, btf_id);
5074 }
5075
5076 static bool rcu_safe_kptr(const struct btf_field *field)
5077 {
5078         const struct btf_field_kptr *kptr = &field->kptr;
5079
5080         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5081 }
5082
5083 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5084                                  int value_regno, int insn_idx,
5085                                  struct btf_field *kptr_field)
5086 {
5087         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5088         int class = BPF_CLASS(insn->code);
5089         struct bpf_reg_state *val_reg;
5090
5091         /* Things we already checked for in check_map_access and caller:
5092          *  - Reject cases where variable offset may touch kptr
5093          *  - size of access (must be BPF_DW)
5094          *  - tnum_is_const(reg->var_off)
5095          *  - kptr_field->offset == off + reg->var_off.value
5096          */
5097         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5098         if (BPF_MODE(insn->code) != BPF_MEM) {
5099                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5100                 return -EACCES;
5101         }
5102
5103         /* We only allow loading referenced kptr, since it will be marked as
5104          * untrusted, similar to unreferenced kptr.
5105          */
5106         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5107                 verbose(env, "store to referenced kptr disallowed\n");
5108                 return -EACCES;
5109         }
5110
5111         if (class == BPF_LDX) {
5112                 val_reg = reg_state(env, value_regno);
5113                 /* We can simply mark the value_regno receiving the pointer
5114                  * value from map as PTR_TO_BTF_ID, with the correct type.
5115                  */
5116                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5117                                 kptr_field->kptr.btf_id,
5118                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5119                                 PTR_MAYBE_NULL | MEM_RCU :
5120                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5121                 /* For mark_ptr_or_null_reg */
5122                 val_reg->id = ++env->id_gen;
5123         } else if (class == BPF_STX) {
5124                 val_reg = reg_state(env, value_regno);
5125                 if (!register_is_null(val_reg) &&
5126                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5127                         return -EACCES;
5128         } else if (class == BPF_ST) {
5129                 if (insn->imm) {
5130                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5131                                 kptr_field->offset);
5132                         return -EACCES;
5133                 }
5134         } else {
5135                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5136                 return -EACCES;
5137         }
5138         return 0;
5139 }
5140
5141 /* check read/write into a map element with possible variable offset */
5142 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5143                             int off, int size, bool zero_size_allowed,
5144                             enum bpf_access_src src)
5145 {
5146         struct bpf_verifier_state *vstate = env->cur_state;
5147         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5148         struct bpf_reg_state *reg = &state->regs[regno];
5149         struct bpf_map *map = reg->map_ptr;
5150         struct btf_record *rec;
5151         int err, i;
5152
5153         err = check_mem_region_access(env, regno, off, size, map->value_size,
5154                                       zero_size_allowed);
5155         if (err)
5156                 return err;
5157
5158         if (IS_ERR_OR_NULL(map->record))
5159                 return 0;
5160         rec = map->record;
5161         for (i = 0; i < rec->cnt; i++) {
5162                 struct btf_field *field = &rec->fields[i];
5163                 u32 p = field->offset;
5164
5165                 /* If any part of a field  can be touched by load/store, reject
5166                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5167                  * it is sufficient to check x1 < y2 && y1 < x2.
5168                  */
5169                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5170                     p < reg->umax_value + off + size) {
5171                         switch (field->type) {
5172                         case BPF_KPTR_UNREF:
5173                         case BPF_KPTR_REF:
5174                                 if (src != ACCESS_DIRECT) {
5175                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5176                                         return -EACCES;
5177                                 }
5178                                 if (!tnum_is_const(reg->var_off)) {
5179                                         verbose(env, "kptr access cannot have variable offset\n");
5180                                         return -EACCES;
5181                                 }
5182                                 if (p != off + reg->var_off.value) {
5183                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5184                                                 p, off + reg->var_off.value);
5185                                         return -EACCES;
5186                                 }
5187                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5188                                         verbose(env, "kptr access size must be BPF_DW\n");
5189                                         return -EACCES;
5190                                 }
5191                                 break;
5192                         default:
5193                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5194                                         btf_field_type_name(field->type));
5195                                 return -EACCES;
5196                         }
5197                 }
5198         }
5199         return 0;
5200 }
5201
5202 #define MAX_PACKET_OFF 0xffff
5203
5204 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5205                                        const struct bpf_call_arg_meta *meta,
5206                                        enum bpf_access_type t)
5207 {
5208         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5209
5210         switch (prog_type) {
5211         /* Program types only with direct read access go here! */
5212         case BPF_PROG_TYPE_LWT_IN:
5213         case BPF_PROG_TYPE_LWT_OUT:
5214         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5215         case BPF_PROG_TYPE_SK_REUSEPORT:
5216         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5217         case BPF_PROG_TYPE_CGROUP_SKB:
5218                 if (t == BPF_WRITE)
5219                         return false;
5220                 fallthrough;
5221
5222         /* Program types with direct read + write access go here! */
5223         case BPF_PROG_TYPE_SCHED_CLS:
5224         case BPF_PROG_TYPE_SCHED_ACT:
5225         case BPF_PROG_TYPE_XDP:
5226         case BPF_PROG_TYPE_LWT_XMIT:
5227         case BPF_PROG_TYPE_SK_SKB:
5228         case BPF_PROG_TYPE_SK_MSG:
5229                 if (meta)
5230                         return meta->pkt_access;
5231
5232                 env->seen_direct_write = true;
5233                 return true;
5234
5235         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5236                 if (t == BPF_WRITE)
5237                         env->seen_direct_write = true;
5238
5239                 return true;
5240
5241         default:
5242                 return false;
5243         }
5244 }
5245
5246 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5247                                int size, bool zero_size_allowed)
5248 {
5249         struct bpf_reg_state *regs = cur_regs(env);
5250         struct bpf_reg_state *reg = &regs[regno];
5251         int err;
5252
5253         /* We may have added a variable offset to the packet pointer; but any
5254          * reg->range we have comes after that.  We are only checking the fixed
5255          * offset.
5256          */
5257
5258         /* We don't allow negative numbers, because we aren't tracking enough
5259          * detail to prove they're safe.
5260          */
5261         if (reg->smin_value < 0) {
5262                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5263                         regno);
5264                 return -EACCES;
5265         }
5266
5267         err = reg->range < 0 ? -EINVAL :
5268               __check_mem_access(env, regno, off, size, reg->range,
5269                                  zero_size_allowed);
5270         if (err) {
5271                 verbose(env, "R%d offset is outside of the packet\n", regno);
5272                 return err;
5273         }
5274
5275         /* __check_mem_access has made sure "off + size - 1" is within u16.
5276          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5277          * otherwise find_good_pkt_pointers would have refused to set range info
5278          * that __check_mem_access would have rejected this pkt access.
5279          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5280          */
5281         env->prog->aux->max_pkt_offset =
5282                 max_t(u32, env->prog->aux->max_pkt_offset,
5283                       off + reg->umax_value + size - 1);
5284
5285         return err;
5286 }
5287
5288 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5289 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5290                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5291                             struct btf **btf, u32 *btf_id)
5292 {
5293         struct bpf_insn_access_aux info = {
5294                 .reg_type = *reg_type,
5295                 .log = &env->log,
5296         };
5297
5298         if (env->ops->is_valid_access &&
5299             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5300                 /* A non zero info.ctx_field_size indicates that this field is a
5301                  * candidate for later verifier transformation to load the whole
5302                  * field and then apply a mask when accessed with a narrower
5303                  * access than actual ctx access size. A zero info.ctx_field_size
5304                  * will only allow for whole field access and rejects any other
5305                  * type of narrower access.
5306                  */
5307                 *reg_type = info.reg_type;
5308
5309                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5310                         *btf = info.btf;
5311                         *btf_id = info.btf_id;
5312                 } else {
5313                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5314                 }
5315                 /* remember the offset of last byte accessed in ctx */
5316                 if (env->prog->aux->max_ctx_offset < off + size)
5317                         env->prog->aux->max_ctx_offset = off + size;
5318                 return 0;
5319         }
5320
5321         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5322         return -EACCES;
5323 }
5324
5325 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5326                                   int size)
5327 {
5328         if (size < 0 || off < 0 ||
5329             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5330                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5331                         off, size);
5332                 return -EACCES;
5333         }
5334         return 0;
5335 }
5336
5337 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5338                              u32 regno, int off, int size,
5339                              enum bpf_access_type t)
5340 {
5341         struct bpf_reg_state *regs = cur_regs(env);
5342         struct bpf_reg_state *reg = &regs[regno];
5343         struct bpf_insn_access_aux info = {};
5344         bool valid;
5345
5346         if (reg->smin_value < 0) {
5347                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5348                         regno);
5349                 return -EACCES;
5350         }
5351
5352         switch (reg->type) {
5353         case PTR_TO_SOCK_COMMON:
5354                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5355                 break;
5356         case PTR_TO_SOCKET:
5357                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5358                 break;
5359         case PTR_TO_TCP_SOCK:
5360                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5361                 break;
5362         case PTR_TO_XDP_SOCK:
5363                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5364                 break;
5365         default:
5366                 valid = false;
5367         }
5368
5369
5370         if (valid) {
5371                 env->insn_aux_data[insn_idx].ctx_field_size =
5372                         info.ctx_field_size;
5373                 return 0;
5374         }
5375
5376         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5377                 regno, reg_type_str(env, reg->type), off, size);
5378
5379         return -EACCES;
5380 }
5381
5382 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5383 {
5384         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5385 }
5386
5387 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5388 {
5389         const struct bpf_reg_state *reg = reg_state(env, regno);
5390
5391         return reg->type == PTR_TO_CTX;
5392 }
5393
5394 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5395 {
5396         const struct bpf_reg_state *reg = reg_state(env, regno);
5397
5398         return type_is_sk_pointer(reg->type);
5399 }
5400
5401 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5402 {
5403         const struct bpf_reg_state *reg = reg_state(env, regno);
5404
5405         return type_is_pkt_pointer(reg->type);
5406 }
5407
5408 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5409 {
5410         const struct bpf_reg_state *reg = reg_state(env, regno);
5411
5412         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5413         return reg->type == PTR_TO_FLOW_KEYS;
5414 }
5415
5416 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5417 #ifdef CONFIG_NET
5418         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5419         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5420         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5421 #endif
5422         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5423 };
5424
5425 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5426 {
5427         /* A referenced register is always trusted. */
5428         if (reg->ref_obj_id)
5429                 return true;
5430
5431         /* Types listed in the reg2btf_ids are always trusted */
5432         if (reg2btf_ids[base_type(reg->type)])
5433                 return true;
5434
5435         /* If a register is not referenced, it is trusted if it has the
5436          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5437          * other type modifiers may be safe, but we elect to take an opt-in
5438          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5439          * not.
5440          *
5441          * Eventually, we should make PTR_TRUSTED the single source of truth
5442          * for whether a register is trusted.
5443          */
5444         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5445                !bpf_type_has_unsafe_modifiers(reg->type);
5446 }
5447
5448 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5449 {
5450         return reg->type & MEM_RCU;
5451 }
5452
5453 static void clear_trusted_flags(enum bpf_type_flag *flag)
5454 {
5455         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5456 }
5457
5458 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5459                                    const struct bpf_reg_state *reg,
5460                                    int off, int size, bool strict)
5461 {
5462         struct tnum reg_off;
5463         int ip_align;
5464
5465         /* Byte size accesses are always allowed. */
5466         if (!strict || size == 1)
5467                 return 0;
5468
5469         /* For platforms that do not have a Kconfig enabling
5470          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5471          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5472          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5473          * to this code only in strict mode where we want to emulate
5474          * the NET_IP_ALIGN==2 checking.  Therefore use an
5475          * unconditional IP align value of '2'.
5476          */
5477         ip_align = 2;
5478
5479         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5480         if (!tnum_is_aligned(reg_off, size)) {
5481                 char tn_buf[48];
5482
5483                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5484                 verbose(env,
5485                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5486                         ip_align, tn_buf, reg->off, off, size);
5487                 return -EACCES;
5488         }
5489
5490         return 0;
5491 }
5492
5493 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5494                                        const struct bpf_reg_state *reg,
5495                                        const char *pointer_desc,
5496                                        int off, int size, bool strict)
5497 {
5498         struct tnum reg_off;
5499
5500         /* Byte size accesses are always allowed. */
5501         if (!strict || size == 1)
5502                 return 0;
5503
5504         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5505         if (!tnum_is_aligned(reg_off, size)) {
5506                 char tn_buf[48];
5507
5508                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5509                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5510                         pointer_desc, tn_buf, reg->off, off, size);
5511                 return -EACCES;
5512         }
5513
5514         return 0;
5515 }
5516
5517 static int check_ptr_alignment(struct bpf_verifier_env *env,
5518                                const struct bpf_reg_state *reg, int off,
5519                                int size, bool strict_alignment_once)
5520 {
5521         bool strict = env->strict_alignment || strict_alignment_once;
5522         const char *pointer_desc = "";
5523
5524         switch (reg->type) {
5525         case PTR_TO_PACKET:
5526         case PTR_TO_PACKET_META:
5527                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5528                  * right in front, treat it the very same way.
5529                  */
5530                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5531         case PTR_TO_FLOW_KEYS:
5532                 pointer_desc = "flow keys ";
5533                 break;
5534         case PTR_TO_MAP_KEY:
5535                 pointer_desc = "key ";
5536                 break;
5537         case PTR_TO_MAP_VALUE:
5538                 pointer_desc = "value ";
5539                 break;
5540         case PTR_TO_CTX:
5541                 pointer_desc = "context ";
5542                 break;
5543         case PTR_TO_STACK:
5544                 pointer_desc = "stack ";
5545                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5546                  * and check_stack_read_fixed_off() relies on stack accesses being
5547                  * aligned.
5548                  */
5549                 strict = true;
5550                 break;
5551         case PTR_TO_SOCKET:
5552                 pointer_desc = "sock ";
5553                 break;
5554         case PTR_TO_SOCK_COMMON:
5555                 pointer_desc = "sock_common ";
5556                 break;
5557         case PTR_TO_TCP_SOCK:
5558                 pointer_desc = "tcp_sock ";
5559                 break;
5560         case PTR_TO_XDP_SOCK:
5561                 pointer_desc = "xdp_sock ";
5562                 break;
5563         default:
5564                 break;
5565         }
5566         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5567                                            strict);
5568 }
5569
5570 static int update_stack_depth(struct bpf_verifier_env *env,
5571                               const struct bpf_func_state *func,
5572                               int off)
5573 {
5574         u16 stack = env->subprog_info[func->subprogno].stack_depth;
5575
5576         if (stack >= -off)
5577                 return 0;
5578
5579         /* update known max for given subprogram */
5580         env->subprog_info[func->subprogno].stack_depth = -off;
5581         return 0;
5582 }
5583
5584 /* starting from main bpf function walk all instructions of the function
5585  * and recursively walk all callees that given function can call.
5586  * Ignore jump and exit insns.
5587  * Since recursion is prevented by check_cfg() this algorithm
5588  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5589  */
5590 static int check_max_stack_depth(struct bpf_verifier_env *env)
5591 {
5592         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5593         struct bpf_subprog_info *subprog = env->subprog_info;
5594         struct bpf_insn *insn = env->prog->insnsi;
5595         bool tail_call_reachable = false;
5596         int ret_insn[MAX_CALL_FRAMES];
5597         int ret_prog[MAX_CALL_FRAMES];
5598         int j;
5599
5600 process_func:
5601         /* protect against potential stack overflow that might happen when
5602          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5603          * depth for such case down to 256 so that the worst case scenario
5604          * would result in 8k stack size (32 which is tailcall limit * 256 =
5605          * 8k).
5606          *
5607          * To get the idea what might happen, see an example:
5608          * func1 -> sub rsp, 128
5609          *  subfunc1 -> sub rsp, 256
5610          *  tailcall1 -> add rsp, 256
5611          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5612          *   subfunc2 -> sub rsp, 64
5613          *   subfunc22 -> sub rsp, 128
5614          *   tailcall2 -> add rsp, 128
5615          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5616          *
5617          * tailcall will unwind the current stack frame but it will not get rid
5618          * of caller's stack as shown on the example above.
5619          */
5620         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5621                 verbose(env,
5622                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5623                         depth);
5624                 return -EACCES;
5625         }
5626         /* round up to 32-bytes, since this is granularity
5627          * of interpreter stack size
5628          */
5629         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5630         if (depth > MAX_BPF_STACK) {
5631                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5632                         frame + 1, depth);
5633                 return -EACCES;
5634         }
5635 continue_func:
5636         subprog_end = subprog[idx + 1].start;
5637         for (; i < subprog_end; i++) {
5638                 int next_insn;
5639
5640                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5641                         continue;
5642                 /* remember insn and function to return to */
5643                 ret_insn[frame] = i + 1;
5644                 ret_prog[frame] = idx;
5645
5646                 /* find the callee */
5647                 next_insn = i + insn[i].imm + 1;
5648                 idx = find_subprog(env, next_insn);
5649                 if (idx < 0) {
5650                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5651                                   next_insn);
5652                         return -EFAULT;
5653                 }
5654                 if (subprog[idx].is_async_cb) {
5655                         if (subprog[idx].has_tail_call) {
5656                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5657                                 return -EFAULT;
5658                         }
5659                         /* async callbacks don't increase bpf prog stack size unless called directly */
5660                         if (!bpf_pseudo_call(insn + i))
5661                                 continue;
5662                 }
5663                 i = next_insn;
5664
5665                 if (subprog[idx].has_tail_call)
5666                         tail_call_reachable = true;
5667
5668                 frame++;
5669                 if (frame >= MAX_CALL_FRAMES) {
5670                         verbose(env, "the call stack of %d frames is too deep !\n",
5671                                 frame);
5672                         return -E2BIG;
5673                 }
5674                 goto process_func;
5675         }
5676         /* if tail call got detected across bpf2bpf calls then mark each of the
5677          * currently present subprog frames as tail call reachable subprogs;
5678          * this info will be utilized by JIT so that we will be preserving the
5679          * tail call counter throughout bpf2bpf calls combined with tailcalls
5680          */
5681         if (tail_call_reachable)
5682                 for (j = 0; j < frame; j++)
5683                         subprog[ret_prog[j]].tail_call_reachable = true;
5684         if (subprog[0].tail_call_reachable)
5685                 env->prog->aux->tail_call_reachable = true;
5686
5687         /* end of for() loop means the last insn of the 'subprog'
5688          * was reached. Doesn't matter whether it was JA or EXIT
5689          */
5690         if (frame == 0)
5691                 return 0;
5692         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5693         frame--;
5694         i = ret_insn[frame];
5695         idx = ret_prog[frame];
5696         goto continue_func;
5697 }
5698
5699 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5700 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5701                                   const struct bpf_insn *insn, int idx)
5702 {
5703         int start = idx + insn->imm + 1, subprog;
5704
5705         subprog = find_subprog(env, start);
5706         if (subprog < 0) {
5707                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5708                           start);
5709                 return -EFAULT;
5710         }
5711         return env->subprog_info[subprog].stack_depth;
5712 }
5713 #endif
5714
5715 static int __check_buffer_access(struct bpf_verifier_env *env,
5716                                  const char *buf_info,
5717                                  const struct bpf_reg_state *reg,
5718                                  int regno, int off, int size)
5719 {
5720         if (off < 0) {
5721                 verbose(env,
5722                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5723                         regno, buf_info, off, size);
5724                 return -EACCES;
5725         }
5726         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5727                 char tn_buf[48];
5728
5729                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5730                 verbose(env,
5731                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5732                         regno, off, tn_buf);
5733                 return -EACCES;
5734         }
5735
5736         return 0;
5737 }
5738
5739 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5740                                   const struct bpf_reg_state *reg,
5741                                   int regno, int off, int size)
5742 {
5743         int err;
5744
5745         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5746         if (err)
5747                 return err;
5748
5749         if (off + size > env->prog->aux->max_tp_access)
5750                 env->prog->aux->max_tp_access = off + size;
5751
5752         return 0;
5753 }
5754
5755 static int check_buffer_access(struct bpf_verifier_env *env,
5756                                const struct bpf_reg_state *reg,
5757                                int regno, int off, int size,
5758                                bool zero_size_allowed,
5759                                u32 *max_access)
5760 {
5761         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5762         int err;
5763
5764         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5765         if (err)
5766                 return err;
5767
5768         if (off + size > *max_access)
5769                 *max_access = off + size;
5770
5771         return 0;
5772 }
5773
5774 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5775 static void zext_32_to_64(struct bpf_reg_state *reg)
5776 {
5777         reg->var_off = tnum_subreg(reg->var_off);
5778         __reg_assign_32_into_64(reg);
5779 }
5780
5781 /* truncate register to smaller size (in bytes)
5782  * must be called with size < BPF_REG_SIZE
5783  */
5784 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5785 {
5786         u64 mask;
5787
5788         /* clear high bits in bit representation */
5789         reg->var_off = tnum_cast(reg->var_off, size);
5790
5791         /* fix arithmetic bounds */
5792         mask = ((u64)1 << (size * 8)) - 1;
5793         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5794                 reg->umin_value &= mask;
5795                 reg->umax_value &= mask;
5796         } else {
5797                 reg->umin_value = 0;
5798                 reg->umax_value = mask;
5799         }
5800         reg->smin_value = reg->umin_value;
5801         reg->smax_value = reg->umax_value;
5802
5803         /* If size is smaller than 32bit register the 32bit register
5804          * values are also truncated so we push 64-bit bounds into
5805          * 32-bit bounds. Above were truncated < 32-bits already.
5806          */
5807         if (size >= 4)
5808                 return;
5809         __reg_combine_64_into_32(reg);
5810 }
5811
5812 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5813 {
5814         /* A map is considered read-only if the following condition are true:
5815          *
5816          * 1) BPF program side cannot change any of the map content. The
5817          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5818          *    and was set at map creation time.
5819          * 2) The map value(s) have been initialized from user space by a
5820          *    loader and then "frozen", such that no new map update/delete
5821          *    operations from syscall side are possible for the rest of
5822          *    the map's lifetime from that point onwards.
5823          * 3) Any parallel/pending map update/delete operations from syscall
5824          *    side have been completed. Only after that point, it's safe to
5825          *    assume that map value(s) are immutable.
5826          */
5827         return (map->map_flags & BPF_F_RDONLY_PROG) &&
5828                READ_ONCE(map->frozen) &&
5829                !bpf_map_write_active(map);
5830 }
5831
5832 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5833 {
5834         void *ptr;
5835         u64 addr;
5836         int err;
5837
5838         err = map->ops->map_direct_value_addr(map, &addr, off);
5839         if (err)
5840                 return err;
5841         ptr = (void *)(long)addr + off;
5842
5843         switch (size) {
5844         case sizeof(u8):
5845                 *val = (u64)*(u8 *)ptr;
5846                 break;
5847         case sizeof(u16):
5848                 *val = (u64)*(u16 *)ptr;
5849                 break;
5850         case sizeof(u32):
5851                 *val = (u64)*(u32 *)ptr;
5852                 break;
5853         case sizeof(u64):
5854                 *val = *(u64 *)ptr;
5855                 break;
5856         default:
5857                 return -EINVAL;
5858         }
5859         return 0;
5860 }
5861
5862 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5863 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5864 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5865
5866 /*
5867  * Allow list few fields as RCU trusted or full trusted.
5868  * This logic doesn't allow mix tagging and will be removed once GCC supports
5869  * btf_type_tag.
5870  */
5871
5872 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5873 BTF_TYPE_SAFE_RCU(struct task_struct) {
5874         const cpumask_t *cpus_ptr;
5875         struct css_set __rcu *cgroups;
5876         struct task_struct __rcu *real_parent;
5877         struct task_struct *group_leader;
5878 };
5879
5880 BTF_TYPE_SAFE_RCU(struct cgroup) {
5881         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5882         struct kernfs_node *kn;
5883 };
5884
5885 BTF_TYPE_SAFE_RCU(struct css_set) {
5886         struct cgroup *dfl_cgrp;
5887 };
5888
5889 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5890 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5891         struct file __rcu *exe_file;
5892 };
5893
5894 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5895  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5896  */
5897 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5898         struct sock *sk;
5899 };
5900
5901 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5902         struct sock *sk;
5903 };
5904
5905 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5906 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5907         struct seq_file *seq;
5908 };
5909
5910 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5911         struct bpf_iter_meta *meta;
5912         struct task_struct *task;
5913 };
5914
5915 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5916         struct file *file;
5917 };
5918
5919 BTF_TYPE_SAFE_TRUSTED(struct file) {
5920         struct inode *f_inode;
5921 };
5922
5923 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5924         /* no negative dentry-s in places where bpf can see it */
5925         struct inode *d_inode;
5926 };
5927
5928 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5929         struct sock *sk;
5930 };
5931
5932 static bool type_is_rcu(struct bpf_verifier_env *env,
5933                         struct bpf_reg_state *reg,
5934                         const char *field_name, u32 btf_id)
5935 {
5936         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5937         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5938         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5939
5940         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5941 }
5942
5943 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5944                                 struct bpf_reg_state *reg,
5945                                 const char *field_name, u32 btf_id)
5946 {
5947         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5948         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5949         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5950
5951         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5952 }
5953
5954 static bool type_is_trusted(struct bpf_verifier_env *env,
5955                             struct bpf_reg_state *reg,
5956                             const char *field_name, u32 btf_id)
5957 {
5958         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5959         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5960         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5961         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5962         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5963         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5964
5965         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5966 }
5967
5968 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5969                                    struct bpf_reg_state *regs,
5970                                    int regno, int off, int size,
5971                                    enum bpf_access_type atype,
5972                                    int value_regno)
5973 {
5974         struct bpf_reg_state *reg = regs + regno;
5975         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5976         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5977         const char *field_name = NULL;
5978         enum bpf_type_flag flag = 0;
5979         u32 btf_id = 0;
5980         int ret;
5981
5982         if (!env->allow_ptr_leaks) {
5983                 verbose(env,
5984                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5985                         tname);
5986                 return -EPERM;
5987         }
5988         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5989                 verbose(env,
5990                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5991                         tname);
5992                 return -EINVAL;
5993         }
5994         if (off < 0) {
5995                 verbose(env,
5996                         "R%d is ptr_%s invalid negative access: off=%d\n",
5997                         regno, tname, off);
5998                 return -EACCES;
5999         }
6000         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6001                 char tn_buf[48];
6002
6003                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6004                 verbose(env,
6005                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6006                         regno, tname, off, tn_buf);
6007                 return -EACCES;
6008         }
6009
6010         if (reg->type & MEM_USER) {
6011                 verbose(env,
6012                         "R%d is ptr_%s access user memory: off=%d\n",
6013                         regno, tname, off);
6014                 return -EACCES;
6015         }
6016
6017         if (reg->type & MEM_PERCPU) {
6018                 verbose(env,
6019                         "R%d is ptr_%s access percpu memory: off=%d\n",
6020                         regno, tname, off);
6021                 return -EACCES;
6022         }
6023
6024         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6025                 if (!btf_is_kernel(reg->btf)) {
6026                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6027                         return -EFAULT;
6028                 }
6029                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6030         } else {
6031                 /* Writes are permitted with default btf_struct_access for
6032                  * program allocated objects (which always have ref_obj_id > 0),
6033                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6034                  */
6035                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6036                         verbose(env, "only read is supported\n");
6037                         return -EACCES;
6038                 }
6039
6040                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6041                     !reg->ref_obj_id) {
6042                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6043                         return -EFAULT;
6044                 }
6045
6046                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6047         }
6048
6049         if (ret < 0)
6050                 return ret;
6051
6052         if (ret != PTR_TO_BTF_ID) {
6053                 /* just mark; */
6054
6055         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6056                 /* If this is an untrusted pointer, all pointers formed by walking it
6057                  * also inherit the untrusted flag.
6058                  */
6059                 flag = PTR_UNTRUSTED;
6060
6061         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6062                 /* By default any pointer obtained from walking a trusted pointer is no
6063                  * longer trusted, unless the field being accessed has explicitly been
6064                  * marked as inheriting its parent's state of trust (either full or RCU).
6065                  * For example:
6066                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6067                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6068                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6069                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6070                  *
6071                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6072                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6073                  */
6074                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6075                         flag |= PTR_TRUSTED;
6076                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6077                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6078                                 /* ignore __rcu tag and mark it MEM_RCU */
6079                                 flag |= MEM_RCU;
6080                         } else if (flag & MEM_RCU ||
6081                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6082                                 /* __rcu tagged pointers can be NULL */
6083                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6084
6085                                 /* We always trust them */
6086                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6087                                     flag & PTR_UNTRUSTED)
6088                                         flag &= ~PTR_UNTRUSTED;
6089                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6090                                 /* keep as-is */
6091                         } else {
6092                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6093                                 clear_trusted_flags(&flag);
6094                         }
6095                 } else {
6096                         /*
6097                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6098                          * aggressively mark as untrusted otherwise such
6099                          * pointers will be plain PTR_TO_BTF_ID without flags
6100                          * and will be allowed to be passed into helpers for
6101                          * compat reasons.
6102                          */
6103                         flag = PTR_UNTRUSTED;
6104                 }
6105         } else {
6106                 /* Old compat. Deprecated */
6107                 clear_trusted_flags(&flag);
6108         }
6109
6110         if (atype == BPF_READ && value_regno >= 0)
6111                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6112
6113         return 0;
6114 }
6115
6116 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6117                                    struct bpf_reg_state *regs,
6118                                    int regno, int off, int size,
6119                                    enum bpf_access_type atype,
6120                                    int value_regno)
6121 {
6122         struct bpf_reg_state *reg = regs + regno;
6123         struct bpf_map *map = reg->map_ptr;
6124         struct bpf_reg_state map_reg;
6125         enum bpf_type_flag flag = 0;
6126         const struct btf_type *t;
6127         const char *tname;
6128         u32 btf_id;
6129         int ret;
6130
6131         if (!btf_vmlinux) {
6132                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6133                 return -ENOTSUPP;
6134         }
6135
6136         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6137                 verbose(env, "map_ptr access not supported for map type %d\n",
6138                         map->map_type);
6139                 return -ENOTSUPP;
6140         }
6141
6142         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6143         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6144
6145         if (!env->allow_ptr_leaks) {
6146                 verbose(env,
6147                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6148                         tname);
6149                 return -EPERM;
6150         }
6151
6152         if (off < 0) {
6153                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6154                         regno, tname, off);
6155                 return -EACCES;
6156         }
6157
6158         if (atype != BPF_READ) {
6159                 verbose(env, "only read from %s is supported\n", tname);
6160                 return -EACCES;
6161         }
6162
6163         /* Simulate access to a PTR_TO_BTF_ID */
6164         memset(&map_reg, 0, sizeof(map_reg));
6165         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6166         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6167         if (ret < 0)
6168                 return ret;
6169
6170         if (value_regno >= 0)
6171                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6172
6173         return 0;
6174 }
6175
6176 /* Check that the stack access at the given offset is within bounds. The
6177  * maximum valid offset is -1.
6178  *
6179  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6180  * -state->allocated_stack for reads.
6181  */
6182 static int check_stack_slot_within_bounds(int off,
6183                                           struct bpf_func_state *state,
6184                                           enum bpf_access_type t)
6185 {
6186         int min_valid_off;
6187
6188         if (t == BPF_WRITE)
6189                 min_valid_off = -MAX_BPF_STACK;
6190         else
6191                 min_valid_off = -state->allocated_stack;
6192
6193         if (off < min_valid_off || off > -1)
6194                 return -EACCES;
6195         return 0;
6196 }
6197
6198 /* Check that the stack access at 'regno + off' falls within the maximum stack
6199  * bounds.
6200  *
6201  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6202  */
6203 static int check_stack_access_within_bounds(
6204                 struct bpf_verifier_env *env,
6205                 int regno, int off, int access_size,
6206                 enum bpf_access_src src, enum bpf_access_type type)
6207 {
6208         struct bpf_reg_state *regs = cur_regs(env);
6209         struct bpf_reg_state *reg = regs + regno;
6210         struct bpf_func_state *state = func(env, reg);
6211         int min_off, max_off;
6212         int err;
6213         char *err_extra;
6214
6215         if (src == ACCESS_HELPER)
6216                 /* We don't know if helpers are reading or writing (or both). */
6217                 err_extra = " indirect access to";
6218         else if (type == BPF_READ)
6219                 err_extra = " read from";
6220         else
6221                 err_extra = " write to";
6222
6223         if (tnum_is_const(reg->var_off)) {
6224                 min_off = reg->var_off.value + off;
6225                 if (access_size > 0)
6226                         max_off = min_off + access_size - 1;
6227                 else
6228                         max_off = min_off;
6229         } else {
6230                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6231                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6232                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6233                                 err_extra, regno);
6234                         return -EACCES;
6235                 }
6236                 min_off = reg->smin_value + off;
6237                 if (access_size > 0)
6238                         max_off = reg->smax_value + off + access_size - 1;
6239                 else
6240                         max_off = min_off;
6241         }
6242
6243         err = check_stack_slot_within_bounds(min_off, state, type);
6244         if (!err)
6245                 err = check_stack_slot_within_bounds(max_off, state, type);
6246
6247         if (err) {
6248                 if (tnum_is_const(reg->var_off)) {
6249                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6250                                 err_extra, regno, off, access_size);
6251                 } else {
6252                         char tn_buf[48];
6253
6254                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6255                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6256                                 err_extra, regno, tn_buf, access_size);
6257                 }
6258         }
6259         return err;
6260 }
6261
6262 /* check whether memory at (regno + off) is accessible for t = (read | write)
6263  * if t==write, value_regno is a register which value is stored into memory
6264  * if t==read, value_regno is a register which will receive the value from memory
6265  * if t==write && value_regno==-1, some unknown value is stored into memory
6266  * if t==read && value_regno==-1, don't care what we read from memory
6267  */
6268 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6269                             int off, int bpf_size, enum bpf_access_type t,
6270                             int value_regno, bool strict_alignment_once)
6271 {
6272         struct bpf_reg_state *regs = cur_regs(env);
6273         struct bpf_reg_state *reg = regs + regno;
6274         struct bpf_func_state *state;
6275         int size, err = 0;
6276
6277         size = bpf_size_to_bytes(bpf_size);
6278         if (size < 0)
6279                 return size;
6280
6281         /* alignment checks will add in reg->off themselves */
6282         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6283         if (err)
6284                 return err;
6285
6286         /* for access checks, reg->off is just part of off */
6287         off += reg->off;
6288
6289         if (reg->type == PTR_TO_MAP_KEY) {
6290                 if (t == BPF_WRITE) {
6291                         verbose(env, "write to change key R%d not allowed\n", regno);
6292                         return -EACCES;
6293                 }
6294
6295                 err = check_mem_region_access(env, regno, off, size,
6296                                               reg->map_ptr->key_size, false);
6297                 if (err)
6298                         return err;
6299                 if (value_regno >= 0)
6300                         mark_reg_unknown(env, regs, value_regno);
6301         } else if (reg->type == PTR_TO_MAP_VALUE) {
6302                 struct btf_field *kptr_field = NULL;
6303
6304                 if (t == BPF_WRITE && value_regno >= 0 &&
6305                     is_pointer_value(env, value_regno)) {
6306                         verbose(env, "R%d leaks addr into map\n", value_regno);
6307                         return -EACCES;
6308                 }
6309                 err = check_map_access_type(env, regno, off, size, t);
6310                 if (err)
6311                         return err;
6312                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6313                 if (err)
6314                         return err;
6315                 if (tnum_is_const(reg->var_off))
6316                         kptr_field = btf_record_find(reg->map_ptr->record,
6317                                                      off + reg->var_off.value, BPF_KPTR);
6318                 if (kptr_field) {
6319                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6320                 } else if (t == BPF_READ && value_regno >= 0) {
6321                         struct bpf_map *map = reg->map_ptr;
6322
6323                         /* if map is read-only, track its contents as scalars */
6324                         if (tnum_is_const(reg->var_off) &&
6325                             bpf_map_is_rdonly(map) &&
6326                             map->ops->map_direct_value_addr) {
6327                                 int map_off = off + reg->var_off.value;
6328                                 u64 val = 0;
6329
6330                                 err = bpf_map_direct_read(map, map_off, size,
6331                                                           &val);
6332                                 if (err)
6333                                         return err;
6334
6335                                 regs[value_regno].type = SCALAR_VALUE;
6336                                 __mark_reg_known(&regs[value_regno], val);
6337                         } else {
6338                                 mark_reg_unknown(env, regs, value_regno);
6339                         }
6340                 }
6341         } else if (base_type(reg->type) == PTR_TO_MEM) {
6342                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6343
6344                 if (type_may_be_null(reg->type)) {
6345                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6346                                 reg_type_str(env, reg->type));
6347                         return -EACCES;
6348                 }
6349
6350                 if (t == BPF_WRITE && rdonly_mem) {
6351                         verbose(env, "R%d cannot write into %s\n",
6352                                 regno, reg_type_str(env, reg->type));
6353                         return -EACCES;
6354                 }
6355
6356                 if (t == BPF_WRITE && value_regno >= 0 &&
6357                     is_pointer_value(env, value_regno)) {
6358                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6359                         return -EACCES;
6360                 }
6361
6362                 err = check_mem_region_access(env, regno, off, size,
6363                                               reg->mem_size, false);
6364                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6365                         mark_reg_unknown(env, regs, value_regno);
6366         } else if (reg->type == PTR_TO_CTX) {
6367                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6368                 struct btf *btf = NULL;
6369                 u32 btf_id = 0;
6370
6371                 if (t == BPF_WRITE && value_regno >= 0 &&
6372                     is_pointer_value(env, value_regno)) {
6373                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6374                         return -EACCES;
6375                 }
6376
6377                 err = check_ptr_off_reg(env, reg, regno);
6378                 if (err < 0)
6379                         return err;
6380
6381                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6382                                        &btf_id);
6383                 if (err)
6384                         verbose_linfo(env, insn_idx, "; ");
6385                 if (!err && t == BPF_READ && value_regno >= 0) {
6386                         /* ctx access returns either a scalar, or a
6387                          * PTR_TO_PACKET[_META,_END]. In the latter
6388                          * case, we know the offset is zero.
6389                          */
6390                         if (reg_type == SCALAR_VALUE) {
6391                                 mark_reg_unknown(env, regs, value_regno);
6392                         } else {
6393                                 mark_reg_known_zero(env, regs,
6394                                                     value_regno);
6395                                 if (type_may_be_null(reg_type))
6396                                         regs[value_regno].id = ++env->id_gen;
6397                                 /* A load of ctx field could have different
6398                                  * actual load size with the one encoded in the
6399                                  * insn. When the dst is PTR, it is for sure not
6400                                  * a sub-register.
6401                                  */
6402                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6403                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6404                                         regs[value_regno].btf = btf;
6405                                         regs[value_regno].btf_id = btf_id;
6406                                 }
6407                         }
6408                         regs[value_regno].type = reg_type;
6409                 }
6410
6411         } else if (reg->type == PTR_TO_STACK) {
6412                 /* Basic bounds checks. */
6413                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6414                 if (err)
6415                         return err;
6416
6417                 state = func(env, reg);
6418                 err = update_stack_depth(env, state, off);
6419                 if (err)
6420                         return err;
6421
6422                 if (t == BPF_READ)
6423                         err = check_stack_read(env, regno, off, size,
6424                                                value_regno);
6425                 else
6426                         err = check_stack_write(env, regno, off, size,
6427                                                 value_regno, insn_idx);
6428         } else if (reg_is_pkt_pointer(reg)) {
6429                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6430                         verbose(env, "cannot write into packet\n");
6431                         return -EACCES;
6432                 }
6433                 if (t == BPF_WRITE && value_regno >= 0 &&
6434                     is_pointer_value(env, value_regno)) {
6435                         verbose(env, "R%d leaks addr into packet\n",
6436                                 value_regno);
6437                         return -EACCES;
6438                 }
6439                 err = check_packet_access(env, regno, off, size, false);
6440                 if (!err && t == BPF_READ && value_regno >= 0)
6441                         mark_reg_unknown(env, regs, value_regno);
6442         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6443                 if (t == BPF_WRITE && value_regno >= 0 &&
6444                     is_pointer_value(env, value_regno)) {
6445                         verbose(env, "R%d leaks addr into flow keys\n",
6446                                 value_regno);
6447                         return -EACCES;
6448                 }
6449
6450                 err = check_flow_keys_access(env, off, size);
6451                 if (!err && t == BPF_READ && value_regno >= 0)
6452                         mark_reg_unknown(env, regs, value_regno);
6453         } else if (type_is_sk_pointer(reg->type)) {
6454                 if (t == BPF_WRITE) {
6455                         verbose(env, "R%d cannot write into %s\n",
6456                                 regno, reg_type_str(env, reg->type));
6457                         return -EACCES;
6458                 }
6459                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6460                 if (!err && value_regno >= 0)
6461                         mark_reg_unknown(env, regs, value_regno);
6462         } else if (reg->type == PTR_TO_TP_BUFFER) {
6463                 err = check_tp_buffer_access(env, reg, regno, off, size);
6464                 if (!err && t == BPF_READ && value_regno >= 0)
6465                         mark_reg_unknown(env, regs, value_regno);
6466         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6467                    !type_may_be_null(reg->type)) {
6468                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6469                                               value_regno);
6470         } else if (reg->type == CONST_PTR_TO_MAP) {
6471                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6472                                               value_regno);
6473         } else if (base_type(reg->type) == PTR_TO_BUF) {
6474                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6475                 u32 *max_access;
6476
6477                 if (rdonly_mem) {
6478                         if (t == BPF_WRITE) {
6479                                 verbose(env, "R%d cannot write into %s\n",
6480                                         regno, reg_type_str(env, reg->type));
6481                                 return -EACCES;
6482                         }
6483                         max_access = &env->prog->aux->max_rdonly_access;
6484                 } else {
6485                         max_access = &env->prog->aux->max_rdwr_access;
6486                 }
6487
6488                 err = check_buffer_access(env, reg, regno, off, size, false,
6489                                           max_access);
6490
6491                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6492                         mark_reg_unknown(env, regs, value_regno);
6493         } else {
6494                 verbose(env, "R%d invalid mem access '%s'\n", regno,
6495                         reg_type_str(env, reg->type));
6496                 return -EACCES;
6497         }
6498
6499         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6500             regs[value_regno].type == SCALAR_VALUE) {
6501                 /* b/h/w load zero-extends, mark upper bits as known 0 */
6502                 coerce_reg_to_size(&regs[value_regno], size);
6503         }
6504         return err;
6505 }
6506
6507 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6508 {
6509         int load_reg;
6510         int err;
6511
6512         switch (insn->imm) {
6513         case BPF_ADD:
6514         case BPF_ADD | BPF_FETCH:
6515         case BPF_AND:
6516         case BPF_AND | BPF_FETCH:
6517         case BPF_OR:
6518         case BPF_OR | BPF_FETCH:
6519         case BPF_XOR:
6520         case BPF_XOR | BPF_FETCH:
6521         case BPF_XCHG:
6522         case BPF_CMPXCHG:
6523                 break;
6524         default:
6525                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6526                 return -EINVAL;
6527         }
6528
6529         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6530                 verbose(env, "invalid atomic operand size\n");
6531                 return -EINVAL;
6532         }
6533
6534         /* check src1 operand */
6535         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6536         if (err)
6537                 return err;
6538
6539         /* check src2 operand */
6540         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6541         if (err)
6542                 return err;
6543
6544         if (insn->imm == BPF_CMPXCHG) {
6545                 /* Check comparison of R0 with memory location */
6546                 const u32 aux_reg = BPF_REG_0;
6547
6548                 err = check_reg_arg(env, aux_reg, SRC_OP);
6549                 if (err)
6550                         return err;
6551
6552                 if (is_pointer_value(env, aux_reg)) {
6553                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6554                         return -EACCES;
6555                 }
6556         }
6557
6558         if (is_pointer_value(env, insn->src_reg)) {
6559                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6560                 return -EACCES;
6561         }
6562
6563         if (is_ctx_reg(env, insn->dst_reg) ||
6564             is_pkt_reg(env, insn->dst_reg) ||
6565             is_flow_key_reg(env, insn->dst_reg) ||
6566             is_sk_reg(env, insn->dst_reg)) {
6567                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6568                         insn->dst_reg,
6569                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6570                 return -EACCES;
6571         }
6572
6573         if (insn->imm & BPF_FETCH) {
6574                 if (insn->imm == BPF_CMPXCHG)
6575                         load_reg = BPF_REG_0;
6576                 else
6577                         load_reg = insn->src_reg;
6578
6579                 /* check and record load of old value */
6580                 err = check_reg_arg(env, load_reg, DST_OP);
6581                 if (err)
6582                         return err;
6583         } else {
6584                 /* This instruction accesses a memory location but doesn't
6585                  * actually load it into a register.
6586                  */
6587                 load_reg = -1;
6588         }
6589
6590         /* Check whether we can read the memory, with second call for fetch
6591          * case to simulate the register fill.
6592          */
6593         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6594                                BPF_SIZE(insn->code), BPF_READ, -1, true);
6595         if (!err && load_reg >= 0)
6596                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6597                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
6598                                        true);
6599         if (err)
6600                 return err;
6601
6602         /* Check whether we can write into the same memory. */
6603         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6604                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6605         if (err)
6606                 return err;
6607
6608         return 0;
6609 }
6610
6611 /* When register 'regno' is used to read the stack (either directly or through
6612  * a helper function) make sure that it's within stack boundary and, depending
6613  * on the access type, that all elements of the stack are initialized.
6614  *
6615  * 'off' includes 'regno->off', but not its dynamic part (if any).
6616  *
6617  * All registers that have been spilled on the stack in the slots within the
6618  * read offsets are marked as read.
6619  */
6620 static int check_stack_range_initialized(
6621                 struct bpf_verifier_env *env, int regno, int off,
6622                 int access_size, bool zero_size_allowed,
6623                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6624 {
6625         struct bpf_reg_state *reg = reg_state(env, regno);
6626         struct bpf_func_state *state = func(env, reg);
6627         int err, min_off, max_off, i, j, slot, spi;
6628         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6629         enum bpf_access_type bounds_check_type;
6630         /* Some accesses can write anything into the stack, others are
6631          * read-only.
6632          */
6633         bool clobber = false;
6634
6635         if (access_size == 0 && !zero_size_allowed) {
6636                 verbose(env, "invalid zero-sized read\n");
6637                 return -EACCES;
6638         }
6639
6640         if (type == ACCESS_HELPER) {
6641                 /* The bounds checks for writes are more permissive than for
6642                  * reads. However, if raw_mode is not set, we'll do extra
6643                  * checks below.
6644                  */
6645                 bounds_check_type = BPF_WRITE;
6646                 clobber = true;
6647         } else {
6648                 bounds_check_type = BPF_READ;
6649         }
6650         err = check_stack_access_within_bounds(env, regno, off, access_size,
6651                                                type, bounds_check_type);
6652         if (err)
6653                 return err;
6654
6655
6656         if (tnum_is_const(reg->var_off)) {
6657                 min_off = max_off = reg->var_off.value + off;
6658         } else {
6659                 /* Variable offset is prohibited for unprivileged mode for
6660                  * simplicity since it requires corresponding support in
6661                  * Spectre masking for stack ALU.
6662                  * See also retrieve_ptr_limit().
6663                  */
6664                 if (!env->bypass_spec_v1) {
6665                         char tn_buf[48];
6666
6667                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6668                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6669                                 regno, err_extra, tn_buf);
6670                         return -EACCES;
6671                 }
6672                 /* Only initialized buffer on stack is allowed to be accessed
6673                  * with variable offset. With uninitialized buffer it's hard to
6674                  * guarantee that whole memory is marked as initialized on
6675                  * helper return since specific bounds are unknown what may
6676                  * cause uninitialized stack leaking.
6677                  */
6678                 if (meta && meta->raw_mode)
6679                         meta = NULL;
6680
6681                 min_off = reg->smin_value + off;
6682                 max_off = reg->smax_value + off;
6683         }
6684
6685         if (meta && meta->raw_mode) {
6686                 /* Ensure we won't be overwriting dynptrs when simulating byte
6687                  * by byte access in check_helper_call using meta.access_size.
6688                  * This would be a problem if we have a helper in the future
6689                  * which takes:
6690                  *
6691                  *      helper(uninit_mem, len, dynptr)
6692                  *
6693                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6694                  * may end up writing to dynptr itself when touching memory from
6695                  * arg 1. This can be relaxed on a case by case basis for known
6696                  * safe cases, but reject due to the possibilitiy of aliasing by
6697                  * default.
6698                  */
6699                 for (i = min_off; i < max_off + access_size; i++) {
6700                         int stack_off = -i - 1;
6701
6702                         spi = __get_spi(i);
6703                         /* raw_mode may write past allocated_stack */
6704                         if (state->allocated_stack <= stack_off)
6705                                 continue;
6706                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6707                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6708                                 return -EACCES;
6709                         }
6710                 }
6711                 meta->access_size = access_size;
6712                 meta->regno = regno;
6713                 return 0;
6714         }
6715
6716         for (i = min_off; i < max_off + access_size; i++) {
6717                 u8 *stype;
6718
6719                 slot = -i - 1;
6720                 spi = slot / BPF_REG_SIZE;
6721                 if (state->allocated_stack <= slot)
6722                         goto err;
6723                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6724                 if (*stype == STACK_MISC)
6725                         goto mark;
6726                 if ((*stype == STACK_ZERO) ||
6727                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6728                         if (clobber) {
6729                                 /* helper can write anything into the stack */
6730                                 *stype = STACK_MISC;
6731                         }
6732                         goto mark;
6733                 }
6734
6735                 if (is_spilled_reg(&state->stack[spi]) &&
6736                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6737                      env->allow_ptr_leaks)) {
6738                         if (clobber) {
6739                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6740                                 for (j = 0; j < BPF_REG_SIZE; j++)
6741                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6742                         }
6743                         goto mark;
6744                 }
6745
6746 err:
6747                 if (tnum_is_const(reg->var_off)) {
6748                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6749                                 err_extra, regno, min_off, i - min_off, access_size);
6750                 } else {
6751                         char tn_buf[48];
6752
6753                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6754                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6755                                 err_extra, regno, tn_buf, i - min_off, access_size);
6756                 }
6757                 return -EACCES;
6758 mark:
6759                 /* reading any byte out of 8-byte 'spill_slot' will cause
6760                  * the whole slot to be marked as 'read'
6761                  */
6762                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6763                               state->stack[spi].spilled_ptr.parent,
6764                               REG_LIVE_READ64);
6765                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6766                  * be sure that whether stack slot is written to or not. Hence,
6767                  * we must still conservatively propagate reads upwards even if
6768                  * helper may write to the entire memory range.
6769                  */
6770         }
6771         return update_stack_depth(env, state, min_off);
6772 }
6773
6774 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6775                                    int access_size, bool zero_size_allowed,
6776                                    struct bpf_call_arg_meta *meta)
6777 {
6778         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6779         u32 *max_access;
6780
6781         switch (base_type(reg->type)) {
6782         case PTR_TO_PACKET:
6783         case PTR_TO_PACKET_META:
6784                 return check_packet_access(env, regno, reg->off, access_size,
6785                                            zero_size_allowed);
6786         case PTR_TO_MAP_KEY:
6787                 if (meta && meta->raw_mode) {
6788                         verbose(env, "R%d cannot write into %s\n", regno,
6789                                 reg_type_str(env, reg->type));
6790                         return -EACCES;
6791                 }
6792                 return check_mem_region_access(env, regno, reg->off, access_size,
6793                                                reg->map_ptr->key_size, false);
6794         case PTR_TO_MAP_VALUE:
6795                 if (check_map_access_type(env, regno, reg->off, access_size,
6796                                           meta && meta->raw_mode ? BPF_WRITE :
6797                                           BPF_READ))
6798                         return -EACCES;
6799                 return check_map_access(env, regno, reg->off, access_size,
6800                                         zero_size_allowed, ACCESS_HELPER);
6801         case PTR_TO_MEM:
6802                 if (type_is_rdonly_mem(reg->type)) {
6803                         if (meta && meta->raw_mode) {
6804                                 verbose(env, "R%d cannot write into %s\n", regno,
6805                                         reg_type_str(env, reg->type));
6806                                 return -EACCES;
6807                         }
6808                 }
6809                 return check_mem_region_access(env, regno, reg->off,
6810                                                access_size, reg->mem_size,
6811                                                zero_size_allowed);
6812         case PTR_TO_BUF:
6813                 if (type_is_rdonly_mem(reg->type)) {
6814                         if (meta && meta->raw_mode) {
6815                                 verbose(env, "R%d cannot write into %s\n", regno,
6816                                         reg_type_str(env, reg->type));
6817                                 return -EACCES;
6818                         }
6819
6820                         max_access = &env->prog->aux->max_rdonly_access;
6821                 } else {
6822                         max_access = &env->prog->aux->max_rdwr_access;
6823                 }
6824                 return check_buffer_access(env, reg, regno, reg->off,
6825                                            access_size, zero_size_allowed,
6826                                            max_access);
6827         case PTR_TO_STACK:
6828                 return check_stack_range_initialized(
6829                                 env,
6830                                 regno, reg->off, access_size,
6831                                 zero_size_allowed, ACCESS_HELPER, meta);
6832         case PTR_TO_BTF_ID:
6833                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6834                                                access_size, BPF_READ, -1);
6835         case PTR_TO_CTX:
6836                 /* in case the function doesn't know how to access the context,
6837                  * (because we are in a program of type SYSCALL for example), we
6838                  * can not statically check its size.
6839                  * Dynamically check it now.
6840                  */
6841                 if (!env->ops->convert_ctx_access) {
6842                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6843                         int offset = access_size - 1;
6844
6845                         /* Allow zero-byte read from PTR_TO_CTX */
6846                         if (access_size == 0)
6847                                 return zero_size_allowed ? 0 : -EACCES;
6848
6849                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6850                                                 atype, -1, false);
6851                 }
6852
6853                 fallthrough;
6854         default: /* scalar_value or invalid ptr */
6855                 /* Allow zero-byte read from NULL, regardless of pointer type */
6856                 if (zero_size_allowed && access_size == 0 &&
6857                     register_is_null(reg))
6858                         return 0;
6859
6860                 verbose(env, "R%d type=%s ", regno,
6861                         reg_type_str(env, reg->type));
6862                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6863                 return -EACCES;
6864         }
6865 }
6866
6867 static int check_mem_size_reg(struct bpf_verifier_env *env,
6868                               struct bpf_reg_state *reg, u32 regno,
6869                               bool zero_size_allowed,
6870                               struct bpf_call_arg_meta *meta)
6871 {
6872         int err;
6873
6874         /* This is used to refine r0 return value bounds for helpers
6875          * that enforce this value as an upper bound on return values.
6876          * See do_refine_retval_range() for helpers that can refine
6877          * the return value. C type of helper is u32 so we pull register
6878          * bound from umax_value however, if negative verifier errors
6879          * out. Only upper bounds can be learned because retval is an
6880          * int type and negative retvals are allowed.
6881          */
6882         meta->msize_max_value = reg->umax_value;
6883
6884         /* The register is SCALAR_VALUE; the access check
6885          * happens using its boundaries.
6886          */
6887         if (!tnum_is_const(reg->var_off))
6888                 /* For unprivileged variable accesses, disable raw
6889                  * mode so that the program is required to
6890                  * initialize all the memory that the helper could
6891                  * just partially fill up.
6892                  */
6893                 meta = NULL;
6894
6895         if (reg->smin_value < 0) {
6896                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6897                         regno);
6898                 return -EACCES;
6899         }
6900
6901         if (reg->umin_value == 0) {
6902                 err = check_helper_mem_access(env, regno - 1, 0,
6903                                               zero_size_allowed,
6904                                               meta);
6905                 if (err)
6906                         return err;
6907         }
6908
6909         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6910                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6911                         regno);
6912                 return -EACCES;
6913         }
6914         err = check_helper_mem_access(env, regno - 1,
6915                                       reg->umax_value,
6916                                       zero_size_allowed, meta);
6917         if (!err)
6918                 err = mark_chain_precision(env, regno);
6919         return err;
6920 }
6921
6922 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6923                    u32 regno, u32 mem_size)
6924 {
6925         bool may_be_null = type_may_be_null(reg->type);
6926         struct bpf_reg_state saved_reg;
6927         struct bpf_call_arg_meta meta;
6928         int err;
6929
6930         if (register_is_null(reg))
6931                 return 0;
6932
6933         memset(&meta, 0, sizeof(meta));
6934         /* Assuming that the register contains a value check if the memory
6935          * access is safe. Temporarily save and restore the register's state as
6936          * the conversion shouldn't be visible to a caller.
6937          */
6938         if (may_be_null) {
6939                 saved_reg = *reg;
6940                 mark_ptr_not_null_reg(reg);
6941         }
6942
6943         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6944         /* Check access for BPF_WRITE */
6945         meta.raw_mode = true;
6946         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6947
6948         if (may_be_null)
6949                 *reg = saved_reg;
6950
6951         return err;
6952 }
6953
6954 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6955                                     u32 regno)
6956 {
6957         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6958         bool may_be_null = type_may_be_null(mem_reg->type);
6959         struct bpf_reg_state saved_reg;
6960         struct bpf_call_arg_meta meta;
6961         int err;
6962
6963         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6964
6965         memset(&meta, 0, sizeof(meta));
6966
6967         if (may_be_null) {
6968                 saved_reg = *mem_reg;
6969                 mark_ptr_not_null_reg(mem_reg);
6970         }
6971
6972         err = check_mem_size_reg(env, reg, regno, true, &meta);
6973         /* Check access for BPF_WRITE */
6974         meta.raw_mode = true;
6975         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6976
6977         if (may_be_null)
6978                 *mem_reg = saved_reg;
6979         return err;
6980 }
6981
6982 /* Implementation details:
6983  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6984  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6985  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6986  * Two separate bpf_obj_new will also have different reg->id.
6987  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6988  * clears reg->id after value_or_null->value transition, since the verifier only
6989  * cares about the range of access to valid map value pointer and doesn't care
6990  * about actual address of the map element.
6991  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6992  * reg->id > 0 after value_or_null->value transition. By doing so
6993  * two bpf_map_lookups will be considered two different pointers that
6994  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6995  * returned from bpf_obj_new.
6996  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6997  * dead-locks.
6998  * Since only one bpf_spin_lock is allowed the checks are simpler than
6999  * reg_is_refcounted() logic. The verifier needs to remember only
7000  * one spin_lock instead of array of acquired_refs.
7001  * cur_state->active_lock remembers which map value element or allocated
7002  * object got locked and clears it after bpf_spin_unlock.
7003  */
7004 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7005                              bool is_lock)
7006 {
7007         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7008         struct bpf_verifier_state *cur = env->cur_state;
7009         bool is_const = tnum_is_const(reg->var_off);
7010         u64 val = reg->var_off.value;
7011         struct bpf_map *map = NULL;
7012         struct btf *btf = NULL;
7013         struct btf_record *rec;
7014
7015         if (!is_const) {
7016                 verbose(env,
7017                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7018                         regno);
7019                 return -EINVAL;
7020         }
7021         if (reg->type == PTR_TO_MAP_VALUE) {
7022                 map = reg->map_ptr;
7023                 if (!map->btf) {
7024                         verbose(env,
7025                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7026                                 map->name);
7027                         return -EINVAL;
7028                 }
7029         } else {
7030                 btf = reg->btf;
7031         }
7032
7033         rec = reg_btf_record(reg);
7034         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7035                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7036                         map ? map->name : "kptr");
7037                 return -EINVAL;
7038         }
7039         if (rec->spin_lock_off != val + reg->off) {
7040                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7041                         val + reg->off, rec->spin_lock_off);
7042                 return -EINVAL;
7043         }
7044         if (is_lock) {
7045                 if (cur->active_lock.ptr) {
7046                         verbose(env,
7047                                 "Locking two bpf_spin_locks are not allowed\n");
7048                         return -EINVAL;
7049                 }
7050                 if (map)
7051                         cur->active_lock.ptr = map;
7052                 else
7053                         cur->active_lock.ptr = btf;
7054                 cur->active_lock.id = reg->id;
7055         } else {
7056                 void *ptr;
7057
7058                 if (map)
7059                         ptr = map;
7060                 else
7061                         ptr = btf;
7062
7063                 if (!cur->active_lock.ptr) {
7064                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7065                         return -EINVAL;
7066                 }
7067                 if (cur->active_lock.ptr != ptr ||
7068                     cur->active_lock.id != reg->id) {
7069                         verbose(env, "bpf_spin_unlock of different lock\n");
7070                         return -EINVAL;
7071                 }
7072
7073                 invalidate_non_owning_refs(env);
7074
7075                 cur->active_lock.ptr = NULL;
7076                 cur->active_lock.id = 0;
7077         }
7078         return 0;
7079 }
7080
7081 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7082                               struct bpf_call_arg_meta *meta)
7083 {
7084         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7085         bool is_const = tnum_is_const(reg->var_off);
7086         struct bpf_map *map = reg->map_ptr;
7087         u64 val = reg->var_off.value;
7088
7089         if (!is_const) {
7090                 verbose(env,
7091                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7092                         regno);
7093                 return -EINVAL;
7094         }
7095         if (!map->btf) {
7096                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7097                         map->name);
7098                 return -EINVAL;
7099         }
7100         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7101                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7102                 return -EINVAL;
7103         }
7104         if (map->record->timer_off != val + reg->off) {
7105                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7106                         val + reg->off, map->record->timer_off);
7107                 return -EINVAL;
7108         }
7109         if (meta->map_ptr) {
7110                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7111                 return -EFAULT;
7112         }
7113         meta->map_uid = reg->map_uid;
7114         meta->map_ptr = map;
7115         return 0;
7116 }
7117
7118 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7119                              struct bpf_call_arg_meta *meta)
7120 {
7121         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7122         struct bpf_map *map_ptr = reg->map_ptr;
7123         struct btf_field *kptr_field;
7124         u32 kptr_off;
7125
7126         if (!tnum_is_const(reg->var_off)) {
7127                 verbose(env,
7128                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7129                         regno);
7130                 return -EINVAL;
7131         }
7132         if (!map_ptr->btf) {
7133                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7134                         map_ptr->name);
7135                 return -EINVAL;
7136         }
7137         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7138                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7139                 return -EINVAL;
7140         }
7141
7142         meta->map_ptr = map_ptr;
7143         kptr_off = reg->off + reg->var_off.value;
7144         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7145         if (!kptr_field) {
7146                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7147                 return -EACCES;
7148         }
7149         if (kptr_field->type != BPF_KPTR_REF) {
7150                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7151                 return -EACCES;
7152         }
7153         meta->kptr_field = kptr_field;
7154         return 0;
7155 }
7156
7157 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7158  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7159  *
7160  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7161  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7162  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7163  *
7164  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7165  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7166  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7167  * mutate the view of the dynptr and also possibly destroy it. In the latter
7168  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7169  * memory that dynptr points to.
7170  *
7171  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7172  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7173  * readonly dynptr view yet, hence only the first case is tracked and checked.
7174  *
7175  * This is consistent with how C applies the const modifier to a struct object,
7176  * where the pointer itself inside bpf_dynptr becomes const but not what it
7177  * points to.
7178  *
7179  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7180  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7181  */
7182 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7183                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7184 {
7185         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7186         int err;
7187
7188         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7189          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7190          */
7191         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7192                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7193                 return -EFAULT;
7194         }
7195
7196         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7197          *               constructing a mutable bpf_dynptr object.
7198          *
7199          *               Currently, this is only possible with PTR_TO_STACK
7200          *               pointing to a region of at least 16 bytes which doesn't
7201          *               contain an existing bpf_dynptr.
7202          *
7203          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7204          *               mutated or destroyed. However, the memory it points to
7205          *               may be mutated.
7206          *
7207          *  None       - Points to a initialized dynptr that can be mutated and
7208          *               destroyed, including mutation of the memory it points
7209          *               to.
7210          */
7211         if (arg_type & MEM_UNINIT) {
7212                 int i;
7213
7214                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7215                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7216                         return -EINVAL;
7217                 }
7218
7219                 /* we write BPF_DW bits (8 bytes) at a time */
7220                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7221                         err = check_mem_access(env, insn_idx, regno,
7222                                                i, BPF_DW, BPF_WRITE, -1, false);
7223                         if (err)
7224                                 return err;
7225                 }
7226
7227                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7228         } else /* MEM_RDONLY and None case from above */ {
7229                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7230                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7231                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7232                         return -EINVAL;
7233                 }
7234
7235                 if (!is_dynptr_reg_valid_init(env, reg)) {
7236                         verbose(env,
7237                                 "Expected an initialized dynptr as arg #%d\n",
7238                                 regno);
7239                         return -EINVAL;
7240                 }
7241
7242                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7243                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7244                         verbose(env,
7245                                 "Expected a dynptr of type %s as arg #%d\n",
7246                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7247                         return -EINVAL;
7248                 }
7249
7250                 err = mark_dynptr_read(env, reg);
7251         }
7252         return err;
7253 }
7254
7255 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7256 {
7257         struct bpf_func_state *state = func(env, reg);
7258
7259         return state->stack[spi].spilled_ptr.ref_obj_id;
7260 }
7261
7262 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7263 {
7264         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7265 }
7266
7267 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7268 {
7269         return meta->kfunc_flags & KF_ITER_NEW;
7270 }
7271
7272 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7273 {
7274         return meta->kfunc_flags & KF_ITER_NEXT;
7275 }
7276
7277 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7278 {
7279         return meta->kfunc_flags & KF_ITER_DESTROY;
7280 }
7281
7282 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7283 {
7284         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7285          * kfunc is iter state pointer
7286          */
7287         return arg == 0 && is_iter_kfunc(meta);
7288 }
7289
7290 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7291                             struct bpf_kfunc_call_arg_meta *meta)
7292 {
7293         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7294         const struct btf_type *t;
7295         const struct btf_param *arg;
7296         int spi, err, i, nr_slots;
7297         u32 btf_id;
7298
7299         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7300         arg = &btf_params(meta->func_proto)[0];
7301         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7302         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7303         nr_slots = t->size / BPF_REG_SIZE;
7304
7305         if (is_iter_new_kfunc(meta)) {
7306                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7307                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7308                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7309                                 iter_type_str(meta->btf, btf_id), regno);
7310                         return -EINVAL;
7311                 }
7312
7313                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7314                         err = check_mem_access(env, insn_idx, regno,
7315                                                i, BPF_DW, BPF_WRITE, -1, false);
7316                         if (err)
7317                                 return err;
7318                 }
7319
7320                 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7321                 if (err)
7322                         return err;
7323         } else {
7324                 /* iter_next() or iter_destroy() expect initialized iter state*/
7325                 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7326                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7327                                 iter_type_str(meta->btf, btf_id), regno);
7328                         return -EINVAL;
7329                 }
7330
7331                 spi = iter_get_spi(env, reg, nr_slots);
7332                 if (spi < 0)
7333                         return spi;
7334
7335                 err = mark_iter_read(env, reg, spi, nr_slots);
7336                 if (err)
7337                         return err;
7338
7339                 /* remember meta->iter info for process_iter_next_call() */
7340                 meta->iter.spi = spi;
7341                 meta->iter.frameno = reg->frameno;
7342                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7343
7344                 if (is_iter_destroy_kfunc(meta)) {
7345                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7346                         if (err)
7347                                 return err;
7348                 }
7349         }
7350
7351         return 0;
7352 }
7353
7354 /* process_iter_next_call() is called when verifier gets to iterator's next
7355  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7356  * to it as just "iter_next()" in comments below.
7357  *
7358  * BPF verifier relies on a crucial contract for any iter_next()
7359  * implementation: it should *eventually* return NULL, and once that happens
7360  * it should keep returning NULL. That is, once iterator exhausts elements to
7361  * iterate, it should never reset or spuriously return new elements.
7362  *
7363  * With the assumption of such contract, process_iter_next_call() simulates
7364  * a fork in the verifier state to validate loop logic correctness and safety
7365  * without having to simulate infinite amount of iterations.
7366  *
7367  * In current state, we first assume that iter_next() returned NULL and
7368  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7369  * conditions we should not form an infinite loop and should eventually reach
7370  * exit.
7371  *
7372  * Besides that, we also fork current state and enqueue it for later
7373  * verification. In a forked state we keep iterator state as ACTIVE
7374  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7375  * also bump iteration depth to prevent erroneous infinite loop detection
7376  * later on (see iter_active_depths_differ() comment for details). In this
7377  * state we assume that we'll eventually loop back to another iter_next()
7378  * calls (it could be in exactly same location or in some other instruction,
7379  * it doesn't matter, we don't make any unnecessary assumptions about this,
7380  * everything revolves around iterator state in a stack slot, not which
7381  * instruction is calling iter_next()). When that happens, we either will come
7382  * to iter_next() with equivalent state and can conclude that next iteration
7383  * will proceed in exactly the same way as we just verified, so it's safe to
7384  * assume that loop converges. If not, we'll go on another iteration
7385  * simulation with a different input state, until all possible starting states
7386  * are validated or we reach maximum number of instructions limit.
7387  *
7388  * This way, we will either exhaustively discover all possible input states
7389  * that iterator loop can start with and eventually will converge, or we'll
7390  * effectively regress into bounded loop simulation logic and either reach
7391  * maximum number of instructions if loop is not provably convergent, or there
7392  * is some statically known limit on number of iterations (e.g., if there is
7393  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7394  *
7395  * One very subtle but very important aspect is that we *always* simulate NULL
7396  * condition first (as the current state) before we simulate non-NULL case.
7397  * This has to do with intricacies of scalar precision tracking. By simulating
7398  * "exit condition" of iter_next() returning NULL first, we make sure all the
7399  * relevant precision marks *that will be set **after** we exit iterator loop*
7400  * are propagated backwards to common parent state of NULL and non-NULL
7401  * branches. Thanks to that, state equivalence checks done later in forked
7402  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7403  * precision marks are finalized and won't change. Because simulating another
7404  * ACTIVE iterator iteration won't change them (because given same input
7405  * states we'll end up with exactly same output states which we are currently
7406  * comparing; and verification after the loop already propagated back what
7407  * needs to be **additionally** tracked as precise). It's subtle, grok
7408  * precision tracking for more intuitive understanding.
7409  */
7410 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7411                                   struct bpf_kfunc_call_arg_meta *meta)
7412 {
7413         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7414         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7415         struct bpf_reg_state *cur_iter, *queued_iter;
7416         int iter_frameno = meta->iter.frameno;
7417         int iter_spi = meta->iter.spi;
7418
7419         BTF_TYPE_EMIT(struct bpf_iter);
7420
7421         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7422
7423         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7424             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7425                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7426                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7427                 return -EFAULT;
7428         }
7429
7430         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7431                 /* branch out active iter state */
7432                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7433                 if (!queued_st)
7434                         return -ENOMEM;
7435
7436                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7437                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7438                 queued_iter->iter.depth++;
7439
7440                 queued_fr = queued_st->frame[queued_st->curframe];
7441                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7442         }
7443
7444         /* switch to DRAINED state, but keep the depth unchanged */
7445         /* mark current iter state as drained and assume returned NULL */
7446         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7447         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7448
7449         return 0;
7450 }
7451
7452 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7453 {
7454         return type == ARG_CONST_SIZE ||
7455                type == ARG_CONST_SIZE_OR_ZERO;
7456 }
7457
7458 static bool arg_type_is_release(enum bpf_arg_type type)
7459 {
7460         return type & OBJ_RELEASE;
7461 }
7462
7463 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7464 {
7465         return base_type(type) == ARG_PTR_TO_DYNPTR;
7466 }
7467
7468 static int int_ptr_type_to_size(enum bpf_arg_type type)
7469 {
7470         if (type == ARG_PTR_TO_INT)
7471                 return sizeof(u32);
7472         else if (type == ARG_PTR_TO_LONG)
7473                 return sizeof(u64);
7474
7475         return -EINVAL;
7476 }
7477
7478 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7479                                  const struct bpf_call_arg_meta *meta,
7480                                  enum bpf_arg_type *arg_type)
7481 {
7482         if (!meta->map_ptr) {
7483                 /* kernel subsystem misconfigured verifier */
7484                 verbose(env, "invalid map_ptr to access map->type\n");
7485                 return -EACCES;
7486         }
7487
7488         switch (meta->map_ptr->map_type) {
7489         case BPF_MAP_TYPE_SOCKMAP:
7490         case BPF_MAP_TYPE_SOCKHASH:
7491                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7492                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7493                 } else {
7494                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
7495                         return -EINVAL;
7496                 }
7497                 break;
7498         case BPF_MAP_TYPE_BLOOM_FILTER:
7499                 if (meta->func_id == BPF_FUNC_map_peek_elem)
7500                         *arg_type = ARG_PTR_TO_MAP_VALUE;
7501                 break;
7502         default:
7503                 break;
7504         }
7505         return 0;
7506 }
7507
7508 struct bpf_reg_types {
7509         const enum bpf_reg_type types[10];
7510         u32 *btf_id;
7511 };
7512
7513 static const struct bpf_reg_types sock_types = {
7514         .types = {
7515                 PTR_TO_SOCK_COMMON,
7516                 PTR_TO_SOCKET,
7517                 PTR_TO_TCP_SOCK,
7518                 PTR_TO_XDP_SOCK,
7519         },
7520 };
7521
7522 #ifdef CONFIG_NET
7523 static const struct bpf_reg_types btf_id_sock_common_types = {
7524         .types = {
7525                 PTR_TO_SOCK_COMMON,
7526                 PTR_TO_SOCKET,
7527                 PTR_TO_TCP_SOCK,
7528                 PTR_TO_XDP_SOCK,
7529                 PTR_TO_BTF_ID,
7530                 PTR_TO_BTF_ID | PTR_TRUSTED,
7531         },
7532         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7533 };
7534 #endif
7535
7536 static const struct bpf_reg_types mem_types = {
7537         .types = {
7538                 PTR_TO_STACK,
7539                 PTR_TO_PACKET,
7540                 PTR_TO_PACKET_META,
7541                 PTR_TO_MAP_KEY,
7542                 PTR_TO_MAP_VALUE,
7543                 PTR_TO_MEM,
7544                 PTR_TO_MEM | MEM_RINGBUF,
7545                 PTR_TO_BUF,
7546                 PTR_TO_BTF_ID | PTR_TRUSTED,
7547         },
7548 };
7549
7550 static const struct bpf_reg_types int_ptr_types = {
7551         .types = {
7552                 PTR_TO_STACK,
7553                 PTR_TO_PACKET,
7554                 PTR_TO_PACKET_META,
7555                 PTR_TO_MAP_KEY,
7556                 PTR_TO_MAP_VALUE,
7557         },
7558 };
7559
7560 static const struct bpf_reg_types spin_lock_types = {
7561         .types = {
7562                 PTR_TO_MAP_VALUE,
7563                 PTR_TO_BTF_ID | MEM_ALLOC,
7564         }
7565 };
7566
7567 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7568 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7569 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7570 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7571 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7572 static const struct bpf_reg_types btf_ptr_types = {
7573         .types = {
7574                 PTR_TO_BTF_ID,
7575                 PTR_TO_BTF_ID | PTR_TRUSTED,
7576                 PTR_TO_BTF_ID | MEM_RCU,
7577         },
7578 };
7579 static const struct bpf_reg_types percpu_btf_ptr_types = {
7580         .types = {
7581                 PTR_TO_BTF_ID | MEM_PERCPU,
7582                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7583         }
7584 };
7585 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7586 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7587 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7588 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7589 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7590 static const struct bpf_reg_types dynptr_types = {
7591         .types = {
7592                 PTR_TO_STACK,
7593                 CONST_PTR_TO_DYNPTR,
7594         }
7595 };
7596
7597 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7598         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
7599         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
7600         [ARG_CONST_SIZE]                = &scalar_types,
7601         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
7602         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
7603         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
7604         [ARG_PTR_TO_CTX]                = &context_types,
7605         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
7606 #ifdef CONFIG_NET
7607         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7608 #endif
7609         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
7610         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
7611         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
7612         [ARG_PTR_TO_MEM]                = &mem_types,
7613         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
7614         [ARG_PTR_TO_INT]                = &int_ptr_types,
7615         [ARG_PTR_TO_LONG]               = &int_ptr_types,
7616         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
7617         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
7618         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
7619         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
7620         [ARG_PTR_TO_TIMER]              = &timer_types,
7621         [ARG_PTR_TO_KPTR]               = &kptr_types,
7622         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
7623 };
7624
7625 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7626                           enum bpf_arg_type arg_type,
7627                           const u32 *arg_btf_id,
7628                           struct bpf_call_arg_meta *meta)
7629 {
7630         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7631         enum bpf_reg_type expected, type = reg->type;
7632         const struct bpf_reg_types *compatible;
7633         int i, j;
7634
7635         compatible = compatible_reg_types[base_type(arg_type)];
7636         if (!compatible) {
7637                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7638                 return -EFAULT;
7639         }
7640
7641         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7642          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7643          *
7644          * Same for MAYBE_NULL:
7645          *
7646          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7647          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7648          *
7649          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7650          *
7651          * Therefore we fold these flags depending on the arg_type before comparison.
7652          */
7653         if (arg_type & MEM_RDONLY)
7654                 type &= ~MEM_RDONLY;
7655         if (arg_type & PTR_MAYBE_NULL)
7656                 type &= ~PTR_MAYBE_NULL;
7657         if (base_type(arg_type) == ARG_PTR_TO_MEM)
7658                 type &= ~DYNPTR_TYPE_FLAG_MASK;
7659
7660         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7661                 type &= ~MEM_ALLOC;
7662
7663         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7664                 expected = compatible->types[i];
7665                 if (expected == NOT_INIT)
7666                         break;
7667
7668                 if (type == expected)
7669                         goto found;
7670         }
7671
7672         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7673         for (j = 0; j + 1 < i; j++)
7674                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7675         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7676         return -EACCES;
7677
7678 found:
7679         if (base_type(reg->type) != PTR_TO_BTF_ID)
7680                 return 0;
7681
7682         if (compatible == &mem_types) {
7683                 if (!(arg_type & MEM_RDONLY)) {
7684                         verbose(env,
7685                                 "%s() may write into memory pointed by R%d type=%s\n",
7686                                 func_id_name(meta->func_id),
7687                                 regno, reg_type_str(env, reg->type));
7688                         return -EACCES;
7689                 }
7690                 return 0;
7691         }
7692
7693         switch ((int)reg->type) {
7694         case PTR_TO_BTF_ID:
7695         case PTR_TO_BTF_ID | PTR_TRUSTED:
7696         case PTR_TO_BTF_ID | MEM_RCU:
7697         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7698         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7699         {
7700                 /* For bpf_sk_release, it needs to match against first member
7701                  * 'struct sock_common', hence make an exception for it. This
7702                  * allows bpf_sk_release to work for multiple socket types.
7703                  */
7704                 bool strict_type_match = arg_type_is_release(arg_type) &&
7705                                          meta->func_id != BPF_FUNC_sk_release;
7706
7707                 if (type_may_be_null(reg->type) &&
7708                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7709                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7710                         return -EACCES;
7711                 }
7712
7713                 if (!arg_btf_id) {
7714                         if (!compatible->btf_id) {
7715                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7716                                 return -EFAULT;
7717                         }
7718                         arg_btf_id = compatible->btf_id;
7719                 }
7720
7721                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7722                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7723                                 return -EACCES;
7724                 } else {
7725                         if (arg_btf_id == BPF_PTR_POISON) {
7726                                 verbose(env, "verifier internal error:");
7727                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7728                                         regno);
7729                                 return -EACCES;
7730                         }
7731
7732                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7733                                                   btf_vmlinux, *arg_btf_id,
7734                                                   strict_type_match)) {
7735                                 verbose(env, "R%d is of type %s but %s is expected\n",
7736                                         regno, btf_type_name(reg->btf, reg->btf_id),
7737                                         btf_type_name(btf_vmlinux, *arg_btf_id));
7738                                 return -EACCES;
7739                         }
7740                 }
7741                 break;
7742         }
7743         case PTR_TO_BTF_ID | MEM_ALLOC:
7744                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7745                     meta->func_id != BPF_FUNC_kptr_xchg) {
7746                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7747                         return -EFAULT;
7748                 }
7749                 /* Handled by helper specific checks */
7750                 break;
7751         case PTR_TO_BTF_ID | MEM_PERCPU:
7752         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7753                 /* Handled by helper specific checks */
7754                 break;
7755         default:
7756                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7757                 return -EFAULT;
7758         }
7759         return 0;
7760 }
7761
7762 static struct btf_field *
7763 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7764 {
7765         struct btf_field *field;
7766         struct btf_record *rec;
7767
7768         rec = reg_btf_record(reg);
7769         if (!rec)
7770                 return NULL;
7771
7772         field = btf_record_find(rec, off, fields);
7773         if (!field)
7774                 return NULL;
7775
7776         return field;
7777 }
7778
7779 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7780                            const struct bpf_reg_state *reg, int regno,
7781                            enum bpf_arg_type arg_type)
7782 {
7783         u32 type = reg->type;
7784
7785         /* When referenced register is passed to release function, its fixed
7786          * offset must be 0.
7787          *
7788          * We will check arg_type_is_release reg has ref_obj_id when storing
7789          * meta->release_regno.
7790          */
7791         if (arg_type_is_release(arg_type)) {
7792                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7793                  * may not directly point to the object being released, but to
7794                  * dynptr pointing to such object, which might be at some offset
7795                  * on the stack. In that case, we simply to fallback to the
7796                  * default handling.
7797                  */
7798                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7799                         return 0;
7800
7801                 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7802                         if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7803                                 return __check_ptr_off_reg(env, reg, regno, true);
7804
7805                         verbose(env, "R%d must have zero offset when passed to release func\n",
7806                                 regno);
7807                         verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7808                                 btf_type_name(reg->btf, reg->btf_id), reg->off);
7809                         return -EINVAL;
7810                 }
7811
7812                 /* Doing check_ptr_off_reg check for the offset will catch this
7813                  * because fixed_off_ok is false, but checking here allows us
7814                  * to give the user a better error message.
7815                  */
7816                 if (reg->off) {
7817                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7818                                 regno);
7819                         return -EINVAL;
7820                 }
7821                 return __check_ptr_off_reg(env, reg, regno, false);
7822         }
7823
7824         switch (type) {
7825         /* Pointer types where both fixed and variable offset is explicitly allowed: */
7826         case PTR_TO_STACK:
7827         case PTR_TO_PACKET:
7828         case PTR_TO_PACKET_META:
7829         case PTR_TO_MAP_KEY:
7830         case PTR_TO_MAP_VALUE:
7831         case PTR_TO_MEM:
7832         case PTR_TO_MEM | MEM_RDONLY:
7833         case PTR_TO_MEM | MEM_RINGBUF:
7834         case PTR_TO_BUF:
7835         case PTR_TO_BUF | MEM_RDONLY:
7836         case SCALAR_VALUE:
7837                 return 0;
7838         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7839          * fixed offset.
7840          */
7841         case PTR_TO_BTF_ID:
7842         case PTR_TO_BTF_ID | MEM_ALLOC:
7843         case PTR_TO_BTF_ID | PTR_TRUSTED:
7844         case PTR_TO_BTF_ID | MEM_RCU:
7845         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7846                 /* When referenced PTR_TO_BTF_ID is passed to release function,
7847                  * its fixed offset must be 0. In the other cases, fixed offset
7848                  * can be non-zero. This was already checked above. So pass
7849                  * fixed_off_ok as true to allow fixed offset for all other
7850                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7851                  * still need to do checks instead of returning.
7852                  */
7853                 return __check_ptr_off_reg(env, reg, regno, true);
7854         default:
7855                 return __check_ptr_off_reg(env, reg, regno, false);
7856         }
7857 }
7858
7859 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7860                                                 const struct bpf_func_proto *fn,
7861                                                 struct bpf_reg_state *regs)
7862 {
7863         struct bpf_reg_state *state = NULL;
7864         int i;
7865
7866         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7867                 if (arg_type_is_dynptr(fn->arg_type[i])) {
7868                         if (state) {
7869                                 verbose(env, "verifier internal error: multiple dynptr args\n");
7870                                 return NULL;
7871                         }
7872                         state = &regs[BPF_REG_1 + i];
7873                 }
7874
7875         if (!state)
7876                 verbose(env, "verifier internal error: no dynptr arg found\n");
7877
7878         return state;
7879 }
7880
7881 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7882 {
7883         struct bpf_func_state *state = func(env, reg);
7884         int spi;
7885
7886         if (reg->type == CONST_PTR_TO_DYNPTR)
7887                 return reg->id;
7888         spi = dynptr_get_spi(env, reg);
7889         if (spi < 0)
7890                 return spi;
7891         return state->stack[spi].spilled_ptr.id;
7892 }
7893
7894 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7895 {
7896         struct bpf_func_state *state = func(env, reg);
7897         int spi;
7898
7899         if (reg->type == CONST_PTR_TO_DYNPTR)
7900                 return reg->ref_obj_id;
7901         spi = dynptr_get_spi(env, reg);
7902         if (spi < 0)
7903                 return spi;
7904         return state->stack[spi].spilled_ptr.ref_obj_id;
7905 }
7906
7907 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7908                                             struct bpf_reg_state *reg)
7909 {
7910         struct bpf_func_state *state = func(env, reg);
7911         int spi;
7912
7913         if (reg->type == CONST_PTR_TO_DYNPTR)
7914                 return reg->dynptr.type;
7915
7916         spi = __get_spi(reg->off);
7917         if (spi < 0) {
7918                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7919                 return BPF_DYNPTR_TYPE_INVALID;
7920         }
7921
7922         return state->stack[spi].spilled_ptr.dynptr.type;
7923 }
7924
7925 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7926                           struct bpf_call_arg_meta *meta,
7927                           const struct bpf_func_proto *fn,
7928                           int insn_idx)
7929 {
7930         u32 regno = BPF_REG_1 + arg;
7931         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7932         enum bpf_arg_type arg_type = fn->arg_type[arg];
7933         enum bpf_reg_type type = reg->type;
7934         u32 *arg_btf_id = NULL;
7935         int err = 0;
7936
7937         if (arg_type == ARG_DONTCARE)
7938                 return 0;
7939
7940         err = check_reg_arg(env, regno, SRC_OP);
7941         if (err)
7942                 return err;
7943
7944         if (arg_type == ARG_ANYTHING) {
7945                 if (is_pointer_value(env, regno)) {
7946                         verbose(env, "R%d leaks addr into helper function\n",
7947                                 regno);
7948                         return -EACCES;
7949                 }
7950                 return 0;
7951         }
7952
7953         if (type_is_pkt_pointer(type) &&
7954             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7955                 verbose(env, "helper access to the packet is not allowed\n");
7956                 return -EACCES;
7957         }
7958
7959         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7960                 err = resolve_map_arg_type(env, meta, &arg_type);
7961                 if (err)
7962                         return err;
7963         }
7964
7965         if (register_is_null(reg) && type_may_be_null(arg_type))
7966                 /* A NULL register has a SCALAR_VALUE type, so skip
7967                  * type checking.
7968                  */
7969                 goto skip_type_check;
7970
7971         /* arg_btf_id and arg_size are in a union. */
7972         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7973             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7974                 arg_btf_id = fn->arg_btf_id[arg];
7975
7976         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7977         if (err)
7978                 return err;
7979
7980         err = check_func_arg_reg_off(env, reg, regno, arg_type);
7981         if (err)
7982                 return err;
7983
7984 skip_type_check:
7985         if (arg_type_is_release(arg_type)) {
7986                 if (arg_type_is_dynptr(arg_type)) {
7987                         struct bpf_func_state *state = func(env, reg);
7988                         int spi;
7989
7990                         /* Only dynptr created on stack can be released, thus
7991                          * the get_spi and stack state checks for spilled_ptr
7992                          * should only be done before process_dynptr_func for
7993                          * PTR_TO_STACK.
7994                          */
7995                         if (reg->type == PTR_TO_STACK) {
7996                                 spi = dynptr_get_spi(env, reg);
7997                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7998                                         verbose(env, "arg %d is an unacquired reference\n", regno);
7999                                         return -EINVAL;
8000                                 }
8001                         } else {
8002                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8003                                 return -EINVAL;
8004                         }
8005                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8006                         verbose(env, "R%d must be referenced when passed to release function\n",
8007                                 regno);
8008                         return -EINVAL;
8009                 }
8010                 if (meta->release_regno) {
8011                         verbose(env, "verifier internal error: more than one release argument\n");
8012                         return -EFAULT;
8013                 }
8014                 meta->release_regno = regno;
8015         }
8016
8017         if (reg->ref_obj_id) {
8018                 if (meta->ref_obj_id) {
8019                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8020                                 regno, reg->ref_obj_id,
8021                                 meta->ref_obj_id);
8022                         return -EFAULT;
8023                 }
8024                 meta->ref_obj_id = reg->ref_obj_id;
8025         }
8026
8027         switch (base_type(arg_type)) {
8028         case ARG_CONST_MAP_PTR:
8029                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8030                 if (meta->map_ptr) {
8031                         /* Use map_uid (which is unique id of inner map) to reject:
8032                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8033                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8034                          * if (inner_map1 && inner_map2) {
8035                          *     timer = bpf_map_lookup_elem(inner_map1);
8036                          *     if (timer)
8037                          *         // mismatch would have been allowed
8038                          *         bpf_timer_init(timer, inner_map2);
8039                          * }
8040                          *
8041                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8042                          */
8043                         if (meta->map_ptr != reg->map_ptr ||
8044                             meta->map_uid != reg->map_uid) {
8045                                 verbose(env,
8046                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8047                                         meta->map_uid, reg->map_uid);
8048                                 return -EINVAL;
8049                         }
8050                 }
8051                 meta->map_ptr = reg->map_ptr;
8052                 meta->map_uid = reg->map_uid;
8053                 break;
8054         case ARG_PTR_TO_MAP_KEY:
8055                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8056                  * check that [key, key + map->key_size) are within
8057                  * stack limits and initialized
8058                  */
8059                 if (!meta->map_ptr) {
8060                         /* in function declaration map_ptr must come before
8061                          * map_key, so that it's verified and known before
8062                          * we have to check map_key here. Otherwise it means
8063                          * that kernel subsystem misconfigured verifier
8064                          */
8065                         verbose(env, "invalid map_ptr to access map->key\n");
8066                         return -EACCES;
8067                 }
8068                 err = check_helper_mem_access(env, regno,
8069                                               meta->map_ptr->key_size, false,
8070                                               NULL);
8071                 break;
8072         case ARG_PTR_TO_MAP_VALUE:
8073                 if (type_may_be_null(arg_type) && register_is_null(reg))
8074                         return 0;
8075
8076                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8077                  * check [value, value + map->value_size) validity
8078                  */
8079                 if (!meta->map_ptr) {
8080                         /* kernel subsystem misconfigured verifier */
8081                         verbose(env, "invalid map_ptr to access map->value\n");
8082                         return -EACCES;
8083                 }
8084                 meta->raw_mode = arg_type & MEM_UNINIT;
8085                 err = check_helper_mem_access(env, regno,
8086                                               meta->map_ptr->value_size, false,
8087                                               meta);
8088                 break;
8089         case ARG_PTR_TO_PERCPU_BTF_ID:
8090                 if (!reg->btf_id) {
8091                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8092                         return -EACCES;
8093                 }
8094                 meta->ret_btf = reg->btf;
8095                 meta->ret_btf_id = reg->btf_id;
8096                 break;
8097         case ARG_PTR_TO_SPIN_LOCK:
8098                 if (in_rbtree_lock_required_cb(env)) {
8099                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8100                         return -EACCES;
8101                 }
8102                 if (meta->func_id == BPF_FUNC_spin_lock) {
8103                         err = process_spin_lock(env, regno, true);
8104                         if (err)
8105                                 return err;
8106                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8107                         err = process_spin_lock(env, regno, false);
8108                         if (err)
8109                                 return err;
8110                 } else {
8111                         verbose(env, "verifier internal error\n");
8112                         return -EFAULT;
8113                 }
8114                 break;
8115         case ARG_PTR_TO_TIMER:
8116                 err = process_timer_func(env, regno, meta);
8117                 if (err)
8118                         return err;
8119                 break;
8120         case ARG_PTR_TO_FUNC:
8121                 meta->subprogno = reg->subprogno;
8122                 break;
8123         case ARG_PTR_TO_MEM:
8124                 /* The access to this pointer is only checked when we hit the
8125                  * next is_mem_size argument below.
8126                  */
8127                 meta->raw_mode = arg_type & MEM_UNINIT;
8128                 if (arg_type & MEM_FIXED_SIZE) {
8129                         err = check_helper_mem_access(env, regno,
8130                                                       fn->arg_size[arg], false,
8131                                                       meta);
8132                 }
8133                 break;
8134         case ARG_CONST_SIZE:
8135                 err = check_mem_size_reg(env, reg, regno, false, meta);
8136                 break;
8137         case ARG_CONST_SIZE_OR_ZERO:
8138                 err = check_mem_size_reg(env, reg, regno, true, meta);
8139                 break;
8140         case ARG_PTR_TO_DYNPTR:
8141                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8142                 if (err)
8143                         return err;
8144                 break;
8145         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8146                 if (!tnum_is_const(reg->var_off)) {
8147                         verbose(env, "R%d is not a known constant'\n",
8148                                 regno);
8149                         return -EACCES;
8150                 }
8151                 meta->mem_size = reg->var_off.value;
8152                 err = mark_chain_precision(env, regno);
8153                 if (err)
8154                         return err;
8155                 break;
8156         case ARG_PTR_TO_INT:
8157         case ARG_PTR_TO_LONG:
8158         {
8159                 int size = int_ptr_type_to_size(arg_type);
8160
8161                 err = check_helper_mem_access(env, regno, size, false, meta);
8162                 if (err)
8163                         return err;
8164                 err = check_ptr_alignment(env, reg, 0, size, true);
8165                 break;
8166         }
8167         case ARG_PTR_TO_CONST_STR:
8168         {
8169                 struct bpf_map *map = reg->map_ptr;
8170                 int map_off;
8171                 u64 map_addr;
8172                 char *str_ptr;
8173
8174                 if (!bpf_map_is_rdonly(map)) {
8175                         verbose(env, "R%d does not point to a readonly map'\n", regno);
8176                         return -EACCES;
8177                 }
8178
8179                 if (!tnum_is_const(reg->var_off)) {
8180                         verbose(env, "R%d is not a constant address'\n", regno);
8181                         return -EACCES;
8182                 }
8183
8184                 if (!map->ops->map_direct_value_addr) {
8185                         verbose(env, "no direct value access support for this map type\n");
8186                         return -EACCES;
8187                 }
8188
8189                 err = check_map_access(env, regno, reg->off,
8190                                        map->value_size - reg->off, false,
8191                                        ACCESS_HELPER);
8192                 if (err)
8193                         return err;
8194
8195                 map_off = reg->off + reg->var_off.value;
8196                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8197                 if (err) {
8198                         verbose(env, "direct value access on string failed\n");
8199                         return err;
8200                 }
8201
8202                 str_ptr = (char *)(long)(map_addr);
8203                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8204                         verbose(env, "string is not zero-terminated\n");
8205                         return -EINVAL;
8206                 }
8207                 break;
8208         }
8209         case ARG_PTR_TO_KPTR:
8210                 err = process_kptr_func(env, regno, meta);
8211                 if (err)
8212                         return err;
8213                 break;
8214         }
8215
8216         return err;
8217 }
8218
8219 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8220 {
8221         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8222         enum bpf_prog_type type = resolve_prog_type(env->prog);
8223
8224         if (func_id != BPF_FUNC_map_update_elem)
8225                 return false;
8226
8227         /* It's not possible to get access to a locked struct sock in these
8228          * contexts, so updating is safe.
8229          */
8230         switch (type) {
8231         case BPF_PROG_TYPE_TRACING:
8232                 if (eatype == BPF_TRACE_ITER)
8233                         return true;
8234                 break;
8235         case BPF_PROG_TYPE_SOCKET_FILTER:
8236         case BPF_PROG_TYPE_SCHED_CLS:
8237         case BPF_PROG_TYPE_SCHED_ACT:
8238         case BPF_PROG_TYPE_XDP:
8239         case BPF_PROG_TYPE_SK_REUSEPORT:
8240         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8241         case BPF_PROG_TYPE_SK_LOOKUP:
8242                 return true;
8243         default:
8244                 break;
8245         }
8246
8247         verbose(env, "cannot update sockmap in this context\n");
8248         return false;
8249 }
8250
8251 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8252 {
8253         return env->prog->jit_requested &&
8254                bpf_jit_supports_subprog_tailcalls();
8255 }
8256
8257 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8258                                         struct bpf_map *map, int func_id)
8259 {
8260         if (!map)
8261                 return 0;
8262
8263         /* We need a two way check, first is from map perspective ... */
8264         switch (map->map_type) {
8265         case BPF_MAP_TYPE_PROG_ARRAY:
8266                 if (func_id != BPF_FUNC_tail_call)
8267                         goto error;
8268                 break;
8269         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8270                 if (func_id != BPF_FUNC_perf_event_read &&
8271                     func_id != BPF_FUNC_perf_event_output &&
8272                     func_id != BPF_FUNC_skb_output &&
8273                     func_id != BPF_FUNC_perf_event_read_value &&
8274                     func_id != BPF_FUNC_xdp_output)
8275                         goto error;
8276                 break;
8277         case BPF_MAP_TYPE_RINGBUF:
8278                 if (func_id != BPF_FUNC_ringbuf_output &&
8279                     func_id != BPF_FUNC_ringbuf_reserve &&
8280                     func_id != BPF_FUNC_ringbuf_query &&
8281                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8282                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8283                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8284                         goto error;
8285                 break;
8286         case BPF_MAP_TYPE_USER_RINGBUF:
8287                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8288                         goto error;
8289                 break;
8290         case BPF_MAP_TYPE_STACK_TRACE:
8291                 if (func_id != BPF_FUNC_get_stackid)
8292                         goto error;
8293                 break;
8294         case BPF_MAP_TYPE_CGROUP_ARRAY:
8295                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8296                     func_id != BPF_FUNC_current_task_under_cgroup)
8297                         goto error;
8298                 break;
8299         case BPF_MAP_TYPE_CGROUP_STORAGE:
8300         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8301                 if (func_id != BPF_FUNC_get_local_storage)
8302                         goto error;
8303                 break;
8304         case BPF_MAP_TYPE_DEVMAP:
8305         case BPF_MAP_TYPE_DEVMAP_HASH:
8306                 if (func_id != BPF_FUNC_redirect_map &&
8307                     func_id != BPF_FUNC_map_lookup_elem)
8308                         goto error;
8309                 break;
8310         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8311          * appear.
8312          */
8313         case BPF_MAP_TYPE_CPUMAP:
8314                 if (func_id != BPF_FUNC_redirect_map)
8315                         goto error;
8316                 break;
8317         case BPF_MAP_TYPE_XSKMAP:
8318                 if (func_id != BPF_FUNC_redirect_map &&
8319                     func_id != BPF_FUNC_map_lookup_elem)
8320                         goto error;
8321                 break;
8322         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8323         case BPF_MAP_TYPE_HASH_OF_MAPS:
8324                 if (func_id != BPF_FUNC_map_lookup_elem)
8325                         goto error;
8326                 break;
8327         case BPF_MAP_TYPE_SOCKMAP:
8328                 if (func_id != BPF_FUNC_sk_redirect_map &&
8329                     func_id != BPF_FUNC_sock_map_update &&
8330                     func_id != BPF_FUNC_map_delete_elem &&
8331                     func_id != BPF_FUNC_msg_redirect_map &&
8332                     func_id != BPF_FUNC_sk_select_reuseport &&
8333                     func_id != BPF_FUNC_map_lookup_elem &&
8334                     !may_update_sockmap(env, func_id))
8335                         goto error;
8336                 break;
8337         case BPF_MAP_TYPE_SOCKHASH:
8338                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8339                     func_id != BPF_FUNC_sock_hash_update &&
8340                     func_id != BPF_FUNC_map_delete_elem &&
8341                     func_id != BPF_FUNC_msg_redirect_hash &&
8342                     func_id != BPF_FUNC_sk_select_reuseport &&
8343                     func_id != BPF_FUNC_map_lookup_elem &&
8344                     !may_update_sockmap(env, func_id))
8345                         goto error;
8346                 break;
8347         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8348                 if (func_id != BPF_FUNC_sk_select_reuseport)
8349                         goto error;
8350                 break;
8351         case BPF_MAP_TYPE_QUEUE:
8352         case BPF_MAP_TYPE_STACK:
8353                 if (func_id != BPF_FUNC_map_peek_elem &&
8354                     func_id != BPF_FUNC_map_pop_elem &&
8355                     func_id != BPF_FUNC_map_push_elem)
8356                         goto error;
8357                 break;
8358         case BPF_MAP_TYPE_SK_STORAGE:
8359                 if (func_id != BPF_FUNC_sk_storage_get &&
8360                     func_id != BPF_FUNC_sk_storage_delete &&
8361                     func_id != BPF_FUNC_kptr_xchg)
8362                         goto error;
8363                 break;
8364         case BPF_MAP_TYPE_INODE_STORAGE:
8365                 if (func_id != BPF_FUNC_inode_storage_get &&
8366                     func_id != BPF_FUNC_inode_storage_delete &&
8367                     func_id != BPF_FUNC_kptr_xchg)
8368                         goto error;
8369                 break;
8370         case BPF_MAP_TYPE_TASK_STORAGE:
8371                 if (func_id != BPF_FUNC_task_storage_get &&
8372                     func_id != BPF_FUNC_task_storage_delete &&
8373                     func_id != BPF_FUNC_kptr_xchg)
8374                         goto error;
8375                 break;
8376         case BPF_MAP_TYPE_CGRP_STORAGE:
8377                 if (func_id != BPF_FUNC_cgrp_storage_get &&
8378                     func_id != BPF_FUNC_cgrp_storage_delete &&
8379                     func_id != BPF_FUNC_kptr_xchg)
8380                         goto error;
8381                 break;
8382         case BPF_MAP_TYPE_BLOOM_FILTER:
8383                 if (func_id != BPF_FUNC_map_peek_elem &&
8384                     func_id != BPF_FUNC_map_push_elem)
8385                         goto error;
8386                 break;
8387         default:
8388                 break;
8389         }
8390
8391         /* ... and second from the function itself. */
8392         switch (func_id) {
8393         case BPF_FUNC_tail_call:
8394                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8395                         goto error;
8396                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8397                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8398                         return -EINVAL;
8399                 }
8400                 break;
8401         case BPF_FUNC_perf_event_read:
8402         case BPF_FUNC_perf_event_output:
8403         case BPF_FUNC_perf_event_read_value:
8404         case BPF_FUNC_skb_output:
8405         case BPF_FUNC_xdp_output:
8406                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8407                         goto error;
8408                 break;
8409         case BPF_FUNC_ringbuf_output:
8410         case BPF_FUNC_ringbuf_reserve:
8411         case BPF_FUNC_ringbuf_query:
8412         case BPF_FUNC_ringbuf_reserve_dynptr:
8413         case BPF_FUNC_ringbuf_submit_dynptr:
8414         case BPF_FUNC_ringbuf_discard_dynptr:
8415                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8416                         goto error;
8417                 break;
8418         case BPF_FUNC_user_ringbuf_drain:
8419                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8420                         goto error;
8421                 break;
8422         case BPF_FUNC_get_stackid:
8423                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8424                         goto error;
8425                 break;
8426         case BPF_FUNC_current_task_under_cgroup:
8427         case BPF_FUNC_skb_under_cgroup:
8428                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8429                         goto error;
8430                 break;
8431         case BPF_FUNC_redirect_map:
8432                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8433                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8434                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
8435                     map->map_type != BPF_MAP_TYPE_XSKMAP)
8436                         goto error;
8437                 break;
8438         case BPF_FUNC_sk_redirect_map:
8439         case BPF_FUNC_msg_redirect_map:
8440         case BPF_FUNC_sock_map_update:
8441                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8442                         goto error;
8443                 break;
8444         case BPF_FUNC_sk_redirect_hash:
8445         case BPF_FUNC_msg_redirect_hash:
8446         case BPF_FUNC_sock_hash_update:
8447                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8448                         goto error;
8449                 break;
8450         case BPF_FUNC_get_local_storage:
8451                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8452                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8453                         goto error;
8454                 break;
8455         case BPF_FUNC_sk_select_reuseport:
8456                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8457                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8458                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
8459                         goto error;
8460                 break;
8461         case BPF_FUNC_map_pop_elem:
8462                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8463                     map->map_type != BPF_MAP_TYPE_STACK)
8464                         goto error;
8465                 break;
8466         case BPF_FUNC_map_peek_elem:
8467         case BPF_FUNC_map_push_elem:
8468                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8469                     map->map_type != BPF_MAP_TYPE_STACK &&
8470                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8471                         goto error;
8472                 break;
8473         case BPF_FUNC_map_lookup_percpu_elem:
8474                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8475                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8476                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8477                         goto error;
8478                 break;
8479         case BPF_FUNC_sk_storage_get:
8480         case BPF_FUNC_sk_storage_delete:
8481                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8482                         goto error;
8483                 break;
8484         case BPF_FUNC_inode_storage_get:
8485         case BPF_FUNC_inode_storage_delete:
8486                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8487                         goto error;
8488                 break;
8489         case BPF_FUNC_task_storage_get:
8490         case BPF_FUNC_task_storage_delete:
8491                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8492                         goto error;
8493                 break;
8494         case BPF_FUNC_cgrp_storage_get:
8495         case BPF_FUNC_cgrp_storage_delete:
8496                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8497                         goto error;
8498                 break;
8499         default:
8500                 break;
8501         }
8502
8503         return 0;
8504 error:
8505         verbose(env, "cannot pass map_type %d into func %s#%d\n",
8506                 map->map_type, func_id_name(func_id), func_id);
8507         return -EINVAL;
8508 }
8509
8510 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8511 {
8512         int count = 0;
8513
8514         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8515                 count++;
8516         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8517                 count++;
8518         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8519                 count++;
8520         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8521                 count++;
8522         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8523                 count++;
8524
8525         /* We only support one arg being in raw mode at the moment,
8526          * which is sufficient for the helper functions we have
8527          * right now.
8528          */
8529         return count <= 1;
8530 }
8531
8532 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8533 {
8534         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8535         bool has_size = fn->arg_size[arg] != 0;
8536         bool is_next_size = false;
8537
8538         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8539                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8540
8541         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8542                 return is_next_size;
8543
8544         return has_size == is_next_size || is_next_size == is_fixed;
8545 }
8546
8547 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8548 {
8549         /* bpf_xxx(..., buf, len) call will access 'len'
8550          * bytes from memory 'buf'. Both arg types need
8551          * to be paired, so make sure there's no buggy
8552          * helper function specification.
8553          */
8554         if (arg_type_is_mem_size(fn->arg1_type) ||
8555             check_args_pair_invalid(fn, 0) ||
8556             check_args_pair_invalid(fn, 1) ||
8557             check_args_pair_invalid(fn, 2) ||
8558             check_args_pair_invalid(fn, 3) ||
8559             check_args_pair_invalid(fn, 4))
8560                 return false;
8561
8562         return true;
8563 }
8564
8565 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8566 {
8567         int i;
8568
8569         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8570                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8571                         return !!fn->arg_btf_id[i];
8572                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8573                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
8574                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8575                     /* arg_btf_id and arg_size are in a union. */
8576                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8577                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8578                         return false;
8579         }
8580
8581         return true;
8582 }
8583
8584 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8585 {
8586         return check_raw_mode_ok(fn) &&
8587                check_arg_pair_ok(fn) &&
8588                check_btf_id_ok(fn) ? 0 : -EINVAL;
8589 }
8590
8591 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8592  * are now invalid, so turn them into unknown SCALAR_VALUE.
8593  *
8594  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8595  * since these slices point to packet data.
8596  */
8597 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8598 {
8599         struct bpf_func_state *state;
8600         struct bpf_reg_state *reg;
8601
8602         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8603                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8604                         mark_reg_invalid(env, reg);
8605         }));
8606 }
8607
8608 enum {
8609         AT_PKT_END = -1,
8610         BEYOND_PKT_END = -2,
8611 };
8612
8613 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8614 {
8615         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8616         struct bpf_reg_state *reg = &state->regs[regn];
8617
8618         if (reg->type != PTR_TO_PACKET)
8619                 /* PTR_TO_PACKET_META is not supported yet */
8620                 return;
8621
8622         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8623          * How far beyond pkt_end it goes is unknown.
8624          * if (!range_open) it's the case of pkt >= pkt_end
8625          * if (range_open) it's the case of pkt > pkt_end
8626          * hence this pointer is at least 1 byte bigger than pkt_end
8627          */
8628         if (range_open)
8629                 reg->range = BEYOND_PKT_END;
8630         else
8631                 reg->range = AT_PKT_END;
8632 }
8633
8634 /* The pointer with the specified id has released its reference to kernel
8635  * resources. Identify all copies of the same pointer and clear the reference.
8636  */
8637 static int release_reference(struct bpf_verifier_env *env,
8638                              int ref_obj_id)
8639 {
8640         struct bpf_func_state *state;
8641         struct bpf_reg_state *reg;
8642         int err;
8643
8644         err = release_reference_state(cur_func(env), ref_obj_id);
8645         if (err)
8646                 return err;
8647
8648         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8649                 if (reg->ref_obj_id == ref_obj_id)
8650                         mark_reg_invalid(env, reg);
8651         }));
8652
8653         return 0;
8654 }
8655
8656 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8657 {
8658         struct bpf_func_state *unused;
8659         struct bpf_reg_state *reg;
8660
8661         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8662                 if (type_is_non_owning_ref(reg->type))
8663                         mark_reg_invalid(env, reg);
8664         }));
8665 }
8666
8667 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8668                                     struct bpf_reg_state *regs)
8669 {
8670         int i;
8671
8672         /* after the call registers r0 - r5 were scratched */
8673         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8674                 mark_reg_not_init(env, regs, caller_saved[i]);
8675                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8676         }
8677 }
8678
8679 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8680                                    struct bpf_func_state *caller,
8681                                    struct bpf_func_state *callee,
8682                                    int insn_idx);
8683
8684 static int set_callee_state(struct bpf_verifier_env *env,
8685                             struct bpf_func_state *caller,
8686                             struct bpf_func_state *callee, int insn_idx);
8687
8688 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8689                              int *insn_idx, int subprog,
8690                              set_callee_state_fn set_callee_state_cb)
8691 {
8692         struct bpf_verifier_state *state = env->cur_state;
8693         struct bpf_func_state *caller, *callee;
8694         int err;
8695
8696         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8697                 verbose(env, "the call stack of %d frames is too deep\n",
8698                         state->curframe + 2);
8699                 return -E2BIG;
8700         }
8701
8702         caller = state->frame[state->curframe];
8703         if (state->frame[state->curframe + 1]) {
8704                 verbose(env, "verifier bug. Frame %d already allocated\n",
8705                         state->curframe + 1);
8706                 return -EFAULT;
8707         }
8708
8709         err = btf_check_subprog_call(env, subprog, caller->regs);
8710         if (err == -EFAULT)
8711                 return err;
8712         if (subprog_is_global(env, subprog)) {
8713                 if (err) {
8714                         verbose(env, "Caller passes invalid args into func#%d\n",
8715                                 subprog);
8716                         return err;
8717                 } else {
8718                         if (env->log.level & BPF_LOG_LEVEL)
8719                                 verbose(env,
8720                                         "Func#%d is global and valid. Skipping.\n",
8721                                         subprog);
8722                         clear_caller_saved_regs(env, caller->regs);
8723
8724                         /* All global functions return a 64-bit SCALAR_VALUE */
8725                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
8726                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8727
8728                         /* continue with next insn after call */
8729                         return 0;
8730                 }
8731         }
8732
8733         /* set_callee_state is used for direct subprog calls, but we are
8734          * interested in validating only BPF helpers that can call subprogs as
8735          * callbacks
8736          */
8737         if (set_callee_state_cb != set_callee_state) {
8738                 if (bpf_pseudo_kfunc_call(insn) &&
8739                     !is_callback_calling_kfunc(insn->imm)) {
8740                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8741                                 func_id_name(insn->imm), insn->imm);
8742                         return -EFAULT;
8743                 } else if (!bpf_pseudo_kfunc_call(insn) &&
8744                            !is_callback_calling_function(insn->imm)) { /* helper */
8745                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8746                                 func_id_name(insn->imm), insn->imm);
8747                         return -EFAULT;
8748                 }
8749         }
8750
8751         if (insn->code == (BPF_JMP | BPF_CALL) &&
8752             insn->src_reg == 0 &&
8753             insn->imm == BPF_FUNC_timer_set_callback) {
8754                 struct bpf_verifier_state *async_cb;
8755
8756                 /* there is no real recursion here. timer callbacks are async */
8757                 env->subprog_info[subprog].is_async_cb = true;
8758                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8759                                          *insn_idx, subprog);
8760                 if (!async_cb)
8761                         return -EFAULT;
8762                 callee = async_cb->frame[0];
8763                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8764
8765                 /* Convert bpf_timer_set_callback() args into timer callback args */
8766                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8767                 if (err)
8768                         return err;
8769
8770                 clear_caller_saved_regs(env, caller->regs);
8771                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8772                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8773                 /* continue with next insn after call */
8774                 return 0;
8775         }
8776
8777         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8778         if (!callee)
8779                 return -ENOMEM;
8780         state->frame[state->curframe + 1] = callee;
8781
8782         /* callee cannot access r0, r6 - r9 for reading and has to write
8783          * into its own stack before reading from it.
8784          * callee can read/write into caller's stack
8785          */
8786         init_func_state(env, callee,
8787                         /* remember the callsite, it will be used by bpf_exit */
8788                         *insn_idx /* callsite */,
8789                         state->curframe + 1 /* frameno within this callchain */,
8790                         subprog /* subprog number within this prog */);
8791
8792         /* Transfer references to the callee */
8793         err = copy_reference_state(callee, caller);
8794         if (err)
8795                 goto err_out;
8796
8797         err = set_callee_state_cb(env, caller, callee, *insn_idx);
8798         if (err)
8799                 goto err_out;
8800
8801         clear_caller_saved_regs(env, caller->regs);
8802
8803         /* only increment it after check_reg_arg() finished */
8804         state->curframe++;
8805
8806         /* and go analyze first insn of the callee */
8807         *insn_idx = env->subprog_info[subprog].start - 1;
8808
8809         if (env->log.level & BPF_LOG_LEVEL) {
8810                 verbose(env, "caller:\n");
8811                 print_verifier_state(env, caller, true);
8812                 verbose(env, "callee:\n");
8813                 print_verifier_state(env, callee, true);
8814         }
8815         return 0;
8816
8817 err_out:
8818         free_func_state(callee);
8819         state->frame[state->curframe + 1] = NULL;
8820         return err;
8821 }
8822
8823 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8824                                    struct bpf_func_state *caller,
8825                                    struct bpf_func_state *callee)
8826 {
8827         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8828          *      void *callback_ctx, u64 flags);
8829          * callback_fn(struct bpf_map *map, void *key, void *value,
8830          *      void *callback_ctx);
8831          */
8832         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8833
8834         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8835         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8836         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8837
8838         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8839         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8840         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8841
8842         /* pointer to stack or null */
8843         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8844
8845         /* unused */
8846         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8847         return 0;
8848 }
8849
8850 static int set_callee_state(struct bpf_verifier_env *env,
8851                             struct bpf_func_state *caller,
8852                             struct bpf_func_state *callee, int insn_idx)
8853 {
8854         int i;
8855
8856         /* copy r1 - r5 args that callee can access.  The copy includes parent
8857          * pointers, which connects us up to the liveness chain
8858          */
8859         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8860                 callee->regs[i] = caller->regs[i];
8861         return 0;
8862 }
8863
8864 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8865                            int *insn_idx)
8866 {
8867         int subprog, target_insn;
8868
8869         target_insn = *insn_idx + insn->imm + 1;
8870         subprog = find_subprog(env, target_insn);
8871         if (subprog < 0) {
8872                 verbose(env, "verifier bug. No program starts at insn %d\n",
8873                         target_insn);
8874                 return -EFAULT;
8875         }
8876
8877         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8878 }
8879
8880 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8881                                        struct bpf_func_state *caller,
8882                                        struct bpf_func_state *callee,
8883                                        int insn_idx)
8884 {
8885         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8886         struct bpf_map *map;
8887         int err;
8888
8889         if (bpf_map_ptr_poisoned(insn_aux)) {
8890                 verbose(env, "tail_call abusing map_ptr\n");
8891                 return -EINVAL;
8892         }
8893
8894         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8895         if (!map->ops->map_set_for_each_callback_args ||
8896             !map->ops->map_for_each_callback) {
8897                 verbose(env, "callback function not allowed for map\n");
8898                 return -ENOTSUPP;
8899         }
8900
8901         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8902         if (err)
8903                 return err;
8904
8905         callee->in_callback_fn = true;
8906         callee->callback_ret_range = tnum_range(0, 1);
8907         return 0;
8908 }
8909
8910 static int set_loop_callback_state(struct bpf_verifier_env *env,
8911                                    struct bpf_func_state *caller,
8912                                    struct bpf_func_state *callee,
8913                                    int insn_idx)
8914 {
8915         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8916          *          u64 flags);
8917          * callback_fn(u32 index, void *callback_ctx);
8918          */
8919         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8920         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8921
8922         /* unused */
8923         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8924         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8925         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8926
8927         callee->in_callback_fn = true;
8928         callee->callback_ret_range = tnum_range(0, 1);
8929         return 0;
8930 }
8931
8932 static int set_timer_callback_state(struct bpf_verifier_env *env,
8933                                     struct bpf_func_state *caller,
8934                                     struct bpf_func_state *callee,
8935                                     int insn_idx)
8936 {
8937         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8938
8939         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8940          * callback_fn(struct bpf_map *map, void *key, void *value);
8941          */
8942         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8943         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8944         callee->regs[BPF_REG_1].map_ptr = map_ptr;
8945
8946         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8947         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8948         callee->regs[BPF_REG_2].map_ptr = map_ptr;
8949
8950         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8951         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8952         callee->regs[BPF_REG_3].map_ptr = map_ptr;
8953
8954         /* unused */
8955         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8956         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8957         callee->in_async_callback_fn = true;
8958         callee->callback_ret_range = tnum_range(0, 1);
8959         return 0;
8960 }
8961
8962 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8963                                        struct bpf_func_state *caller,
8964                                        struct bpf_func_state *callee,
8965                                        int insn_idx)
8966 {
8967         /* bpf_find_vma(struct task_struct *task, u64 addr,
8968          *               void *callback_fn, void *callback_ctx, u64 flags)
8969          * (callback_fn)(struct task_struct *task,
8970          *               struct vm_area_struct *vma, void *callback_ctx);
8971          */
8972         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8973
8974         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8975         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8976         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8977         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8978
8979         /* pointer to stack or null */
8980         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8981
8982         /* unused */
8983         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8984         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8985         callee->in_callback_fn = true;
8986         callee->callback_ret_range = tnum_range(0, 1);
8987         return 0;
8988 }
8989
8990 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8991                                            struct bpf_func_state *caller,
8992                                            struct bpf_func_state *callee,
8993                                            int insn_idx)
8994 {
8995         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8996          *                        callback_ctx, u64 flags);
8997          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8998          */
8999         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9000         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9001         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9002
9003         /* unused */
9004         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9005         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9006         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9007
9008         callee->in_callback_fn = true;
9009         callee->callback_ret_range = tnum_range(0, 1);
9010         return 0;
9011 }
9012
9013 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9014                                          struct bpf_func_state *caller,
9015                                          struct bpf_func_state *callee,
9016                                          int insn_idx)
9017 {
9018         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9019          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9020          *
9021          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9022          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9023          * by this point, so look at 'root'
9024          */
9025         struct btf_field *field;
9026
9027         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9028                                       BPF_RB_ROOT);
9029         if (!field || !field->graph_root.value_btf_id)
9030                 return -EFAULT;
9031
9032         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9033         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9034         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9035         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9036
9037         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9038         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9039         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9040         callee->in_callback_fn = true;
9041         callee->callback_ret_range = tnum_range(0, 1);
9042         return 0;
9043 }
9044
9045 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9046
9047 /* Are we currently verifying the callback for a rbtree helper that must
9048  * be called with lock held? If so, no need to complain about unreleased
9049  * lock
9050  */
9051 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9052 {
9053         struct bpf_verifier_state *state = env->cur_state;
9054         struct bpf_insn *insn = env->prog->insnsi;
9055         struct bpf_func_state *callee;
9056         int kfunc_btf_id;
9057
9058         if (!state->curframe)
9059                 return false;
9060
9061         callee = state->frame[state->curframe];
9062
9063         if (!callee->in_callback_fn)
9064                 return false;
9065
9066         kfunc_btf_id = insn[callee->callsite].imm;
9067         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9068 }
9069
9070 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9071 {
9072         struct bpf_verifier_state *state = env->cur_state;
9073         struct bpf_func_state *caller, *callee;
9074         struct bpf_reg_state *r0;
9075         int err;
9076
9077         callee = state->frame[state->curframe];
9078         r0 = &callee->regs[BPF_REG_0];
9079         if (r0->type == PTR_TO_STACK) {
9080                 /* technically it's ok to return caller's stack pointer
9081                  * (or caller's caller's pointer) back to the caller,
9082                  * since these pointers are valid. Only current stack
9083                  * pointer will be invalid as soon as function exits,
9084                  * but let's be conservative
9085                  */
9086                 verbose(env, "cannot return stack pointer to the caller\n");
9087                 return -EINVAL;
9088         }
9089
9090         caller = state->frame[state->curframe - 1];
9091         if (callee->in_callback_fn) {
9092                 /* enforce R0 return value range [0, 1]. */
9093                 struct tnum range = callee->callback_ret_range;
9094
9095                 if (r0->type != SCALAR_VALUE) {
9096                         verbose(env, "R0 not a scalar value\n");
9097                         return -EACCES;
9098                 }
9099                 if (!tnum_in(range, r0->var_off)) {
9100                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9101                         return -EINVAL;
9102                 }
9103         } else {
9104                 /* return to the caller whatever r0 had in the callee */
9105                 caller->regs[BPF_REG_0] = *r0;
9106         }
9107
9108         /* callback_fn frame should have released its own additions to parent's
9109          * reference state at this point, or check_reference_leak would
9110          * complain, hence it must be the same as the caller. There is no need
9111          * to copy it back.
9112          */
9113         if (!callee->in_callback_fn) {
9114                 /* Transfer references to the caller */
9115                 err = copy_reference_state(caller, callee);
9116                 if (err)
9117                         return err;
9118         }
9119
9120         *insn_idx = callee->callsite + 1;
9121         if (env->log.level & BPF_LOG_LEVEL) {
9122                 verbose(env, "returning from callee:\n");
9123                 print_verifier_state(env, callee, true);
9124                 verbose(env, "to caller at %d:\n", *insn_idx);
9125                 print_verifier_state(env, caller, true);
9126         }
9127         /* clear everything in the callee */
9128         free_func_state(callee);
9129         state->frame[state->curframe--] = NULL;
9130         return 0;
9131 }
9132
9133 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9134                                    int func_id,
9135                                    struct bpf_call_arg_meta *meta)
9136 {
9137         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9138
9139         if (ret_type != RET_INTEGER)
9140                 return;
9141
9142         switch (func_id) {
9143         case BPF_FUNC_get_stack:
9144         case BPF_FUNC_get_task_stack:
9145         case BPF_FUNC_probe_read_str:
9146         case BPF_FUNC_probe_read_kernel_str:
9147         case BPF_FUNC_probe_read_user_str:
9148                 ret_reg->smax_value = meta->msize_max_value;
9149                 ret_reg->s32_max_value = meta->msize_max_value;
9150                 ret_reg->smin_value = -MAX_ERRNO;
9151                 ret_reg->s32_min_value = -MAX_ERRNO;
9152                 reg_bounds_sync(ret_reg);
9153                 break;
9154         case BPF_FUNC_get_smp_processor_id:
9155                 ret_reg->umax_value = nr_cpu_ids - 1;
9156                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9157                 ret_reg->smax_value = nr_cpu_ids - 1;
9158                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9159                 ret_reg->umin_value = 0;
9160                 ret_reg->u32_min_value = 0;
9161                 ret_reg->smin_value = 0;
9162                 ret_reg->s32_min_value = 0;
9163                 reg_bounds_sync(ret_reg);
9164                 break;
9165         }
9166 }
9167
9168 static int
9169 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9170                 int func_id, int insn_idx)
9171 {
9172         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9173         struct bpf_map *map = meta->map_ptr;
9174
9175         if (func_id != BPF_FUNC_tail_call &&
9176             func_id != BPF_FUNC_map_lookup_elem &&
9177             func_id != BPF_FUNC_map_update_elem &&
9178             func_id != BPF_FUNC_map_delete_elem &&
9179             func_id != BPF_FUNC_map_push_elem &&
9180             func_id != BPF_FUNC_map_pop_elem &&
9181             func_id != BPF_FUNC_map_peek_elem &&
9182             func_id != BPF_FUNC_for_each_map_elem &&
9183             func_id != BPF_FUNC_redirect_map &&
9184             func_id != BPF_FUNC_map_lookup_percpu_elem)
9185                 return 0;
9186
9187         if (map == NULL) {
9188                 verbose(env, "kernel subsystem misconfigured verifier\n");
9189                 return -EINVAL;
9190         }
9191
9192         /* In case of read-only, some additional restrictions
9193          * need to be applied in order to prevent altering the
9194          * state of the map from program side.
9195          */
9196         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9197             (func_id == BPF_FUNC_map_delete_elem ||
9198              func_id == BPF_FUNC_map_update_elem ||
9199              func_id == BPF_FUNC_map_push_elem ||
9200              func_id == BPF_FUNC_map_pop_elem)) {
9201                 verbose(env, "write into map forbidden\n");
9202                 return -EACCES;
9203         }
9204
9205         if (!BPF_MAP_PTR(aux->map_ptr_state))
9206                 bpf_map_ptr_store(aux, meta->map_ptr,
9207                                   !meta->map_ptr->bypass_spec_v1);
9208         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9209                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9210                                   !meta->map_ptr->bypass_spec_v1);
9211         return 0;
9212 }
9213
9214 static int
9215 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9216                 int func_id, int insn_idx)
9217 {
9218         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9219         struct bpf_reg_state *regs = cur_regs(env), *reg;
9220         struct bpf_map *map = meta->map_ptr;
9221         u64 val, max;
9222         int err;
9223
9224         if (func_id != BPF_FUNC_tail_call)
9225                 return 0;
9226         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9227                 verbose(env, "kernel subsystem misconfigured verifier\n");
9228                 return -EINVAL;
9229         }
9230
9231         reg = &regs[BPF_REG_3];
9232         val = reg->var_off.value;
9233         max = map->max_entries;
9234
9235         if (!(register_is_const(reg) && val < max)) {
9236                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9237                 return 0;
9238         }
9239
9240         err = mark_chain_precision(env, BPF_REG_3);
9241         if (err)
9242                 return err;
9243         if (bpf_map_key_unseen(aux))
9244                 bpf_map_key_store(aux, val);
9245         else if (!bpf_map_key_poisoned(aux) &&
9246                   bpf_map_key_immediate(aux) != val)
9247                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9248         return 0;
9249 }
9250
9251 static int check_reference_leak(struct bpf_verifier_env *env)
9252 {
9253         struct bpf_func_state *state = cur_func(env);
9254         bool refs_lingering = false;
9255         int i;
9256
9257         if (state->frameno && !state->in_callback_fn)
9258                 return 0;
9259
9260         for (i = 0; i < state->acquired_refs; i++) {
9261                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9262                         continue;
9263                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9264                         state->refs[i].id, state->refs[i].insn_idx);
9265                 refs_lingering = true;
9266         }
9267         return refs_lingering ? -EINVAL : 0;
9268 }
9269
9270 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9271                                    struct bpf_reg_state *regs)
9272 {
9273         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9274         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9275         struct bpf_map *fmt_map = fmt_reg->map_ptr;
9276         struct bpf_bprintf_data data = {};
9277         int err, fmt_map_off, num_args;
9278         u64 fmt_addr;
9279         char *fmt;
9280
9281         /* data must be an array of u64 */
9282         if (data_len_reg->var_off.value % 8)
9283                 return -EINVAL;
9284         num_args = data_len_reg->var_off.value / 8;
9285
9286         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9287          * and map_direct_value_addr is set.
9288          */
9289         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9290         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9291                                                   fmt_map_off);
9292         if (err) {
9293                 verbose(env, "verifier bug\n");
9294                 return -EFAULT;
9295         }
9296         fmt = (char *)(long)fmt_addr + fmt_map_off;
9297
9298         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9299          * can focus on validating the format specifiers.
9300          */
9301         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9302         if (err < 0)
9303                 verbose(env, "Invalid format string\n");
9304
9305         return err;
9306 }
9307
9308 static int check_get_func_ip(struct bpf_verifier_env *env)
9309 {
9310         enum bpf_prog_type type = resolve_prog_type(env->prog);
9311         int func_id = BPF_FUNC_get_func_ip;
9312
9313         if (type == BPF_PROG_TYPE_TRACING) {
9314                 if (!bpf_prog_has_trampoline(env->prog)) {
9315                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9316                                 func_id_name(func_id), func_id);
9317                         return -ENOTSUPP;
9318                 }
9319                 return 0;
9320         } else if (type == BPF_PROG_TYPE_KPROBE) {
9321                 return 0;
9322         }
9323
9324         verbose(env, "func %s#%d not supported for program type %d\n",
9325                 func_id_name(func_id), func_id, type);
9326         return -ENOTSUPP;
9327 }
9328
9329 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9330 {
9331         return &env->insn_aux_data[env->insn_idx];
9332 }
9333
9334 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9335 {
9336         struct bpf_reg_state *regs = cur_regs(env);
9337         struct bpf_reg_state *reg = &regs[BPF_REG_4];
9338         bool reg_is_null = register_is_null(reg);
9339
9340         if (reg_is_null)
9341                 mark_chain_precision(env, BPF_REG_4);
9342
9343         return reg_is_null;
9344 }
9345
9346 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9347 {
9348         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9349
9350         if (!state->initialized) {
9351                 state->initialized = 1;
9352                 state->fit_for_inline = loop_flag_is_zero(env);
9353                 state->callback_subprogno = subprogno;
9354                 return;
9355         }
9356
9357         if (!state->fit_for_inline)
9358                 return;
9359
9360         state->fit_for_inline = (loop_flag_is_zero(env) &&
9361                                  state->callback_subprogno == subprogno);
9362 }
9363
9364 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9365                              int *insn_idx_p)
9366 {
9367         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9368         const struct bpf_func_proto *fn = NULL;
9369         enum bpf_return_type ret_type;
9370         enum bpf_type_flag ret_flag;
9371         struct bpf_reg_state *regs;
9372         struct bpf_call_arg_meta meta;
9373         int insn_idx = *insn_idx_p;
9374         bool changes_data;
9375         int i, err, func_id;
9376
9377         /* find function prototype */
9378         func_id = insn->imm;
9379         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9380                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9381                         func_id);
9382                 return -EINVAL;
9383         }
9384
9385         if (env->ops->get_func_proto)
9386                 fn = env->ops->get_func_proto(func_id, env->prog);
9387         if (!fn) {
9388                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9389                         func_id);
9390                 return -EINVAL;
9391         }
9392
9393         /* eBPF programs must be GPL compatible to use GPL-ed functions */
9394         if (!env->prog->gpl_compatible && fn->gpl_only) {
9395                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9396                 return -EINVAL;
9397         }
9398
9399         if (fn->allowed && !fn->allowed(env->prog)) {
9400                 verbose(env, "helper call is not allowed in probe\n");
9401                 return -EINVAL;
9402         }
9403
9404         if (!env->prog->aux->sleepable && fn->might_sleep) {
9405                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9406                 return -EINVAL;
9407         }
9408
9409         /* With LD_ABS/IND some JITs save/restore skb from r1. */
9410         changes_data = bpf_helper_changes_pkt_data(fn->func);
9411         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9412                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9413                         func_id_name(func_id), func_id);
9414                 return -EINVAL;
9415         }
9416
9417         memset(&meta, 0, sizeof(meta));
9418         meta.pkt_access = fn->pkt_access;
9419
9420         err = check_func_proto(fn, func_id);
9421         if (err) {
9422                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9423                         func_id_name(func_id), func_id);
9424                 return err;
9425         }
9426
9427         if (env->cur_state->active_rcu_lock) {
9428                 if (fn->might_sleep) {
9429                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9430                                 func_id_name(func_id), func_id);
9431                         return -EINVAL;
9432                 }
9433
9434                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9435                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9436         }
9437
9438         meta.func_id = func_id;
9439         /* check args */
9440         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9441                 err = check_func_arg(env, i, &meta, fn, insn_idx);
9442                 if (err)
9443                         return err;
9444         }
9445
9446         err = record_func_map(env, &meta, func_id, insn_idx);
9447         if (err)
9448                 return err;
9449
9450         err = record_func_key(env, &meta, func_id, insn_idx);
9451         if (err)
9452                 return err;
9453
9454         /* Mark slots with STACK_MISC in case of raw mode, stack offset
9455          * is inferred from register state.
9456          */
9457         for (i = 0; i < meta.access_size; i++) {
9458                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9459                                        BPF_WRITE, -1, false);
9460                 if (err)
9461                         return err;
9462         }
9463
9464         regs = cur_regs(env);
9465
9466         if (meta.release_regno) {
9467                 err = -EINVAL;
9468                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9469                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9470                  * is safe to do directly.
9471                  */
9472                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9473                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9474                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9475                                 return -EFAULT;
9476                         }
9477                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9478                 } else if (meta.ref_obj_id) {
9479                         err = release_reference(env, meta.ref_obj_id);
9480                 } else if (register_is_null(&regs[meta.release_regno])) {
9481                         /* meta.ref_obj_id can only be 0 if register that is meant to be
9482                          * released is NULL, which must be > R0.
9483                          */
9484                         err = 0;
9485                 }
9486                 if (err) {
9487                         verbose(env, "func %s#%d reference has not been acquired before\n",
9488                                 func_id_name(func_id), func_id);
9489                         return err;
9490                 }
9491         }
9492
9493         switch (func_id) {
9494         case BPF_FUNC_tail_call:
9495                 err = check_reference_leak(env);
9496                 if (err) {
9497                         verbose(env, "tail_call would lead to reference leak\n");
9498                         return err;
9499                 }
9500                 break;
9501         case BPF_FUNC_get_local_storage:
9502                 /* check that flags argument in get_local_storage(map, flags) is 0,
9503                  * this is required because get_local_storage() can't return an error.
9504                  */
9505                 if (!register_is_null(&regs[BPF_REG_2])) {
9506                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9507                         return -EINVAL;
9508                 }
9509                 break;
9510         case BPF_FUNC_for_each_map_elem:
9511                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9512                                         set_map_elem_callback_state);
9513                 break;
9514         case BPF_FUNC_timer_set_callback:
9515                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9516                                         set_timer_callback_state);
9517                 break;
9518         case BPF_FUNC_find_vma:
9519                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9520                                         set_find_vma_callback_state);
9521                 break;
9522         case BPF_FUNC_snprintf:
9523                 err = check_bpf_snprintf_call(env, regs);
9524                 break;
9525         case BPF_FUNC_loop:
9526                 update_loop_inline_state(env, meta.subprogno);
9527                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9528                                         set_loop_callback_state);
9529                 break;
9530         case BPF_FUNC_dynptr_from_mem:
9531                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9532                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9533                                 reg_type_str(env, regs[BPF_REG_1].type));
9534                         return -EACCES;
9535                 }
9536                 break;
9537         case BPF_FUNC_set_retval:
9538                 if (prog_type == BPF_PROG_TYPE_LSM &&
9539                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9540                         if (!env->prog->aux->attach_func_proto->type) {
9541                                 /* Make sure programs that attach to void
9542                                  * hooks don't try to modify return value.
9543                                  */
9544                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9545                                 return -EINVAL;
9546                         }
9547                 }
9548                 break;
9549         case BPF_FUNC_dynptr_data:
9550         {
9551                 struct bpf_reg_state *reg;
9552                 int id, ref_obj_id;
9553
9554                 reg = get_dynptr_arg_reg(env, fn, regs);
9555                 if (!reg)
9556                         return -EFAULT;
9557
9558
9559                 if (meta.dynptr_id) {
9560                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9561                         return -EFAULT;
9562                 }
9563                 if (meta.ref_obj_id) {
9564                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9565                         return -EFAULT;
9566                 }
9567
9568                 id = dynptr_id(env, reg);
9569                 if (id < 0) {
9570                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9571                         return id;
9572                 }
9573
9574                 ref_obj_id = dynptr_ref_obj_id(env, reg);
9575                 if (ref_obj_id < 0) {
9576                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9577                         return ref_obj_id;
9578                 }
9579
9580                 meta.dynptr_id = id;
9581                 meta.ref_obj_id = ref_obj_id;
9582
9583                 break;
9584         }
9585         case BPF_FUNC_dynptr_write:
9586         {
9587                 enum bpf_dynptr_type dynptr_type;
9588                 struct bpf_reg_state *reg;
9589
9590                 reg = get_dynptr_arg_reg(env, fn, regs);
9591                 if (!reg)
9592                         return -EFAULT;
9593
9594                 dynptr_type = dynptr_get_type(env, reg);
9595                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9596                         return -EFAULT;
9597
9598                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9599                         /* this will trigger clear_all_pkt_pointers(), which will
9600                          * invalidate all dynptr slices associated with the skb
9601                          */
9602                         changes_data = true;
9603
9604                 break;
9605         }
9606         case BPF_FUNC_user_ringbuf_drain:
9607                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9608                                         set_user_ringbuf_callback_state);
9609                 break;
9610         }
9611
9612         if (err)
9613                 return err;
9614
9615         /* reset caller saved regs */
9616         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9617                 mark_reg_not_init(env, regs, caller_saved[i]);
9618                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9619         }
9620
9621         /* helper call returns 64-bit value. */
9622         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9623
9624         /* update return register (already marked as written above) */
9625         ret_type = fn->ret_type;
9626         ret_flag = type_flag(ret_type);
9627
9628         switch (base_type(ret_type)) {
9629         case RET_INTEGER:
9630                 /* sets type to SCALAR_VALUE */
9631                 mark_reg_unknown(env, regs, BPF_REG_0);
9632                 break;
9633         case RET_VOID:
9634                 regs[BPF_REG_0].type = NOT_INIT;
9635                 break;
9636         case RET_PTR_TO_MAP_VALUE:
9637                 /* There is no offset yet applied, variable or fixed */
9638                 mark_reg_known_zero(env, regs, BPF_REG_0);
9639                 /* remember map_ptr, so that check_map_access()
9640                  * can check 'value_size' boundary of memory access
9641                  * to map element returned from bpf_map_lookup_elem()
9642                  */
9643                 if (meta.map_ptr == NULL) {
9644                         verbose(env,
9645                                 "kernel subsystem misconfigured verifier\n");
9646                         return -EINVAL;
9647                 }
9648                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9649                 regs[BPF_REG_0].map_uid = meta.map_uid;
9650                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9651                 if (!type_may_be_null(ret_type) &&
9652                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9653                         regs[BPF_REG_0].id = ++env->id_gen;
9654                 }
9655                 break;
9656         case RET_PTR_TO_SOCKET:
9657                 mark_reg_known_zero(env, regs, BPF_REG_0);
9658                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9659                 break;
9660         case RET_PTR_TO_SOCK_COMMON:
9661                 mark_reg_known_zero(env, regs, BPF_REG_0);
9662                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9663                 break;
9664         case RET_PTR_TO_TCP_SOCK:
9665                 mark_reg_known_zero(env, regs, BPF_REG_0);
9666                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9667                 break;
9668         case RET_PTR_TO_MEM:
9669                 mark_reg_known_zero(env, regs, BPF_REG_0);
9670                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9671                 regs[BPF_REG_0].mem_size = meta.mem_size;
9672                 break;
9673         case RET_PTR_TO_MEM_OR_BTF_ID:
9674         {
9675                 const struct btf_type *t;
9676
9677                 mark_reg_known_zero(env, regs, BPF_REG_0);
9678                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9679                 if (!btf_type_is_struct(t)) {
9680                         u32 tsize;
9681                         const struct btf_type *ret;
9682                         const char *tname;
9683
9684                         /* resolve the type size of ksym. */
9685                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9686                         if (IS_ERR(ret)) {
9687                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9688                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9689                                         tname, PTR_ERR(ret));
9690                                 return -EINVAL;
9691                         }
9692                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9693                         regs[BPF_REG_0].mem_size = tsize;
9694                 } else {
9695                         /* MEM_RDONLY may be carried from ret_flag, but it
9696                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9697                          * it will confuse the check of PTR_TO_BTF_ID in
9698                          * check_mem_access().
9699                          */
9700                         ret_flag &= ~MEM_RDONLY;
9701
9702                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9703                         regs[BPF_REG_0].btf = meta.ret_btf;
9704                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9705                 }
9706                 break;
9707         }
9708         case RET_PTR_TO_BTF_ID:
9709         {
9710                 struct btf *ret_btf;
9711                 int ret_btf_id;
9712
9713                 mark_reg_known_zero(env, regs, BPF_REG_0);
9714                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9715                 if (func_id == BPF_FUNC_kptr_xchg) {
9716                         ret_btf = meta.kptr_field->kptr.btf;
9717                         ret_btf_id = meta.kptr_field->kptr.btf_id;
9718                         if (!btf_is_kernel(ret_btf))
9719                                 regs[BPF_REG_0].type |= MEM_ALLOC;
9720                 } else {
9721                         if (fn->ret_btf_id == BPF_PTR_POISON) {
9722                                 verbose(env, "verifier internal error:");
9723                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9724                                         func_id_name(func_id));
9725                                 return -EINVAL;
9726                         }
9727                         ret_btf = btf_vmlinux;
9728                         ret_btf_id = *fn->ret_btf_id;
9729                 }
9730                 if (ret_btf_id == 0) {
9731                         verbose(env, "invalid return type %u of func %s#%d\n",
9732                                 base_type(ret_type), func_id_name(func_id),
9733                                 func_id);
9734                         return -EINVAL;
9735                 }
9736                 regs[BPF_REG_0].btf = ret_btf;
9737                 regs[BPF_REG_0].btf_id = ret_btf_id;
9738                 break;
9739         }
9740         default:
9741                 verbose(env, "unknown return type %u of func %s#%d\n",
9742                         base_type(ret_type), func_id_name(func_id), func_id);
9743                 return -EINVAL;
9744         }
9745
9746         if (type_may_be_null(regs[BPF_REG_0].type))
9747                 regs[BPF_REG_0].id = ++env->id_gen;
9748
9749         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9750                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9751                         func_id_name(func_id), func_id);
9752                 return -EFAULT;
9753         }
9754
9755         if (is_dynptr_ref_function(func_id))
9756                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9757
9758         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9759                 /* For release_reference() */
9760                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9761         } else if (is_acquire_function(func_id, meta.map_ptr)) {
9762                 int id = acquire_reference_state(env, insn_idx);
9763
9764                 if (id < 0)
9765                         return id;
9766                 /* For mark_ptr_or_null_reg() */
9767                 regs[BPF_REG_0].id = id;
9768                 /* For release_reference() */
9769                 regs[BPF_REG_0].ref_obj_id = id;
9770         }
9771
9772         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9773
9774         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9775         if (err)
9776                 return err;
9777
9778         if ((func_id == BPF_FUNC_get_stack ||
9779              func_id == BPF_FUNC_get_task_stack) &&
9780             !env->prog->has_callchain_buf) {
9781                 const char *err_str;
9782
9783 #ifdef CONFIG_PERF_EVENTS
9784                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9785                 err_str = "cannot get callchain buffer for func %s#%d\n";
9786 #else
9787                 err = -ENOTSUPP;
9788                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9789 #endif
9790                 if (err) {
9791                         verbose(env, err_str, func_id_name(func_id), func_id);
9792                         return err;
9793                 }
9794
9795                 env->prog->has_callchain_buf = true;
9796         }
9797
9798         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9799                 env->prog->call_get_stack = true;
9800
9801         if (func_id == BPF_FUNC_get_func_ip) {
9802                 if (check_get_func_ip(env))
9803                         return -ENOTSUPP;
9804                 env->prog->call_get_func_ip = true;
9805         }
9806
9807         if (changes_data)
9808                 clear_all_pkt_pointers(env);
9809         return 0;
9810 }
9811
9812 /* mark_btf_func_reg_size() is used when the reg size is determined by
9813  * the BTF func_proto's return value size and argument.
9814  */
9815 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9816                                    size_t reg_size)
9817 {
9818         struct bpf_reg_state *reg = &cur_regs(env)[regno];
9819
9820         if (regno == BPF_REG_0) {
9821                 /* Function return value */
9822                 reg->live |= REG_LIVE_WRITTEN;
9823                 reg->subreg_def = reg_size == sizeof(u64) ?
9824                         DEF_NOT_SUBREG : env->insn_idx + 1;
9825         } else {
9826                 /* Function argument */
9827                 if (reg_size == sizeof(u64)) {
9828                         mark_insn_zext(env, reg);
9829                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9830                 } else {
9831                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9832                 }
9833         }
9834 }
9835
9836 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9837 {
9838         return meta->kfunc_flags & KF_ACQUIRE;
9839 }
9840
9841 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9842 {
9843         return meta->kfunc_flags & KF_RELEASE;
9844 }
9845
9846 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9847 {
9848         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9849 }
9850
9851 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9852 {
9853         return meta->kfunc_flags & KF_SLEEPABLE;
9854 }
9855
9856 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9857 {
9858         return meta->kfunc_flags & KF_DESTRUCTIVE;
9859 }
9860
9861 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9862 {
9863         return meta->kfunc_flags & KF_RCU;
9864 }
9865
9866 static bool __kfunc_param_match_suffix(const struct btf *btf,
9867                                        const struct btf_param *arg,
9868                                        const char *suffix)
9869 {
9870         int suffix_len = strlen(suffix), len;
9871         const char *param_name;
9872
9873         /* In the future, this can be ported to use BTF tagging */
9874         param_name = btf_name_by_offset(btf, arg->name_off);
9875         if (str_is_empty(param_name))
9876                 return false;
9877         len = strlen(param_name);
9878         if (len < suffix_len)
9879                 return false;
9880         param_name += len - suffix_len;
9881         return !strncmp(param_name, suffix, suffix_len);
9882 }
9883
9884 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9885                                   const struct btf_param *arg,
9886                                   const struct bpf_reg_state *reg)
9887 {
9888         const struct btf_type *t;
9889
9890         t = btf_type_skip_modifiers(btf, arg->type, NULL);
9891         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9892                 return false;
9893
9894         return __kfunc_param_match_suffix(btf, arg, "__sz");
9895 }
9896
9897 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9898                                         const struct btf_param *arg,
9899                                         const struct bpf_reg_state *reg)
9900 {
9901         const struct btf_type *t;
9902
9903         t = btf_type_skip_modifiers(btf, arg->type, NULL);
9904         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9905                 return false;
9906
9907         return __kfunc_param_match_suffix(btf, arg, "__szk");
9908 }
9909
9910 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9911 {
9912         return __kfunc_param_match_suffix(btf, arg, "__opt");
9913 }
9914
9915 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9916 {
9917         return __kfunc_param_match_suffix(btf, arg, "__k");
9918 }
9919
9920 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9921 {
9922         return __kfunc_param_match_suffix(btf, arg, "__ign");
9923 }
9924
9925 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9926 {
9927         return __kfunc_param_match_suffix(btf, arg, "__alloc");
9928 }
9929
9930 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9931 {
9932         return __kfunc_param_match_suffix(btf, arg, "__uninit");
9933 }
9934
9935 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9936 {
9937         return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9938 }
9939
9940 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9941                                           const struct btf_param *arg,
9942                                           const char *name)
9943 {
9944         int len, target_len = strlen(name);
9945         const char *param_name;
9946
9947         param_name = btf_name_by_offset(btf, arg->name_off);
9948         if (str_is_empty(param_name))
9949                 return false;
9950         len = strlen(param_name);
9951         if (len != target_len)
9952                 return false;
9953         if (strcmp(param_name, name))
9954                 return false;
9955
9956         return true;
9957 }
9958
9959 enum {
9960         KF_ARG_DYNPTR_ID,
9961         KF_ARG_LIST_HEAD_ID,
9962         KF_ARG_LIST_NODE_ID,
9963         KF_ARG_RB_ROOT_ID,
9964         KF_ARG_RB_NODE_ID,
9965 };
9966
9967 BTF_ID_LIST(kf_arg_btf_ids)
9968 BTF_ID(struct, bpf_dynptr_kern)
9969 BTF_ID(struct, bpf_list_head)
9970 BTF_ID(struct, bpf_list_node)
9971 BTF_ID(struct, bpf_rb_root)
9972 BTF_ID(struct, bpf_rb_node)
9973
9974 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9975                                     const struct btf_param *arg, int type)
9976 {
9977         const struct btf_type *t;
9978         u32 res_id;
9979
9980         t = btf_type_skip_modifiers(btf, arg->type, NULL);
9981         if (!t)
9982                 return false;
9983         if (!btf_type_is_ptr(t))
9984                 return false;
9985         t = btf_type_skip_modifiers(btf, t->type, &res_id);
9986         if (!t)
9987                 return false;
9988         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9989 }
9990
9991 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9992 {
9993         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9994 }
9995
9996 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9997 {
9998         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9999 }
10000
10001 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10002 {
10003         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10004 }
10005
10006 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10007 {
10008         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10009 }
10010
10011 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10012 {
10013         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10014 }
10015
10016 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10017                                   const struct btf_param *arg)
10018 {
10019         const struct btf_type *t;
10020
10021         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10022         if (!t)
10023                 return false;
10024
10025         return true;
10026 }
10027
10028 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10029 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10030                                         const struct btf *btf,
10031                                         const struct btf_type *t, int rec)
10032 {
10033         const struct btf_type *member_type;
10034         const struct btf_member *member;
10035         u32 i;
10036
10037         if (!btf_type_is_struct(t))
10038                 return false;
10039
10040         for_each_member(i, t, member) {
10041                 const struct btf_array *array;
10042
10043                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10044                 if (btf_type_is_struct(member_type)) {
10045                         if (rec >= 3) {
10046                                 verbose(env, "max struct nesting depth exceeded\n");
10047                                 return false;
10048                         }
10049                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10050                                 return false;
10051                         continue;
10052                 }
10053                 if (btf_type_is_array(member_type)) {
10054                         array = btf_array(member_type);
10055                         if (!array->nelems)
10056                                 return false;
10057                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10058                         if (!btf_type_is_scalar(member_type))
10059                                 return false;
10060                         continue;
10061                 }
10062                 if (!btf_type_is_scalar(member_type))
10063                         return false;
10064         }
10065         return true;
10066 }
10067
10068 enum kfunc_ptr_arg_type {
10069         KF_ARG_PTR_TO_CTX,
10070         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10071         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10072         KF_ARG_PTR_TO_DYNPTR,
10073         KF_ARG_PTR_TO_ITER,
10074         KF_ARG_PTR_TO_LIST_HEAD,
10075         KF_ARG_PTR_TO_LIST_NODE,
10076         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10077         KF_ARG_PTR_TO_MEM,
10078         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10079         KF_ARG_PTR_TO_CALLBACK,
10080         KF_ARG_PTR_TO_RB_ROOT,
10081         KF_ARG_PTR_TO_RB_NODE,
10082 };
10083
10084 enum special_kfunc_type {
10085         KF_bpf_obj_new_impl,
10086         KF_bpf_obj_drop_impl,
10087         KF_bpf_refcount_acquire_impl,
10088         KF_bpf_list_push_front_impl,
10089         KF_bpf_list_push_back_impl,
10090         KF_bpf_list_pop_front,
10091         KF_bpf_list_pop_back,
10092         KF_bpf_cast_to_kern_ctx,
10093         KF_bpf_rdonly_cast,
10094         KF_bpf_rcu_read_lock,
10095         KF_bpf_rcu_read_unlock,
10096         KF_bpf_rbtree_remove,
10097         KF_bpf_rbtree_add_impl,
10098         KF_bpf_rbtree_first,
10099         KF_bpf_dynptr_from_skb,
10100         KF_bpf_dynptr_from_xdp,
10101         KF_bpf_dynptr_slice,
10102         KF_bpf_dynptr_slice_rdwr,
10103         KF_bpf_dynptr_clone,
10104 };
10105
10106 BTF_SET_START(special_kfunc_set)
10107 BTF_ID(func, bpf_obj_new_impl)
10108 BTF_ID(func, bpf_obj_drop_impl)
10109 BTF_ID(func, bpf_refcount_acquire_impl)
10110 BTF_ID(func, bpf_list_push_front_impl)
10111 BTF_ID(func, bpf_list_push_back_impl)
10112 BTF_ID(func, bpf_list_pop_front)
10113 BTF_ID(func, bpf_list_pop_back)
10114 BTF_ID(func, bpf_cast_to_kern_ctx)
10115 BTF_ID(func, bpf_rdonly_cast)
10116 BTF_ID(func, bpf_rbtree_remove)
10117 BTF_ID(func, bpf_rbtree_add_impl)
10118 BTF_ID(func, bpf_rbtree_first)
10119 BTF_ID(func, bpf_dynptr_from_skb)
10120 BTF_ID(func, bpf_dynptr_from_xdp)
10121 BTF_ID(func, bpf_dynptr_slice)
10122 BTF_ID(func, bpf_dynptr_slice_rdwr)
10123 BTF_ID(func, bpf_dynptr_clone)
10124 BTF_SET_END(special_kfunc_set)
10125
10126 BTF_ID_LIST(special_kfunc_list)
10127 BTF_ID(func, bpf_obj_new_impl)
10128 BTF_ID(func, bpf_obj_drop_impl)
10129 BTF_ID(func, bpf_refcount_acquire_impl)
10130 BTF_ID(func, bpf_list_push_front_impl)
10131 BTF_ID(func, bpf_list_push_back_impl)
10132 BTF_ID(func, bpf_list_pop_front)
10133 BTF_ID(func, bpf_list_pop_back)
10134 BTF_ID(func, bpf_cast_to_kern_ctx)
10135 BTF_ID(func, bpf_rdonly_cast)
10136 BTF_ID(func, bpf_rcu_read_lock)
10137 BTF_ID(func, bpf_rcu_read_unlock)
10138 BTF_ID(func, bpf_rbtree_remove)
10139 BTF_ID(func, bpf_rbtree_add_impl)
10140 BTF_ID(func, bpf_rbtree_first)
10141 BTF_ID(func, bpf_dynptr_from_skb)
10142 BTF_ID(func, bpf_dynptr_from_xdp)
10143 BTF_ID(func, bpf_dynptr_slice)
10144 BTF_ID(func, bpf_dynptr_slice_rdwr)
10145 BTF_ID(func, bpf_dynptr_clone)
10146
10147 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10148 {
10149         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10150             meta->arg_owning_ref) {
10151                 return false;
10152         }
10153
10154         return meta->kfunc_flags & KF_RET_NULL;
10155 }
10156
10157 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10158 {
10159         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10160 }
10161
10162 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10163 {
10164         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10165 }
10166
10167 static enum kfunc_ptr_arg_type
10168 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10169                        struct bpf_kfunc_call_arg_meta *meta,
10170                        const struct btf_type *t, const struct btf_type *ref_t,
10171                        const char *ref_tname, const struct btf_param *args,
10172                        int argno, int nargs)
10173 {
10174         u32 regno = argno + 1;
10175         struct bpf_reg_state *regs = cur_regs(env);
10176         struct bpf_reg_state *reg = &regs[regno];
10177         bool arg_mem_size = false;
10178
10179         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10180                 return KF_ARG_PTR_TO_CTX;
10181
10182         /* In this function, we verify the kfunc's BTF as per the argument type,
10183          * leaving the rest of the verification with respect to the register
10184          * type to our caller. When a set of conditions hold in the BTF type of
10185          * arguments, we resolve it to a known kfunc_ptr_arg_type.
10186          */
10187         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10188                 return KF_ARG_PTR_TO_CTX;
10189
10190         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10191                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10192
10193         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10194                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10195
10196         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10197                 return KF_ARG_PTR_TO_DYNPTR;
10198
10199         if (is_kfunc_arg_iter(meta, argno))
10200                 return KF_ARG_PTR_TO_ITER;
10201
10202         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10203                 return KF_ARG_PTR_TO_LIST_HEAD;
10204
10205         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10206                 return KF_ARG_PTR_TO_LIST_NODE;
10207
10208         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10209                 return KF_ARG_PTR_TO_RB_ROOT;
10210
10211         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10212                 return KF_ARG_PTR_TO_RB_NODE;
10213
10214         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10215                 if (!btf_type_is_struct(ref_t)) {
10216                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10217                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10218                         return -EINVAL;
10219                 }
10220                 return KF_ARG_PTR_TO_BTF_ID;
10221         }
10222
10223         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10224                 return KF_ARG_PTR_TO_CALLBACK;
10225
10226
10227         if (argno + 1 < nargs &&
10228             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10229              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10230                 arg_mem_size = true;
10231
10232         /* This is the catch all argument type of register types supported by
10233          * check_helper_mem_access. However, we only allow when argument type is
10234          * pointer to scalar, or struct composed (recursively) of scalars. When
10235          * arg_mem_size is true, the pointer can be void *.
10236          */
10237         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10238             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10239                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10240                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10241                 return -EINVAL;
10242         }
10243         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10244 }
10245
10246 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10247                                         struct bpf_reg_state *reg,
10248                                         const struct btf_type *ref_t,
10249                                         const char *ref_tname, u32 ref_id,
10250                                         struct bpf_kfunc_call_arg_meta *meta,
10251                                         int argno)
10252 {
10253         const struct btf_type *reg_ref_t;
10254         bool strict_type_match = false;
10255         const struct btf *reg_btf;
10256         const char *reg_ref_tname;
10257         u32 reg_ref_id;
10258
10259         if (base_type(reg->type) == PTR_TO_BTF_ID) {
10260                 reg_btf = reg->btf;
10261                 reg_ref_id = reg->btf_id;
10262         } else {
10263                 reg_btf = btf_vmlinux;
10264                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10265         }
10266
10267         /* Enforce strict type matching for calls to kfuncs that are acquiring
10268          * or releasing a reference, or are no-cast aliases. We do _not_
10269          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10270          * as we want to enable BPF programs to pass types that are bitwise
10271          * equivalent without forcing them to explicitly cast with something
10272          * like bpf_cast_to_kern_ctx().
10273          *
10274          * For example, say we had a type like the following:
10275          *
10276          * struct bpf_cpumask {
10277          *      cpumask_t cpumask;
10278          *      refcount_t usage;
10279          * };
10280          *
10281          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10282          * to a struct cpumask, so it would be safe to pass a struct
10283          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10284          *
10285          * The philosophy here is similar to how we allow scalars of different
10286          * types to be passed to kfuncs as long as the size is the same. The
10287          * only difference here is that we're simply allowing
10288          * btf_struct_ids_match() to walk the struct at the 0th offset, and
10289          * resolve types.
10290          */
10291         if (is_kfunc_acquire(meta) ||
10292             (is_kfunc_release(meta) && reg->ref_obj_id) ||
10293             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10294                 strict_type_match = true;
10295
10296         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10297
10298         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10299         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10300         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10301                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10302                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10303                         btf_type_str(reg_ref_t), reg_ref_tname);
10304                 return -EINVAL;
10305         }
10306         return 0;
10307 }
10308
10309 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10310 {
10311         struct bpf_verifier_state *state = env->cur_state;
10312
10313         if (!state->active_lock.ptr) {
10314                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10315                 return -EFAULT;
10316         }
10317
10318         if (type_flag(reg->type) & NON_OWN_REF) {
10319                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10320                 return -EFAULT;
10321         }
10322
10323         reg->type |= NON_OWN_REF;
10324         return 0;
10325 }
10326
10327 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10328 {
10329         struct bpf_func_state *state, *unused;
10330         struct bpf_reg_state *reg;
10331         int i;
10332
10333         state = cur_func(env);
10334
10335         if (!ref_obj_id) {
10336                 verbose(env, "verifier internal error: ref_obj_id is zero for "
10337                              "owning -> non-owning conversion\n");
10338                 return -EFAULT;
10339         }
10340
10341         for (i = 0; i < state->acquired_refs; i++) {
10342                 if (state->refs[i].id != ref_obj_id)
10343                         continue;
10344
10345                 /* Clear ref_obj_id here so release_reference doesn't clobber
10346                  * the whole reg
10347                  */
10348                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10349                         if (reg->ref_obj_id == ref_obj_id) {
10350                                 reg->ref_obj_id = 0;
10351                                 ref_set_non_owning(env, reg);
10352                         }
10353                 }));
10354                 return 0;
10355         }
10356
10357         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10358         return -EFAULT;
10359 }
10360
10361 /* Implementation details:
10362  *
10363  * Each register points to some region of memory, which we define as an
10364  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10365  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10366  * allocation. The lock and the data it protects are colocated in the same
10367  * memory region.
10368  *
10369  * Hence, everytime a register holds a pointer value pointing to such
10370  * allocation, the verifier preserves a unique reg->id for it.
10371  *
10372  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10373  * bpf_spin_lock is called.
10374  *
10375  * To enable this, lock state in the verifier captures two values:
10376  *      active_lock.ptr = Register's type specific pointer
10377  *      active_lock.id  = A unique ID for each register pointer value
10378  *
10379  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10380  * supported register types.
10381  *
10382  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10383  * allocated objects is the reg->btf pointer.
10384  *
10385  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10386  * can establish the provenance of the map value statically for each distinct
10387  * lookup into such maps. They always contain a single map value hence unique
10388  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10389  *
10390  * So, in case of global variables, they use array maps with max_entries = 1,
10391  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10392  * into the same map value as max_entries is 1, as described above).
10393  *
10394  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10395  * outer map pointer (in verifier context), but each lookup into an inner map
10396  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10397  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10398  * will get different reg->id assigned to each lookup, hence different
10399  * active_lock.id.
10400  *
10401  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10402  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10403  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10404  */
10405 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10406 {
10407         void *ptr;
10408         u32 id;
10409
10410         switch ((int)reg->type) {
10411         case PTR_TO_MAP_VALUE:
10412                 ptr = reg->map_ptr;
10413                 break;
10414         case PTR_TO_BTF_ID | MEM_ALLOC:
10415                 ptr = reg->btf;
10416                 break;
10417         default:
10418                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10419                 return -EFAULT;
10420         }
10421         id = reg->id;
10422
10423         if (!env->cur_state->active_lock.ptr)
10424                 return -EINVAL;
10425         if (env->cur_state->active_lock.ptr != ptr ||
10426             env->cur_state->active_lock.id != id) {
10427                 verbose(env, "held lock and object are not in the same allocation\n");
10428                 return -EINVAL;
10429         }
10430         return 0;
10431 }
10432
10433 static bool is_bpf_list_api_kfunc(u32 btf_id)
10434 {
10435         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10436                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10437                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10438                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10439 }
10440
10441 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10442 {
10443         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10444                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10445                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10446 }
10447
10448 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10449 {
10450         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10451                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10452 }
10453
10454 static bool is_callback_calling_kfunc(u32 btf_id)
10455 {
10456         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10457 }
10458
10459 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10460 {
10461         return is_bpf_rbtree_api_kfunc(btf_id);
10462 }
10463
10464 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10465                                           enum btf_field_type head_field_type,
10466                                           u32 kfunc_btf_id)
10467 {
10468         bool ret;
10469
10470         switch (head_field_type) {
10471         case BPF_LIST_HEAD:
10472                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10473                 break;
10474         case BPF_RB_ROOT:
10475                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10476                 break;
10477         default:
10478                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10479                         btf_field_type_name(head_field_type));
10480                 return false;
10481         }
10482
10483         if (!ret)
10484                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10485                         btf_field_type_name(head_field_type));
10486         return ret;
10487 }
10488
10489 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10490                                           enum btf_field_type node_field_type,
10491                                           u32 kfunc_btf_id)
10492 {
10493         bool ret;
10494
10495         switch (node_field_type) {
10496         case BPF_LIST_NODE:
10497                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10498                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10499                 break;
10500         case BPF_RB_NODE:
10501                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10502                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10503                 break;
10504         default:
10505                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10506                         btf_field_type_name(node_field_type));
10507                 return false;
10508         }
10509
10510         if (!ret)
10511                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10512                         btf_field_type_name(node_field_type));
10513         return ret;
10514 }
10515
10516 static int
10517 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10518                                    struct bpf_reg_state *reg, u32 regno,
10519                                    struct bpf_kfunc_call_arg_meta *meta,
10520                                    enum btf_field_type head_field_type,
10521                                    struct btf_field **head_field)
10522 {
10523         const char *head_type_name;
10524         struct btf_field *field;
10525         struct btf_record *rec;
10526         u32 head_off;
10527
10528         if (meta->btf != btf_vmlinux) {
10529                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10530                 return -EFAULT;
10531         }
10532
10533         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10534                 return -EFAULT;
10535
10536         head_type_name = btf_field_type_name(head_field_type);
10537         if (!tnum_is_const(reg->var_off)) {
10538                 verbose(env,
10539                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10540                         regno, head_type_name);
10541                 return -EINVAL;
10542         }
10543
10544         rec = reg_btf_record(reg);
10545         head_off = reg->off + reg->var_off.value;
10546         field = btf_record_find(rec, head_off, head_field_type);
10547         if (!field) {
10548                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10549                 return -EINVAL;
10550         }
10551
10552         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10553         if (check_reg_allocation_locked(env, reg)) {
10554                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10555                         rec->spin_lock_off, head_type_name);
10556                 return -EINVAL;
10557         }
10558
10559         if (*head_field) {
10560                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10561                 return -EFAULT;
10562         }
10563         *head_field = field;
10564         return 0;
10565 }
10566
10567 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10568                                            struct bpf_reg_state *reg, u32 regno,
10569                                            struct bpf_kfunc_call_arg_meta *meta)
10570 {
10571         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10572                                                           &meta->arg_list_head.field);
10573 }
10574
10575 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10576                                              struct bpf_reg_state *reg, u32 regno,
10577                                              struct bpf_kfunc_call_arg_meta *meta)
10578 {
10579         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10580                                                           &meta->arg_rbtree_root.field);
10581 }
10582
10583 static int
10584 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10585                                    struct bpf_reg_state *reg, u32 regno,
10586                                    struct bpf_kfunc_call_arg_meta *meta,
10587                                    enum btf_field_type head_field_type,
10588                                    enum btf_field_type node_field_type,
10589                                    struct btf_field **node_field)
10590 {
10591         const char *node_type_name;
10592         const struct btf_type *et, *t;
10593         struct btf_field *field;
10594         u32 node_off;
10595
10596         if (meta->btf != btf_vmlinux) {
10597                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10598                 return -EFAULT;
10599         }
10600
10601         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10602                 return -EFAULT;
10603
10604         node_type_name = btf_field_type_name(node_field_type);
10605         if (!tnum_is_const(reg->var_off)) {
10606                 verbose(env,
10607                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10608                         regno, node_type_name);
10609                 return -EINVAL;
10610         }
10611
10612         node_off = reg->off + reg->var_off.value;
10613         field = reg_find_field_offset(reg, node_off, node_field_type);
10614         if (!field || field->offset != node_off) {
10615                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10616                 return -EINVAL;
10617         }
10618
10619         field = *node_field;
10620
10621         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10622         t = btf_type_by_id(reg->btf, reg->btf_id);
10623         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10624                                   field->graph_root.value_btf_id, true)) {
10625                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10626                         "in struct %s, but arg is at offset=%d in struct %s\n",
10627                         btf_field_type_name(head_field_type),
10628                         btf_field_type_name(node_field_type),
10629                         field->graph_root.node_offset,
10630                         btf_name_by_offset(field->graph_root.btf, et->name_off),
10631                         node_off, btf_name_by_offset(reg->btf, t->name_off));
10632                 return -EINVAL;
10633         }
10634         meta->arg_btf = reg->btf;
10635         meta->arg_btf_id = reg->btf_id;
10636
10637         if (node_off != field->graph_root.node_offset) {
10638                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10639                         node_off, btf_field_type_name(node_field_type),
10640                         field->graph_root.node_offset,
10641                         btf_name_by_offset(field->graph_root.btf, et->name_off));
10642                 return -EINVAL;
10643         }
10644
10645         return 0;
10646 }
10647
10648 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10649                                            struct bpf_reg_state *reg, u32 regno,
10650                                            struct bpf_kfunc_call_arg_meta *meta)
10651 {
10652         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10653                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
10654                                                   &meta->arg_list_head.field);
10655 }
10656
10657 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10658                                              struct bpf_reg_state *reg, u32 regno,
10659                                              struct bpf_kfunc_call_arg_meta *meta)
10660 {
10661         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10662                                                   BPF_RB_ROOT, BPF_RB_NODE,
10663                                                   &meta->arg_rbtree_root.field);
10664 }
10665
10666 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10667                             int insn_idx)
10668 {
10669         const char *func_name = meta->func_name, *ref_tname;
10670         const struct btf *btf = meta->btf;
10671         const struct btf_param *args;
10672         struct btf_record *rec;
10673         u32 i, nargs;
10674         int ret;
10675
10676         args = (const struct btf_param *)(meta->func_proto + 1);
10677         nargs = btf_type_vlen(meta->func_proto);
10678         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10679                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10680                         MAX_BPF_FUNC_REG_ARGS);
10681                 return -EINVAL;
10682         }
10683
10684         /* Check that BTF function arguments match actual types that the
10685          * verifier sees.
10686          */
10687         for (i = 0; i < nargs; i++) {
10688                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10689                 const struct btf_type *t, *ref_t, *resolve_ret;
10690                 enum bpf_arg_type arg_type = ARG_DONTCARE;
10691                 u32 regno = i + 1, ref_id, type_size;
10692                 bool is_ret_buf_sz = false;
10693                 int kf_arg_type;
10694
10695                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10696
10697                 if (is_kfunc_arg_ignore(btf, &args[i]))
10698                         continue;
10699
10700                 if (btf_type_is_scalar(t)) {
10701                         if (reg->type != SCALAR_VALUE) {
10702                                 verbose(env, "R%d is not a scalar\n", regno);
10703                                 return -EINVAL;
10704                         }
10705
10706                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10707                                 if (meta->arg_constant.found) {
10708                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10709                                         return -EFAULT;
10710                                 }
10711                                 if (!tnum_is_const(reg->var_off)) {
10712                                         verbose(env, "R%d must be a known constant\n", regno);
10713                                         return -EINVAL;
10714                                 }
10715                                 ret = mark_chain_precision(env, regno);
10716                                 if (ret < 0)
10717                                         return ret;
10718                                 meta->arg_constant.found = true;
10719                                 meta->arg_constant.value = reg->var_off.value;
10720                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10721                                 meta->r0_rdonly = true;
10722                                 is_ret_buf_sz = true;
10723                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10724                                 is_ret_buf_sz = true;
10725                         }
10726
10727                         if (is_ret_buf_sz) {
10728                                 if (meta->r0_size) {
10729                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10730                                         return -EINVAL;
10731                                 }
10732
10733                                 if (!tnum_is_const(reg->var_off)) {
10734                                         verbose(env, "R%d is not a const\n", regno);
10735                                         return -EINVAL;
10736                                 }
10737
10738                                 meta->r0_size = reg->var_off.value;
10739                                 ret = mark_chain_precision(env, regno);
10740                                 if (ret)
10741                                         return ret;
10742                         }
10743                         continue;
10744                 }
10745
10746                 if (!btf_type_is_ptr(t)) {
10747                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10748                         return -EINVAL;
10749                 }
10750
10751                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10752                     (register_is_null(reg) || type_may_be_null(reg->type))) {
10753                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10754                         return -EACCES;
10755                 }
10756
10757                 if (reg->ref_obj_id) {
10758                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
10759                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10760                                         regno, reg->ref_obj_id,
10761                                         meta->ref_obj_id);
10762                                 return -EFAULT;
10763                         }
10764                         meta->ref_obj_id = reg->ref_obj_id;
10765                         if (is_kfunc_release(meta))
10766                                 meta->release_regno = regno;
10767                 }
10768
10769                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10770                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10771
10772                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10773                 if (kf_arg_type < 0)
10774                         return kf_arg_type;
10775
10776                 switch (kf_arg_type) {
10777                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10778                 case KF_ARG_PTR_TO_BTF_ID:
10779                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10780                                 break;
10781
10782                         if (!is_trusted_reg(reg)) {
10783                                 if (!is_kfunc_rcu(meta)) {
10784                                         verbose(env, "R%d must be referenced or trusted\n", regno);
10785                                         return -EINVAL;
10786                                 }
10787                                 if (!is_rcu_reg(reg)) {
10788                                         verbose(env, "R%d must be a rcu pointer\n", regno);
10789                                         return -EINVAL;
10790                                 }
10791                         }
10792
10793                         fallthrough;
10794                 case KF_ARG_PTR_TO_CTX:
10795                         /* Trusted arguments have the same offset checks as release arguments */
10796                         arg_type |= OBJ_RELEASE;
10797                         break;
10798                 case KF_ARG_PTR_TO_DYNPTR:
10799                 case KF_ARG_PTR_TO_ITER:
10800                 case KF_ARG_PTR_TO_LIST_HEAD:
10801                 case KF_ARG_PTR_TO_LIST_NODE:
10802                 case KF_ARG_PTR_TO_RB_ROOT:
10803                 case KF_ARG_PTR_TO_RB_NODE:
10804                 case KF_ARG_PTR_TO_MEM:
10805                 case KF_ARG_PTR_TO_MEM_SIZE:
10806                 case KF_ARG_PTR_TO_CALLBACK:
10807                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10808                         /* Trusted by default */
10809                         break;
10810                 default:
10811                         WARN_ON_ONCE(1);
10812                         return -EFAULT;
10813                 }
10814
10815                 if (is_kfunc_release(meta) && reg->ref_obj_id)
10816                         arg_type |= OBJ_RELEASE;
10817                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10818                 if (ret < 0)
10819                         return ret;
10820
10821                 switch (kf_arg_type) {
10822                 case KF_ARG_PTR_TO_CTX:
10823                         if (reg->type != PTR_TO_CTX) {
10824                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10825                                 return -EINVAL;
10826                         }
10827
10828                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10829                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10830                                 if (ret < 0)
10831                                         return -EINVAL;
10832                                 meta->ret_btf_id  = ret;
10833                         }
10834                         break;
10835                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10836                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10837                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10838                                 return -EINVAL;
10839                         }
10840                         if (!reg->ref_obj_id) {
10841                                 verbose(env, "allocated object must be referenced\n");
10842                                 return -EINVAL;
10843                         }
10844                         if (meta->btf == btf_vmlinux &&
10845                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10846                                 meta->arg_btf = reg->btf;
10847                                 meta->arg_btf_id = reg->btf_id;
10848                         }
10849                         break;
10850                 case KF_ARG_PTR_TO_DYNPTR:
10851                 {
10852                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10853                         int clone_ref_obj_id = 0;
10854
10855                         if (reg->type != PTR_TO_STACK &&
10856                             reg->type != CONST_PTR_TO_DYNPTR) {
10857                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10858                                 return -EINVAL;
10859                         }
10860
10861                         if (reg->type == CONST_PTR_TO_DYNPTR)
10862                                 dynptr_arg_type |= MEM_RDONLY;
10863
10864                         if (is_kfunc_arg_uninit(btf, &args[i]))
10865                                 dynptr_arg_type |= MEM_UNINIT;
10866
10867                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10868                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
10869                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10870                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
10871                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10872                                    (dynptr_arg_type & MEM_UNINIT)) {
10873                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10874
10875                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10876                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10877                                         return -EFAULT;
10878                                 }
10879
10880                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10881                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10882                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10883                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10884                                         return -EFAULT;
10885                                 }
10886                         }
10887
10888                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10889                         if (ret < 0)
10890                                 return ret;
10891
10892                         if (!(dynptr_arg_type & MEM_UNINIT)) {
10893                                 int id = dynptr_id(env, reg);
10894
10895                                 if (id < 0) {
10896                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10897                                         return id;
10898                                 }
10899                                 meta->initialized_dynptr.id = id;
10900                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10901                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10902                         }
10903
10904                         break;
10905                 }
10906                 case KF_ARG_PTR_TO_ITER:
10907                         ret = process_iter_arg(env, regno, insn_idx, meta);
10908                         if (ret < 0)
10909                                 return ret;
10910                         break;
10911                 case KF_ARG_PTR_TO_LIST_HEAD:
10912                         if (reg->type != PTR_TO_MAP_VALUE &&
10913                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10914                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10915                                 return -EINVAL;
10916                         }
10917                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10918                                 verbose(env, "allocated object must be referenced\n");
10919                                 return -EINVAL;
10920                         }
10921                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10922                         if (ret < 0)
10923                                 return ret;
10924                         break;
10925                 case KF_ARG_PTR_TO_RB_ROOT:
10926                         if (reg->type != PTR_TO_MAP_VALUE &&
10927                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10928                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10929                                 return -EINVAL;
10930                         }
10931                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10932                                 verbose(env, "allocated object must be referenced\n");
10933                                 return -EINVAL;
10934                         }
10935                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10936                         if (ret < 0)
10937                                 return ret;
10938                         break;
10939                 case KF_ARG_PTR_TO_LIST_NODE:
10940                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10941                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10942                                 return -EINVAL;
10943                         }
10944                         if (!reg->ref_obj_id) {
10945                                 verbose(env, "allocated object must be referenced\n");
10946                                 return -EINVAL;
10947                         }
10948                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10949                         if (ret < 0)
10950                                 return ret;
10951                         break;
10952                 case KF_ARG_PTR_TO_RB_NODE:
10953                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10954                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10955                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
10956                                         return -EINVAL;
10957                                 }
10958                                 if (in_rbtree_lock_required_cb(env)) {
10959                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10960                                         return -EINVAL;
10961                                 }
10962                         } else {
10963                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10964                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
10965                                         return -EINVAL;
10966                                 }
10967                                 if (!reg->ref_obj_id) {
10968                                         verbose(env, "allocated object must be referenced\n");
10969                                         return -EINVAL;
10970                                 }
10971                         }
10972
10973                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10974                         if (ret < 0)
10975                                 return ret;
10976                         break;
10977                 case KF_ARG_PTR_TO_BTF_ID:
10978                         /* Only base_type is checked, further checks are done here */
10979                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10980                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10981                             !reg2btf_ids[base_type(reg->type)]) {
10982                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10983                                 verbose(env, "expected %s or socket\n",
10984                                         reg_type_str(env, base_type(reg->type) |
10985                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10986                                 return -EINVAL;
10987                         }
10988                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10989                         if (ret < 0)
10990                                 return ret;
10991                         break;
10992                 case KF_ARG_PTR_TO_MEM:
10993                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10994                         if (IS_ERR(resolve_ret)) {
10995                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10996                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10997                                 return -EINVAL;
10998                         }
10999                         ret = check_mem_reg(env, reg, regno, type_size);
11000                         if (ret < 0)
11001                                 return ret;
11002                         break;
11003                 case KF_ARG_PTR_TO_MEM_SIZE:
11004                 {
11005                         struct bpf_reg_state *buff_reg = &regs[regno];
11006                         const struct btf_param *buff_arg = &args[i];
11007                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11008                         const struct btf_param *size_arg = &args[i + 1];
11009
11010                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11011                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11012                                 if (ret < 0) {
11013                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11014                                         return ret;
11015                                 }
11016                         }
11017
11018                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11019                                 if (meta->arg_constant.found) {
11020                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11021                                         return -EFAULT;
11022                                 }
11023                                 if (!tnum_is_const(size_reg->var_off)) {
11024                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11025                                         return -EINVAL;
11026                                 }
11027                                 meta->arg_constant.found = true;
11028                                 meta->arg_constant.value = size_reg->var_off.value;
11029                         }
11030
11031                         /* Skip next '__sz' or '__szk' argument */
11032                         i++;
11033                         break;
11034                 }
11035                 case KF_ARG_PTR_TO_CALLBACK:
11036                         meta->subprogno = reg->subprogno;
11037                         break;
11038                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11039                         if (!type_is_ptr_alloc_obj(reg->type)) {
11040                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11041                                 return -EINVAL;
11042                         }
11043                         if (!type_is_non_owning_ref(reg->type))
11044                                 meta->arg_owning_ref = true;
11045
11046                         rec = reg_btf_record(reg);
11047                         if (!rec) {
11048                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11049                                 return -EFAULT;
11050                         }
11051
11052                         if (rec->refcount_off < 0) {
11053                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11054                                 return -EINVAL;
11055                         }
11056                         if (rec->refcount_off >= 0) {
11057                                 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11058                                 return -EINVAL;
11059                         }
11060                         meta->arg_btf = reg->btf;
11061                         meta->arg_btf_id = reg->btf_id;
11062                         break;
11063                 }
11064         }
11065
11066         if (is_kfunc_release(meta) && !meta->release_regno) {
11067                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11068                         func_name);
11069                 return -EINVAL;
11070         }
11071
11072         return 0;
11073 }
11074
11075 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11076                             struct bpf_insn *insn,
11077                             struct bpf_kfunc_call_arg_meta *meta,
11078                             const char **kfunc_name)
11079 {
11080         const struct btf_type *func, *func_proto;
11081         u32 func_id, *kfunc_flags;
11082         const char *func_name;
11083         struct btf *desc_btf;
11084
11085         if (kfunc_name)
11086                 *kfunc_name = NULL;
11087
11088         if (!insn->imm)
11089                 return -EINVAL;
11090
11091         desc_btf = find_kfunc_desc_btf(env, insn->off);
11092         if (IS_ERR(desc_btf))
11093                 return PTR_ERR(desc_btf);
11094
11095         func_id = insn->imm;
11096         func = btf_type_by_id(desc_btf, func_id);
11097         func_name = btf_name_by_offset(desc_btf, func->name_off);
11098         if (kfunc_name)
11099                 *kfunc_name = func_name;
11100         func_proto = btf_type_by_id(desc_btf, func->type);
11101
11102         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11103         if (!kfunc_flags) {
11104                 return -EACCES;
11105         }
11106
11107         memset(meta, 0, sizeof(*meta));
11108         meta->btf = desc_btf;
11109         meta->func_id = func_id;
11110         meta->kfunc_flags = *kfunc_flags;
11111         meta->func_proto = func_proto;
11112         meta->func_name = func_name;
11113
11114         return 0;
11115 }
11116
11117 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11118                             int *insn_idx_p)
11119 {
11120         const struct btf_type *t, *ptr_type;
11121         u32 i, nargs, ptr_type_id, release_ref_obj_id;
11122         struct bpf_reg_state *regs = cur_regs(env);
11123         const char *func_name, *ptr_type_name;
11124         bool sleepable, rcu_lock, rcu_unlock;
11125         struct bpf_kfunc_call_arg_meta meta;
11126         struct bpf_insn_aux_data *insn_aux;
11127         int err, insn_idx = *insn_idx_p;
11128         const struct btf_param *args;
11129         const struct btf_type *ret_t;
11130         struct btf *desc_btf;
11131
11132         /* skip for now, but return error when we find this in fixup_kfunc_call */
11133         if (!insn->imm)
11134                 return 0;
11135
11136         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11137         if (err == -EACCES && func_name)
11138                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11139         if (err)
11140                 return err;
11141         desc_btf = meta.btf;
11142         insn_aux = &env->insn_aux_data[insn_idx];
11143
11144         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11145
11146         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11147                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11148                 return -EACCES;
11149         }
11150
11151         sleepable = is_kfunc_sleepable(&meta);
11152         if (sleepable && !env->prog->aux->sleepable) {
11153                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11154                 return -EACCES;
11155         }
11156
11157         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11158         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11159
11160         if (env->cur_state->active_rcu_lock) {
11161                 struct bpf_func_state *state;
11162                 struct bpf_reg_state *reg;
11163
11164                 if (rcu_lock) {
11165                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11166                         return -EINVAL;
11167                 } else if (rcu_unlock) {
11168                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11169                                 if (reg->type & MEM_RCU) {
11170                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11171                                         reg->type |= PTR_UNTRUSTED;
11172                                 }
11173                         }));
11174                         env->cur_state->active_rcu_lock = false;
11175                 } else if (sleepable) {
11176                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11177                         return -EACCES;
11178                 }
11179         } else if (rcu_lock) {
11180                 env->cur_state->active_rcu_lock = true;
11181         } else if (rcu_unlock) {
11182                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11183                 return -EINVAL;
11184         }
11185
11186         /* Check the arguments */
11187         err = check_kfunc_args(env, &meta, insn_idx);
11188         if (err < 0)
11189                 return err;
11190         /* In case of release function, we get register number of refcounted
11191          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11192          */
11193         if (meta.release_regno) {
11194                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11195                 if (err) {
11196                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11197                                 func_name, meta.func_id);
11198                         return err;
11199                 }
11200         }
11201
11202         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11203             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11204             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11205                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11206                 insn_aux->insert_off = regs[BPF_REG_2].off;
11207                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11208                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11209                 if (err) {
11210                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11211                                 func_name, meta.func_id);
11212                         return err;
11213                 }
11214
11215                 err = release_reference(env, release_ref_obj_id);
11216                 if (err) {
11217                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11218                                 func_name, meta.func_id);
11219                         return err;
11220                 }
11221         }
11222
11223         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11224                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11225                                         set_rbtree_add_callback_state);
11226                 if (err) {
11227                         verbose(env, "kfunc %s#%d failed callback verification\n",
11228                                 func_name, meta.func_id);
11229                         return err;
11230                 }
11231         }
11232
11233         for (i = 0; i < CALLER_SAVED_REGS; i++)
11234                 mark_reg_not_init(env, regs, caller_saved[i]);
11235
11236         /* Check return type */
11237         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11238
11239         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11240                 /* Only exception is bpf_obj_new_impl */
11241                 if (meta.btf != btf_vmlinux ||
11242                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11243                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11244                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11245                         return -EINVAL;
11246                 }
11247         }
11248
11249         if (btf_type_is_scalar(t)) {
11250                 mark_reg_unknown(env, regs, BPF_REG_0);
11251                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11252         } else if (btf_type_is_ptr(t)) {
11253                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11254
11255                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11256                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11257                                 struct btf *ret_btf;
11258                                 u32 ret_btf_id;
11259
11260                                 if (unlikely(!bpf_global_ma_set))
11261                                         return -ENOMEM;
11262
11263                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11264                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11265                                         return -EINVAL;
11266                                 }
11267
11268                                 ret_btf = env->prog->aux->btf;
11269                                 ret_btf_id = meta.arg_constant.value;
11270
11271                                 /* This may be NULL due to user not supplying a BTF */
11272                                 if (!ret_btf) {
11273                                         verbose(env, "bpf_obj_new requires prog BTF\n");
11274                                         return -EINVAL;
11275                                 }
11276
11277                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11278                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11279                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11280                                         return -EINVAL;
11281                                 }
11282
11283                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11284                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11285                                 regs[BPF_REG_0].btf = ret_btf;
11286                                 regs[BPF_REG_0].btf_id = ret_btf_id;
11287
11288                                 insn_aux->obj_new_size = ret_t->size;
11289                                 insn_aux->kptr_struct_meta =
11290                                         btf_find_struct_meta(ret_btf, ret_btf_id);
11291                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11292                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11293                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11294                                 regs[BPF_REG_0].btf = meta.arg_btf;
11295                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11296
11297                                 insn_aux->kptr_struct_meta =
11298                                         btf_find_struct_meta(meta.arg_btf,
11299                                                              meta.arg_btf_id);
11300                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11301                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11302                                 struct btf_field *field = meta.arg_list_head.field;
11303
11304                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11305                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11306                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11307                                 struct btf_field *field = meta.arg_rbtree_root.field;
11308
11309                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11310                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11311                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11312                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11313                                 regs[BPF_REG_0].btf = desc_btf;
11314                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11315                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11316                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11317                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
11318                                         verbose(env,
11319                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11320                                         return -EINVAL;
11321                                 }
11322
11323                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11324                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11325                                 regs[BPF_REG_0].btf = desc_btf;
11326                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11327                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11328                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11329                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11330
11331                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11332
11333                                 if (!meta.arg_constant.found) {
11334                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11335                                         return -EFAULT;
11336                                 }
11337
11338                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11339
11340                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11341                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11342
11343                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11344                                         regs[BPF_REG_0].type |= MEM_RDONLY;
11345                                 } else {
11346                                         /* this will set env->seen_direct_write to true */
11347                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11348                                                 verbose(env, "the prog does not allow writes to packet data\n");
11349                                                 return -EINVAL;
11350                                         }
11351                                 }
11352
11353                                 if (!meta.initialized_dynptr.id) {
11354                                         verbose(env, "verifier internal error: no dynptr id\n");
11355                                         return -EFAULT;
11356                                 }
11357                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11358
11359                                 /* we don't need to set BPF_REG_0's ref obj id
11360                                  * because packet slices are not refcounted (see
11361                                  * dynptr_type_refcounted)
11362                                  */
11363                         } else {
11364                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
11365                                         meta.func_name);
11366                                 return -EFAULT;
11367                         }
11368                 } else if (!__btf_type_is_struct(ptr_type)) {
11369                         if (!meta.r0_size) {
11370                                 __u32 sz;
11371
11372                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11373                                         meta.r0_size = sz;
11374                                         meta.r0_rdonly = true;
11375                                 }
11376                         }
11377                         if (!meta.r0_size) {
11378                                 ptr_type_name = btf_name_by_offset(desc_btf,
11379                                                                    ptr_type->name_off);
11380                                 verbose(env,
11381                                         "kernel function %s returns pointer type %s %s is not supported\n",
11382                                         func_name,
11383                                         btf_type_str(ptr_type),
11384                                         ptr_type_name);
11385                                 return -EINVAL;
11386                         }
11387
11388                         mark_reg_known_zero(env, regs, BPF_REG_0);
11389                         regs[BPF_REG_0].type = PTR_TO_MEM;
11390                         regs[BPF_REG_0].mem_size = meta.r0_size;
11391
11392                         if (meta.r0_rdonly)
11393                                 regs[BPF_REG_0].type |= MEM_RDONLY;
11394
11395                         /* Ensures we don't access the memory after a release_reference() */
11396                         if (meta.ref_obj_id)
11397                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11398                 } else {
11399                         mark_reg_known_zero(env, regs, BPF_REG_0);
11400                         regs[BPF_REG_0].btf = desc_btf;
11401                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11402                         regs[BPF_REG_0].btf_id = ptr_type_id;
11403                 }
11404
11405                 if (is_kfunc_ret_null(&meta)) {
11406                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11407                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11408                         regs[BPF_REG_0].id = ++env->id_gen;
11409                 }
11410                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11411                 if (is_kfunc_acquire(&meta)) {
11412                         int id = acquire_reference_state(env, insn_idx);
11413
11414                         if (id < 0)
11415                                 return id;
11416                         if (is_kfunc_ret_null(&meta))
11417                                 regs[BPF_REG_0].id = id;
11418                         regs[BPF_REG_0].ref_obj_id = id;
11419                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11420                         ref_set_non_owning(env, &regs[BPF_REG_0]);
11421                 }
11422
11423                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11424                         regs[BPF_REG_0].id = ++env->id_gen;
11425         } else if (btf_type_is_void(t)) {
11426                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11427                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11428                                 insn_aux->kptr_struct_meta =
11429                                         btf_find_struct_meta(meta.arg_btf,
11430                                                              meta.arg_btf_id);
11431                         }
11432                 }
11433         }
11434
11435         nargs = btf_type_vlen(meta.func_proto);
11436         args = (const struct btf_param *)(meta.func_proto + 1);
11437         for (i = 0; i < nargs; i++) {
11438                 u32 regno = i + 1;
11439
11440                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11441                 if (btf_type_is_ptr(t))
11442                         mark_btf_func_reg_size(env, regno, sizeof(void *));
11443                 else
11444                         /* scalar. ensured by btf_check_kfunc_arg_match() */
11445                         mark_btf_func_reg_size(env, regno, t->size);
11446         }
11447
11448         if (is_iter_next_kfunc(&meta)) {
11449                 err = process_iter_next_call(env, insn_idx, &meta);
11450                 if (err)
11451                         return err;
11452         }
11453
11454         return 0;
11455 }
11456
11457 static bool signed_add_overflows(s64 a, s64 b)
11458 {
11459         /* Do the add in u64, where overflow is well-defined */
11460         s64 res = (s64)((u64)a + (u64)b);
11461
11462         if (b < 0)
11463                 return res > a;
11464         return res < a;
11465 }
11466
11467 static bool signed_add32_overflows(s32 a, s32 b)
11468 {
11469         /* Do the add in u32, where overflow is well-defined */
11470         s32 res = (s32)((u32)a + (u32)b);
11471
11472         if (b < 0)
11473                 return res > a;
11474         return res < a;
11475 }
11476
11477 static bool signed_sub_overflows(s64 a, s64 b)
11478 {
11479         /* Do the sub in u64, where overflow is well-defined */
11480         s64 res = (s64)((u64)a - (u64)b);
11481
11482         if (b < 0)
11483                 return res < a;
11484         return res > a;
11485 }
11486
11487 static bool signed_sub32_overflows(s32 a, s32 b)
11488 {
11489         /* Do the sub in u32, where overflow is well-defined */
11490         s32 res = (s32)((u32)a - (u32)b);
11491
11492         if (b < 0)
11493                 return res < a;
11494         return res > a;
11495 }
11496
11497 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11498                                   const struct bpf_reg_state *reg,
11499                                   enum bpf_reg_type type)
11500 {
11501         bool known = tnum_is_const(reg->var_off);
11502         s64 val = reg->var_off.value;
11503         s64 smin = reg->smin_value;
11504
11505         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11506                 verbose(env, "math between %s pointer and %lld is not allowed\n",
11507                         reg_type_str(env, type), val);
11508                 return false;
11509         }
11510
11511         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11512                 verbose(env, "%s pointer offset %d is not allowed\n",
11513                         reg_type_str(env, type), reg->off);
11514                 return false;
11515         }
11516
11517         if (smin == S64_MIN) {
11518                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11519                         reg_type_str(env, type));
11520                 return false;
11521         }
11522
11523         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11524                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11525                         smin, reg_type_str(env, type));
11526                 return false;
11527         }
11528
11529         return true;
11530 }
11531
11532 enum {
11533         REASON_BOUNDS   = -1,
11534         REASON_TYPE     = -2,
11535         REASON_PATHS    = -3,
11536         REASON_LIMIT    = -4,
11537         REASON_STACK    = -5,
11538 };
11539
11540 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11541                               u32 *alu_limit, bool mask_to_left)
11542 {
11543         u32 max = 0, ptr_limit = 0;
11544
11545         switch (ptr_reg->type) {
11546         case PTR_TO_STACK:
11547                 /* Offset 0 is out-of-bounds, but acceptable start for the
11548                  * left direction, see BPF_REG_FP. Also, unknown scalar
11549                  * offset where we would need to deal with min/max bounds is
11550                  * currently prohibited for unprivileged.
11551                  */
11552                 max = MAX_BPF_STACK + mask_to_left;
11553                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11554                 break;
11555         case PTR_TO_MAP_VALUE:
11556                 max = ptr_reg->map_ptr->value_size;
11557                 ptr_limit = (mask_to_left ?
11558                              ptr_reg->smin_value :
11559                              ptr_reg->umax_value) + ptr_reg->off;
11560                 break;
11561         default:
11562                 return REASON_TYPE;
11563         }
11564
11565         if (ptr_limit >= max)
11566                 return REASON_LIMIT;
11567         *alu_limit = ptr_limit;
11568         return 0;
11569 }
11570
11571 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11572                                     const struct bpf_insn *insn)
11573 {
11574         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11575 }
11576
11577 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11578                                        u32 alu_state, u32 alu_limit)
11579 {
11580         /* If we arrived here from different branches with different
11581          * state or limits to sanitize, then this won't work.
11582          */
11583         if (aux->alu_state &&
11584             (aux->alu_state != alu_state ||
11585              aux->alu_limit != alu_limit))
11586                 return REASON_PATHS;
11587
11588         /* Corresponding fixup done in do_misc_fixups(). */
11589         aux->alu_state = alu_state;
11590         aux->alu_limit = alu_limit;
11591         return 0;
11592 }
11593
11594 static int sanitize_val_alu(struct bpf_verifier_env *env,
11595                             struct bpf_insn *insn)
11596 {
11597         struct bpf_insn_aux_data *aux = cur_aux(env);
11598
11599         if (can_skip_alu_sanitation(env, insn))
11600                 return 0;
11601
11602         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11603 }
11604
11605 static bool sanitize_needed(u8 opcode)
11606 {
11607         return opcode == BPF_ADD || opcode == BPF_SUB;
11608 }
11609
11610 struct bpf_sanitize_info {
11611         struct bpf_insn_aux_data aux;
11612         bool mask_to_left;
11613 };
11614
11615 static struct bpf_verifier_state *
11616 sanitize_speculative_path(struct bpf_verifier_env *env,
11617                           const struct bpf_insn *insn,
11618                           u32 next_idx, u32 curr_idx)
11619 {
11620         struct bpf_verifier_state *branch;
11621         struct bpf_reg_state *regs;
11622
11623         branch = push_stack(env, next_idx, curr_idx, true);
11624         if (branch && insn) {
11625                 regs = branch->frame[branch->curframe]->regs;
11626                 if (BPF_SRC(insn->code) == BPF_K) {
11627                         mark_reg_unknown(env, regs, insn->dst_reg);
11628                 } else if (BPF_SRC(insn->code) == BPF_X) {
11629                         mark_reg_unknown(env, regs, insn->dst_reg);
11630                         mark_reg_unknown(env, regs, insn->src_reg);
11631                 }
11632         }
11633         return branch;
11634 }
11635
11636 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11637                             struct bpf_insn *insn,
11638                             const struct bpf_reg_state *ptr_reg,
11639                             const struct bpf_reg_state *off_reg,
11640                             struct bpf_reg_state *dst_reg,
11641                             struct bpf_sanitize_info *info,
11642                             const bool commit_window)
11643 {
11644         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11645         struct bpf_verifier_state *vstate = env->cur_state;
11646         bool off_is_imm = tnum_is_const(off_reg->var_off);
11647         bool off_is_neg = off_reg->smin_value < 0;
11648         bool ptr_is_dst_reg = ptr_reg == dst_reg;
11649         u8 opcode = BPF_OP(insn->code);
11650         u32 alu_state, alu_limit;
11651         struct bpf_reg_state tmp;
11652         bool ret;
11653         int err;
11654
11655         if (can_skip_alu_sanitation(env, insn))
11656                 return 0;
11657
11658         /* We already marked aux for masking from non-speculative
11659          * paths, thus we got here in the first place. We only care
11660          * to explore bad access from here.
11661          */
11662         if (vstate->speculative)
11663                 goto do_sim;
11664
11665         if (!commit_window) {
11666                 if (!tnum_is_const(off_reg->var_off) &&
11667                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11668                         return REASON_BOUNDS;
11669
11670                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11671                                      (opcode == BPF_SUB && !off_is_neg);
11672         }
11673
11674         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11675         if (err < 0)
11676                 return err;
11677
11678         if (commit_window) {
11679                 /* In commit phase we narrow the masking window based on
11680                  * the observed pointer move after the simulated operation.
11681                  */
11682                 alu_state = info->aux.alu_state;
11683                 alu_limit = abs(info->aux.alu_limit - alu_limit);
11684         } else {
11685                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11686                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11687                 alu_state |= ptr_is_dst_reg ?
11688                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11689
11690                 /* Limit pruning on unknown scalars to enable deep search for
11691                  * potential masking differences from other program paths.
11692                  */
11693                 if (!off_is_imm)
11694                         env->explore_alu_limits = true;
11695         }
11696
11697         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11698         if (err < 0)
11699                 return err;
11700 do_sim:
11701         /* If we're in commit phase, we're done here given we already
11702          * pushed the truncated dst_reg into the speculative verification
11703          * stack.
11704          *
11705          * Also, when register is a known constant, we rewrite register-based
11706          * operation to immediate-based, and thus do not need masking (and as
11707          * a consequence, do not need to simulate the zero-truncation either).
11708          */
11709         if (commit_window || off_is_imm)
11710                 return 0;
11711
11712         /* Simulate and find potential out-of-bounds access under
11713          * speculative execution from truncation as a result of
11714          * masking when off was not within expected range. If off
11715          * sits in dst, then we temporarily need to move ptr there
11716          * to simulate dst (== 0) +/-= ptr. Needed, for example,
11717          * for cases where we use K-based arithmetic in one direction
11718          * and truncated reg-based in the other in order to explore
11719          * bad access.
11720          */
11721         if (!ptr_is_dst_reg) {
11722                 tmp = *dst_reg;
11723                 copy_register_state(dst_reg, ptr_reg);
11724         }
11725         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11726                                         env->insn_idx);
11727         if (!ptr_is_dst_reg && ret)
11728                 *dst_reg = tmp;
11729         return !ret ? REASON_STACK : 0;
11730 }
11731
11732 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11733 {
11734         struct bpf_verifier_state *vstate = env->cur_state;
11735
11736         /* If we simulate paths under speculation, we don't update the
11737          * insn as 'seen' such that when we verify unreachable paths in
11738          * the non-speculative domain, sanitize_dead_code() can still
11739          * rewrite/sanitize them.
11740          */
11741         if (!vstate->speculative)
11742                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11743 }
11744
11745 static int sanitize_err(struct bpf_verifier_env *env,
11746                         const struct bpf_insn *insn, int reason,
11747                         const struct bpf_reg_state *off_reg,
11748                         const struct bpf_reg_state *dst_reg)
11749 {
11750         static const char *err = "pointer arithmetic with it prohibited for !root";
11751         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11752         u32 dst = insn->dst_reg, src = insn->src_reg;
11753
11754         switch (reason) {
11755         case REASON_BOUNDS:
11756                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11757                         off_reg == dst_reg ? dst : src, err);
11758                 break;
11759         case REASON_TYPE:
11760                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11761                         off_reg == dst_reg ? src : dst, err);
11762                 break;
11763         case REASON_PATHS:
11764                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11765                         dst, op, err);
11766                 break;
11767         case REASON_LIMIT:
11768                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11769                         dst, op, err);
11770                 break;
11771         case REASON_STACK:
11772                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11773                         dst, err);
11774                 break;
11775         default:
11776                 verbose(env, "verifier internal error: unknown reason (%d)\n",
11777                         reason);
11778                 break;
11779         }
11780
11781         return -EACCES;
11782 }
11783
11784 /* check that stack access falls within stack limits and that 'reg' doesn't
11785  * have a variable offset.
11786  *
11787  * Variable offset is prohibited for unprivileged mode for simplicity since it
11788  * requires corresponding support in Spectre masking for stack ALU.  See also
11789  * retrieve_ptr_limit().
11790  *
11791  *
11792  * 'off' includes 'reg->off'.
11793  */
11794 static int check_stack_access_for_ptr_arithmetic(
11795                                 struct bpf_verifier_env *env,
11796                                 int regno,
11797                                 const struct bpf_reg_state *reg,
11798                                 int off)
11799 {
11800         if (!tnum_is_const(reg->var_off)) {
11801                 char tn_buf[48];
11802
11803                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11804                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11805                         regno, tn_buf, off);
11806                 return -EACCES;
11807         }
11808
11809         if (off >= 0 || off < -MAX_BPF_STACK) {
11810                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11811                         "prohibited for !root; off=%d\n", regno, off);
11812                 return -EACCES;
11813         }
11814
11815         return 0;
11816 }
11817
11818 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11819                                  const struct bpf_insn *insn,
11820                                  const struct bpf_reg_state *dst_reg)
11821 {
11822         u32 dst = insn->dst_reg;
11823
11824         /* For unprivileged we require that resulting offset must be in bounds
11825          * in order to be able to sanitize access later on.
11826          */
11827         if (env->bypass_spec_v1)
11828                 return 0;
11829
11830         switch (dst_reg->type) {
11831         case PTR_TO_STACK:
11832                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11833                                         dst_reg->off + dst_reg->var_off.value))
11834                         return -EACCES;
11835                 break;
11836         case PTR_TO_MAP_VALUE:
11837                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11838                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11839                                 "prohibited for !root\n", dst);
11840                         return -EACCES;
11841                 }
11842                 break;
11843         default:
11844                 break;
11845         }
11846
11847         return 0;
11848 }
11849
11850 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11851  * Caller should also handle BPF_MOV case separately.
11852  * If we return -EACCES, caller may want to try again treating pointer as a
11853  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11854  */
11855 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11856                                    struct bpf_insn *insn,
11857                                    const struct bpf_reg_state *ptr_reg,
11858                                    const struct bpf_reg_state *off_reg)
11859 {
11860         struct bpf_verifier_state *vstate = env->cur_state;
11861         struct bpf_func_state *state = vstate->frame[vstate->curframe];
11862         struct bpf_reg_state *regs = state->regs, *dst_reg;
11863         bool known = tnum_is_const(off_reg->var_off);
11864         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11865             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11866         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11867             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11868         struct bpf_sanitize_info info = {};
11869         u8 opcode = BPF_OP(insn->code);
11870         u32 dst = insn->dst_reg;
11871         int ret;
11872
11873         dst_reg = &regs[dst];
11874
11875         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11876             smin_val > smax_val || umin_val > umax_val) {
11877                 /* Taint dst register if offset had invalid bounds derived from
11878                  * e.g. dead branches.
11879                  */
11880                 __mark_reg_unknown(env, dst_reg);
11881                 return 0;
11882         }
11883
11884         if (BPF_CLASS(insn->code) != BPF_ALU64) {
11885                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
11886                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11887                         __mark_reg_unknown(env, dst_reg);
11888                         return 0;
11889                 }
11890
11891                 verbose(env,
11892                         "R%d 32-bit pointer arithmetic prohibited\n",
11893                         dst);
11894                 return -EACCES;
11895         }
11896
11897         if (ptr_reg->type & PTR_MAYBE_NULL) {
11898                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11899                         dst, reg_type_str(env, ptr_reg->type));
11900                 return -EACCES;
11901         }
11902
11903         switch (base_type(ptr_reg->type)) {
11904         case CONST_PTR_TO_MAP:
11905                 /* smin_val represents the known value */
11906                 if (known && smin_val == 0 && opcode == BPF_ADD)
11907                         break;
11908                 fallthrough;
11909         case PTR_TO_PACKET_END:
11910         case PTR_TO_SOCKET:
11911         case PTR_TO_SOCK_COMMON:
11912         case PTR_TO_TCP_SOCK:
11913         case PTR_TO_XDP_SOCK:
11914                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11915                         dst, reg_type_str(env, ptr_reg->type));
11916                 return -EACCES;
11917         default:
11918                 break;
11919         }
11920
11921         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11922          * The id may be overwritten later if we create a new variable offset.
11923          */
11924         dst_reg->type = ptr_reg->type;
11925         dst_reg->id = ptr_reg->id;
11926
11927         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11928             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11929                 return -EINVAL;
11930
11931         /* pointer types do not carry 32-bit bounds at the moment. */
11932         __mark_reg32_unbounded(dst_reg);
11933
11934         if (sanitize_needed(opcode)) {
11935                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11936                                        &info, false);
11937                 if (ret < 0)
11938                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
11939         }
11940
11941         switch (opcode) {
11942         case BPF_ADD:
11943                 /* We can take a fixed offset as long as it doesn't overflow
11944                  * the s32 'off' field
11945                  */
11946                 if (known && (ptr_reg->off + smin_val ==
11947                               (s64)(s32)(ptr_reg->off + smin_val))) {
11948                         /* pointer += K.  Accumulate it into fixed offset */
11949                         dst_reg->smin_value = smin_ptr;
11950                         dst_reg->smax_value = smax_ptr;
11951                         dst_reg->umin_value = umin_ptr;
11952                         dst_reg->umax_value = umax_ptr;
11953                         dst_reg->var_off = ptr_reg->var_off;
11954                         dst_reg->off = ptr_reg->off + smin_val;
11955                         dst_reg->raw = ptr_reg->raw;
11956                         break;
11957                 }
11958                 /* A new variable offset is created.  Note that off_reg->off
11959                  * == 0, since it's a scalar.
11960                  * dst_reg gets the pointer type and since some positive
11961                  * integer value was added to the pointer, give it a new 'id'
11962                  * if it's a PTR_TO_PACKET.
11963                  * this creates a new 'base' pointer, off_reg (variable) gets
11964                  * added into the variable offset, and we copy the fixed offset
11965                  * from ptr_reg.
11966                  */
11967                 if (signed_add_overflows(smin_ptr, smin_val) ||
11968                     signed_add_overflows(smax_ptr, smax_val)) {
11969                         dst_reg->smin_value = S64_MIN;
11970                         dst_reg->smax_value = S64_MAX;
11971                 } else {
11972                         dst_reg->smin_value = smin_ptr + smin_val;
11973                         dst_reg->smax_value = smax_ptr + smax_val;
11974                 }
11975                 if (umin_ptr + umin_val < umin_ptr ||
11976                     umax_ptr + umax_val < umax_ptr) {
11977                         dst_reg->umin_value = 0;
11978                         dst_reg->umax_value = U64_MAX;
11979                 } else {
11980                         dst_reg->umin_value = umin_ptr + umin_val;
11981                         dst_reg->umax_value = umax_ptr + umax_val;
11982                 }
11983                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11984                 dst_reg->off = ptr_reg->off;
11985                 dst_reg->raw = ptr_reg->raw;
11986                 if (reg_is_pkt_pointer(ptr_reg)) {
11987                         dst_reg->id = ++env->id_gen;
11988                         /* something was added to pkt_ptr, set range to zero */
11989                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11990                 }
11991                 break;
11992         case BPF_SUB:
11993                 if (dst_reg == off_reg) {
11994                         /* scalar -= pointer.  Creates an unknown scalar */
11995                         verbose(env, "R%d tried to subtract pointer from scalar\n",
11996                                 dst);
11997                         return -EACCES;
11998                 }
11999                 /* We don't allow subtraction from FP, because (according to
12000                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12001                  * be able to deal with it.
12002                  */
12003                 if (ptr_reg->type == PTR_TO_STACK) {
12004                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12005                                 dst);
12006                         return -EACCES;
12007                 }
12008                 if (known && (ptr_reg->off - smin_val ==
12009                               (s64)(s32)(ptr_reg->off - smin_val))) {
12010                         /* pointer -= K.  Subtract it from fixed offset */
12011                         dst_reg->smin_value = smin_ptr;
12012                         dst_reg->smax_value = smax_ptr;
12013                         dst_reg->umin_value = umin_ptr;
12014                         dst_reg->umax_value = umax_ptr;
12015                         dst_reg->var_off = ptr_reg->var_off;
12016                         dst_reg->id = ptr_reg->id;
12017                         dst_reg->off = ptr_reg->off - smin_val;
12018                         dst_reg->raw = ptr_reg->raw;
12019                         break;
12020                 }
12021                 /* A new variable offset is created.  If the subtrahend is known
12022                  * nonnegative, then any reg->range we had before is still good.
12023                  */
12024                 if (signed_sub_overflows(smin_ptr, smax_val) ||
12025                     signed_sub_overflows(smax_ptr, smin_val)) {
12026                         /* Overflow possible, we know nothing */
12027                         dst_reg->smin_value = S64_MIN;
12028                         dst_reg->smax_value = S64_MAX;
12029                 } else {
12030                         dst_reg->smin_value = smin_ptr - smax_val;
12031                         dst_reg->smax_value = smax_ptr - smin_val;
12032                 }
12033                 if (umin_ptr < umax_val) {
12034                         /* Overflow possible, we know nothing */
12035                         dst_reg->umin_value = 0;
12036                         dst_reg->umax_value = U64_MAX;
12037                 } else {
12038                         /* Cannot overflow (as long as bounds are consistent) */
12039                         dst_reg->umin_value = umin_ptr - umax_val;
12040                         dst_reg->umax_value = umax_ptr - umin_val;
12041                 }
12042                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12043                 dst_reg->off = ptr_reg->off;
12044                 dst_reg->raw = ptr_reg->raw;
12045                 if (reg_is_pkt_pointer(ptr_reg)) {
12046                         dst_reg->id = ++env->id_gen;
12047                         /* something was added to pkt_ptr, set range to zero */
12048                         if (smin_val < 0)
12049                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12050                 }
12051                 break;
12052         case BPF_AND:
12053         case BPF_OR:
12054         case BPF_XOR:
12055                 /* bitwise ops on pointers are troublesome, prohibit. */
12056                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12057                         dst, bpf_alu_string[opcode >> 4]);
12058                 return -EACCES;
12059         default:
12060                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12061                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12062                         dst, bpf_alu_string[opcode >> 4]);
12063                 return -EACCES;
12064         }
12065
12066         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12067                 return -EINVAL;
12068         reg_bounds_sync(dst_reg);
12069         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12070                 return -EACCES;
12071         if (sanitize_needed(opcode)) {
12072                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12073                                        &info, true);
12074                 if (ret < 0)
12075                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12076         }
12077
12078         return 0;
12079 }
12080
12081 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12082                                  struct bpf_reg_state *src_reg)
12083 {
12084         s32 smin_val = src_reg->s32_min_value;
12085         s32 smax_val = src_reg->s32_max_value;
12086         u32 umin_val = src_reg->u32_min_value;
12087         u32 umax_val = src_reg->u32_max_value;
12088
12089         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12090             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12091                 dst_reg->s32_min_value = S32_MIN;
12092                 dst_reg->s32_max_value = S32_MAX;
12093         } else {
12094                 dst_reg->s32_min_value += smin_val;
12095                 dst_reg->s32_max_value += smax_val;
12096         }
12097         if (dst_reg->u32_min_value + umin_val < umin_val ||
12098             dst_reg->u32_max_value + umax_val < umax_val) {
12099                 dst_reg->u32_min_value = 0;
12100                 dst_reg->u32_max_value = U32_MAX;
12101         } else {
12102                 dst_reg->u32_min_value += umin_val;
12103                 dst_reg->u32_max_value += umax_val;
12104         }
12105 }
12106
12107 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12108                                struct bpf_reg_state *src_reg)
12109 {
12110         s64 smin_val = src_reg->smin_value;
12111         s64 smax_val = src_reg->smax_value;
12112         u64 umin_val = src_reg->umin_value;
12113         u64 umax_val = src_reg->umax_value;
12114
12115         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12116             signed_add_overflows(dst_reg->smax_value, smax_val)) {
12117                 dst_reg->smin_value = S64_MIN;
12118                 dst_reg->smax_value = S64_MAX;
12119         } else {
12120                 dst_reg->smin_value += smin_val;
12121                 dst_reg->smax_value += smax_val;
12122         }
12123         if (dst_reg->umin_value + umin_val < umin_val ||
12124             dst_reg->umax_value + umax_val < umax_val) {
12125                 dst_reg->umin_value = 0;
12126                 dst_reg->umax_value = U64_MAX;
12127         } else {
12128                 dst_reg->umin_value += umin_val;
12129                 dst_reg->umax_value += umax_val;
12130         }
12131 }
12132
12133 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12134                                  struct bpf_reg_state *src_reg)
12135 {
12136         s32 smin_val = src_reg->s32_min_value;
12137         s32 smax_val = src_reg->s32_max_value;
12138         u32 umin_val = src_reg->u32_min_value;
12139         u32 umax_val = src_reg->u32_max_value;
12140
12141         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12142             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12143                 /* Overflow possible, we know nothing */
12144                 dst_reg->s32_min_value = S32_MIN;
12145                 dst_reg->s32_max_value = S32_MAX;
12146         } else {
12147                 dst_reg->s32_min_value -= smax_val;
12148                 dst_reg->s32_max_value -= smin_val;
12149         }
12150         if (dst_reg->u32_min_value < umax_val) {
12151                 /* Overflow possible, we know nothing */
12152                 dst_reg->u32_min_value = 0;
12153                 dst_reg->u32_max_value = U32_MAX;
12154         } else {
12155                 /* Cannot overflow (as long as bounds are consistent) */
12156                 dst_reg->u32_min_value -= umax_val;
12157                 dst_reg->u32_max_value -= umin_val;
12158         }
12159 }
12160
12161 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12162                                struct bpf_reg_state *src_reg)
12163 {
12164         s64 smin_val = src_reg->smin_value;
12165         s64 smax_val = src_reg->smax_value;
12166         u64 umin_val = src_reg->umin_value;
12167         u64 umax_val = src_reg->umax_value;
12168
12169         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12170             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12171                 /* Overflow possible, we know nothing */
12172                 dst_reg->smin_value = S64_MIN;
12173                 dst_reg->smax_value = S64_MAX;
12174         } else {
12175                 dst_reg->smin_value -= smax_val;
12176                 dst_reg->smax_value -= smin_val;
12177         }
12178         if (dst_reg->umin_value < umax_val) {
12179                 /* Overflow possible, we know nothing */
12180                 dst_reg->umin_value = 0;
12181                 dst_reg->umax_value = U64_MAX;
12182         } else {
12183                 /* Cannot overflow (as long as bounds are consistent) */
12184                 dst_reg->umin_value -= umax_val;
12185                 dst_reg->umax_value -= umin_val;
12186         }
12187 }
12188
12189 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12190                                  struct bpf_reg_state *src_reg)
12191 {
12192         s32 smin_val = src_reg->s32_min_value;
12193         u32 umin_val = src_reg->u32_min_value;
12194         u32 umax_val = src_reg->u32_max_value;
12195
12196         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12197                 /* Ain't nobody got time to multiply that sign */
12198                 __mark_reg32_unbounded(dst_reg);
12199                 return;
12200         }
12201         /* Both values are positive, so we can work with unsigned and
12202          * copy the result to signed (unless it exceeds S32_MAX).
12203          */
12204         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12205                 /* Potential overflow, we know nothing */
12206                 __mark_reg32_unbounded(dst_reg);
12207                 return;
12208         }
12209         dst_reg->u32_min_value *= umin_val;
12210         dst_reg->u32_max_value *= umax_val;
12211         if (dst_reg->u32_max_value > S32_MAX) {
12212                 /* Overflow possible, we know nothing */
12213                 dst_reg->s32_min_value = S32_MIN;
12214                 dst_reg->s32_max_value = S32_MAX;
12215         } else {
12216                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12217                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12218         }
12219 }
12220
12221 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12222                                struct bpf_reg_state *src_reg)
12223 {
12224         s64 smin_val = src_reg->smin_value;
12225         u64 umin_val = src_reg->umin_value;
12226         u64 umax_val = src_reg->umax_value;
12227
12228         if (smin_val < 0 || dst_reg->smin_value < 0) {
12229                 /* Ain't nobody got time to multiply that sign */
12230                 __mark_reg64_unbounded(dst_reg);
12231                 return;
12232         }
12233         /* Both values are positive, so we can work with unsigned and
12234          * copy the result to signed (unless it exceeds S64_MAX).
12235          */
12236         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12237                 /* Potential overflow, we know nothing */
12238                 __mark_reg64_unbounded(dst_reg);
12239                 return;
12240         }
12241         dst_reg->umin_value *= umin_val;
12242         dst_reg->umax_value *= umax_val;
12243         if (dst_reg->umax_value > S64_MAX) {
12244                 /* Overflow possible, we know nothing */
12245                 dst_reg->smin_value = S64_MIN;
12246                 dst_reg->smax_value = S64_MAX;
12247         } else {
12248                 dst_reg->smin_value = dst_reg->umin_value;
12249                 dst_reg->smax_value = dst_reg->umax_value;
12250         }
12251 }
12252
12253 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12254                                  struct bpf_reg_state *src_reg)
12255 {
12256         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12257         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12258         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12259         s32 smin_val = src_reg->s32_min_value;
12260         u32 umax_val = src_reg->u32_max_value;
12261
12262         if (src_known && dst_known) {
12263                 __mark_reg32_known(dst_reg, var32_off.value);
12264                 return;
12265         }
12266
12267         /* We get our minimum from the var_off, since that's inherently
12268          * bitwise.  Our maximum is the minimum of the operands' maxima.
12269          */
12270         dst_reg->u32_min_value = var32_off.value;
12271         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12272         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12273                 /* Lose signed bounds when ANDing negative numbers,
12274                  * ain't nobody got time for that.
12275                  */
12276                 dst_reg->s32_min_value = S32_MIN;
12277                 dst_reg->s32_max_value = S32_MAX;
12278         } else {
12279                 /* ANDing two positives gives a positive, so safe to
12280                  * cast result into s64.
12281                  */
12282                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12283                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12284         }
12285 }
12286
12287 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12288                                struct bpf_reg_state *src_reg)
12289 {
12290         bool src_known = tnum_is_const(src_reg->var_off);
12291         bool dst_known = tnum_is_const(dst_reg->var_off);
12292         s64 smin_val = src_reg->smin_value;
12293         u64 umax_val = src_reg->umax_value;
12294
12295         if (src_known && dst_known) {
12296                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12297                 return;
12298         }
12299
12300         /* We get our minimum from the var_off, since that's inherently
12301          * bitwise.  Our maximum is the minimum of the operands' maxima.
12302          */
12303         dst_reg->umin_value = dst_reg->var_off.value;
12304         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12305         if (dst_reg->smin_value < 0 || smin_val < 0) {
12306                 /* Lose signed bounds when ANDing negative numbers,
12307                  * ain't nobody got time for that.
12308                  */
12309                 dst_reg->smin_value = S64_MIN;
12310                 dst_reg->smax_value = S64_MAX;
12311         } else {
12312                 /* ANDing two positives gives a positive, so safe to
12313                  * cast result into s64.
12314                  */
12315                 dst_reg->smin_value = dst_reg->umin_value;
12316                 dst_reg->smax_value = dst_reg->umax_value;
12317         }
12318         /* We may learn something more from the var_off */
12319         __update_reg_bounds(dst_reg);
12320 }
12321
12322 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12323                                 struct bpf_reg_state *src_reg)
12324 {
12325         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12326         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12327         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12328         s32 smin_val = src_reg->s32_min_value;
12329         u32 umin_val = src_reg->u32_min_value;
12330
12331         if (src_known && dst_known) {
12332                 __mark_reg32_known(dst_reg, var32_off.value);
12333                 return;
12334         }
12335
12336         /* We get our maximum from the var_off, and our minimum is the
12337          * maximum of the operands' minima
12338          */
12339         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12340         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12341         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12342                 /* Lose signed bounds when ORing negative numbers,
12343                  * ain't nobody got time for that.
12344                  */
12345                 dst_reg->s32_min_value = S32_MIN;
12346                 dst_reg->s32_max_value = S32_MAX;
12347         } else {
12348                 /* ORing two positives gives a positive, so safe to
12349                  * cast result into s64.
12350                  */
12351                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12352                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12353         }
12354 }
12355
12356 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12357                               struct bpf_reg_state *src_reg)
12358 {
12359         bool src_known = tnum_is_const(src_reg->var_off);
12360         bool dst_known = tnum_is_const(dst_reg->var_off);
12361         s64 smin_val = src_reg->smin_value;
12362         u64 umin_val = src_reg->umin_value;
12363
12364         if (src_known && dst_known) {
12365                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12366                 return;
12367         }
12368
12369         /* We get our maximum from the var_off, and our minimum is the
12370          * maximum of the operands' minima
12371          */
12372         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12373         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12374         if (dst_reg->smin_value < 0 || smin_val < 0) {
12375                 /* Lose signed bounds when ORing negative numbers,
12376                  * ain't nobody got time for that.
12377                  */
12378                 dst_reg->smin_value = S64_MIN;
12379                 dst_reg->smax_value = S64_MAX;
12380         } else {
12381                 /* ORing two positives gives a positive, so safe to
12382                  * cast result into s64.
12383                  */
12384                 dst_reg->smin_value = dst_reg->umin_value;
12385                 dst_reg->smax_value = dst_reg->umax_value;
12386         }
12387         /* We may learn something more from the var_off */
12388         __update_reg_bounds(dst_reg);
12389 }
12390
12391 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12392                                  struct bpf_reg_state *src_reg)
12393 {
12394         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12395         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12396         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12397         s32 smin_val = src_reg->s32_min_value;
12398
12399         if (src_known && dst_known) {
12400                 __mark_reg32_known(dst_reg, var32_off.value);
12401                 return;
12402         }
12403
12404         /* We get both minimum and maximum from the var32_off. */
12405         dst_reg->u32_min_value = var32_off.value;
12406         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12407
12408         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12409                 /* XORing two positive sign numbers gives a positive,
12410                  * so safe to cast u32 result into s32.
12411                  */
12412                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12413                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12414         } else {
12415                 dst_reg->s32_min_value = S32_MIN;
12416                 dst_reg->s32_max_value = S32_MAX;
12417         }
12418 }
12419
12420 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12421                                struct bpf_reg_state *src_reg)
12422 {
12423         bool src_known = tnum_is_const(src_reg->var_off);
12424         bool dst_known = tnum_is_const(dst_reg->var_off);
12425         s64 smin_val = src_reg->smin_value;
12426
12427         if (src_known && dst_known) {
12428                 /* dst_reg->var_off.value has been updated earlier */
12429                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12430                 return;
12431         }
12432
12433         /* We get both minimum and maximum from the var_off. */
12434         dst_reg->umin_value = dst_reg->var_off.value;
12435         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12436
12437         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12438                 /* XORing two positive sign numbers gives a positive,
12439                  * so safe to cast u64 result into s64.
12440                  */
12441                 dst_reg->smin_value = dst_reg->umin_value;
12442                 dst_reg->smax_value = dst_reg->umax_value;
12443         } else {
12444                 dst_reg->smin_value = S64_MIN;
12445                 dst_reg->smax_value = S64_MAX;
12446         }
12447
12448         __update_reg_bounds(dst_reg);
12449 }
12450
12451 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12452                                    u64 umin_val, u64 umax_val)
12453 {
12454         /* We lose all sign bit information (except what we can pick
12455          * up from var_off)
12456          */
12457         dst_reg->s32_min_value = S32_MIN;
12458         dst_reg->s32_max_value = S32_MAX;
12459         /* If we might shift our top bit out, then we know nothing */
12460         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12461                 dst_reg->u32_min_value = 0;
12462                 dst_reg->u32_max_value = U32_MAX;
12463         } else {
12464                 dst_reg->u32_min_value <<= umin_val;
12465                 dst_reg->u32_max_value <<= umax_val;
12466         }
12467 }
12468
12469 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12470                                  struct bpf_reg_state *src_reg)
12471 {
12472         u32 umax_val = src_reg->u32_max_value;
12473         u32 umin_val = src_reg->u32_min_value;
12474         /* u32 alu operation will zext upper bits */
12475         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12476
12477         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12478         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12479         /* Not required but being careful mark reg64 bounds as unknown so
12480          * that we are forced to pick them up from tnum and zext later and
12481          * if some path skips this step we are still safe.
12482          */
12483         __mark_reg64_unbounded(dst_reg);
12484         __update_reg32_bounds(dst_reg);
12485 }
12486
12487 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12488                                    u64 umin_val, u64 umax_val)
12489 {
12490         /* Special case <<32 because it is a common compiler pattern to sign
12491          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12492          * positive we know this shift will also be positive so we can track
12493          * bounds correctly. Otherwise we lose all sign bit information except
12494          * what we can pick up from var_off. Perhaps we can generalize this
12495          * later to shifts of any length.
12496          */
12497         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12498                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12499         else
12500                 dst_reg->smax_value = S64_MAX;
12501
12502         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12503                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12504         else
12505                 dst_reg->smin_value = S64_MIN;
12506
12507         /* If we might shift our top bit out, then we know nothing */
12508         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12509                 dst_reg->umin_value = 0;
12510                 dst_reg->umax_value = U64_MAX;
12511         } else {
12512                 dst_reg->umin_value <<= umin_val;
12513                 dst_reg->umax_value <<= umax_val;
12514         }
12515 }
12516
12517 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12518                                struct bpf_reg_state *src_reg)
12519 {
12520         u64 umax_val = src_reg->umax_value;
12521         u64 umin_val = src_reg->umin_value;
12522
12523         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12524         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12525         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12526
12527         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12528         /* We may learn something more from the var_off */
12529         __update_reg_bounds(dst_reg);
12530 }
12531
12532 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12533                                  struct bpf_reg_state *src_reg)
12534 {
12535         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12536         u32 umax_val = src_reg->u32_max_value;
12537         u32 umin_val = src_reg->u32_min_value;
12538
12539         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12540          * be negative, then either:
12541          * 1) src_reg might be zero, so the sign bit of the result is
12542          *    unknown, so we lose our signed bounds
12543          * 2) it's known negative, thus the unsigned bounds capture the
12544          *    signed bounds
12545          * 3) the signed bounds cross zero, so they tell us nothing
12546          *    about the result
12547          * If the value in dst_reg is known nonnegative, then again the
12548          * unsigned bounds capture the signed bounds.
12549          * Thus, in all cases it suffices to blow away our signed bounds
12550          * and rely on inferring new ones from the unsigned bounds and
12551          * var_off of the result.
12552          */
12553         dst_reg->s32_min_value = S32_MIN;
12554         dst_reg->s32_max_value = S32_MAX;
12555
12556         dst_reg->var_off = tnum_rshift(subreg, umin_val);
12557         dst_reg->u32_min_value >>= umax_val;
12558         dst_reg->u32_max_value >>= umin_val;
12559
12560         __mark_reg64_unbounded(dst_reg);
12561         __update_reg32_bounds(dst_reg);
12562 }
12563
12564 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12565                                struct bpf_reg_state *src_reg)
12566 {
12567         u64 umax_val = src_reg->umax_value;
12568         u64 umin_val = src_reg->umin_value;
12569
12570         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12571          * be negative, then either:
12572          * 1) src_reg might be zero, so the sign bit of the result is
12573          *    unknown, so we lose our signed bounds
12574          * 2) it's known negative, thus the unsigned bounds capture the
12575          *    signed bounds
12576          * 3) the signed bounds cross zero, so they tell us nothing
12577          *    about the result
12578          * If the value in dst_reg is known nonnegative, then again the
12579          * unsigned bounds capture the signed bounds.
12580          * Thus, in all cases it suffices to blow away our signed bounds
12581          * and rely on inferring new ones from the unsigned bounds and
12582          * var_off of the result.
12583          */
12584         dst_reg->smin_value = S64_MIN;
12585         dst_reg->smax_value = S64_MAX;
12586         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12587         dst_reg->umin_value >>= umax_val;
12588         dst_reg->umax_value >>= umin_val;
12589
12590         /* Its not easy to operate on alu32 bounds here because it depends
12591          * on bits being shifted in. Take easy way out and mark unbounded
12592          * so we can recalculate later from tnum.
12593          */
12594         __mark_reg32_unbounded(dst_reg);
12595         __update_reg_bounds(dst_reg);
12596 }
12597
12598 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12599                                   struct bpf_reg_state *src_reg)
12600 {
12601         u64 umin_val = src_reg->u32_min_value;
12602
12603         /* Upon reaching here, src_known is true and
12604          * umax_val is equal to umin_val.
12605          */
12606         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12607         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12608
12609         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12610
12611         /* blow away the dst_reg umin_value/umax_value and rely on
12612          * dst_reg var_off to refine the result.
12613          */
12614         dst_reg->u32_min_value = 0;
12615         dst_reg->u32_max_value = U32_MAX;
12616
12617         __mark_reg64_unbounded(dst_reg);
12618         __update_reg32_bounds(dst_reg);
12619 }
12620
12621 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12622                                 struct bpf_reg_state *src_reg)
12623 {
12624         u64 umin_val = src_reg->umin_value;
12625
12626         /* Upon reaching here, src_known is true and umax_val is equal
12627          * to umin_val.
12628          */
12629         dst_reg->smin_value >>= umin_val;
12630         dst_reg->smax_value >>= umin_val;
12631
12632         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12633
12634         /* blow away the dst_reg umin_value/umax_value and rely on
12635          * dst_reg var_off to refine the result.
12636          */
12637         dst_reg->umin_value = 0;
12638         dst_reg->umax_value = U64_MAX;
12639
12640         /* Its not easy to operate on alu32 bounds here because it depends
12641          * on bits being shifted in from upper 32-bits. Take easy way out
12642          * and mark unbounded so we can recalculate later from tnum.
12643          */
12644         __mark_reg32_unbounded(dst_reg);
12645         __update_reg_bounds(dst_reg);
12646 }
12647
12648 /* WARNING: This function does calculations on 64-bit values, but the actual
12649  * execution may occur on 32-bit values. Therefore, things like bitshifts
12650  * need extra checks in the 32-bit case.
12651  */
12652 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12653                                       struct bpf_insn *insn,
12654                                       struct bpf_reg_state *dst_reg,
12655                                       struct bpf_reg_state src_reg)
12656 {
12657         struct bpf_reg_state *regs = cur_regs(env);
12658         u8 opcode = BPF_OP(insn->code);
12659         bool src_known;
12660         s64 smin_val, smax_val;
12661         u64 umin_val, umax_val;
12662         s32 s32_min_val, s32_max_val;
12663         u32 u32_min_val, u32_max_val;
12664         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12665         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12666         int ret;
12667
12668         smin_val = src_reg.smin_value;
12669         smax_val = src_reg.smax_value;
12670         umin_val = src_reg.umin_value;
12671         umax_val = src_reg.umax_value;
12672
12673         s32_min_val = src_reg.s32_min_value;
12674         s32_max_val = src_reg.s32_max_value;
12675         u32_min_val = src_reg.u32_min_value;
12676         u32_max_val = src_reg.u32_max_value;
12677
12678         if (alu32) {
12679                 src_known = tnum_subreg_is_const(src_reg.var_off);
12680                 if ((src_known &&
12681                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12682                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12683                         /* Taint dst register if offset had invalid bounds
12684                          * derived from e.g. dead branches.
12685                          */
12686                         __mark_reg_unknown(env, dst_reg);
12687                         return 0;
12688                 }
12689         } else {
12690                 src_known = tnum_is_const(src_reg.var_off);
12691                 if ((src_known &&
12692                      (smin_val != smax_val || umin_val != umax_val)) ||
12693                     smin_val > smax_val || umin_val > umax_val) {
12694                         /* Taint dst register if offset had invalid bounds
12695                          * derived from e.g. dead branches.
12696                          */
12697                         __mark_reg_unknown(env, dst_reg);
12698                         return 0;
12699                 }
12700         }
12701
12702         if (!src_known &&
12703             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12704                 __mark_reg_unknown(env, dst_reg);
12705                 return 0;
12706         }
12707
12708         if (sanitize_needed(opcode)) {
12709                 ret = sanitize_val_alu(env, insn);
12710                 if (ret < 0)
12711                         return sanitize_err(env, insn, ret, NULL, NULL);
12712         }
12713
12714         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12715          * There are two classes of instructions: The first class we track both
12716          * alu32 and alu64 sign/unsigned bounds independently this provides the
12717          * greatest amount of precision when alu operations are mixed with jmp32
12718          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12719          * and BPF_OR. This is possible because these ops have fairly easy to
12720          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12721          * See alu32 verifier tests for examples. The second class of
12722          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12723          * with regards to tracking sign/unsigned bounds because the bits may
12724          * cross subreg boundaries in the alu64 case. When this happens we mark
12725          * the reg unbounded in the subreg bound space and use the resulting
12726          * tnum to calculate an approximation of the sign/unsigned bounds.
12727          */
12728         switch (opcode) {
12729         case BPF_ADD:
12730                 scalar32_min_max_add(dst_reg, &src_reg);
12731                 scalar_min_max_add(dst_reg, &src_reg);
12732                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12733                 break;
12734         case BPF_SUB:
12735                 scalar32_min_max_sub(dst_reg, &src_reg);
12736                 scalar_min_max_sub(dst_reg, &src_reg);
12737                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12738                 break;
12739         case BPF_MUL:
12740                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12741                 scalar32_min_max_mul(dst_reg, &src_reg);
12742                 scalar_min_max_mul(dst_reg, &src_reg);
12743                 break;
12744         case BPF_AND:
12745                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12746                 scalar32_min_max_and(dst_reg, &src_reg);
12747                 scalar_min_max_and(dst_reg, &src_reg);
12748                 break;
12749         case BPF_OR:
12750                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12751                 scalar32_min_max_or(dst_reg, &src_reg);
12752                 scalar_min_max_or(dst_reg, &src_reg);
12753                 break;
12754         case BPF_XOR:
12755                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12756                 scalar32_min_max_xor(dst_reg, &src_reg);
12757                 scalar_min_max_xor(dst_reg, &src_reg);
12758                 break;
12759         case BPF_LSH:
12760                 if (umax_val >= insn_bitness) {
12761                         /* Shifts greater than 31 or 63 are undefined.
12762                          * This includes shifts by a negative number.
12763                          */
12764                         mark_reg_unknown(env, regs, insn->dst_reg);
12765                         break;
12766                 }
12767                 if (alu32)
12768                         scalar32_min_max_lsh(dst_reg, &src_reg);
12769                 else
12770                         scalar_min_max_lsh(dst_reg, &src_reg);
12771                 break;
12772         case BPF_RSH:
12773                 if (umax_val >= insn_bitness) {
12774                         /* Shifts greater than 31 or 63 are undefined.
12775                          * This includes shifts by a negative number.
12776                          */
12777                         mark_reg_unknown(env, regs, insn->dst_reg);
12778                         break;
12779                 }
12780                 if (alu32)
12781                         scalar32_min_max_rsh(dst_reg, &src_reg);
12782                 else
12783                         scalar_min_max_rsh(dst_reg, &src_reg);
12784                 break;
12785         case BPF_ARSH:
12786                 if (umax_val >= insn_bitness) {
12787                         /* Shifts greater than 31 or 63 are undefined.
12788                          * This includes shifts by a negative number.
12789                          */
12790                         mark_reg_unknown(env, regs, insn->dst_reg);
12791                         break;
12792                 }
12793                 if (alu32)
12794                         scalar32_min_max_arsh(dst_reg, &src_reg);
12795                 else
12796                         scalar_min_max_arsh(dst_reg, &src_reg);
12797                 break;
12798         default:
12799                 mark_reg_unknown(env, regs, insn->dst_reg);
12800                 break;
12801         }
12802
12803         /* ALU32 ops are zero extended into 64bit register */
12804         if (alu32)
12805                 zext_32_to_64(dst_reg);
12806         reg_bounds_sync(dst_reg);
12807         return 0;
12808 }
12809
12810 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12811  * and var_off.
12812  */
12813 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12814                                    struct bpf_insn *insn)
12815 {
12816         struct bpf_verifier_state *vstate = env->cur_state;
12817         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12818         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12819         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12820         u8 opcode = BPF_OP(insn->code);
12821         int err;
12822
12823         dst_reg = &regs[insn->dst_reg];
12824         src_reg = NULL;
12825         if (dst_reg->type != SCALAR_VALUE)
12826                 ptr_reg = dst_reg;
12827         else
12828                 /* Make sure ID is cleared otherwise dst_reg min/max could be
12829                  * incorrectly propagated into other registers by find_equal_scalars()
12830                  */
12831                 dst_reg->id = 0;
12832         if (BPF_SRC(insn->code) == BPF_X) {
12833                 src_reg = &regs[insn->src_reg];
12834                 if (src_reg->type != SCALAR_VALUE) {
12835                         if (dst_reg->type != SCALAR_VALUE) {
12836                                 /* Combining two pointers by any ALU op yields
12837                                  * an arbitrary scalar. Disallow all math except
12838                                  * pointer subtraction
12839                                  */
12840                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12841                                         mark_reg_unknown(env, regs, insn->dst_reg);
12842                                         return 0;
12843                                 }
12844                                 verbose(env, "R%d pointer %s pointer prohibited\n",
12845                                         insn->dst_reg,
12846                                         bpf_alu_string[opcode >> 4]);
12847                                 return -EACCES;
12848                         } else {
12849                                 /* scalar += pointer
12850                                  * This is legal, but we have to reverse our
12851                                  * src/dest handling in computing the range
12852                                  */
12853                                 err = mark_chain_precision(env, insn->dst_reg);
12854                                 if (err)
12855                                         return err;
12856                                 return adjust_ptr_min_max_vals(env, insn,
12857                                                                src_reg, dst_reg);
12858                         }
12859                 } else if (ptr_reg) {
12860                         /* pointer += scalar */
12861                         err = mark_chain_precision(env, insn->src_reg);
12862                         if (err)
12863                                 return err;
12864                         return adjust_ptr_min_max_vals(env, insn,
12865                                                        dst_reg, src_reg);
12866                 } else if (dst_reg->precise) {
12867                         /* if dst_reg is precise, src_reg should be precise as well */
12868                         err = mark_chain_precision(env, insn->src_reg);
12869                         if (err)
12870                                 return err;
12871                 }
12872         } else {
12873                 /* Pretend the src is a reg with a known value, since we only
12874                  * need to be able to read from this state.
12875                  */
12876                 off_reg.type = SCALAR_VALUE;
12877                 __mark_reg_known(&off_reg, insn->imm);
12878                 src_reg = &off_reg;
12879                 if (ptr_reg) /* pointer += K */
12880                         return adjust_ptr_min_max_vals(env, insn,
12881                                                        ptr_reg, src_reg);
12882         }
12883
12884         /* Got here implies adding two SCALAR_VALUEs */
12885         if (WARN_ON_ONCE(ptr_reg)) {
12886                 print_verifier_state(env, state, true);
12887                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
12888                 return -EINVAL;
12889         }
12890         if (WARN_ON(!src_reg)) {
12891                 print_verifier_state(env, state, true);
12892                 verbose(env, "verifier internal error: no src_reg\n");
12893                 return -EINVAL;
12894         }
12895         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12896 }
12897
12898 /* check validity of 32-bit and 64-bit arithmetic operations */
12899 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12900 {
12901         struct bpf_reg_state *regs = cur_regs(env);
12902         u8 opcode = BPF_OP(insn->code);
12903         int err;
12904
12905         if (opcode == BPF_END || opcode == BPF_NEG) {
12906                 if (opcode == BPF_NEG) {
12907                         if (BPF_SRC(insn->code) != BPF_K ||
12908                             insn->src_reg != BPF_REG_0 ||
12909                             insn->off != 0 || insn->imm != 0) {
12910                                 verbose(env, "BPF_NEG uses reserved fields\n");
12911                                 return -EINVAL;
12912                         }
12913                 } else {
12914                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12915                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12916                             BPF_CLASS(insn->code) == BPF_ALU64) {
12917                                 verbose(env, "BPF_END uses reserved fields\n");
12918                                 return -EINVAL;
12919                         }
12920                 }
12921
12922                 /* check src operand */
12923                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12924                 if (err)
12925                         return err;
12926
12927                 if (is_pointer_value(env, insn->dst_reg)) {
12928                         verbose(env, "R%d pointer arithmetic prohibited\n",
12929                                 insn->dst_reg);
12930                         return -EACCES;
12931                 }
12932
12933                 /* check dest operand */
12934                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
12935                 if (err)
12936                         return err;
12937
12938         } else if (opcode == BPF_MOV) {
12939
12940                 if (BPF_SRC(insn->code) == BPF_X) {
12941                         if (insn->imm != 0 || insn->off != 0) {
12942                                 verbose(env, "BPF_MOV uses reserved fields\n");
12943                                 return -EINVAL;
12944                         }
12945
12946                         /* check src operand */
12947                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12948                         if (err)
12949                                 return err;
12950                 } else {
12951                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12952                                 verbose(env, "BPF_MOV uses reserved fields\n");
12953                                 return -EINVAL;
12954                         }
12955                 }
12956
12957                 /* check dest operand, mark as required later */
12958                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12959                 if (err)
12960                         return err;
12961
12962                 if (BPF_SRC(insn->code) == BPF_X) {
12963                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
12964                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12965                         bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
12966                                        !tnum_is_const(src_reg->var_off);
12967
12968                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
12969                                 /* case: R1 = R2
12970                                  * copy register state to dest reg
12971                                  */
12972                                 if (need_id)
12973                                         /* Assign src and dst registers the same ID
12974                                          * that will be used by find_equal_scalars()
12975                                          * to propagate min/max range.
12976                                          */
12977                                         src_reg->id = ++env->id_gen;
12978                                 copy_register_state(dst_reg, src_reg);
12979                                 dst_reg->live |= REG_LIVE_WRITTEN;
12980                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
12981                         } else {
12982                                 /* R1 = (u32) R2 */
12983                                 if (is_pointer_value(env, insn->src_reg)) {
12984                                         verbose(env,
12985                                                 "R%d partial copy of pointer\n",
12986                                                 insn->src_reg);
12987                                         return -EACCES;
12988                                 } else if (src_reg->type == SCALAR_VALUE) {
12989                                         bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12990
12991                                         if (is_src_reg_u32 && need_id)
12992                                                 src_reg->id = ++env->id_gen;
12993                                         copy_register_state(dst_reg, src_reg);
12994                                         /* Make sure ID is cleared if src_reg is not in u32 range otherwise
12995                                          * dst_reg min/max could be incorrectly
12996                                          * propagated into src_reg by find_equal_scalars()
12997                                          */
12998                                         if (!is_src_reg_u32)
12999                                                 dst_reg->id = 0;
13000                                         dst_reg->live |= REG_LIVE_WRITTEN;
13001                                         dst_reg->subreg_def = env->insn_idx + 1;
13002                                 } else {
13003                                         mark_reg_unknown(env, regs,
13004                                                          insn->dst_reg);
13005                                 }
13006                                 zext_32_to_64(dst_reg);
13007                                 reg_bounds_sync(dst_reg);
13008                         }
13009                 } else {
13010                         /* case: R = imm
13011                          * remember the value we stored into this reg
13012                          */
13013                         /* clear any state __mark_reg_known doesn't set */
13014                         mark_reg_unknown(env, regs, insn->dst_reg);
13015                         regs[insn->dst_reg].type = SCALAR_VALUE;
13016                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13017                                 __mark_reg_known(regs + insn->dst_reg,
13018                                                  insn->imm);
13019                         } else {
13020                                 __mark_reg_known(regs + insn->dst_reg,
13021                                                  (u32)insn->imm);
13022                         }
13023                 }
13024
13025         } else if (opcode > BPF_END) {
13026                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13027                 return -EINVAL;
13028
13029         } else {        /* all other ALU ops: and, sub, xor, add, ... */
13030
13031                 if (BPF_SRC(insn->code) == BPF_X) {
13032                         if (insn->imm != 0 || insn->off != 0) {
13033                                 verbose(env, "BPF_ALU uses reserved fields\n");
13034                                 return -EINVAL;
13035                         }
13036                         /* check src1 operand */
13037                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13038                         if (err)
13039                                 return err;
13040                 } else {
13041                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13042                                 verbose(env, "BPF_ALU uses reserved fields\n");
13043                                 return -EINVAL;
13044                         }
13045                 }
13046
13047                 /* check src2 operand */
13048                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13049                 if (err)
13050                         return err;
13051
13052                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13053                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13054                         verbose(env, "div by zero\n");
13055                         return -EINVAL;
13056                 }
13057
13058                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13059                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13060                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13061
13062                         if (insn->imm < 0 || insn->imm >= size) {
13063                                 verbose(env, "invalid shift %d\n", insn->imm);
13064                                 return -EINVAL;
13065                         }
13066                 }
13067
13068                 /* check dest operand */
13069                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13070                 if (err)
13071                         return err;
13072
13073                 return adjust_reg_min_max_vals(env, insn);
13074         }
13075
13076         return 0;
13077 }
13078
13079 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13080                                    struct bpf_reg_state *dst_reg,
13081                                    enum bpf_reg_type type,
13082                                    bool range_right_open)
13083 {
13084         struct bpf_func_state *state;
13085         struct bpf_reg_state *reg;
13086         int new_range;
13087
13088         if (dst_reg->off < 0 ||
13089             (dst_reg->off == 0 && range_right_open))
13090                 /* This doesn't give us any range */
13091                 return;
13092
13093         if (dst_reg->umax_value > MAX_PACKET_OFF ||
13094             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13095                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
13096                  * than pkt_end, but that's because it's also less than pkt.
13097                  */
13098                 return;
13099
13100         new_range = dst_reg->off;
13101         if (range_right_open)
13102                 new_range++;
13103
13104         /* Examples for register markings:
13105          *
13106          * pkt_data in dst register:
13107          *
13108          *   r2 = r3;
13109          *   r2 += 8;
13110          *   if (r2 > pkt_end) goto <handle exception>
13111          *   <access okay>
13112          *
13113          *   r2 = r3;
13114          *   r2 += 8;
13115          *   if (r2 < pkt_end) goto <access okay>
13116          *   <handle exception>
13117          *
13118          *   Where:
13119          *     r2 == dst_reg, pkt_end == src_reg
13120          *     r2=pkt(id=n,off=8,r=0)
13121          *     r3=pkt(id=n,off=0,r=0)
13122          *
13123          * pkt_data in src register:
13124          *
13125          *   r2 = r3;
13126          *   r2 += 8;
13127          *   if (pkt_end >= r2) goto <access okay>
13128          *   <handle exception>
13129          *
13130          *   r2 = r3;
13131          *   r2 += 8;
13132          *   if (pkt_end <= r2) goto <handle exception>
13133          *   <access okay>
13134          *
13135          *   Where:
13136          *     pkt_end == dst_reg, r2 == src_reg
13137          *     r2=pkt(id=n,off=8,r=0)
13138          *     r3=pkt(id=n,off=0,r=0)
13139          *
13140          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13141          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13142          * and [r3, r3 + 8-1) respectively is safe to access depending on
13143          * the check.
13144          */
13145
13146         /* If our ids match, then we must have the same max_value.  And we
13147          * don't care about the other reg's fixed offset, since if it's too big
13148          * the range won't allow anything.
13149          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13150          */
13151         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13152                 if (reg->type == type && reg->id == dst_reg->id)
13153                         /* keep the maximum range already checked */
13154                         reg->range = max(reg->range, new_range);
13155         }));
13156 }
13157
13158 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13159 {
13160         struct tnum subreg = tnum_subreg(reg->var_off);
13161         s32 sval = (s32)val;
13162
13163         switch (opcode) {
13164         case BPF_JEQ:
13165                 if (tnum_is_const(subreg))
13166                         return !!tnum_equals_const(subreg, val);
13167                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13168                         return 0;
13169                 break;
13170         case BPF_JNE:
13171                 if (tnum_is_const(subreg))
13172                         return !tnum_equals_const(subreg, val);
13173                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13174                         return 1;
13175                 break;
13176         case BPF_JSET:
13177                 if ((~subreg.mask & subreg.value) & val)
13178                         return 1;
13179                 if (!((subreg.mask | subreg.value) & val))
13180                         return 0;
13181                 break;
13182         case BPF_JGT:
13183                 if (reg->u32_min_value > val)
13184                         return 1;
13185                 else if (reg->u32_max_value <= val)
13186                         return 0;
13187                 break;
13188         case BPF_JSGT:
13189                 if (reg->s32_min_value > sval)
13190                         return 1;
13191                 else if (reg->s32_max_value <= sval)
13192                         return 0;
13193                 break;
13194         case BPF_JLT:
13195                 if (reg->u32_max_value < val)
13196                         return 1;
13197                 else if (reg->u32_min_value >= val)
13198                         return 0;
13199                 break;
13200         case BPF_JSLT:
13201                 if (reg->s32_max_value < sval)
13202                         return 1;
13203                 else if (reg->s32_min_value >= sval)
13204                         return 0;
13205                 break;
13206         case BPF_JGE:
13207                 if (reg->u32_min_value >= val)
13208                         return 1;
13209                 else if (reg->u32_max_value < val)
13210                         return 0;
13211                 break;
13212         case BPF_JSGE:
13213                 if (reg->s32_min_value >= sval)
13214                         return 1;
13215                 else if (reg->s32_max_value < sval)
13216                         return 0;
13217                 break;
13218         case BPF_JLE:
13219                 if (reg->u32_max_value <= val)
13220                         return 1;
13221                 else if (reg->u32_min_value > val)
13222                         return 0;
13223                 break;
13224         case BPF_JSLE:
13225                 if (reg->s32_max_value <= sval)
13226                         return 1;
13227                 else if (reg->s32_min_value > sval)
13228                         return 0;
13229                 break;
13230         }
13231
13232         return -1;
13233 }
13234
13235
13236 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13237 {
13238         s64 sval = (s64)val;
13239
13240         switch (opcode) {
13241         case BPF_JEQ:
13242                 if (tnum_is_const(reg->var_off))
13243                         return !!tnum_equals_const(reg->var_off, val);
13244                 else if (val < reg->umin_value || val > reg->umax_value)
13245                         return 0;
13246                 break;
13247         case BPF_JNE:
13248                 if (tnum_is_const(reg->var_off))
13249                         return !tnum_equals_const(reg->var_off, val);
13250                 else if (val < reg->umin_value || val > reg->umax_value)
13251                         return 1;
13252                 break;
13253         case BPF_JSET:
13254                 if ((~reg->var_off.mask & reg->var_off.value) & val)
13255                         return 1;
13256                 if (!((reg->var_off.mask | reg->var_off.value) & val))
13257                         return 0;
13258                 break;
13259         case BPF_JGT:
13260                 if (reg->umin_value > val)
13261                         return 1;
13262                 else if (reg->umax_value <= val)
13263                         return 0;
13264                 break;
13265         case BPF_JSGT:
13266                 if (reg->smin_value > sval)
13267                         return 1;
13268                 else if (reg->smax_value <= sval)
13269                         return 0;
13270                 break;
13271         case BPF_JLT:
13272                 if (reg->umax_value < val)
13273                         return 1;
13274                 else if (reg->umin_value >= val)
13275                         return 0;
13276                 break;
13277         case BPF_JSLT:
13278                 if (reg->smax_value < sval)
13279                         return 1;
13280                 else if (reg->smin_value >= sval)
13281                         return 0;
13282                 break;
13283         case BPF_JGE:
13284                 if (reg->umin_value >= val)
13285                         return 1;
13286                 else if (reg->umax_value < val)
13287                         return 0;
13288                 break;
13289         case BPF_JSGE:
13290                 if (reg->smin_value >= sval)
13291                         return 1;
13292                 else if (reg->smax_value < sval)
13293                         return 0;
13294                 break;
13295         case BPF_JLE:
13296                 if (reg->umax_value <= val)
13297                         return 1;
13298                 else if (reg->umin_value > val)
13299                         return 0;
13300                 break;
13301         case BPF_JSLE:
13302                 if (reg->smax_value <= sval)
13303                         return 1;
13304                 else if (reg->smin_value > sval)
13305                         return 0;
13306                 break;
13307         }
13308
13309         return -1;
13310 }
13311
13312 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13313  * and return:
13314  *  1 - branch will be taken and "goto target" will be executed
13315  *  0 - branch will not be taken and fall-through to next insn
13316  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13317  *      range [0,10]
13318  */
13319 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13320                            bool is_jmp32)
13321 {
13322         if (__is_pointer_value(false, reg)) {
13323                 if (!reg_not_null(reg))
13324                         return -1;
13325
13326                 /* If pointer is valid tests against zero will fail so we can
13327                  * use this to direct branch taken.
13328                  */
13329                 if (val != 0)
13330                         return -1;
13331
13332                 switch (opcode) {
13333                 case BPF_JEQ:
13334                         return 0;
13335                 case BPF_JNE:
13336                         return 1;
13337                 default:
13338                         return -1;
13339                 }
13340         }
13341
13342         if (is_jmp32)
13343                 return is_branch32_taken(reg, val, opcode);
13344         return is_branch64_taken(reg, val, opcode);
13345 }
13346
13347 static int flip_opcode(u32 opcode)
13348 {
13349         /* How can we transform "a <op> b" into "b <op> a"? */
13350         static const u8 opcode_flip[16] = {
13351                 /* these stay the same */
13352                 [BPF_JEQ  >> 4] = BPF_JEQ,
13353                 [BPF_JNE  >> 4] = BPF_JNE,
13354                 [BPF_JSET >> 4] = BPF_JSET,
13355                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13356                 [BPF_JGE  >> 4] = BPF_JLE,
13357                 [BPF_JGT  >> 4] = BPF_JLT,
13358                 [BPF_JLE  >> 4] = BPF_JGE,
13359                 [BPF_JLT  >> 4] = BPF_JGT,
13360                 [BPF_JSGE >> 4] = BPF_JSLE,
13361                 [BPF_JSGT >> 4] = BPF_JSLT,
13362                 [BPF_JSLE >> 4] = BPF_JSGE,
13363                 [BPF_JSLT >> 4] = BPF_JSGT
13364         };
13365         return opcode_flip[opcode >> 4];
13366 }
13367
13368 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13369                                    struct bpf_reg_state *src_reg,
13370                                    u8 opcode)
13371 {
13372         struct bpf_reg_state *pkt;
13373
13374         if (src_reg->type == PTR_TO_PACKET_END) {
13375                 pkt = dst_reg;
13376         } else if (dst_reg->type == PTR_TO_PACKET_END) {
13377                 pkt = src_reg;
13378                 opcode = flip_opcode(opcode);
13379         } else {
13380                 return -1;
13381         }
13382
13383         if (pkt->range >= 0)
13384                 return -1;
13385
13386         switch (opcode) {
13387         case BPF_JLE:
13388                 /* pkt <= pkt_end */
13389                 fallthrough;
13390         case BPF_JGT:
13391                 /* pkt > pkt_end */
13392                 if (pkt->range == BEYOND_PKT_END)
13393                         /* pkt has at last one extra byte beyond pkt_end */
13394                         return opcode == BPF_JGT;
13395                 break;
13396         case BPF_JLT:
13397                 /* pkt < pkt_end */
13398                 fallthrough;
13399         case BPF_JGE:
13400                 /* pkt >= pkt_end */
13401                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13402                         return opcode == BPF_JGE;
13403                 break;
13404         }
13405         return -1;
13406 }
13407
13408 /* Adjusts the register min/max values in the case that the dst_reg is the
13409  * variable register that we are working on, and src_reg is a constant or we're
13410  * simply doing a BPF_K check.
13411  * In JEQ/JNE cases we also adjust the var_off values.
13412  */
13413 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13414                             struct bpf_reg_state *false_reg,
13415                             u64 val, u32 val32,
13416                             u8 opcode, bool is_jmp32)
13417 {
13418         struct tnum false_32off = tnum_subreg(false_reg->var_off);
13419         struct tnum false_64off = false_reg->var_off;
13420         struct tnum true_32off = tnum_subreg(true_reg->var_off);
13421         struct tnum true_64off = true_reg->var_off;
13422         s64 sval = (s64)val;
13423         s32 sval32 = (s32)val32;
13424
13425         /* If the dst_reg is a pointer, we can't learn anything about its
13426          * variable offset from the compare (unless src_reg were a pointer into
13427          * the same object, but we don't bother with that.
13428          * Since false_reg and true_reg have the same type by construction, we
13429          * only need to check one of them for pointerness.
13430          */
13431         if (__is_pointer_value(false, false_reg))
13432                 return;
13433
13434         switch (opcode) {
13435         /* JEQ/JNE comparison doesn't change the register equivalence.
13436          *
13437          * r1 = r2;
13438          * if (r1 == 42) goto label;
13439          * ...
13440          * label: // here both r1 and r2 are known to be 42.
13441          *
13442          * Hence when marking register as known preserve it's ID.
13443          */
13444         case BPF_JEQ:
13445                 if (is_jmp32) {
13446                         __mark_reg32_known(true_reg, val32);
13447                         true_32off = tnum_subreg(true_reg->var_off);
13448                 } else {
13449                         ___mark_reg_known(true_reg, val);
13450                         true_64off = true_reg->var_off;
13451                 }
13452                 break;
13453         case BPF_JNE:
13454                 if (is_jmp32) {
13455                         __mark_reg32_known(false_reg, val32);
13456                         false_32off = tnum_subreg(false_reg->var_off);
13457                 } else {
13458                         ___mark_reg_known(false_reg, val);
13459                         false_64off = false_reg->var_off;
13460                 }
13461                 break;
13462         case BPF_JSET:
13463                 if (is_jmp32) {
13464                         false_32off = tnum_and(false_32off, tnum_const(~val32));
13465                         if (is_power_of_2(val32))
13466                                 true_32off = tnum_or(true_32off,
13467                                                      tnum_const(val32));
13468                 } else {
13469                         false_64off = tnum_and(false_64off, tnum_const(~val));
13470                         if (is_power_of_2(val))
13471                                 true_64off = tnum_or(true_64off,
13472                                                      tnum_const(val));
13473                 }
13474                 break;
13475         case BPF_JGE:
13476         case BPF_JGT:
13477         {
13478                 if (is_jmp32) {
13479                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13480                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13481
13482                         false_reg->u32_max_value = min(false_reg->u32_max_value,
13483                                                        false_umax);
13484                         true_reg->u32_min_value = max(true_reg->u32_min_value,
13485                                                       true_umin);
13486                 } else {
13487                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13488                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13489
13490                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
13491                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
13492                 }
13493                 break;
13494         }
13495         case BPF_JSGE:
13496         case BPF_JSGT:
13497         {
13498                 if (is_jmp32) {
13499                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13500                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13501
13502                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13503                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13504                 } else {
13505                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13506                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13507
13508                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
13509                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
13510                 }
13511                 break;
13512         }
13513         case BPF_JLE:
13514         case BPF_JLT:
13515         {
13516                 if (is_jmp32) {
13517                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13518                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13519
13520                         false_reg->u32_min_value = max(false_reg->u32_min_value,
13521                                                        false_umin);
13522                         true_reg->u32_max_value = min(true_reg->u32_max_value,
13523                                                       true_umax);
13524                 } else {
13525                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13526                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13527
13528                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
13529                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
13530                 }
13531                 break;
13532         }
13533         case BPF_JSLE:
13534         case BPF_JSLT:
13535         {
13536                 if (is_jmp32) {
13537                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13538                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13539
13540                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13541                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13542                 } else {
13543                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13544                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13545
13546                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
13547                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
13548                 }
13549                 break;
13550         }
13551         default:
13552                 return;
13553         }
13554
13555         if (is_jmp32) {
13556                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13557                                              tnum_subreg(false_32off));
13558                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13559                                             tnum_subreg(true_32off));
13560                 __reg_combine_32_into_64(false_reg);
13561                 __reg_combine_32_into_64(true_reg);
13562         } else {
13563                 false_reg->var_off = false_64off;
13564                 true_reg->var_off = true_64off;
13565                 __reg_combine_64_into_32(false_reg);
13566                 __reg_combine_64_into_32(true_reg);
13567         }
13568 }
13569
13570 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13571  * the variable reg.
13572  */
13573 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13574                                 struct bpf_reg_state *false_reg,
13575                                 u64 val, u32 val32,
13576                                 u8 opcode, bool is_jmp32)
13577 {
13578         opcode = flip_opcode(opcode);
13579         /* This uses zero as "not present in table"; luckily the zero opcode,
13580          * BPF_JA, can't get here.
13581          */
13582         if (opcode)
13583                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13584 }
13585
13586 /* Regs are known to be equal, so intersect their min/max/var_off */
13587 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13588                                   struct bpf_reg_state *dst_reg)
13589 {
13590         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13591                                                         dst_reg->umin_value);
13592         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13593                                                         dst_reg->umax_value);
13594         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13595                                                         dst_reg->smin_value);
13596         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13597                                                         dst_reg->smax_value);
13598         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13599                                                              dst_reg->var_off);
13600         reg_bounds_sync(src_reg);
13601         reg_bounds_sync(dst_reg);
13602 }
13603
13604 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13605                                 struct bpf_reg_state *true_dst,
13606                                 struct bpf_reg_state *false_src,
13607                                 struct bpf_reg_state *false_dst,
13608                                 u8 opcode)
13609 {
13610         switch (opcode) {
13611         case BPF_JEQ:
13612                 __reg_combine_min_max(true_src, true_dst);
13613                 break;
13614         case BPF_JNE:
13615                 __reg_combine_min_max(false_src, false_dst);
13616                 break;
13617         }
13618 }
13619
13620 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13621                                  struct bpf_reg_state *reg, u32 id,
13622                                  bool is_null)
13623 {
13624         if (type_may_be_null(reg->type) && reg->id == id &&
13625             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13626                 /* Old offset (both fixed and variable parts) should have been
13627                  * known-zero, because we don't allow pointer arithmetic on
13628                  * pointers that might be NULL. If we see this happening, don't
13629                  * convert the register.
13630                  *
13631                  * But in some cases, some helpers that return local kptrs
13632                  * advance offset for the returned pointer. In those cases, it
13633                  * is fine to expect to see reg->off.
13634                  */
13635                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13636                         return;
13637                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13638                     WARN_ON_ONCE(reg->off))
13639                         return;
13640
13641                 if (is_null) {
13642                         reg->type = SCALAR_VALUE;
13643                         /* We don't need id and ref_obj_id from this point
13644                          * onwards anymore, thus we should better reset it,
13645                          * so that state pruning has chances to take effect.
13646                          */
13647                         reg->id = 0;
13648                         reg->ref_obj_id = 0;
13649
13650                         return;
13651                 }
13652
13653                 mark_ptr_not_null_reg(reg);
13654
13655                 if (!reg_may_point_to_spin_lock(reg)) {
13656                         /* For not-NULL ptr, reg->ref_obj_id will be reset
13657                          * in release_reference().
13658                          *
13659                          * reg->id is still used by spin_lock ptr. Other
13660                          * than spin_lock ptr type, reg->id can be reset.
13661                          */
13662                         reg->id = 0;
13663                 }
13664         }
13665 }
13666
13667 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13668  * be folded together at some point.
13669  */
13670 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13671                                   bool is_null)
13672 {
13673         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13674         struct bpf_reg_state *regs = state->regs, *reg;
13675         u32 ref_obj_id = regs[regno].ref_obj_id;
13676         u32 id = regs[regno].id;
13677
13678         if (ref_obj_id && ref_obj_id == id && is_null)
13679                 /* regs[regno] is in the " == NULL" branch.
13680                  * No one could have freed the reference state before
13681                  * doing the NULL check.
13682                  */
13683                 WARN_ON_ONCE(release_reference_state(state, id));
13684
13685         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13686                 mark_ptr_or_null_reg(state, reg, id, is_null);
13687         }));
13688 }
13689
13690 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13691                                    struct bpf_reg_state *dst_reg,
13692                                    struct bpf_reg_state *src_reg,
13693                                    struct bpf_verifier_state *this_branch,
13694                                    struct bpf_verifier_state *other_branch)
13695 {
13696         if (BPF_SRC(insn->code) != BPF_X)
13697                 return false;
13698
13699         /* Pointers are always 64-bit. */
13700         if (BPF_CLASS(insn->code) == BPF_JMP32)
13701                 return false;
13702
13703         switch (BPF_OP(insn->code)) {
13704         case BPF_JGT:
13705                 if ((dst_reg->type == PTR_TO_PACKET &&
13706                      src_reg->type == PTR_TO_PACKET_END) ||
13707                     (dst_reg->type == PTR_TO_PACKET_META &&
13708                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13709                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13710                         find_good_pkt_pointers(this_branch, dst_reg,
13711                                                dst_reg->type, false);
13712                         mark_pkt_end(other_branch, insn->dst_reg, true);
13713                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13714                             src_reg->type == PTR_TO_PACKET) ||
13715                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13716                             src_reg->type == PTR_TO_PACKET_META)) {
13717                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13718                         find_good_pkt_pointers(other_branch, src_reg,
13719                                                src_reg->type, true);
13720                         mark_pkt_end(this_branch, insn->src_reg, false);
13721                 } else {
13722                         return false;
13723                 }
13724                 break;
13725         case BPF_JLT:
13726                 if ((dst_reg->type == PTR_TO_PACKET &&
13727                      src_reg->type == PTR_TO_PACKET_END) ||
13728                     (dst_reg->type == PTR_TO_PACKET_META &&
13729                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13730                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13731                         find_good_pkt_pointers(other_branch, dst_reg,
13732                                                dst_reg->type, true);
13733                         mark_pkt_end(this_branch, insn->dst_reg, false);
13734                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13735                             src_reg->type == PTR_TO_PACKET) ||
13736                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13737                             src_reg->type == PTR_TO_PACKET_META)) {
13738                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13739                         find_good_pkt_pointers(this_branch, src_reg,
13740                                                src_reg->type, false);
13741                         mark_pkt_end(other_branch, insn->src_reg, true);
13742                 } else {
13743                         return false;
13744                 }
13745                 break;
13746         case BPF_JGE:
13747                 if ((dst_reg->type == PTR_TO_PACKET &&
13748                      src_reg->type == PTR_TO_PACKET_END) ||
13749                     (dst_reg->type == PTR_TO_PACKET_META &&
13750                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13751                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13752                         find_good_pkt_pointers(this_branch, dst_reg,
13753                                                dst_reg->type, true);
13754                         mark_pkt_end(other_branch, insn->dst_reg, false);
13755                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13756                             src_reg->type == PTR_TO_PACKET) ||
13757                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13758                             src_reg->type == PTR_TO_PACKET_META)) {
13759                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13760                         find_good_pkt_pointers(other_branch, src_reg,
13761                                                src_reg->type, false);
13762                         mark_pkt_end(this_branch, insn->src_reg, true);
13763                 } else {
13764                         return false;
13765                 }
13766                 break;
13767         case BPF_JLE:
13768                 if ((dst_reg->type == PTR_TO_PACKET &&
13769                      src_reg->type == PTR_TO_PACKET_END) ||
13770                     (dst_reg->type == PTR_TO_PACKET_META &&
13771                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13772                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13773                         find_good_pkt_pointers(other_branch, dst_reg,
13774                                                dst_reg->type, false);
13775                         mark_pkt_end(this_branch, insn->dst_reg, true);
13776                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13777                             src_reg->type == PTR_TO_PACKET) ||
13778                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13779                             src_reg->type == PTR_TO_PACKET_META)) {
13780                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13781                         find_good_pkt_pointers(this_branch, src_reg,
13782                                                src_reg->type, true);
13783                         mark_pkt_end(other_branch, insn->src_reg, false);
13784                 } else {
13785                         return false;
13786                 }
13787                 break;
13788         default:
13789                 return false;
13790         }
13791
13792         return true;
13793 }
13794
13795 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13796                                struct bpf_reg_state *known_reg)
13797 {
13798         struct bpf_func_state *state;
13799         struct bpf_reg_state *reg;
13800
13801         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13802                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13803                         copy_register_state(reg, known_reg);
13804         }));
13805 }
13806
13807 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13808                              struct bpf_insn *insn, int *insn_idx)
13809 {
13810         struct bpf_verifier_state *this_branch = env->cur_state;
13811         struct bpf_verifier_state *other_branch;
13812         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13813         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13814         struct bpf_reg_state *eq_branch_regs;
13815         u8 opcode = BPF_OP(insn->code);
13816         bool is_jmp32;
13817         int pred = -1;
13818         int err;
13819
13820         /* Only conditional jumps are expected to reach here. */
13821         if (opcode == BPF_JA || opcode > BPF_JSLE) {
13822                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13823                 return -EINVAL;
13824         }
13825
13826         if (BPF_SRC(insn->code) == BPF_X) {
13827                 if (insn->imm != 0) {
13828                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13829                         return -EINVAL;
13830                 }
13831
13832                 /* check src1 operand */
13833                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13834                 if (err)
13835                         return err;
13836
13837                 if (is_pointer_value(env, insn->src_reg)) {
13838                         verbose(env, "R%d pointer comparison prohibited\n",
13839                                 insn->src_reg);
13840                         return -EACCES;
13841                 }
13842                 src_reg = &regs[insn->src_reg];
13843         } else {
13844                 if (insn->src_reg != BPF_REG_0) {
13845                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13846                         return -EINVAL;
13847                 }
13848         }
13849
13850         /* check src2 operand */
13851         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13852         if (err)
13853                 return err;
13854
13855         dst_reg = &regs[insn->dst_reg];
13856         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13857
13858         if (BPF_SRC(insn->code) == BPF_K) {
13859                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13860         } else if (src_reg->type == SCALAR_VALUE &&
13861                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13862                 pred = is_branch_taken(dst_reg,
13863                                        tnum_subreg(src_reg->var_off).value,
13864                                        opcode,
13865                                        is_jmp32);
13866         } else if (src_reg->type == SCALAR_VALUE &&
13867                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13868                 pred = is_branch_taken(dst_reg,
13869                                        src_reg->var_off.value,
13870                                        opcode,
13871                                        is_jmp32);
13872         } else if (dst_reg->type == SCALAR_VALUE &&
13873                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13874                 pred = is_branch_taken(src_reg,
13875                                        tnum_subreg(dst_reg->var_off).value,
13876                                        flip_opcode(opcode),
13877                                        is_jmp32);
13878         } else if (dst_reg->type == SCALAR_VALUE &&
13879                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13880                 pred = is_branch_taken(src_reg,
13881                                        dst_reg->var_off.value,
13882                                        flip_opcode(opcode),
13883                                        is_jmp32);
13884         } else if (reg_is_pkt_pointer_any(dst_reg) &&
13885                    reg_is_pkt_pointer_any(src_reg) &&
13886                    !is_jmp32) {
13887                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13888         }
13889
13890         if (pred >= 0) {
13891                 /* If we get here with a dst_reg pointer type it is because
13892                  * above is_branch_taken() special cased the 0 comparison.
13893                  */
13894                 if (!__is_pointer_value(false, dst_reg))
13895                         err = mark_chain_precision(env, insn->dst_reg);
13896                 if (BPF_SRC(insn->code) == BPF_X && !err &&
13897                     !__is_pointer_value(false, src_reg))
13898                         err = mark_chain_precision(env, insn->src_reg);
13899                 if (err)
13900                         return err;
13901         }
13902
13903         if (pred == 1) {
13904                 /* Only follow the goto, ignore fall-through. If needed, push
13905                  * the fall-through branch for simulation under speculative
13906                  * execution.
13907                  */
13908                 if (!env->bypass_spec_v1 &&
13909                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
13910                                                *insn_idx))
13911                         return -EFAULT;
13912                 *insn_idx += insn->off;
13913                 return 0;
13914         } else if (pred == 0) {
13915                 /* Only follow the fall-through branch, since that's where the
13916                  * program will go. If needed, push the goto branch for
13917                  * simulation under speculative execution.
13918                  */
13919                 if (!env->bypass_spec_v1 &&
13920                     !sanitize_speculative_path(env, insn,
13921                                                *insn_idx + insn->off + 1,
13922                                                *insn_idx))
13923                         return -EFAULT;
13924                 return 0;
13925         }
13926
13927         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13928                                   false);
13929         if (!other_branch)
13930                 return -EFAULT;
13931         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13932
13933         /* detect if we are comparing against a constant value so we can adjust
13934          * our min/max values for our dst register.
13935          * this is only legit if both are scalars (or pointers to the same
13936          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13937          * because otherwise the different base pointers mean the offsets aren't
13938          * comparable.
13939          */
13940         if (BPF_SRC(insn->code) == BPF_X) {
13941                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13942
13943                 if (dst_reg->type == SCALAR_VALUE &&
13944                     src_reg->type == SCALAR_VALUE) {
13945                         if (tnum_is_const(src_reg->var_off) ||
13946                             (is_jmp32 &&
13947                              tnum_is_const(tnum_subreg(src_reg->var_off))))
13948                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13949                                                 dst_reg,
13950                                                 src_reg->var_off.value,
13951                                                 tnum_subreg(src_reg->var_off).value,
13952                                                 opcode, is_jmp32);
13953                         else if (tnum_is_const(dst_reg->var_off) ||
13954                                  (is_jmp32 &&
13955                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
13956                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13957                                                     src_reg,
13958                                                     dst_reg->var_off.value,
13959                                                     tnum_subreg(dst_reg->var_off).value,
13960                                                     opcode, is_jmp32);
13961                         else if (!is_jmp32 &&
13962                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
13963                                 /* Comparing for equality, we can combine knowledge */
13964                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
13965                                                     &other_branch_regs[insn->dst_reg],
13966                                                     src_reg, dst_reg, opcode);
13967                         if (src_reg->id &&
13968                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13969                                 find_equal_scalars(this_branch, src_reg);
13970                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13971                         }
13972
13973                 }
13974         } else if (dst_reg->type == SCALAR_VALUE) {
13975                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13976                                         dst_reg, insn->imm, (u32)insn->imm,
13977                                         opcode, is_jmp32);
13978         }
13979
13980         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13981             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13982                 find_equal_scalars(this_branch, dst_reg);
13983                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13984         }
13985
13986         /* if one pointer register is compared to another pointer
13987          * register check if PTR_MAYBE_NULL could be lifted.
13988          * E.g. register A - maybe null
13989          *      register B - not null
13990          * for JNE A, B, ... - A is not null in the false branch;
13991          * for JEQ A, B, ... - A is not null in the true branch.
13992          *
13993          * Since PTR_TO_BTF_ID points to a kernel struct that does
13994          * not need to be null checked by the BPF program, i.e.,
13995          * could be null even without PTR_MAYBE_NULL marking, so
13996          * only propagate nullness when neither reg is that type.
13997          */
13998         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13999             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14000             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14001             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14002             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14003                 eq_branch_regs = NULL;
14004                 switch (opcode) {
14005                 case BPF_JEQ:
14006                         eq_branch_regs = other_branch_regs;
14007                         break;
14008                 case BPF_JNE:
14009                         eq_branch_regs = regs;
14010                         break;
14011                 default:
14012                         /* do nothing */
14013                         break;
14014                 }
14015                 if (eq_branch_regs) {
14016                         if (type_may_be_null(src_reg->type))
14017                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14018                         else
14019                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14020                 }
14021         }
14022
14023         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14024          * NOTE: these optimizations below are related with pointer comparison
14025          *       which will never be JMP32.
14026          */
14027         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14028             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14029             type_may_be_null(dst_reg->type)) {
14030                 /* Mark all identical registers in each branch as either
14031                  * safe or unknown depending R == 0 or R != 0 conditional.
14032                  */
14033                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14034                                       opcode == BPF_JNE);
14035                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14036                                       opcode == BPF_JEQ);
14037         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14038                                            this_branch, other_branch) &&
14039                    is_pointer_value(env, insn->dst_reg)) {
14040                 verbose(env, "R%d pointer comparison prohibited\n",
14041                         insn->dst_reg);
14042                 return -EACCES;
14043         }
14044         if (env->log.level & BPF_LOG_LEVEL)
14045                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14046         return 0;
14047 }
14048
14049 /* verify BPF_LD_IMM64 instruction */
14050 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14051 {
14052         struct bpf_insn_aux_data *aux = cur_aux(env);
14053         struct bpf_reg_state *regs = cur_regs(env);
14054         struct bpf_reg_state *dst_reg;
14055         struct bpf_map *map;
14056         int err;
14057
14058         if (BPF_SIZE(insn->code) != BPF_DW) {
14059                 verbose(env, "invalid BPF_LD_IMM insn\n");
14060                 return -EINVAL;
14061         }
14062         if (insn->off != 0) {
14063                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14064                 return -EINVAL;
14065         }
14066
14067         err = check_reg_arg(env, insn->dst_reg, DST_OP);
14068         if (err)
14069                 return err;
14070
14071         dst_reg = &regs[insn->dst_reg];
14072         if (insn->src_reg == 0) {
14073                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14074
14075                 dst_reg->type = SCALAR_VALUE;
14076                 __mark_reg_known(&regs[insn->dst_reg], imm);
14077                 return 0;
14078         }
14079
14080         /* All special src_reg cases are listed below. From this point onwards
14081          * we either succeed and assign a corresponding dst_reg->type after
14082          * zeroing the offset, or fail and reject the program.
14083          */
14084         mark_reg_known_zero(env, regs, insn->dst_reg);
14085
14086         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14087                 dst_reg->type = aux->btf_var.reg_type;
14088                 switch (base_type(dst_reg->type)) {
14089                 case PTR_TO_MEM:
14090                         dst_reg->mem_size = aux->btf_var.mem_size;
14091                         break;
14092                 case PTR_TO_BTF_ID:
14093                         dst_reg->btf = aux->btf_var.btf;
14094                         dst_reg->btf_id = aux->btf_var.btf_id;
14095                         break;
14096                 default:
14097                         verbose(env, "bpf verifier is misconfigured\n");
14098                         return -EFAULT;
14099                 }
14100                 return 0;
14101         }
14102
14103         if (insn->src_reg == BPF_PSEUDO_FUNC) {
14104                 struct bpf_prog_aux *aux = env->prog->aux;
14105                 u32 subprogno = find_subprog(env,
14106                                              env->insn_idx + insn->imm + 1);
14107
14108                 if (!aux->func_info) {
14109                         verbose(env, "missing btf func_info\n");
14110                         return -EINVAL;
14111                 }
14112                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14113                         verbose(env, "callback function not static\n");
14114                         return -EINVAL;
14115                 }
14116
14117                 dst_reg->type = PTR_TO_FUNC;
14118                 dst_reg->subprogno = subprogno;
14119                 return 0;
14120         }
14121
14122         map = env->used_maps[aux->map_index];
14123         dst_reg->map_ptr = map;
14124
14125         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14126             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14127                 dst_reg->type = PTR_TO_MAP_VALUE;
14128                 dst_reg->off = aux->map_off;
14129                 WARN_ON_ONCE(map->max_entries != 1);
14130                 /* We want reg->id to be same (0) as map_value is not distinct */
14131         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14132                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14133                 dst_reg->type = CONST_PTR_TO_MAP;
14134         } else {
14135                 verbose(env, "bpf verifier is misconfigured\n");
14136                 return -EINVAL;
14137         }
14138
14139         return 0;
14140 }
14141
14142 static bool may_access_skb(enum bpf_prog_type type)
14143 {
14144         switch (type) {
14145         case BPF_PROG_TYPE_SOCKET_FILTER:
14146         case BPF_PROG_TYPE_SCHED_CLS:
14147         case BPF_PROG_TYPE_SCHED_ACT:
14148                 return true;
14149         default:
14150                 return false;
14151         }
14152 }
14153
14154 /* verify safety of LD_ABS|LD_IND instructions:
14155  * - they can only appear in the programs where ctx == skb
14156  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14157  *   preserve R6-R9, and store return value into R0
14158  *
14159  * Implicit input:
14160  *   ctx == skb == R6 == CTX
14161  *
14162  * Explicit input:
14163  *   SRC == any register
14164  *   IMM == 32-bit immediate
14165  *
14166  * Output:
14167  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14168  */
14169 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14170 {
14171         struct bpf_reg_state *regs = cur_regs(env);
14172         static const int ctx_reg = BPF_REG_6;
14173         u8 mode = BPF_MODE(insn->code);
14174         int i, err;
14175
14176         if (!may_access_skb(resolve_prog_type(env->prog))) {
14177                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14178                 return -EINVAL;
14179         }
14180
14181         if (!env->ops->gen_ld_abs) {
14182                 verbose(env, "bpf verifier is misconfigured\n");
14183                 return -EINVAL;
14184         }
14185
14186         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14187             BPF_SIZE(insn->code) == BPF_DW ||
14188             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14189                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14190                 return -EINVAL;
14191         }
14192
14193         /* check whether implicit source operand (register R6) is readable */
14194         err = check_reg_arg(env, ctx_reg, SRC_OP);
14195         if (err)
14196                 return err;
14197
14198         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14199          * gen_ld_abs() may terminate the program at runtime, leading to
14200          * reference leak.
14201          */
14202         err = check_reference_leak(env);
14203         if (err) {
14204                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14205                 return err;
14206         }
14207
14208         if (env->cur_state->active_lock.ptr) {
14209                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14210                 return -EINVAL;
14211         }
14212
14213         if (env->cur_state->active_rcu_lock) {
14214                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14215                 return -EINVAL;
14216         }
14217
14218         if (regs[ctx_reg].type != PTR_TO_CTX) {
14219                 verbose(env,
14220                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14221                 return -EINVAL;
14222         }
14223
14224         if (mode == BPF_IND) {
14225                 /* check explicit source operand */
14226                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14227                 if (err)
14228                         return err;
14229         }
14230
14231         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14232         if (err < 0)
14233                 return err;
14234
14235         /* reset caller saved regs to unreadable */
14236         for (i = 0; i < CALLER_SAVED_REGS; i++) {
14237                 mark_reg_not_init(env, regs, caller_saved[i]);
14238                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14239         }
14240
14241         /* mark destination R0 register as readable, since it contains
14242          * the value fetched from the packet.
14243          * Already marked as written above.
14244          */
14245         mark_reg_unknown(env, regs, BPF_REG_0);
14246         /* ld_abs load up to 32-bit skb data. */
14247         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14248         return 0;
14249 }
14250
14251 static int check_return_code(struct bpf_verifier_env *env)
14252 {
14253         struct tnum enforce_attach_type_range = tnum_unknown;
14254         const struct bpf_prog *prog = env->prog;
14255         struct bpf_reg_state *reg;
14256         struct tnum range = tnum_range(0, 1);
14257         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14258         int err;
14259         struct bpf_func_state *frame = env->cur_state->frame[0];
14260         const bool is_subprog = frame->subprogno;
14261
14262         /* LSM and struct_ops func-ptr's return type could be "void" */
14263         if (!is_subprog) {
14264                 switch (prog_type) {
14265                 case BPF_PROG_TYPE_LSM:
14266                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
14267                                 /* See below, can be 0 or 0-1 depending on hook. */
14268                                 break;
14269                         fallthrough;
14270                 case BPF_PROG_TYPE_STRUCT_OPS:
14271                         if (!prog->aux->attach_func_proto->type)
14272                                 return 0;
14273                         break;
14274                 default:
14275                         break;
14276                 }
14277         }
14278
14279         /* eBPF calling convention is such that R0 is used
14280          * to return the value from eBPF program.
14281          * Make sure that it's readable at this time
14282          * of bpf_exit, which means that program wrote
14283          * something into it earlier
14284          */
14285         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14286         if (err)
14287                 return err;
14288
14289         if (is_pointer_value(env, BPF_REG_0)) {
14290                 verbose(env, "R0 leaks addr as return value\n");
14291                 return -EACCES;
14292         }
14293
14294         reg = cur_regs(env) + BPF_REG_0;
14295
14296         if (frame->in_async_callback_fn) {
14297                 /* enforce return zero from async callbacks like timer */
14298                 if (reg->type != SCALAR_VALUE) {
14299                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14300                                 reg_type_str(env, reg->type));
14301                         return -EINVAL;
14302                 }
14303
14304                 if (!tnum_in(tnum_const(0), reg->var_off)) {
14305                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14306                         return -EINVAL;
14307                 }
14308                 return 0;
14309         }
14310
14311         if (is_subprog) {
14312                 if (reg->type != SCALAR_VALUE) {
14313                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14314                                 reg_type_str(env, reg->type));
14315                         return -EINVAL;
14316                 }
14317                 return 0;
14318         }
14319
14320         switch (prog_type) {
14321         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14322                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14323                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14324                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14325                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14326                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14327                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14328                         range = tnum_range(1, 1);
14329                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14330                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14331                         range = tnum_range(0, 3);
14332                 break;
14333         case BPF_PROG_TYPE_CGROUP_SKB:
14334                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14335                         range = tnum_range(0, 3);
14336                         enforce_attach_type_range = tnum_range(2, 3);
14337                 }
14338                 break;
14339         case BPF_PROG_TYPE_CGROUP_SOCK:
14340         case BPF_PROG_TYPE_SOCK_OPS:
14341         case BPF_PROG_TYPE_CGROUP_DEVICE:
14342         case BPF_PROG_TYPE_CGROUP_SYSCTL:
14343         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14344                 break;
14345         case BPF_PROG_TYPE_RAW_TRACEPOINT:
14346                 if (!env->prog->aux->attach_btf_id)
14347                         return 0;
14348                 range = tnum_const(0);
14349                 break;
14350         case BPF_PROG_TYPE_TRACING:
14351                 switch (env->prog->expected_attach_type) {
14352                 case BPF_TRACE_FENTRY:
14353                 case BPF_TRACE_FEXIT:
14354                         range = tnum_const(0);
14355                         break;
14356                 case BPF_TRACE_RAW_TP:
14357                 case BPF_MODIFY_RETURN:
14358                         return 0;
14359                 case BPF_TRACE_ITER:
14360                         break;
14361                 default:
14362                         return -ENOTSUPP;
14363                 }
14364                 break;
14365         case BPF_PROG_TYPE_SK_LOOKUP:
14366                 range = tnum_range(SK_DROP, SK_PASS);
14367                 break;
14368
14369         case BPF_PROG_TYPE_LSM:
14370                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14371                         /* Regular BPF_PROG_TYPE_LSM programs can return
14372                          * any value.
14373                          */
14374                         return 0;
14375                 }
14376                 if (!env->prog->aux->attach_func_proto->type) {
14377                         /* Make sure programs that attach to void
14378                          * hooks don't try to modify return value.
14379                          */
14380                         range = tnum_range(1, 1);
14381                 }
14382                 break;
14383
14384         case BPF_PROG_TYPE_NETFILTER:
14385                 range = tnum_range(NF_DROP, NF_ACCEPT);
14386                 break;
14387         case BPF_PROG_TYPE_EXT:
14388                 /* freplace program can return anything as its return value
14389                  * depends on the to-be-replaced kernel func or bpf program.
14390                  */
14391         default:
14392                 return 0;
14393         }
14394
14395         if (reg->type != SCALAR_VALUE) {
14396                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14397                         reg_type_str(env, reg->type));
14398                 return -EINVAL;
14399         }
14400
14401         if (!tnum_in(range, reg->var_off)) {
14402                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14403                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14404                     prog_type == BPF_PROG_TYPE_LSM &&
14405                     !prog->aux->attach_func_proto->type)
14406                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14407                 return -EINVAL;
14408         }
14409
14410         if (!tnum_is_unknown(enforce_attach_type_range) &&
14411             tnum_in(enforce_attach_type_range, reg->var_off))
14412                 env->prog->enforce_expected_attach_type = 1;
14413         return 0;
14414 }
14415
14416 /* non-recursive DFS pseudo code
14417  * 1  procedure DFS-iterative(G,v):
14418  * 2      label v as discovered
14419  * 3      let S be a stack
14420  * 4      S.push(v)
14421  * 5      while S is not empty
14422  * 6            t <- S.peek()
14423  * 7            if t is what we're looking for:
14424  * 8                return t
14425  * 9            for all edges e in G.adjacentEdges(t) do
14426  * 10               if edge e is already labelled
14427  * 11                   continue with the next edge
14428  * 12               w <- G.adjacentVertex(t,e)
14429  * 13               if vertex w is not discovered and not explored
14430  * 14                   label e as tree-edge
14431  * 15                   label w as discovered
14432  * 16                   S.push(w)
14433  * 17                   continue at 5
14434  * 18               else if vertex w is discovered
14435  * 19                   label e as back-edge
14436  * 20               else
14437  * 21                   // vertex w is explored
14438  * 22                   label e as forward- or cross-edge
14439  * 23           label t as explored
14440  * 24           S.pop()
14441  *
14442  * convention:
14443  * 0x10 - discovered
14444  * 0x11 - discovered and fall-through edge labelled
14445  * 0x12 - discovered and fall-through and branch edges labelled
14446  * 0x20 - explored
14447  */
14448
14449 enum {
14450         DISCOVERED = 0x10,
14451         EXPLORED = 0x20,
14452         FALLTHROUGH = 1,
14453         BRANCH = 2,
14454 };
14455
14456 static u32 state_htab_size(struct bpf_verifier_env *env)
14457 {
14458         return env->prog->len;
14459 }
14460
14461 static struct bpf_verifier_state_list **explored_state(
14462                                         struct bpf_verifier_env *env,
14463                                         int idx)
14464 {
14465         struct bpf_verifier_state *cur = env->cur_state;
14466         struct bpf_func_state *state = cur->frame[cur->curframe];
14467
14468         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14469 }
14470
14471 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14472 {
14473         env->insn_aux_data[idx].prune_point = true;
14474 }
14475
14476 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14477 {
14478         return env->insn_aux_data[insn_idx].prune_point;
14479 }
14480
14481 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14482 {
14483         env->insn_aux_data[idx].force_checkpoint = true;
14484 }
14485
14486 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14487 {
14488         return env->insn_aux_data[insn_idx].force_checkpoint;
14489 }
14490
14491
14492 enum {
14493         DONE_EXPLORING = 0,
14494         KEEP_EXPLORING = 1,
14495 };
14496
14497 /* t, w, e - match pseudo-code above:
14498  * t - index of current instruction
14499  * w - next instruction
14500  * e - edge
14501  */
14502 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14503                      bool loop_ok)
14504 {
14505         int *insn_stack = env->cfg.insn_stack;
14506         int *insn_state = env->cfg.insn_state;
14507
14508         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14509                 return DONE_EXPLORING;
14510
14511         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14512                 return DONE_EXPLORING;
14513
14514         if (w < 0 || w >= env->prog->len) {
14515                 verbose_linfo(env, t, "%d: ", t);
14516                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14517                 return -EINVAL;
14518         }
14519
14520         if (e == BRANCH) {
14521                 /* mark branch target for state pruning */
14522                 mark_prune_point(env, w);
14523                 mark_jmp_point(env, w);
14524         }
14525
14526         if (insn_state[w] == 0) {
14527                 /* tree-edge */
14528                 insn_state[t] = DISCOVERED | e;
14529                 insn_state[w] = DISCOVERED;
14530                 if (env->cfg.cur_stack >= env->prog->len)
14531                         return -E2BIG;
14532                 insn_stack[env->cfg.cur_stack++] = w;
14533                 return KEEP_EXPLORING;
14534         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14535                 if (loop_ok && env->bpf_capable)
14536                         return DONE_EXPLORING;
14537                 verbose_linfo(env, t, "%d: ", t);
14538                 verbose_linfo(env, w, "%d: ", w);
14539                 verbose(env, "back-edge from insn %d to %d\n", t, w);
14540                 return -EINVAL;
14541         } else if (insn_state[w] == EXPLORED) {
14542                 /* forward- or cross-edge */
14543                 insn_state[t] = DISCOVERED | e;
14544         } else {
14545                 verbose(env, "insn state internal bug\n");
14546                 return -EFAULT;
14547         }
14548         return DONE_EXPLORING;
14549 }
14550
14551 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14552                                 struct bpf_verifier_env *env,
14553                                 bool visit_callee)
14554 {
14555         int ret;
14556
14557         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14558         if (ret)
14559                 return ret;
14560
14561         mark_prune_point(env, t + 1);
14562         /* when we exit from subprog, we need to record non-linear history */
14563         mark_jmp_point(env, t + 1);
14564
14565         if (visit_callee) {
14566                 mark_prune_point(env, t);
14567                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14568                                 /* It's ok to allow recursion from CFG point of
14569                                  * view. __check_func_call() will do the actual
14570                                  * check.
14571                                  */
14572                                 bpf_pseudo_func(insns + t));
14573         }
14574         return ret;
14575 }
14576
14577 /* Visits the instruction at index t and returns one of the following:
14578  *  < 0 - an error occurred
14579  *  DONE_EXPLORING - the instruction was fully explored
14580  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14581  */
14582 static int visit_insn(int t, struct bpf_verifier_env *env)
14583 {
14584         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14585         int ret;
14586
14587         if (bpf_pseudo_func(insn))
14588                 return visit_func_call_insn(t, insns, env, true);
14589
14590         /* All non-branch instructions have a single fall-through edge. */
14591         if (BPF_CLASS(insn->code) != BPF_JMP &&
14592             BPF_CLASS(insn->code) != BPF_JMP32)
14593                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14594
14595         switch (BPF_OP(insn->code)) {
14596         case BPF_EXIT:
14597                 return DONE_EXPLORING;
14598
14599         case BPF_CALL:
14600                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14601                         /* Mark this call insn as a prune point to trigger
14602                          * is_state_visited() check before call itself is
14603                          * processed by __check_func_call(). Otherwise new
14604                          * async state will be pushed for further exploration.
14605                          */
14606                         mark_prune_point(env, t);
14607                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14608                         struct bpf_kfunc_call_arg_meta meta;
14609
14610                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14611                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
14612                                 mark_prune_point(env, t);
14613                                 /* Checking and saving state checkpoints at iter_next() call
14614                                  * is crucial for fast convergence of open-coded iterator loop
14615                                  * logic, so we need to force it. If we don't do that,
14616                                  * is_state_visited() might skip saving a checkpoint, causing
14617                                  * unnecessarily long sequence of not checkpointed
14618                                  * instructions and jumps, leading to exhaustion of jump
14619                                  * history buffer, and potentially other undesired outcomes.
14620                                  * It is expected that with correct open-coded iterators
14621                                  * convergence will happen quickly, so we don't run a risk of
14622                                  * exhausting memory.
14623                                  */
14624                                 mark_force_checkpoint(env, t);
14625                         }
14626                 }
14627                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14628
14629         case BPF_JA:
14630                 if (BPF_SRC(insn->code) != BPF_K)
14631                         return -EINVAL;
14632
14633                 /* unconditional jump with single edge */
14634                 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14635                                 true);
14636                 if (ret)
14637                         return ret;
14638
14639                 mark_prune_point(env, t + insn->off + 1);
14640                 mark_jmp_point(env, t + insn->off + 1);
14641
14642                 return ret;
14643
14644         default:
14645                 /* conditional jump with two edges */
14646                 mark_prune_point(env, t);
14647
14648                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14649                 if (ret)
14650                         return ret;
14651
14652                 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14653         }
14654 }
14655
14656 /* non-recursive depth-first-search to detect loops in BPF program
14657  * loop == back-edge in directed graph
14658  */
14659 static int check_cfg(struct bpf_verifier_env *env)
14660 {
14661         int insn_cnt = env->prog->len;
14662         int *insn_stack, *insn_state;
14663         int ret = 0;
14664         int i;
14665
14666         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14667         if (!insn_state)
14668                 return -ENOMEM;
14669
14670         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14671         if (!insn_stack) {
14672                 kvfree(insn_state);
14673                 return -ENOMEM;
14674         }
14675
14676         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14677         insn_stack[0] = 0; /* 0 is the first instruction */
14678         env->cfg.cur_stack = 1;
14679
14680         while (env->cfg.cur_stack > 0) {
14681                 int t = insn_stack[env->cfg.cur_stack - 1];
14682
14683                 ret = visit_insn(t, env);
14684                 switch (ret) {
14685                 case DONE_EXPLORING:
14686                         insn_state[t] = EXPLORED;
14687                         env->cfg.cur_stack--;
14688                         break;
14689                 case KEEP_EXPLORING:
14690                         break;
14691                 default:
14692                         if (ret > 0) {
14693                                 verbose(env, "visit_insn internal bug\n");
14694                                 ret = -EFAULT;
14695                         }
14696                         goto err_free;
14697                 }
14698         }
14699
14700         if (env->cfg.cur_stack < 0) {
14701                 verbose(env, "pop stack internal bug\n");
14702                 ret = -EFAULT;
14703                 goto err_free;
14704         }
14705
14706         for (i = 0; i < insn_cnt; i++) {
14707                 if (insn_state[i] != EXPLORED) {
14708                         verbose(env, "unreachable insn %d\n", i);
14709                         ret = -EINVAL;
14710                         goto err_free;
14711                 }
14712         }
14713         ret = 0; /* cfg looks good */
14714
14715 err_free:
14716         kvfree(insn_state);
14717         kvfree(insn_stack);
14718         env->cfg.insn_state = env->cfg.insn_stack = NULL;
14719         return ret;
14720 }
14721
14722 static int check_abnormal_return(struct bpf_verifier_env *env)
14723 {
14724         int i;
14725
14726         for (i = 1; i < env->subprog_cnt; i++) {
14727                 if (env->subprog_info[i].has_ld_abs) {
14728                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14729                         return -EINVAL;
14730                 }
14731                 if (env->subprog_info[i].has_tail_call) {
14732                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14733                         return -EINVAL;
14734                 }
14735         }
14736         return 0;
14737 }
14738
14739 /* The minimum supported BTF func info size */
14740 #define MIN_BPF_FUNCINFO_SIZE   8
14741 #define MAX_FUNCINFO_REC_SIZE   252
14742
14743 static int check_btf_func(struct bpf_verifier_env *env,
14744                           const union bpf_attr *attr,
14745                           bpfptr_t uattr)
14746 {
14747         const struct btf_type *type, *func_proto, *ret_type;
14748         u32 i, nfuncs, urec_size, min_size;
14749         u32 krec_size = sizeof(struct bpf_func_info);
14750         struct bpf_func_info *krecord;
14751         struct bpf_func_info_aux *info_aux = NULL;
14752         struct bpf_prog *prog;
14753         const struct btf *btf;
14754         bpfptr_t urecord;
14755         u32 prev_offset = 0;
14756         bool scalar_return;
14757         int ret = -ENOMEM;
14758
14759         nfuncs = attr->func_info_cnt;
14760         if (!nfuncs) {
14761                 if (check_abnormal_return(env))
14762                         return -EINVAL;
14763                 return 0;
14764         }
14765
14766         if (nfuncs != env->subprog_cnt) {
14767                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14768                 return -EINVAL;
14769         }
14770
14771         urec_size = attr->func_info_rec_size;
14772         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14773             urec_size > MAX_FUNCINFO_REC_SIZE ||
14774             urec_size % sizeof(u32)) {
14775                 verbose(env, "invalid func info rec size %u\n", urec_size);
14776                 return -EINVAL;
14777         }
14778
14779         prog = env->prog;
14780         btf = prog->aux->btf;
14781
14782         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14783         min_size = min_t(u32, krec_size, urec_size);
14784
14785         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14786         if (!krecord)
14787                 return -ENOMEM;
14788         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14789         if (!info_aux)
14790                 goto err_free;
14791
14792         for (i = 0; i < nfuncs; i++) {
14793                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14794                 if (ret) {
14795                         if (ret == -E2BIG) {
14796                                 verbose(env, "nonzero tailing record in func info");
14797                                 /* set the size kernel expects so loader can zero
14798                                  * out the rest of the record.
14799                                  */
14800                                 if (copy_to_bpfptr_offset(uattr,
14801                                                           offsetof(union bpf_attr, func_info_rec_size),
14802                                                           &min_size, sizeof(min_size)))
14803                                         ret = -EFAULT;
14804                         }
14805                         goto err_free;
14806                 }
14807
14808                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14809                         ret = -EFAULT;
14810                         goto err_free;
14811                 }
14812
14813                 /* check insn_off */
14814                 ret = -EINVAL;
14815                 if (i == 0) {
14816                         if (krecord[i].insn_off) {
14817                                 verbose(env,
14818                                         "nonzero insn_off %u for the first func info record",
14819                                         krecord[i].insn_off);
14820                                 goto err_free;
14821                         }
14822                 } else if (krecord[i].insn_off <= prev_offset) {
14823                         verbose(env,
14824                                 "same or smaller insn offset (%u) than previous func info record (%u)",
14825                                 krecord[i].insn_off, prev_offset);
14826                         goto err_free;
14827                 }
14828
14829                 if (env->subprog_info[i].start != krecord[i].insn_off) {
14830                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14831                         goto err_free;
14832                 }
14833
14834                 /* check type_id */
14835                 type = btf_type_by_id(btf, krecord[i].type_id);
14836                 if (!type || !btf_type_is_func(type)) {
14837                         verbose(env, "invalid type id %d in func info",
14838                                 krecord[i].type_id);
14839                         goto err_free;
14840                 }
14841                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14842
14843                 func_proto = btf_type_by_id(btf, type->type);
14844                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14845                         /* btf_func_check() already verified it during BTF load */
14846                         goto err_free;
14847                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14848                 scalar_return =
14849                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14850                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14851                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14852                         goto err_free;
14853                 }
14854                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14855                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14856                         goto err_free;
14857                 }
14858
14859                 prev_offset = krecord[i].insn_off;
14860                 bpfptr_add(&urecord, urec_size);
14861         }
14862
14863         prog->aux->func_info = krecord;
14864         prog->aux->func_info_cnt = nfuncs;
14865         prog->aux->func_info_aux = info_aux;
14866         return 0;
14867
14868 err_free:
14869         kvfree(krecord);
14870         kfree(info_aux);
14871         return ret;
14872 }
14873
14874 static void adjust_btf_func(struct bpf_verifier_env *env)
14875 {
14876         struct bpf_prog_aux *aux = env->prog->aux;
14877         int i;
14878
14879         if (!aux->func_info)
14880                 return;
14881
14882         for (i = 0; i < env->subprog_cnt; i++)
14883                 aux->func_info[i].insn_off = env->subprog_info[i].start;
14884 }
14885
14886 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
14887 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
14888
14889 static int check_btf_line(struct bpf_verifier_env *env,
14890                           const union bpf_attr *attr,
14891                           bpfptr_t uattr)
14892 {
14893         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14894         struct bpf_subprog_info *sub;
14895         struct bpf_line_info *linfo;
14896         struct bpf_prog *prog;
14897         const struct btf *btf;
14898         bpfptr_t ulinfo;
14899         int err;
14900
14901         nr_linfo = attr->line_info_cnt;
14902         if (!nr_linfo)
14903                 return 0;
14904         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14905                 return -EINVAL;
14906
14907         rec_size = attr->line_info_rec_size;
14908         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14909             rec_size > MAX_LINEINFO_REC_SIZE ||
14910             rec_size & (sizeof(u32) - 1))
14911                 return -EINVAL;
14912
14913         /* Need to zero it in case the userspace may
14914          * pass in a smaller bpf_line_info object.
14915          */
14916         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14917                          GFP_KERNEL | __GFP_NOWARN);
14918         if (!linfo)
14919                 return -ENOMEM;
14920
14921         prog = env->prog;
14922         btf = prog->aux->btf;
14923
14924         s = 0;
14925         sub = env->subprog_info;
14926         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14927         expected_size = sizeof(struct bpf_line_info);
14928         ncopy = min_t(u32, expected_size, rec_size);
14929         for (i = 0; i < nr_linfo; i++) {
14930                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14931                 if (err) {
14932                         if (err == -E2BIG) {
14933                                 verbose(env, "nonzero tailing record in line_info");
14934                                 if (copy_to_bpfptr_offset(uattr,
14935                                                           offsetof(union bpf_attr, line_info_rec_size),
14936                                                           &expected_size, sizeof(expected_size)))
14937                                         err = -EFAULT;
14938                         }
14939                         goto err_free;
14940                 }
14941
14942                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14943                         err = -EFAULT;
14944                         goto err_free;
14945                 }
14946
14947                 /*
14948                  * Check insn_off to ensure
14949                  * 1) strictly increasing AND
14950                  * 2) bounded by prog->len
14951                  *
14952                  * The linfo[0].insn_off == 0 check logically falls into
14953                  * the later "missing bpf_line_info for func..." case
14954                  * because the first linfo[0].insn_off must be the
14955                  * first sub also and the first sub must have
14956                  * subprog_info[0].start == 0.
14957                  */
14958                 if ((i && linfo[i].insn_off <= prev_offset) ||
14959                     linfo[i].insn_off >= prog->len) {
14960                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14961                                 i, linfo[i].insn_off, prev_offset,
14962                                 prog->len);
14963                         err = -EINVAL;
14964                         goto err_free;
14965                 }
14966
14967                 if (!prog->insnsi[linfo[i].insn_off].code) {
14968                         verbose(env,
14969                                 "Invalid insn code at line_info[%u].insn_off\n",
14970                                 i);
14971                         err = -EINVAL;
14972                         goto err_free;
14973                 }
14974
14975                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14976                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14977                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14978                         err = -EINVAL;
14979                         goto err_free;
14980                 }
14981
14982                 if (s != env->subprog_cnt) {
14983                         if (linfo[i].insn_off == sub[s].start) {
14984                                 sub[s].linfo_idx = i;
14985                                 s++;
14986                         } else if (sub[s].start < linfo[i].insn_off) {
14987                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
14988                                 err = -EINVAL;
14989                                 goto err_free;
14990                         }
14991                 }
14992
14993                 prev_offset = linfo[i].insn_off;
14994                 bpfptr_add(&ulinfo, rec_size);
14995         }
14996
14997         if (s != env->subprog_cnt) {
14998                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14999                         env->subprog_cnt - s, s);
15000                 err = -EINVAL;
15001                 goto err_free;
15002         }
15003
15004         prog->aux->linfo = linfo;
15005         prog->aux->nr_linfo = nr_linfo;
15006
15007         return 0;
15008
15009 err_free:
15010         kvfree(linfo);
15011         return err;
15012 }
15013
15014 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
15015 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
15016
15017 static int check_core_relo(struct bpf_verifier_env *env,
15018                            const union bpf_attr *attr,
15019                            bpfptr_t uattr)
15020 {
15021         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15022         struct bpf_core_relo core_relo = {};
15023         struct bpf_prog *prog = env->prog;
15024         const struct btf *btf = prog->aux->btf;
15025         struct bpf_core_ctx ctx = {
15026                 .log = &env->log,
15027                 .btf = btf,
15028         };
15029         bpfptr_t u_core_relo;
15030         int err;
15031
15032         nr_core_relo = attr->core_relo_cnt;
15033         if (!nr_core_relo)
15034                 return 0;
15035         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15036                 return -EINVAL;
15037
15038         rec_size = attr->core_relo_rec_size;
15039         if (rec_size < MIN_CORE_RELO_SIZE ||
15040             rec_size > MAX_CORE_RELO_SIZE ||
15041             rec_size % sizeof(u32))
15042                 return -EINVAL;
15043
15044         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15045         expected_size = sizeof(struct bpf_core_relo);
15046         ncopy = min_t(u32, expected_size, rec_size);
15047
15048         /* Unlike func_info and line_info, copy and apply each CO-RE
15049          * relocation record one at a time.
15050          */
15051         for (i = 0; i < nr_core_relo; i++) {
15052                 /* future proofing when sizeof(bpf_core_relo) changes */
15053                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15054                 if (err) {
15055                         if (err == -E2BIG) {
15056                                 verbose(env, "nonzero tailing record in core_relo");
15057                                 if (copy_to_bpfptr_offset(uattr,
15058                                                           offsetof(union bpf_attr, core_relo_rec_size),
15059                                                           &expected_size, sizeof(expected_size)))
15060                                         err = -EFAULT;
15061                         }
15062                         break;
15063                 }
15064
15065                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15066                         err = -EFAULT;
15067                         break;
15068                 }
15069
15070                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15071                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15072                                 i, core_relo.insn_off, prog->len);
15073                         err = -EINVAL;
15074                         break;
15075                 }
15076
15077                 err = bpf_core_apply(&ctx, &core_relo, i,
15078                                      &prog->insnsi[core_relo.insn_off / 8]);
15079                 if (err)
15080                         break;
15081                 bpfptr_add(&u_core_relo, rec_size);
15082         }
15083         return err;
15084 }
15085
15086 static int check_btf_info(struct bpf_verifier_env *env,
15087                           const union bpf_attr *attr,
15088                           bpfptr_t uattr)
15089 {
15090         struct btf *btf;
15091         int err;
15092
15093         if (!attr->func_info_cnt && !attr->line_info_cnt) {
15094                 if (check_abnormal_return(env))
15095                         return -EINVAL;
15096                 return 0;
15097         }
15098
15099         btf = btf_get_by_fd(attr->prog_btf_fd);
15100         if (IS_ERR(btf))
15101                 return PTR_ERR(btf);
15102         if (btf_is_kernel(btf)) {
15103                 btf_put(btf);
15104                 return -EACCES;
15105         }
15106         env->prog->aux->btf = btf;
15107
15108         err = check_btf_func(env, attr, uattr);
15109         if (err)
15110                 return err;
15111
15112         err = check_btf_line(env, attr, uattr);
15113         if (err)
15114                 return err;
15115
15116         err = check_core_relo(env, attr, uattr);
15117         if (err)
15118                 return err;
15119
15120         return 0;
15121 }
15122
15123 /* check %cur's range satisfies %old's */
15124 static bool range_within(struct bpf_reg_state *old,
15125                          struct bpf_reg_state *cur)
15126 {
15127         return old->umin_value <= cur->umin_value &&
15128                old->umax_value >= cur->umax_value &&
15129                old->smin_value <= cur->smin_value &&
15130                old->smax_value >= cur->smax_value &&
15131                old->u32_min_value <= cur->u32_min_value &&
15132                old->u32_max_value >= cur->u32_max_value &&
15133                old->s32_min_value <= cur->s32_min_value &&
15134                old->s32_max_value >= cur->s32_max_value;
15135 }
15136
15137 /* If in the old state two registers had the same id, then they need to have
15138  * the same id in the new state as well.  But that id could be different from
15139  * the old state, so we need to track the mapping from old to new ids.
15140  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15141  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15142  * regs with a different old id could still have new id 9, we don't care about
15143  * that.
15144  * So we look through our idmap to see if this old id has been seen before.  If
15145  * so, we require the new id to match; otherwise, we add the id pair to the map.
15146  */
15147 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15148 {
15149         struct bpf_id_pair *map = idmap->map;
15150         unsigned int i;
15151
15152         /* either both IDs should be set or both should be zero */
15153         if (!!old_id != !!cur_id)
15154                 return false;
15155
15156         if (old_id == 0) /* cur_id == 0 as well */
15157                 return true;
15158
15159         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15160                 if (!map[i].old) {
15161                         /* Reached an empty slot; haven't seen this id before */
15162                         map[i].old = old_id;
15163                         map[i].cur = cur_id;
15164                         return true;
15165                 }
15166                 if (map[i].old == old_id)
15167                         return map[i].cur == cur_id;
15168                 if (map[i].cur == cur_id)
15169                         return false;
15170         }
15171         /* We ran out of idmap slots, which should be impossible */
15172         WARN_ON_ONCE(1);
15173         return false;
15174 }
15175
15176 /* Similar to check_ids(), but allocate a unique temporary ID
15177  * for 'old_id' or 'cur_id' of zero.
15178  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15179  */
15180 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15181 {
15182         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15183         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15184
15185         return check_ids(old_id, cur_id, idmap);
15186 }
15187
15188 static void clean_func_state(struct bpf_verifier_env *env,
15189                              struct bpf_func_state *st)
15190 {
15191         enum bpf_reg_liveness live;
15192         int i, j;
15193
15194         for (i = 0; i < BPF_REG_FP; i++) {
15195                 live = st->regs[i].live;
15196                 /* liveness must not touch this register anymore */
15197                 st->regs[i].live |= REG_LIVE_DONE;
15198                 if (!(live & REG_LIVE_READ))
15199                         /* since the register is unused, clear its state
15200                          * to make further comparison simpler
15201                          */
15202                         __mark_reg_not_init(env, &st->regs[i]);
15203         }
15204
15205         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15206                 live = st->stack[i].spilled_ptr.live;
15207                 /* liveness must not touch this stack slot anymore */
15208                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15209                 if (!(live & REG_LIVE_READ)) {
15210                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15211                         for (j = 0; j < BPF_REG_SIZE; j++)
15212                                 st->stack[i].slot_type[j] = STACK_INVALID;
15213                 }
15214         }
15215 }
15216
15217 static void clean_verifier_state(struct bpf_verifier_env *env,
15218                                  struct bpf_verifier_state *st)
15219 {
15220         int i;
15221
15222         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15223                 /* all regs in this state in all frames were already marked */
15224                 return;
15225
15226         for (i = 0; i <= st->curframe; i++)
15227                 clean_func_state(env, st->frame[i]);
15228 }
15229
15230 /* the parentage chains form a tree.
15231  * the verifier states are added to state lists at given insn and
15232  * pushed into state stack for future exploration.
15233  * when the verifier reaches bpf_exit insn some of the verifer states
15234  * stored in the state lists have their final liveness state already,
15235  * but a lot of states will get revised from liveness point of view when
15236  * the verifier explores other branches.
15237  * Example:
15238  * 1: r0 = 1
15239  * 2: if r1 == 100 goto pc+1
15240  * 3: r0 = 2
15241  * 4: exit
15242  * when the verifier reaches exit insn the register r0 in the state list of
15243  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15244  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15245  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15246  *
15247  * Since the verifier pushes the branch states as it sees them while exploring
15248  * the program the condition of walking the branch instruction for the second
15249  * time means that all states below this branch were already explored and
15250  * their final liveness marks are already propagated.
15251  * Hence when the verifier completes the search of state list in is_state_visited()
15252  * we can call this clean_live_states() function to mark all liveness states
15253  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15254  * will not be used.
15255  * This function also clears the registers and stack for states that !READ
15256  * to simplify state merging.
15257  *
15258  * Important note here that walking the same branch instruction in the callee
15259  * doesn't meant that the states are DONE. The verifier has to compare
15260  * the callsites
15261  */
15262 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15263                               struct bpf_verifier_state *cur)
15264 {
15265         struct bpf_verifier_state_list *sl;
15266         int i;
15267
15268         sl = *explored_state(env, insn);
15269         while (sl) {
15270                 if (sl->state.branches)
15271                         goto next;
15272                 if (sl->state.insn_idx != insn ||
15273                     sl->state.curframe != cur->curframe)
15274                         goto next;
15275                 for (i = 0; i <= cur->curframe; i++)
15276                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15277                                 goto next;
15278                 clean_verifier_state(env, &sl->state);
15279 next:
15280                 sl = sl->next;
15281         }
15282 }
15283
15284 static bool regs_exact(const struct bpf_reg_state *rold,
15285                        const struct bpf_reg_state *rcur,
15286                        struct bpf_idmap *idmap)
15287 {
15288         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15289                check_ids(rold->id, rcur->id, idmap) &&
15290                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15291 }
15292
15293 /* Returns true if (rold safe implies rcur safe) */
15294 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15295                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15296 {
15297         if (!(rold->live & REG_LIVE_READ))
15298                 /* explored state didn't use this */
15299                 return true;
15300         if (rold->type == NOT_INIT)
15301                 /* explored state can't have used this */
15302                 return true;
15303         if (rcur->type == NOT_INIT)
15304                 return false;
15305
15306         /* Enforce that register types have to match exactly, including their
15307          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15308          * rule.
15309          *
15310          * One can make a point that using a pointer register as unbounded
15311          * SCALAR would be technically acceptable, but this could lead to
15312          * pointer leaks because scalars are allowed to leak while pointers
15313          * are not. We could make this safe in special cases if root is
15314          * calling us, but it's probably not worth the hassle.
15315          *
15316          * Also, register types that are *not* MAYBE_NULL could technically be
15317          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15318          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15319          * to the same map).
15320          * However, if the old MAYBE_NULL register then got NULL checked,
15321          * doing so could have affected others with the same id, and we can't
15322          * check for that because we lost the id when we converted to
15323          * a non-MAYBE_NULL variant.
15324          * So, as a general rule we don't allow mixing MAYBE_NULL and
15325          * non-MAYBE_NULL registers as well.
15326          */
15327         if (rold->type != rcur->type)
15328                 return false;
15329
15330         switch (base_type(rold->type)) {
15331         case SCALAR_VALUE:
15332                 if (env->explore_alu_limits) {
15333                         /* explore_alu_limits disables tnum_in() and range_within()
15334                          * logic and requires everything to be strict
15335                          */
15336                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15337                                check_scalar_ids(rold->id, rcur->id, idmap);
15338                 }
15339                 if (!rold->precise)
15340                         return true;
15341                 /* Why check_ids() for scalar registers?
15342                  *
15343                  * Consider the following BPF code:
15344                  *   1: r6 = ... unbound scalar, ID=a ...
15345                  *   2: r7 = ... unbound scalar, ID=b ...
15346                  *   3: if (r6 > r7) goto +1
15347                  *   4: r6 = r7
15348                  *   5: if (r6 > X) goto ...
15349                  *   6: ... memory operation using r7 ...
15350                  *
15351                  * First verification path is [1-6]:
15352                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15353                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15354                  *   r7 <= X, because r6 and r7 share same id.
15355                  * Next verification path is [1-4, 6].
15356                  *
15357                  * Instruction (6) would be reached in two states:
15358                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15359                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15360                  *
15361                  * Use check_ids() to distinguish these states.
15362                  * ---
15363                  * Also verify that new value satisfies old value range knowledge.
15364                  */
15365                 return range_within(rold, rcur) &&
15366                        tnum_in(rold->var_off, rcur->var_off) &&
15367                        check_scalar_ids(rold->id, rcur->id, idmap);
15368         case PTR_TO_MAP_KEY:
15369         case PTR_TO_MAP_VALUE:
15370         case PTR_TO_MEM:
15371         case PTR_TO_BUF:
15372         case PTR_TO_TP_BUFFER:
15373                 /* If the new min/max/var_off satisfy the old ones and
15374                  * everything else matches, we are OK.
15375                  */
15376                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15377                        range_within(rold, rcur) &&
15378                        tnum_in(rold->var_off, rcur->var_off) &&
15379                        check_ids(rold->id, rcur->id, idmap) &&
15380                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15381         case PTR_TO_PACKET_META:
15382         case PTR_TO_PACKET:
15383                 /* We must have at least as much range as the old ptr
15384                  * did, so that any accesses which were safe before are
15385                  * still safe.  This is true even if old range < old off,
15386                  * since someone could have accessed through (ptr - k), or
15387                  * even done ptr -= k in a register, to get a safe access.
15388                  */
15389                 if (rold->range > rcur->range)
15390                         return false;
15391                 /* If the offsets don't match, we can't trust our alignment;
15392                  * nor can we be sure that we won't fall out of range.
15393                  */
15394                 if (rold->off != rcur->off)
15395                         return false;
15396                 /* id relations must be preserved */
15397                 if (!check_ids(rold->id, rcur->id, idmap))
15398                         return false;
15399                 /* new val must satisfy old val knowledge */
15400                 return range_within(rold, rcur) &&
15401                        tnum_in(rold->var_off, rcur->var_off);
15402         case PTR_TO_STACK:
15403                 /* two stack pointers are equal only if they're pointing to
15404                  * the same stack frame, since fp-8 in foo != fp-8 in bar
15405                  */
15406                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15407         default:
15408                 return regs_exact(rold, rcur, idmap);
15409         }
15410 }
15411
15412 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15413                       struct bpf_func_state *cur, struct bpf_idmap *idmap)
15414 {
15415         int i, spi;
15416
15417         /* walk slots of the explored stack and ignore any additional
15418          * slots in the current stack, since explored(safe) state
15419          * didn't use them
15420          */
15421         for (i = 0; i < old->allocated_stack; i++) {
15422                 struct bpf_reg_state *old_reg, *cur_reg;
15423
15424                 spi = i / BPF_REG_SIZE;
15425
15426                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15427                         i += BPF_REG_SIZE - 1;
15428                         /* explored state didn't use this */
15429                         continue;
15430                 }
15431
15432                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15433                         continue;
15434
15435                 if (env->allow_uninit_stack &&
15436                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15437                         continue;
15438
15439                 /* explored stack has more populated slots than current stack
15440                  * and these slots were used
15441                  */
15442                 if (i >= cur->allocated_stack)
15443                         return false;
15444
15445                 /* if old state was safe with misc data in the stack
15446                  * it will be safe with zero-initialized stack.
15447                  * The opposite is not true
15448                  */
15449                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15450                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15451                         continue;
15452                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15453                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15454                         /* Ex: old explored (safe) state has STACK_SPILL in
15455                          * this stack slot, but current has STACK_MISC ->
15456                          * this verifier states are not equivalent,
15457                          * return false to continue verification of this path
15458                          */
15459                         return false;
15460                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15461                         continue;
15462                 /* Both old and cur are having same slot_type */
15463                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15464                 case STACK_SPILL:
15465                         /* when explored and current stack slot are both storing
15466                          * spilled registers, check that stored pointers types
15467                          * are the same as well.
15468                          * Ex: explored safe path could have stored
15469                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15470                          * but current path has stored:
15471                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15472                          * such verifier states are not equivalent.
15473                          * return false to continue verification of this path
15474                          */
15475                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
15476                                      &cur->stack[spi].spilled_ptr, idmap))
15477                                 return false;
15478                         break;
15479                 case STACK_DYNPTR:
15480                         old_reg = &old->stack[spi].spilled_ptr;
15481                         cur_reg = &cur->stack[spi].spilled_ptr;
15482                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15483                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15484                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15485                                 return false;
15486                         break;
15487                 case STACK_ITER:
15488                         old_reg = &old->stack[spi].spilled_ptr;
15489                         cur_reg = &cur->stack[spi].spilled_ptr;
15490                         /* iter.depth is not compared between states as it
15491                          * doesn't matter for correctness and would otherwise
15492                          * prevent convergence; we maintain it only to prevent
15493                          * infinite loop check triggering, see
15494                          * iter_active_depths_differ()
15495                          */
15496                         if (old_reg->iter.btf != cur_reg->iter.btf ||
15497                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15498                             old_reg->iter.state != cur_reg->iter.state ||
15499                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
15500                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15501                                 return false;
15502                         break;
15503                 case STACK_MISC:
15504                 case STACK_ZERO:
15505                 case STACK_INVALID:
15506                         continue;
15507                 /* Ensure that new unhandled slot types return false by default */
15508                 default:
15509                         return false;
15510                 }
15511         }
15512         return true;
15513 }
15514
15515 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15516                     struct bpf_idmap *idmap)
15517 {
15518         int i;
15519
15520         if (old->acquired_refs != cur->acquired_refs)
15521                 return false;
15522
15523         for (i = 0; i < old->acquired_refs; i++) {
15524                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15525                         return false;
15526         }
15527
15528         return true;
15529 }
15530
15531 /* compare two verifier states
15532  *
15533  * all states stored in state_list are known to be valid, since
15534  * verifier reached 'bpf_exit' instruction through them
15535  *
15536  * this function is called when verifier exploring different branches of
15537  * execution popped from the state stack. If it sees an old state that has
15538  * more strict register state and more strict stack state then this execution
15539  * branch doesn't need to be explored further, since verifier already
15540  * concluded that more strict state leads to valid finish.
15541  *
15542  * Therefore two states are equivalent if register state is more conservative
15543  * and explored stack state is more conservative than the current one.
15544  * Example:
15545  *       explored                   current
15546  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15547  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15548  *
15549  * In other words if current stack state (one being explored) has more
15550  * valid slots than old one that already passed validation, it means
15551  * the verifier can stop exploring and conclude that current state is valid too
15552  *
15553  * Similarly with registers. If explored state has register type as invalid
15554  * whereas register type in current state is meaningful, it means that
15555  * the current state will reach 'bpf_exit' instruction safely
15556  */
15557 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15558                               struct bpf_func_state *cur)
15559 {
15560         int i;
15561
15562         for (i = 0; i < MAX_BPF_REG; i++)
15563                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15564                              &env->idmap_scratch))
15565                         return false;
15566
15567         if (!stacksafe(env, old, cur, &env->idmap_scratch))
15568                 return false;
15569
15570         if (!refsafe(old, cur, &env->idmap_scratch))
15571                 return false;
15572
15573         return true;
15574 }
15575
15576 static bool states_equal(struct bpf_verifier_env *env,
15577                          struct bpf_verifier_state *old,
15578                          struct bpf_verifier_state *cur)
15579 {
15580         int i;
15581
15582         if (old->curframe != cur->curframe)
15583                 return false;
15584
15585         env->idmap_scratch.tmp_id_gen = env->id_gen;
15586         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15587
15588         /* Verification state from speculative execution simulation
15589          * must never prune a non-speculative execution one.
15590          */
15591         if (old->speculative && !cur->speculative)
15592                 return false;
15593
15594         if (old->active_lock.ptr != cur->active_lock.ptr)
15595                 return false;
15596
15597         /* Old and cur active_lock's have to be either both present
15598          * or both absent.
15599          */
15600         if (!!old->active_lock.id != !!cur->active_lock.id)
15601                 return false;
15602
15603         if (old->active_lock.id &&
15604             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15605                 return false;
15606
15607         if (old->active_rcu_lock != cur->active_rcu_lock)
15608                 return false;
15609
15610         /* for states to be equal callsites have to be the same
15611          * and all frame states need to be equivalent
15612          */
15613         for (i = 0; i <= old->curframe; i++) {
15614                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15615                         return false;
15616                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15617                         return false;
15618         }
15619         return true;
15620 }
15621
15622 /* Return 0 if no propagation happened. Return negative error code if error
15623  * happened. Otherwise, return the propagated bit.
15624  */
15625 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15626                                   struct bpf_reg_state *reg,
15627                                   struct bpf_reg_state *parent_reg)
15628 {
15629         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15630         u8 flag = reg->live & REG_LIVE_READ;
15631         int err;
15632
15633         /* When comes here, read flags of PARENT_REG or REG could be any of
15634          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15635          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15636          */
15637         if (parent_flag == REG_LIVE_READ64 ||
15638             /* Or if there is no read flag from REG. */
15639             !flag ||
15640             /* Or if the read flag from REG is the same as PARENT_REG. */
15641             parent_flag == flag)
15642                 return 0;
15643
15644         err = mark_reg_read(env, reg, parent_reg, flag);
15645         if (err)
15646                 return err;
15647
15648         return flag;
15649 }
15650
15651 /* A write screens off any subsequent reads; but write marks come from the
15652  * straight-line code between a state and its parent.  When we arrive at an
15653  * equivalent state (jump target or such) we didn't arrive by the straight-line
15654  * code, so read marks in the state must propagate to the parent regardless
15655  * of the state's write marks. That's what 'parent == state->parent' comparison
15656  * in mark_reg_read() is for.
15657  */
15658 static int propagate_liveness(struct bpf_verifier_env *env,
15659                               const struct bpf_verifier_state *vstate,
15660                               struct bpf_verifier_state *vparent)
15661 {
15662         struct bpf_reg_state *state_reg, *parent_reg;
15663         struct bpf_func_state *state, *parent;
15664         int i, frame, err = 0;
15665
15666         if (vparent->curframe != vstate->curframe) {
15667                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15668                      vparent->curframe, vstate->curframe);
15669                 return -EFAULT;
15670         }
15671         /* Propagate read liveness of registers... */
15672         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15673         for (frame = 0; frame <= vstate->curframe; frame++) {
15674                 parent = vparent->frame[frame];
15675                 state = vstate->frame[frame];
15676                 parent_reg = parent->regs;
15677                 state_reg = state->regs;
15678                 /* We don't need to worry about FP liveness, it's read-only */
15679                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15680                         err = propagate_liveness_reg(env, &state_reg[i],
15681                                                      &parent_reg[i]);
15682                         if (err < 0)
15683                                 return err;
15684                         if (err == REG_LIVE_READ64)
15685                                 mark_insn_zext(env, &parent_reg[i]);
15686                 }
15687
15688                 /* Propagate stack slots. */
15689                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15690                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15691                         parent_reg = &parent->stack[i].spilled_ptr;
15692                         state_reg = &state->stack[i].spilled_ptr;
15693                         err = propagate_liveness_reg(env, state_reg,
15694                                                      parent_reg);
15695                         if (err < 0)
15696                                 return err;
15697                 }
15698         }
15699         return 0;
15700 }
15701
15702 /* find precise scalars in the previous equivalent state and
15703  * propagate them into the current state
15704  */
15705 static int propagate_precision(struct bpf_verifier_env *env,
15706                                const struct bpf_verifier_state *old)
15707 {
15708         struct bpf_reg_state *state_reg;
15709         struct bpf_func_state *state;
15710         int i, err = 0, fr;
15711         bool first;
15712
15713         for (fr = old->curframe; fr >= 0; fr--) {
15714                 state = old->frame[fr];
15715                 state_reg = state->regs;
15716                 first = true;
15717                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15718                         if (state_reg->type != SCALAR_VALUE ||
15719                             !state_reg->precise ||
15720                             !(state_reg->live & REG_LIVE_READ))
15721                                 continue;
15722                         if (env->log.level & BPF_LOG_LEVEL2) {
15723                                 if (first)
15724                                         verbose(env, "frame %d: propagating r%d", fr, i);
15725                                 else
15726                                         verbose(env, ",r%d", i);
15727                         }
15728                         bt_set_frame_reg(&env->bt, fr, i);
15729                         first = false;
15730                 }
15731
15732                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15733                         if (!is_spilled_reg(&state->stack[i]))
15734                                 continue;
15735                         state_reg = &state->stack[i].spilled_ptr;
15736                         if (state_reg->type != SCALAR_VALUE ||
15737                             !state_reg->precise ||
15738                             !(state_reg->live & REG_LIVE_READ))
15739                                 continue;
15740                         if (env->log.level & BPF_LOG_LEVEL2) {
15741                                 if (first)
15742                                         verbose(env, "frame %d: propagating fp%d",
15743                                                 fr, (-i - 1) * BPF_REG_SIZE);
15744                                 else
15745                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15746                         }
15747                         bt_set_frame_slot(&env->bt, fr, i);
15748                         first = false;
15749                 }
15750                 if (!first)
15751                         verbose(env, "\n");
15752         }
15753
15754         err = mark_chain_precision_batch(env);
15755         if (err < 0)
15756                 return err;
15757
15758         return 0;
15759 }
15760
15761 static bool states_maybe_looping(struct bpf_verifier_state *old,
15762                                  struct bpf_verifier_state *cur)
15763 {
15764         struct bpf_func_state *fold, *fcur;
15765         int i, fr = cur->curframe;
15766
15767         if (old->curframe != fr)
15768                 return false;
15769
15770         fold = old->frame[fr];
15771         fcur = cur->frame[fr];
15772         for (i = 0; i < MAX_BPF_REG; i++)
15773                 if (memcmp(&fold->regs[i], &fcur->regs[i],
15774                            offsetof(struct bpf_reg_state, parent)))
15775                         return false;
15776         return true;
15777 }
15778
15779 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15780 {
15781         return env->insn_aux_data[insn_idx].is_iter_next;
15782 }
15783
15784 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15785  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15786  * states to match, which otherwise would look like an infinite loop. So while
15787  * iter_next() calls are taken care of, we still need to be careful and
15788  * prevent erroneous and too eager declaration of "ininite loop", when
15789  * iterators are involved.
15790  *
15791  * Here's a situation in pseudo-BPF assembly form:
15792  *
15793  *   0: again:                          ; set up iter_next() call args
15794  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15795  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15796  *   3:   if r0 == 0 goto done
15797  *   4:   ... something useful here ...
15798  *   5:   goto again                    ; another iteration
15799  *   6: done:
15800  *   7:   r1 = &it
15801  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15802  *   9:   exit
15803  *
15804  * This is a typical loop. Let's assume that we have a prune point at 1:,
15805  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15806  * again`, assuming other heuristics don't get in a way).
15807  *
15808  * When we first time come to 1:, let's say we have some state X. We proceed
15809  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15810  * Now we come back to validate that forked ACTIVE state. We proceed through
15811  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15812  * are converging. But the problem is that we don't know that yet, as this
15813  * convergence has to happen at iter_next() call site only. So if nothing is
15814  * done, at 1: verifier will use bounded loop logic and declare infinite
15815  * looping (and would be *technically* correct, if not for iterator's
15816  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15817  * don't want that. So what we do in process_iter_next_call() when we go on
15818  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15819  * a different iteration. So when we suspect an infinite loop, we additionally
15820  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15821  * pretend we are not looping and wait for next iter_next() call.
15822  *
15823  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15824  * loop, because that would actually mean infinite loop, as DRAINED state is
15825  * "sticky", and so we'll keep returning into the same instruction with the
15826  * same state (at least in one of possible code paths).
15827  *
15828  * This approach allows to keep infinite loop heuristic even in the face of
15829  * active iterator. E.g., C snippet below is and will be detected as
15830  * inifintely looping:
15831  *
15832  *   struct bpf_iter_num it;
15833  *   int *p, x;
15834  *
15835  *   bpf_iter_num_new(&it, 0, 10);
15836  *   while ((p = bpf_iter_num_next(&t))) {
15837  *       x = p;
15838  *       while (x--) {} // <<-- infinite loop here
15839  *   }
15840  *
15841  */
15842 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15843 {
15844         struct bpf_reg_state *slot, *cur_slot;
15845         struct bpf_func_state *state;
15846         int i, fr;
15847
15848         for (fr = old->curframe; fr >= 0; fr--) {
15849                 state = old->frame[fr];
15850                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15851                         if (state->stack[i].slot_type[0] != STACK_ITER)
15852                                 continue;
15853
15854                         slot = &state->stack[i].spilled_ptr;
15855                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15856                                 continue;
15857
15858                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15859                         if (cur_slot->iter.depth != slot->iter.depth)
15860                                 return true;
15861                 }
15862         }
15863         return false;
15864 }
15865
15866 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15867 {
15868         struct bpf_verifier_state_list *new_sl;
15869         struct bpf_verifier_state_list *sl, **pprev;
15870         struct bpf_verifier_state *cur = env->cur_state, *new;
15871         int i, j, err, states_cnt = 0;
15872         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15873         bool add_new_state = force_new_state;
15874
15875         /* bpf progs typically have pruning point every 4 instructions
15876          * http://vger.kernel.org/bpfconf2019.html#session-1
15877          * Do not add new state for future pruning if the verifier hasn't seen
15878          * at least 2 jumps and at least 8 instructions.
15879          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15880          * In tests that amounts to up to 50% reduction into total verifier
15881          * memory consumption and 20% verifier time speedup.
15882          */
15883         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15884             env->insn_processed - env->prev_insn_processed >= 8)
15885                 add_new_state = true;
15886
15887         pprev = explored_state(env, insn_idx);
15888         sl = *pprev;
15889
15890         clean_live_states(env, insn_idx, cur);
15891
15892         while (sl) {
15893                 states_cnt++;
15894                 if (sl->state.insn_idx != insn_idx)
15895                         goto next;
15896
15897                 if (sl->state.branches) {
15898                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15899
15900                         if (frame->in_async_callback_fn &&
15901                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15902                                 /* Different async_entry_cnt means that the verifier is
15903                                  * processing another entry into async callback.
15904                                  * Seeing the same state is not an indication of infinite
15905                                  * loop or infinite recursion.
15906                                  * But finding the same state doesn't mean that it's safe
15907                                  * to stop processing the current state. The previous state
15908                                  * hasn't yet reached bpf_exit, since state.branches > 0.
15909                                  * Checking in_async_callback_fn alone is not enough either.
15910                                  * Since the verifier still needs to catch infinite loops
15911                                  * inside async callbacks.
15912                                  */
15913                                 goto skip_inf_loop_check;
15914                         }
15915                         /* BPF open-coded iterators loop detection is special.
15916                          * states_maybe_looping() logic is too simplistic in detecting
15917                          * states that *might* be equivalent, because it doesn't know
15918                          * about ID remapping, so don't even perform it.
15919                          * See process_iter_next_call() and iter_active_depths_differ()
15920                          * for overview of the logic. When current and one of parent
15921                          * states are detected as equivalent, it's a good thing: we prove
15922                          * convergence and can stop simulating further iterations.
15923                          * It's safe to assume that iterator loop will finish, taking into
15924                          * account iter_next() contract of eventually returning
15925                          * sticky NULL result.
15926                          */
15927                         if (is_iter_next_insn(env, insn_idx)) {
15928                                 if (states_equal(env, &sl->state, cur)) {
15929                                         struct bpf_func_state *cur_frame;
15930                                         struct bpf_reg_state *iter_state, *iter_reg;
15931                                         int spi;
15932
15933                                         cur_frame = cur->frame[cur->curframe];
15934                                         /* btf_check_iter_kfuncs() enforces that
15935                                          * iter state pointer is always the first arg
15936                                          */
15937                                         iter_reg = &cur_frame->regs[BPF_REG_1];
15938                                         /* current state is valid due to states_equal(),
15939                                          * so we can assume valid iter and reg state,
15940                                          * no need for extra (re-)validations
15941                                          */
15942                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15943                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15944                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15945                                                 goto hit;
15946                                 }
15947                                 goto skip_inf_loop_check;
15948                         }
15949                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
15950                         if (states_maybe_looping(&sl->state, cur) &&
15951                             states_equal(env, &sl->state, cur) &&
15952                             !iter_active_depths_differ(&sl->state, cur)) {
15953                                 verbose_linfo(env, insn_idx, "; ");
15954                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15955                                 return -EINVAL;
15956                         }
15957                         /* if the verifier is processing a loop, avoid adding new state
15958                          * too often, since different loop iterations have distinct
15959                          * states and may not help future pruning.
15960                          * This threshold shouldn't be too low to make sure that
15961                          * a loop with large bound will be rejected quickly.
15962                          * The most abusive loop will be:
15963                          * r1 += 1
15964                          * if r1 < 1000000 goto pc-2
15965                          * 1M insn_procssed limit / 100 == 10k peak states.
15966                          * This threshold shouldn't be too high either, since states
15967                          * at the end of the loop are likely to be useful in pruning.
15968                          */
15969 skip_inf_loop_check:
15970                         if (!force_new_state &&
15971                             env->jmps_processed - env->prev_jmps_processed < 20 &&
15972                             env->insn_processed - env->prev_insn_processed < 100)
15973                                 add_new_state = false;
15974                         goto miss;
15975                 }
15976                 if (states_equal(env, &sl->state, cur)) {
15977 hit:
15978                         sl->hit_cnt++;
15979                         /* reached equivalent register/stack state,
15980                          * prune the search.
15981                          * Registers read by the continuation are read by us.
15982                          * If we have any write marks in env->cur_state, they
15983                          * will prevent corresponding reads in the continuation
15984                          * from reaching our parent (an explored_state).  Our
15985                          * own state will get the read marks recorded, but
15986                          * they'll be immediately forgotten as we're pruning
15987                          * this state and will pop a new one.
15988                          */
15989                         err = propagate_liveness(env, &sl->state, cur);
15990
15991                         /* if previous state reached the exit with precision and
15992                          * current state is equivalent to it (except precsion marks)
15993                          * the precision needs to be propagated back in
15994                          * the current state.
15995                          */
15996                         err = err ? : push_jmp_history(env, cur);
15997                         err = err ? : propagate_precision(env, &sl->state);
15998                         if (err)
15999                                 return err;
16000                         return 1;
16001                 }
16002 miss:
16003                 /* when new state is not going to be added do not increase miss count.
16004                  * Otherwise several loop iterations will remove the state
16005                  * recorded earlier. The goal of these heuristics is to have
16006                  * states from some iterations of the loop (some in the beginning
16007                  * and some at the end) to help pruning.
16008                  */
16009                 if (add_new_state)
16010                         sl->miss_cnt++;
16011                 /* heuristic to determine whether this state is beneficial
16012                  * to keep checking from state equivalence point of view.
16013                  * Higher numbers increase max_states_per_insn and verification time,
16014                  * but do not meaningfully decrease insn_processed.
16015                  */
16016                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16017                         /* the state is unlikely to be useful. Remove it to
16018                          * speed up verification
16019                          */
16020                         *pprev = sl->next;
16021                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16022                                 u32 br = sl->state.branches;
16023
16024                                 WARN_ONCE(br,
16025                                           "BUG live_done but branches_to_explore %d\n",
16026                                           br);
16027                                 free_verifier_state(&sl->state, false);
16028                                 kfree(sl);
16029                                 env->peak_states--;
16030                         } else {
16031                                 /* cannot free this state, since parentage chain may
16032                                  * walk it later. Add it for free_list instead to
16033                                  * be freed at the end of verification
16034                                  */
16035                                 sl->next = env->free_list;
16036                                 env->free_list = sl;
16037                         }
16038                         sl = *pprev;
16039                         continue;
16040                 }
16041 next:
16042                 pprev = &sl->next;
16043                 sl = *pprev;
16044         }
16045
16046         if (env->max_states_per_insn < states_cnt)
16047                 env->max_states_per_insn = states_cnt;
16048
16049         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16050                 return 0;
16051
16052         if (!add_new_state)
16053                 return 0;
16054
16055         /* There were no equivalent states, remember the current one.
16056          * Technically the current state is not proven to be safe yet,
16057          * but it will either reach outer most bpf_exit (which means it's safe)
16058          * or it will be rejected. When there are no loops the verifier won't be
16059          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16060          * again on the way to bpf_exit.
16061          * When looping the sl->state.branches will be > 0 and this state
16062          * will not be considered for equivalence until branches == 0.
16063          */
16064         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16065         if (!new_sl)
16066                 return -ENOMEM;
16067         env->total_states++;
16068         env->peak_states++;
16069         env->prev_jmps_processed = env->jmps_processed;
16070         env->prev_insn_processed = env->insn_processed;
16071
16072         /* forget precise markings we inherited, see __mark_chain_precision */
16073         if (env->bpf_capable)
16074                 mark_all_scalars_imprecise(env, cur);
16075
16076         /* add new state to the head of linked list */
16077         new = &new_sl->state;
16078         err = copy_verifier_state(new, cur);
16079         if (err) {
16080                 free_verifier_state(new, false);
16081                 kfree(new_sl);
16082                 return err;
16083         }
16084         new->insn_idx = insn_idx;
16085         WARN_ONCE(new->branches != 1,
16086                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16087
16088         cur->parent = new;
16089         cur->first_insn_idx = insn_idx;
16090         clear_jmp_history(cur);
16091         new_sl->next = *explored_state(env, insn_idx);
16092         *explored_state(env, insn_idx) = new_sl;
16093         /* connect new state to parentage chain. Current frame needs all
16094          * registers connected. Only r6 - r9 of the callers are alive (pushed
16095          * to the stack implicitly by JITs) so in callers' frames connect just
16096          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16097          * the state of the call instruction (with WRITTEN set), and r0 comes
16098          * from callee with its full parentage chain, anyway.
16099          */
16100         /* clear write marks in current state: the writes we did are not writes
16101          * our child did, so they don't screen off its reads from us.
16102          * (There are no read marks in current state, because reads always mark
16103          * their parent and current state never has children yet.  Only
16104          * explored_states can get read marks.)
16105          */
16106         for (j = 0; j <= cur->curframe; j++) {
16107                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16108                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16109                 for (i = 0; i < BPF_REG_FP; i++)
16110                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16111         }
16112
16113         /* all stack frames are accessible from callee, clear them all */
16114         for (j = 0; j <= cur->curframe; j++) {
16115                 struct bpf_func_state *frame = cur->frame[j];
16116                 struct bpf_func_state *newframe = new->frame[j];
16117
16118                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16119                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16120                         frame->stack[i].spilled_ptr.parent =
16121                                                 &newframe->stack[i].spilled_ptr;
16122                 }
16123         }
16124         return 0;
16125 }
16126
16127 /* Return true if it's OK to have the same insn return a different type. */
16128 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16129 {
16130         switch (base_type(type)) {
16131         case PTR_TO_CTX:
16132         case PTR_TO_SOCKET:
16133         case PTR_TO_SOCK_COMMON:
16134         case PTR_TO_TCP_SOCK:
16135         case PTR_TO_XDP_SOCK:
16136         case PTR_TO_BTF_ID:
16137                 return false;
16138         default:
16139                 return true;
16140         }
16141 }
16142
16143 /* If an instruction was previously used with particular pointer types, then we
16144  * need to be careful to avoid cases such as the below, where it may be ok
16145  * for one branch accessing the pointer, but not ok for the other branch:
16146  *
16147  * R1 = sock_ptr
16148  * goto X;
16149  * ...
16150  * R1 = some_other_valid_ptr;
16151  * goto X;
16152  * ...
16153  * R2 = *(u32 *)(R1 + 0);
16154  */
16155 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16156 {
16157         return src != prev && (!reg_type_mismatch_ok(src) ||
16158                                !reg_type_mismatch_ok(prev));
16159 }
16160
16161 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16162                              bool allow_trust_missmatch)
16163 {
16164         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16165
16166         if (*prev_type == NOT_INIT) {
16167                 /* Saw a valid insn
16168                  * dst_reg = *(u32 *)(src_reg + off)
16169                  * save type to validate intersecting paths
16170                  */
16171                 *prev_type = type;
16172         } else if (reg_type_mismatch(type, *prev_type)) {
16173                 /* Abuser program is trying to use the same insn
16174                  * dst_reg = *(u32*) (src_reg + off)
16175                  * with different pointer types:
16176                  * src_reg == ctx in one branch and
16177                  * src_reg == stack|map in some other branch.
16178                  * Reject it.
16179                  */
16180                 if (allow_trust_missmatch &&
16181                     base_type(type) == PTR_TO_BTF_ID &&
16182                     base_type(*prev_type) == PTR_TO_BTF_ID) {
16183                         /*
16184                          * Have to support a use case when one path through
16185                          * the program yields TRUSTED pointer while another
16186                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
16187                          * BPF_PROBE_MEM.
16188                          */
16189                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16190                 } else {
16191                         verbose(env, "same insn cannot be used with different pointers\n");
16192                         return -EINVAL;
16193                 }
16194         }
16195
16196         return 0;
16197 }
16198
16199 static int do_check(struct bpf_verifier_env *env)
16200 {
16201         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16202         struct bpf_verifier_state *state = env->cur_state;
16203         struct bpf_insn *insns = env->prog->insnsi;
16204         struct bpf_reg_state *regs;
16205         int insn_cnt = env->prog->len;
16206         bool do_print_state = false;
16207         int prev_insn_idx = -1;
16208
16209         for (;;) {
16210                 struct bpf_insn *insn;
16211                 u8 class;
16212                 int err;
16213
16214                 env->prev_insn_idx = prev_insn_idx;
16215                 if (env->insn_idx >= insn_cnt) {
16216                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
16217                                 env->insn_idx, insn_cnt);
16218                         return -EFAULT;
16219                 }
16220
16221                 insn = &insns[env->insn_idx];
16222                 class = BPF_CLASS(insn->code);
16223
16224                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16225                         verbose(env,
16226                                 "BPF program is too large. Processed %d insn\n",
16227                                 env->insn_processed);
16228                         return -E2BIG;
16229                 }
16230
16231                 state->last_insn_idx = env->prev_insn_idx;
16232
16233                 if (is_prune_point(env, env->insn_idx)) {
16234                         err = is_state_visited(env, env->insn_idx);
16235                         if (err < 0)
16236                                 return err;
16237                         if (err == 1) {
16238                                 /* found equivalent state, can prune the search */
16239                                 if (env->log.level & BPF_LOG_LEVEL) {
16240                                         if (do_print_state)
16241                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
16242                                                         env->prev_insn_idx, env->insn_idx,
16243                                                         env->cur_state->speculative ?
16244                                                         " (speculative execution)" : "");
16245                                         else
16246                                                 verbose(env, "%d: safe\n", env->insn_idx);
16247                                 }
16248                                 goto process_bpf_exit;
16249                         }
16250                 }
16251
16252                 if (is_jmp_point(env, env->insn_idx)) {
16253                         err = push_jmp_history(env, state);
16254                         if (err)
16255                                 return err;
16256                 }
16257
16258                 if (signal_pending(current))
16259                         return -EAGAIN;
16260
16261                 if (need_resched())
16262                         cond_resched();
16263
16264                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16265                         verbose(env, "\nfrom %d to %d%s:",
16266                                 env->prev_insn_idx, env->insn_idx,
16267                                 env->cur_state->speculative ?
16268                                 " (speculative execution)" : "");
16269                         print_verifier_state(env, state->frame[state->curframe], true);
16270                         do_print_state = false;
16271                 }
16272
16273                 if (env->log.level & BPF_LOG_LEVEL) {
16274                         const struct bpf_insn_cbs cbs = {
16275                                 .cb_call        = disasm_kfunc_name,
16276                                 .cb_print       = verbose,
16277                                 .private_data   = env,
16278                         };
16279
16280                         if (verifier_state_scratched(env))
16281                                 print_insn_state(env, state->frame[state->curframe]);
16282
16283                         verbose_linfo(env, env->insn_idx, "; ");
16284                         env->prev_log_pos = env->log.end_pos;
16285                         verbose(env, "%d: ", env->insn_idx);
16286                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16287                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16288                         env->prev_log_pos = env->log.end_pos;
16289                 }
16290
16291                 if (bpf_prog_is_offloaded(env->prog->aux)) {
16292                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16293                                                            env->prev_insn_idx);
16294                         if (err)
16295                                 return err;
16296                 }
16297
16298                 regs = cur_regs(env);
16299                 sanitize_mark_insn_seen(env);
16300                 prev_insn_idx = env->insn_idx;
16301
16302                 if (class == BPF_ALU || class == BPF_ALU64) {
16303                         err = check_alu_op(env, insn);
16304                         if (err)
16305                                 return err;
16306
16307                 } else if (class == BPF_LDX) {
16308                         enum bpf_reg_type src_reg_type;
16309
16310                         /* check for reserved fields is already done */
16311
16312                         /* check src operand */
16313                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16314                         if (err)
16315                                 return err;
16316
16317                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16318                         if (err)
16319                                 return err;
16320
16321                         src_reg_type = regs[insn->src_reg].type;
16322
16323                         /* check that memory (src_reg + off) is readable,
16324                          * the state of dst_reg will be updated by this func
16325                          */
16326                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
16327                                                insn->off, BPF_SIZE(insn->code),
16328                                                BPF_READ, insn->dst_reg, false);
16329                         if (err)
16330                                 return err;
16331
16332                         err = save_aux_ptr_type(env, src_reg_type, true);
16333                         if (err)
16334                                 return err;
16335                 } else if (class == BPF_STX) {
16336                         enum bpf_reg_type dst_reg_type;
16337
16338                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16339                                 err = check_atomic(env, env->insn_idx, insn);
16340                                 if (err)
16341                                         return err;
16342                                 env->insn_idx++;
16343                                 continue;
16344                         }
16345
16346                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16347                                 verbose(env, "BPF_STX uses reserved fields\n");
16348                                 return -EINVAL;
16349                         }
16350
16351                         /* check src1 operand */
16352                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16353                         if (err)
16354                                 return err;
16355                         /* check src2 operand */
16356                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16357                         if (err)
16358                                 return err;
16359
16360                         dst_reg_type = regs[insn->dst_reg].type;
16361
16362                         /* check that memory (dst_reg + off) is writeable */
16363                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16364                                                insn->off, BPF_SIZE(insn->code),
16365                                                BPF_WRITE, insn->src_reg, false);
16366                         if (err)
16367                                 return err;
16368
16369                         err = save_aux_ptr_type(env, dst_reg_type, false);
16370                         if (err)
16371                                 return err;
16372                 } else if (class == BPF_ST) {
16373                         enum bpf_reg_type dst_reg_type;
16374
16375                         if (BPF_MODE(insn->code) != BPF_MEM ||
16376                             insn->src_reg != BPF_REG_0) {
16377                                 verbose(env, "BPF_ST uses reserved fields\n");
16378                                 return -EINVAL;
16379                         }
16380                         /* check src operand */
16381                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16382                         if (err)
16383                                 return err;
16384
16385                         dst_reg_type = regs[insn->dst_reg].type;
16386
16387                         /* check that memory (dst_reg + off) is writeable */
16388                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16389                                                insn->off, BPF_SIZE(insn->code),
16390                                                BPF_WRITE, -1, false);
16391                         if (err)
16392                                 return err;
16393
16394                         err = save_aux_ptr_type(env, dst_reg_type, false);
16395                         if (err)
16396                                 return err;
16397                 } else if (class == BPF_JMP || class == BPF_JMP32) {
16398                         u8 opcode = BPF_OP(insn->code);
16399
16400                         env->jmps_processed++;
16401                         if (opcode == BPF_CALL) {
16402                                 if (BPF_SRC(insn->code) != BPF_K ||
16403                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16404                                      && insn->off != 0) ||
16405                                     (insn->src_reg != BPF_REG_0 &&
16406                                      insn->src_reg != BPF_PSEUDO_CALL &&
16407                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16408                                     insn->dst_reg != BPF_REG_0 ||
16409                                     class == BPF_JMP32) {
16410                                         verbose(env, "BPF_CALL uses reserved fields\n");
16411                                         return -EINVAL;
16412                                 }
16413
16414                                 if (env->cur_state->active_lock.ptr) {
16415                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16416                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
16417                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16418                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16419                                                 verbose(env, "function calls are not allowed while holding a lock\n");
16420                                                 return -EINVAL;
16421                                         }
16422                                 }
16423                                 if (insn->src_reg == BPF_PSEUDO_CALL)
16424                                         err = check_func_call(env, insn, &env->insn_idx);
16425                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16426                                         err = check_kfunc_call(env, insn, &env->insn_idx);
16427                                 else
16428                                         err = check_helper_call(env, insn, &env->insn_idx);
16429                                 if (err)
16430                                         return err;
16431
16432                                 mark_reg_scratched(env, BPF_REG_0);
16433                         } else if (opcode == BPF_JA) {
16434                                 if (BPF_SRC(insn->code) != BPF_K ||
16435                                     insn->imm != 0 ||
16436                                     insn->src_reg != BPF_REG_0 ||
16437                                     insn->dst_reg != BPF_REG_0 ||
16438                                     class == BPF_JMP32) {
16439                                         verbose(env, "BPF_JA uses reserved fields\n");
16440                                         return -EINVAL;
16441                                 }
16442
16443                                 env->insn_idx += insn->off + 1;
16444                                 continue;
16445
16446                         } else if (opcode == BPF_EXIT) {
16447                                 if (BPF_SRC(insn->code) != BPF_K ||
16448                                     insn->imm != 0 ||
16449                                     insn->src_reg != BPF_REG_0 ||
16450                                     insn->dst_reg != BPF_REG_0 ||
16451                                     class == BPF_JMP32) {
16452                                         verbose(env, "BPF_EXIT uses reserved fields\n");
16453                                         return -EINVAL;
16454                                 }
16455
16456                                 if (env->cur_state->active_lock.ptr &&
16457                                     !in_rbtree_lock_required_cb(env)) {
16458                                         verbose(env, "bpf_spin_unlock is missing\n");
16459                                         return -EINVAL;
16460                                 }
16461
16462                                 if (env->cur_state->active_rcu_lock) {
16463                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
16464                                         return -EINVAL;
16465                                 }
16466
16467                                 /* We must do check_reference_leak here before
16468                                  * prepare_func_exit to handle the case when
16469                                  * state->curframe > 0, it may be a callback
16470                                  * function, for which reference_state must
16471                                  * match caller reference state when it exits.
16472                                  */
16473                                 err = check_reference_leak(env);
16474                                 if (err)
16475                                         return err;
16476
16477                                 if (state->curframe) {
16478                                         /* exit from nested function */
16479                                         err = prepare_func_exit(env, &env->insn_idx);
16480                                         if (err)
16481                                                 return err;
16482                                         do_print_state = true;
16483                                         continue;
16484                                 }
16485
16486                                 err = check_return_code(env);
16487                                 if (err)
16488                                         return err;
16489 process_bpf_exit:
16490                                 mark_verifier_state_scratched(env);
16491                                 update_branch_counts(env, env->cur_state);
16492                                 err = pop_stack(env, &prev_insn_idx,
16493                                                 &env->insn_idx, pop_log);
16494                                 if (err < 0) {
16495                                         if (err != -ENOENT)
16496                                                 return err;
16497                                         break;
16498                                 } else {
16499                                         do_print_state = true;
16500                                         continue;
16501                                 }
16502                         } else {
16503                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16504                                 if (err)
16505                                         return err;
16506                         }
16507                 } else if (class == BPF_LD) {
16508                         u8 mode = BPF_MODE(insn->code);
16509
16510                         if (mode == BPF_ABS || mode == BPF_IND) {
16511                                 err = check_ld_abs(env, insn);
16512                                 if (err)
16513                                         return err;
16514
16515                         } else if (mode == BPF_IMM) {
16516                                 err = check_ld_imm(env, insn);
16517                                 if (err)
16518                                         return err;
16519
16520                                 env->insn_idx++;
16521                                 sanitize_mark_insn_seen(env);
16522                         } else {
16523                                 verbose(env, "invalid BPF_LD mode\n");
16524                                 return -EINVAL;
16525                         }
16526                 } else {
16527                         verbose(env, "unknown insn class %d\n", class);
16528                         return -EINVAL;
16529                 }
16530
16531                 env->insn_idx++;
16532         }
16533
16534         return 0;
16535 }
16536
16537 static int find_btf_percpu_datasec(struct btf *btf)
16538 {
16539         const struct btf_type *t;
16540         const char *tname;
16541         int i, n;
16542
16543         /*
16544          * Both vmlinux and module each have their own ".data..percpu"
16545          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16546          * types to look at only module's own BTF types.
16547          */
16548         n = btf_nr_types(btf);
16549         if (btf_is_module(btf))
16550                 i = btf_nr_types(btf_vmlinux);
16551         else
16552                 i = 1;
16553
16554         for(; i < n; i++) {
16555                 t = btf_type_by_id(btf, i);
16556                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16557                         continue;
16558
16559                 tname = btf_name_by_offset(btf, t->name_off);
16560                 if (!strcmp(tname, ".data..percpu"))
16561                         return i;
16562         }
16563
16564         return -ENOENT;
16565 }
16566
16567 /* replace pseudo btf_id with kernel symbol address */
16568 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16569                                struct bpf_insn *insn,
16570                                struct bpf_insn_aux_data *aux)
16571 {
16572         const struct btf_var_secinfo *vsi;
16573         const struct btf_type *datasec;
16574         struct btf_mod_pair *btf_mod;
16575         const struct btf_type *t;
16576         const char *sym_name;
16577         bool percpu = false;
16578         u32 type, id = insn->imm;
16579         struct btf *btf;
16580         s32 datasec_id;
16581         u64 addr;
16582         int i, btf_fd, err;
16583
16584         btf_fd = insn[1].imm;
16585         if (btf_fd) {
16586                 btf = btf_get_by_fd(btf_fd);
16587                 if (IS_ERR(btf)) {
16588                         verbose(env, "invalid module BTF object FD specified.\n");
16589                         return -EINVAL;
16590                 }
16591         } else {
16592                 if (!btf_vmlinux) {
16593                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16594                         return -EINVAL;
16595                 }
16596                 btf = btf_vmlinux;
16597                 btf_get(btf);
16598         }
16599
16600         t = btf_type_by_id(btf, id);
16601         if (!t) {
16602                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16603                 err = -ENOENT;
16604                 goto err_put;
16605         }
16606
16607         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16608                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16609                 err = -EINVAL;
16610                 goto err_put;
16611         }
16612
16613         sym_name = btf_name_by_offset(btf, t->name_off);
16614         addr = kallsyms_lookup_name(sym_name);
16615         if (!addr) {
16616                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16617                         sym_name);
16618                 err = -ENOENT;
16619                 goto err_put;
16620         }
16621         insn[0].imm = (u32)addr;
16622         insn[1].imm = addr >> 32;
16623
16624         if (btf_type_is_func(t)) {
16625                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16626                 aux->btf_var.mem_size = 0;
16627                 goto check_btf;
16628         }
16629
16630         datasec_id = find_btf_percpu_datasec(btf);
16631         if (datasec_id > 0) {
16632                 datasec = btf_type_by_id(btf, datasec_id);
16633                 for_each_vsi(i, datasec, vsi) {
16634                         if (vsi->type == id) {
16635                                 percpu = true;
16636                                 break;
16637                         }
16638                 }
16639         }
16640
16641         type = t->type;
16642         t = btf_type_skip_modifiers(btf, type, NULL);
16643         if (percpu) {
16644                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16645                 aux->btf_var.btf = btf;
16646                 aux->btf_var.btf_id = type;
16647         } else if (!btf_type_is_struct(t)) {
16648                 const struct btf_type *ret;
16649                 const char *tname;
16650                 u32 tsize;
16651
16652                 /* resolve the type size of ksym. */
16653                 ret = btf_resolve_size(btf, t, &tsize);
16654                 if (IS_ERR(ret)) {
16655                         tname = btf_name_by_offset(btf, t->name_off);
16656                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16657                                 tname, PTR_ERR(ret));
16658                         err = -EINVAL;
16659                         goto err_put;
16660                 }
16661                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16662                 aux->btf_var.mem_size = tsize;
16663         } else {
16664                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16665                 aux->btf_var.btf = btf;
16666                 aux->btf_var.btf_id = type;
16667         }
16668 check_btf:
16669         /* check whether we recorded this BTF (and maybe module) already */
16670         for (i = 0; i < env->used_btf_cnt; i++) {
16671                 if (env->used_btfs[i].btf == btf) {
16672                         btf_put(btf);
16673                         return 0;
16674                 }
16675         }
16676
16677         if (env->used_btf_cnt >= MAX_USED_BTFS) {
16678                 err = -E2BIG;
16679                 goto err_put;
16680         }
16681
16682         btf_mod = &env->used_btfs[env->used_btf_cnt];
16683         btf_mod->btf = btf;
16684         btf_mod->module = NULL;
16685
16686         /* if we reference variables from kernel module, bump its refcount */
16687         if (btf_is_module(btf)) {
16688                 btf_mod->module = btf_try_get_module(btf);
16689                 if (!btf_mod->module) {
16690                         err = -ENXIO;
16691                         goto err_put;
16692                 }
16693         }
16694
16695         env->used_btf_cnt++;
16696
16697         return 0;
16698 err_put:
16699         btf_put(btf);
16700         return err;
16701 }
16702
16703 static bool is_tracing_prog_type(enum bpf_prog_type type)
16704 {
16705         switch (type) {
16706         case BPF_PROG_TYPE_KPROBE:
16707         case BPF_PROG_TYPE_TRACEPOINT:
16708         case BPF_PROG_TYPE_PERF_EVENT:
16709         case BPF_PROG_TYPE_RAW_TRACEPOINT:
16710         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16711                 return true;
16712         default:
16713                 return false;
16714         }
16715 }
16716
16717 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16718                                         struct bpf_map *map,
16719                                         struct bpf_prog *prog)
16720
16721 {
16722         enum bpf_prog_type prog_type = resolve_prog_type(prog);
16723
16724         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16725             btf_record_has_field(map->record, BPF_RB_ROOT)) {
16726                 if (is_tracing_prog_type(prog_type)) {
16727                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16728                         return -EINVAL;
16729                 }
16730         }
16731
16732         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16733                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16734                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16735                         return -EINVAL;
16736                 }
16737
16738                 if (is_tracing_prog_type(prog_type)) {
16739                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16740                         return -EINVAL;
16741                 }
16742
16743                 if (prog->aux->sleepable) {
16744                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16745                         return -EINVAL;
16746                 }
16747         }
16748
16749         if (btf_record_has_field(map->record, BPF_TIMER)) {
16750                 if (is_tracing_prog_type(prog_type)) {
16751                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
16752                         return -EINVAL;
16753                 }
16754         }
16755
16756         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16757             !bpf_offload_prog_map_match(prog, map)) {
16758                 verbose(env, "offload device mismatch between prog and map\n");
16759                 return -EINVAL;
16760         }
16761
16762         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16763                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16764                 return -EINVAL;
16765         }
16766
16767         if (prog->aux->sleepable)
16768                 switch (map->map_type) {
16769                 case BPF_MAP_TYPE_HASH:
16770                 case BPF_MAP_TYPE_LRU_HASH:
16771                 case BPF_MAP_TYPE_ARRAY:
16772                 case BPF_MAP_TYPE_PERCPU_HASH:
16773                 case BPF_MAP_TYPE_PERCPU_ARRAY:
16774                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16775                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16776                 case BPF_MAP_TYPE_HASH_OF_MAPS:
16777                 case BPF_MAP_TYPE_RINGBUF:
16778                 case BPF_MAP_TYPE_USER_RINGBUF:
16779                 case BPF_MAP_TYPE_INODE_STORAGE:
16780                 case BPF_MAP_TYPE_SK_STORAGE:
16781                 case BPF_MAP_TYPE_TASK_STORAGE:
16782                 case BPF_MAP_TYPE_CGRP_STORAGE:
16783                         break;
16784                 default:
16785                         verbose(env,
16786                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16787                         return -EINVAL;
16788                 }
16789
16790         return 0;
16791 }
16792
16793 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16794 {
16795         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16796                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16797 }
16798
16799 /* find and rewrite pseudo imm in ld_imm64 instructions:
16800  *
16801  * 1. if it accesses map FD, replace it with actual map pointer.
16802  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16803  *
16804  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16805  */
16806 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16807 {
16808         struct bpf_insn *insn = env->prog->insnsi;
16809         int insn_cnt = env->prog->len;
16810         int i, j, err;
16811
16812         err = bpf_prog_calc_tag(env->prog);
16813         if (err)
16814                 return err;
16815
16816         for (i = 0; i < insn_cnt; i++, insn++) {
16817                 if (BPF_CLASS(insn->code) == BPF_LDX &&
16818                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16819                         verbose(env, "BPF_LDX uses reserved fields\n");
16820                         return -EINVAL;
16821                 }
16822
16823                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16824                         struct bpf_insn_aux_data *aux;
16825                         struct bpf_map *map;
16826                         struct fd f;
16827                         u64 addr;
16828                         u32 fd;
16829
16830                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
16831                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16832                             insn[1].off != 0) {
16833                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
16834                                 return -EINVAL;
16835                         }
16836
16837                         if (insn[0].src_reg == 0)
16838                                 /* valid generic load 64-bit imm */
16839                                 goto next_insn;
16840
16841                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16842                                 aux = &env->insn_aux_data[i];
16843                                 err = check_pseudo_btf_id(env, insn, aux);
16844                                 if (err)
16845                                         return err;
16846                                 goto next_insn;
16847                         }
16848
16849                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16850                                 aux = &env->insn_aux_data[i];
16851                                 aux->ptr_type = PTR_TO_FUNC;
16852                                 goto next_insn;
16853                         }
16854
16855                         /* In final convert_pseudo_ld_imm64() step, this is
16856                          * converted into regular 64-bit imm load insn.
16857                          */
16858                         switch (insn[0].src_reg) {
16859                         case BPF_PSEUDO_MAP_VALUE:
16860                         case BPF_PSEUDO_MAP_IDX_VALUE:
16861                                 break;
16862                         case BPF_PSEUDO_MAP_FD:
16863                         case BPF_PSEUDO_MAP_IDX:
16864                                 if (insn[1].imm == 0)
16865                                         break;
16866                                 fallthrough;
16867                         default:
16868                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16869                                 return -EINVAL;
16870                         }
16871
16872                         switch (insn[0].src_reg) {
16873                         case BPF_PSEUDO_MAP_IDX_VALUE:
16874                         case BPF_PSEUDO_MAP_IDX:
16875                                 if (bpfptr_is_null(env->fd_array)) {
16876                                         verbose(env, "fd_idx without fd_array is invalid\n");
16877                                         return -EPROTO;
16878                                 }
16879                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16880                                                             insn[0].imm * sizeof(fd),
16881                                                             sizeof(fd)))
16882                                         return -EFAULT;
16883                                 break;
16884                         default:
16885                                 fd = insn[0].imm;
16886                                 break;
16887                         }
16888
16889                         f = fdget(fd);
16890                         map = __bpf_map_get(f);
16891                         if (IS_ERR(map)) {
16892                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
16893                                         insn[0].imm);
16894                                 return PTR_ERR(map);
16895                         }
16896
16897                         err = check_map_prog_compatibility(env, map, env->prog);
16898                         if (err) {
16899                                 fdput(f);
16900                                 return err;
16901                         }
16902
16903                         aux = &env->insn_aux_data[i];
16904                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16905                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16906                                 addr = (unsigned long)map;
16907                         } else {
16908                                 u32 off = insn[1].imm;
16909
16910                                 if (off >= BPF_MAX_VAR_OFF) {
16911                                         verbose(env, "direct value offset of %u is not allowed\n", off);
16912                                         fdput(f);
16913                                         return -EINVAL;
16914                                 }
16915
16916                                 if (!map->ops->map_direct_value_addr) {
16917                                         verbose(env, "no direct value access support for this map type\n");
16918                                         fdput(f);
16919                                         return -EINVAL;
16920                                 }
16921
16922                                 err = map->ops->map_direct_value_addr(map, &addr, off);
16923                                 if (err) {
16924                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16925                                                 map->value_size, off);
16926                                         fdput(f);
16927                                         return err;
16928                                 }
16929
16930                                 aux->map_off = off;
16931                                 addr += off;
16932                         }
16933
16934                         insn[0].imm = (u32)addr;
16935                         insn[1].imm = addr >> 32;
16936
16937                         /* check whether we recorded this map already */
16938                         for (j = 0; j < env->used_map_cnt; j++) {
16939                                 if (env->used_maps[j] == map) {
16940                                         aux->map_index = j;
16941                                         fdput(f);
16942                                         goto next_insn;
16943                                 }
16944                         }
16945
16946                         if (env->used_map_cnt >= MAX_USED_MAPS) {
16947                                 fdput(f);
16948                                 return -E2BIG;
16949                         }
16950
16951                         /* hold the map. If the program is rejected by verifier,
16952                          * the map will be released by release_maps() or it
16953                          * will be used by the valid program until it's unloaded
16954                          * and all maps are released in free_used_maps()
16955                          */
16956                         bpf_map_inc(map);
16957
16958                         aux->map_index = env->used_map_cnt;
16959                         env->used_maps[env->used_map_cnt++] = map;
16960
16961                         if (bpf_map_is_cgroup_storage(map) &&
16962                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
16963                                 verbose(env, "only one cgroup storage of each type is allowed\n");
16964                                 fdput(f);
16965                                 return -EBUSY;
16966                         }
16967
16968                         fdput(f);
16969 next_insn:
16970                         insn++;
16971                         i++;
16972                         continue;
16973                 }
16974
16975                 /* Basic sanity check before we invest more work here. */
16976                 if (!bpf_opcode_in_insntable(insn->code)) {
16977                         verbose(env, "unknown opcode %02x\n", insn->code);
16978                         return -EINVAL;
16979                 }
16980         }
16981
16982         /* now all pseudo BPF_LD_IMM64 instructions load valid
16983          * 'struct bpf_map *' into a register instead of user map_fd.
16984          * These pointers will be used later by verifier to validate map access.
16985          */
16986         return 0;
16987 }
16988
16989 /* drop refcnt of maps used by the rejected program */
16990 static void release_maps(struct bpf_verifier_env *env)
16991 {
16992         __bpf_free_used_maps(env->prog->aux, env->used_maps,
16993                              env->used_map_cnt);
16994 }
16995
16996 /* drop refcnt of maps used by the rejected program */
16997 static void release_btfs(struct bpf_verifier_env *env)
16998 {
16999         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17000                              env->used_btf_cnt);
17001 }
17002
17003 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17004 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17005 {
17006         struct bpf_insn *insn = env->prog->insnsi;
17007         int insn_cnt = env->prog->len;
17008         int i;
17009
17010         for (i = 0; i < insn_cnt; i++, insn++) {
17011                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17012                         continue;
17013                 if (insn->src_reg == BPF_PSEUDO_FUNC)
17014                         continue;
17015                 insn->src_reg = 0;
17016         }
17017 }
17018
17019 /* single env->prog->insni[off] instruction was replaced with the range
17020  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17021  * [0, off) and [off, end) to new locations, so the patched range stays zero
17022  */
17023 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17024                                  struct bpf_insn_aux_data *new_data,
17025                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
17026 {
17027         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17028         struct bpf_insn *insn = new_prog->insnsi;
17029         u32 old_seen = old_data[off].seen;
17030         u32 prog_len;
17031         int i;
17032
17033         /* aux info at OFF always needs adjustment, no matter fast path
17034          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17035          * original insn at old prog.
17036          */
17037         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17038
17039         if (cnt == 1)
17040                 return;
17041         prog_len = new_prog->len;
17042
17043         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17044         memcpy(new_data + off + cnt - 1, old_data + off,
17045                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17046         for (i = off; i < off + cnt - 1; i++) {
17047                 /* Expand insni[off]'s seen count to the patched range. */
17048                 new_data[i].seen = old_seen;
17049                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17050         }
17051         env->insn_aux_data = new_data;
17052         vfree(old_data);
17053 }
17054
17055 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17056 {
17057         int i;
17058
17059         if (len == 1)
17060                 return;
17061         /* NOTE: fake 'exit' subprog should be updated as well. */
17062         for (i = 0; i <= env->subprog_cnt; i++) {
17063                 if (env->subprog_info[i].start <= off)
17064                         continue;
17065                 env->subprog_info[i].start += len - 1;
17066         }
17067 }
17068
17069 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17070 {
17071         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17072         int i, sz = prog->aux->size_poke_tab;
17073         struct bpf_jit_poke_descriptor *desc;
17074
17075         for (i = 0; i < sz; i++) {
17076                 desc = &tab[i];
17077                 if (desc->insn_idx <= off)
17078                         continue;
17079                 desc->insn_idx += len - 1;
17080         }
17081 }
17082
17083 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17084                                             const struct bpf_insn *patch, u32 len)
17085 {
17086         struct bpf_prog *new_prog;
17087         struct bpf_insn_aux_data *new_data = NULL;
17088
17089         if (len > 1) {
17090                 new_data = vzalloc(array_size(env->prog->len + len - 1,
17091                                               sizeof(struct bpf_insn_aux_data)));
17092                 if (!new_data)
17093                         return NULL;
17094         }
17095
17096         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17097         if (IS_ERR(new_prog)) {
17098                 if (PTR_ERR(new_prog) == -ERANGE)
17099                         verbose(env,
17100                                 "insn %d cannot be patched due to 16-bit range\n",
17101                                 env->insn_aux_data[off].orig_idx);
17102                 vfree(new_data);
17103                 return NULL;
17104         }
17105         adjust_insn_aux_data(env, new_data, new_prog, off, len);
17106         adjust_subprog_starts(env, off, len);
17107         adjust_poke_descs(new_prog, off, len);
17108         return new_prog;
17109 }
17110
17111 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17112                                               u32 off, u32 cnt)
17113 {
17114         int i, j;
17115
17116         /* find first prog starting at or after off (first to remove) */
17117         for (i = 0; i < env->subprog_cnt; i++)
17118                 if (env->subprog_info[i].start >= off)
17119                         break;
17120         /* find first prog starting at or after off + cnt (first to stay) */
17121         for (j = i; j < env->subprog_cnt; j++)
17122                 if (env->subprog_info[j].start >= off + cnt)
17123                         break;
17124         /* if j doesn't start exactly at off + cnt, we are just removing
17125          * the front of previous prog
17126          */
17127         if (env->subprog_info[j].start != off + cnt)
17128                 j--;
17129
17130         if (j > i) {
17131                 struct bpf_prog_aux *aux = env->prog->aux;
17132                 int move;
17133
17134                 /* move fake 'exit' subprog as well */
17135                 move = env->subprog_cnt + 1 - j;
17136
17137                 memmove(env->subprog_info + i,
17138                         env->subprog_info + j,
17139                         sizeof(*env->subprog_info) * move);
17140                 env->subprog_cnt -= j - i;
17141
17142                 /* remove func_info */
17143                 if (aux->func_info) {
17144                         move = aux->func_info_cnt - j;
17145
17146                         memmove(aux->func_info + i,
17147                                 aux->func_info + j,
17148                                 sizeof(*aux->func_info) * move);
17149                         aux->func_info_cnt -= j - i;
17150                         /* func_info->insn_off is set after all code rewrites,
17151                          * in adjust_btf_func() - no need to adjust
17152                          */
17153                 }
17154         } else {
17155                 /* convert i from "first prog to remove" to "first to adjust" */
17156                 if (env->subprog_info[i].start == off)
17157                         i++;
17158         }
17159
17160         /* update fake 'exit' subprog as well */
17161         for (; i <= env->subprog_cnt; i++)
17162                 env->subprog_info[i].start -= cnt;
17163
17164         return 0;
17165 }
17166
17167 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17168                                       u32 cnt)
17169 {
17170         struct bpf_prog *prog = env->prog;
17171         u32 i, l_off, l_cnt, nr_linfo;
17172         struct bpf_line_info *linfo;
17173
17174         nr_linfo = prog->aux->nr_linfo;
17175         if (!nr_linfo)
17176                 return 0;
17177
17178         linfo = prog->aux->linfo;
17179
17180         /* find first line info to remove, count lines to be removed */
17181         for (i = 0; i < nr_linfo; i++)
17182                 if (linfo[i].insn_off >= off)
17183                         break;
17184
17185         l_off = i;
17186         l_cnt = 0;
17187         for (; i < nr_linfo; i++)
17188                 if (linfo[i].insn_off < off + cnt)
17189                         l_cnt++;
17190                 else
17191                         break;
17192
17193         /* First live insn doesn't match first live linfo, it needs to "inherit"
17194          * last removed linfo.  prog is already modified, so prog->len == off
17195          * means no live instructions after (tail of the program was removed).
17196          */
17197         if (prog->len != off && l_cnt &&
17198             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17199                 l_cnt--;
17200                 linfo[--i].insn_off = off + cnt;
17201         }
17202
17203         /* remove the line info which refer to the removed instructions */
17204         if (l_cnt) {
17205                 memmove(linfo + l_off, linfo + i,
17206                         sizeof(*linfo) * (nr_linfo - i));
17207
17208                 prog->aux->nr_linfo -= l_cnt;
17209                 nr_linfo = prog->aux->nr_linfo;
17210         }
17211
17212         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17213         for (i = l_off; i < nr_linfo; i++)
17214                 linfo[i].insn_off -= cnt;
17215
17216         /* fix up all subprogs (incl. 'exit') which start >= off */
17217         for (i = 0; i <= env->subprog_cnt; i++)
17218                 if (env->subprog_info[i].linfo_idx > l_off) {
17219                         /* program may have started in the removed region but
17220                          * may not be fully removed
17221                          */
17222                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17223                                 env->subprog_info[i].linfo_idx -= l_cnt;
17224                         else
17225                                 env->subprog_info[i].linfo_idx = l_off;
17226                 }
17227
17228         return 0;
17229 }
17230
17231 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17232 {
17233         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17234         unsigned int orig_prog_len = env->prog->len;
17235         int err;
17236
17237         if (bpf_prog_is_offloaded(env->prog->aux))
17238                 bpf_prog_offload_remove_insns(env, off, cnt);
17239
17240         err = bpf_remove_insns(env->prog, off, cnt);
17241         if (err)
17242                 return err;
17243
17244         err = adjust_subprog_starts_after_remove(env, off, cnt);
17245         if (err)
17246                 return err;
17247
17248         err = bpf_adj_linfo_after_remove(env, off, cnt);
17249         if (err)
17250                 return err;
17251
17252         memmove(aux_data + off, aux_data + off + cnt,
17253                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17254
17255         return 0;
17256 }
17257
17258 /* The verifier does more data flow analysis than llvm and will not
17259  * explore branches that are dead at run time. Malicious programs can
17260  * have dead code too. Therefore replace all dead at-run-time code
17261  * with 'ja -1'.
17262  *
17263  * Just nops are not optimal, e.g. if they would sit at the end of the
17264  * program and through another bug we would manage to jump there, then
17265  * we'd execute beyond program memory otherwise. Returning exception
17266  * code also wouldn't work since we can have subprogs where the dead
17267  * code could be located.
17268  */
17269 static void sanitize_dead_code(struct bpf_verifier_env *env)
17270 {
17271         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17272         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17273         struct bpf_insn *insn = env->prog->insnsi;
17274         const int insn_cnt = env->prog->len;
17275         int i;
17276
17277         for (i = 0; i < insn_cnt; i++) {
17278                 if (aux_data[i].seen)
17279                         continue;
17280                 memcpy(insn + i, &trap, sizeof(trap));
17281                 aux_data[i].zext_dst = false;
17282         }
17283 }
17284
17285 static bool insn_is_cond_jump(u8 code)
17286 {
17287         u8 op;
17288
17289         if (BPF_CLASS(code) == BPF_JMP32)
17290                 return true;
17291
17292         if (BPF_CLASS(code) != BPF_JMP)
17293                 return false;
17294
17295         op = BPF_OP(code);
17296         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17297 }
17298
17299 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17300 {
17301         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17302         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17303         struct bpf_insn *insn = env->prog->insnsi;
17304         const int insn_cnt = env->prog->len;
17305         int i;
17306
17307         for (i = 0; i < insn_cnt; i++, insn++) {
17308                 if (!insn_is_cond_jump(insn->code))
17309                         continue;
17310
17311                 if (!aux_data[i + 1].seen)
17312                         ja.off = insn->off;
17313                 else if (!aux_data[i + 1 + insn->off].seen)
17314                         ja.off = 0;
17315                 else
17316                         continue;
17317
17318                 if (bpf_prog_is_offloaded(env->prog->aux))
17319                         bpf_prog_offload_replace_insn(env, i, &ja);
17320
17321                 memcpy(insn, &ja, sizeof(ja));
17322         }
17323 }
17324
17325 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17326 {
17327         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17328         int insn_cnt = env->prog->len;
17329         int i, err;
17330
17331         for (i = 0; i < insn_cnt; i++) {
17332                 int j;
17333
17334                 j = 0;
17335                 while (i + j < insn_cnt && !aux_data[i + j].seen)
17336                         j++;
17337                 if (!j)
17338                         continue;
17339
17340                 err = verifier_remove_insns(env, i, j);
17341                 if (err)
17342                         return err;
17343                 insn_cnt = env->prog->len;
17344         }
17345
17346         return 0;
17347 }
17348
17349 static int opt_remove_nops(struct bpf_verifier_env *env)
17350 {
17351         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17352         struct bpf_insn *insn = env->prog->insnsi;
17353         int insn_cnt = env->prog->len;
17354         int i, err;
17355
17356         for (i = 0; i < insn_cnt; i++) {
17357                 if (memcmp(&insn[i], &ja, sizeof(ja)))
17358                         continue;
17359
17360                 err = verifier_remove_insns(env, i, 1);
17361                 if (err)
17362                         return err;
17363                 insn_cnt--;
17364                 i--;
17365         }
17366
17367         return 0;
17368 }
17369
17370 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17371                                          const union bpf_attr *attr)
17372 {
17373         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17374         struct bpf_insn_aux_data *aux = env->insn_aux_data;
17375         int i, patch_len, delta = 0, len = env->prog->len;
17376         struct bpf_insn *insns = env->prog->insnsi;
17377         struct bpf_prog *new_prog;
17378         bool rnd_hi32;
17379
17380         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17381         zext_patch[1] = BPF_ZEXT_REG(0);
17382         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17383         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17384         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17385         for (i = 0; i < len; i++) {
17386                 int adj_idx = i + delta;
17387                 struct bpf_insn insn;
17388                 int load_reg;
17389
17390                 insn = insns[adj_idx];
17391                 load_reg = insn_def_regno(&insn);
17392                 if (!aux[adj_idx].zext_dst) {
17393                         u8 code, class;
17394                         u32 imm_rnd;
17395
17396                         if (!rnd_hi32)
17397                                 continue;
17398
17399                         code = insn.code;
17400                         class = BPF_CLASS(code);
17401                         if (load_reg == -1)
17402                                 continue;
17403
17404                         /* NOTE: arg "reg" (the fourth one) is only used for
17405                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
17406                          *       here.
17407                          */
17408                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17409                                 if (class == BPF_LD &&
17410                                     BPF_MODE(code) == BPF_IMM)
17411                                         i++;
17412                                 continue;
17413                         }
17414
17415                         /* ctx load could be transformed into wider load. */
17416                         if (class == BPF_LDX &&
17417                             aux[adj_idx].ptr_type == PTR_TO_CTX)
17418                                 continue;
17419
17420                         imm_rnd = get_random_u32();
17421                         rnd_hi32_patch[0] = insn;
17422                         rnd_hi32_patch[1].imm = imm_rnd;
17423                         rnd_hi32_patch[3].dst_reg = load_reg;
17424                         patch = rnd_hi32_patch;
17425                         patch_len = 4;
17426                         goto apply_patch_buffer;
17427                 }
17428
17429                 /* Add in an zero-extend instruction if a) the JIT has requested
17430                  * it or b) it's a CMPXCHG.
17431                  *
17432                  * The latter is because: BPF_CMPXCHG always loads a value into
17433                  * R0, therefore always zero-extends. However some archs'
17434                  * equivalent instruction only does this load when the
17435                  * comparison is successful. This detail of CMPXCHG is
17436                  * orthogonal to the general zero-extension behaviour of the
17437                  * CPU, so it's treated independently of bpf_jit_needs_zext.
17438                  */
17439                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17440                         continue;
17441
17442                 /* Zero-extension is done by the caller. */
17443                 if (bpf_pseudo_kfunc_call(&insn))
17444                         continue;
17445
17446                 if (WARN_ON(load_reg == -1)) {
17447                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17448                         return -EFAULT;
17449                 }
17450
17451                 zext_patch[0] = insn;
17452                 zext_patch[1].dst_reg = load_reg;
17453                 zext_patch[1].src_reg = load_reg;
17454                 patch = zext_patch;
17455                 patch_len = 2;
17456 apply_patch_buffer:
17457                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17458                 if (!new_prog)
17459                         return -ENOMEM;
17460                 env->prog = new_prog;
17461                 insns = new_prog->insnsi;
17462                 aux = env->insn_aux_data;
17463                 delta += patch_len - 1;
17464         }
17465
17466         return 0;
17467 }
17468
17469 /* convert load instructions that access fields of a context type into a
17470  * sequence of instructions that access fields of the underlying structure:
17471  *     struct __sk_buff    -> struct sk_buff
17472  *     struct bpf_sock_ops -> struct sock
17473  */
17474 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17475 {
17476         const struct bpf_verifier_ops *ops = env->ops;
17477         int i, cnt, size, ctx_field_size, delta = 0;
17478         const int insn_cnt = env->prog->len;
17479         struct bpf_insn insn_buf[16], *insn;
17480         u32 target_size, size_default, off;
17481         struct bpf_prog *new_prog;
17482         enum bpf_access_type type;
17483         bool is_narrower_load;
17484
17485         if (ops->gen_prologue || env->seen_direct_write) {
17486                 if (!ops->gen_prologue) {
17487                         verbose(env, "bpf verifier is misconfigured\n");
17488                         return -EINVAL;
17489                 }
17490                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17491                                         env->prog);
17492                 if (cnt >= ARRAY_SIZE(insn_buf)) {
17493                         verbose(env, "bpf verifier is misconfigured\n");
17494                         return -EINVAL;
17495                 } else if (cnt) {
17496                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17497                         if (!new_prog)
17498                                 return -ENOMEM;
17499
17500                         env->prog = new_prog;
17501                         delta += cnt - 1;
17502                 }
17503         }
17504
17505         if (bpf_prog_is_offloaded(env->prog->aux))
17506                 return 0;
17507
17508         insn = env->prog->insnsi + delta;
17509
17510         for (i = 0; i < insn_cnt; i++, insn++) {
17511                 bpf_convert_ctx_access_t convert_ctx_access;
17512
17513                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17514                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17515                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17516                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17517                         type = BPF_READ;
17518                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17519                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17520                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17521                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17522                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17523                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17524                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17525                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17526                         type = BPF_WRITE;
17527                 } else {
17528                         continue;
17529                 }
17530
17531                 if (type == BPF_WRITE &&
17532                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
17533                         struct bpf_insn patch[] = {
17534                                 *insn,
17535                                 BPF_ST_NOSPEC(),
17536                         };
17537
17538                         cnt = ARRAY_SIZE(patch);
17539                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17540                         if (!new_prog)
17541                                 return -ENOMEM;
17542
17543                         delta    += cnt - 1;
17544                         env->prog = new_prog;
17545                         insn      = new_prog->insnsi + i + delta;
17546                         continue;
17547                 }
17548
17549                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17550                 case PTR_TO_CTX:
17551                         if (!ops->convert_ctx_access)
17552                                 continue;
17553                         convert_ctx_access = ops->convert_ctx_access;
17554                         break;
17555                 case PTR_TO_SOCKET:
17556                 case PTR_TO_SOCK_COMMON:
17557                         convert_ctx_access = bpf_sock_convert_ctx_access;
17558                         break;
17559                 case PTR_TO_TCP_SOCK:
17560                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17561                         break;
17562                 case PTR_TO_XDP_SOCK:
17563                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17564                         break;
17565                 case PTR_TO_BTF_ID:
17566                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17567                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17568                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17569                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
17570                  * any faults for loads into such types. BPF_WRITE is disallowed
17571                  * for this case.
17572                  */
17573                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17574                         if (type == BPF_READ) {
17575                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
17576                                         BPF_SIZE((insn)->code);
17577                                 env->prog->aux->num_exentries++;
17578                         }
17579                         continue;
17580                 default:
17581                         continue;
17582                 }
17583
17584                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17585                 size = BPF_LDST_BYTES(insn);
17586
17587                 /* If the read access is a narrower load of the field,
17588                  * convert to a 4/8-byte load, to minimum program type specific
17589                  * convert_ctx_access changes. If conversion is successful,
17590                  * we will apply proper mask to the result.
17591                  */
17592                 is_narrower_load = size < ctx_field_size;
17593                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17594                 off = insn->off;
17595                 if (is_narrower_load) {
17596                         u8 size_code;
17597
17598                         if (type == BPF_WRITE) {
17599                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17600                                 return -EINVAL;
17601                         }
17602
17603                         size_code = BPF_H;
17604                         if (ctx_field_size == 4)
17605                                 size_code = BPF_W;
17606                         else if (ctx_field_size == 8)
17607                                 size_code = BPF_DW;
17608
17609                         insn->off = off & ~(size_default - 1);
17610                         insn->code = BPF_LDX | BPF_MEM | size_code;
17611                 }
17612
17613                 target_size = 0;
17614                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17615                                          &target_size);
17616                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17617                     (ctx_field_size && !target_size)) {
17618                         verbose(env, "bpf verifier is misconfigured\n");
17619                         return -EINVAL;
17620                 }
17621
17622                 if (is_narrower_load && size < target_size) {
17623                         u8 shift = bpf_ctx_narrow_access_offset(
17624                                 off, size, size_default) * 8;
17625                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17626                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17627                                 return -EINVAL;
17628                         }
17629                         if (ctx_field_size <= 4) {
17630                                 if (shift)
17631                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17632                                                                         insn->dst_reg,
17633                                                                         shift);
17634                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17635                                                                 (1 << size * 8) - 1);
17636                         } else {
17637                                 if (shift)
17638                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17639                                                                         insn->dst_reg,
17640                                                                         shift);
17641                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17642                                                                 (1ULL << size * 8) - 1);
17643                         }
17644                 }
17645
17646                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17647                 if (!new_prog)
17648                         return -ENOMEM;
17649
17650                 delta += cnt - 1;
17651
17652                 /* keep walking new program and skip insns we just inserted */
17653                 env->prog = new_prog;
17654                 insn      = new_prog->insnsi + i + delta;
17655         }
17656
17657         return 0;
17658 }
17659
17660 static int jit_subprogs(struct bpf_verifier_env *env)
17661 {
17662         struct bpf_prog *prog = env->prog, **func, *tmp;
17663         int i, j, subprog_start, subprog_end = 0, len, subprog;
17664         struct bpf_map *map_ptr;
17665         struct bpf_insn *insn;
17666         void *old_bpf_func;
17667         int err, num_exentries;
17668
17669         if (env->subprog_cnt <= 1)
17670                 return 0;
17671
17672         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17673                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17674                         continue;
17675
17676                 /* Upon error here we cannot fall back to interpreter but
17677                  * need a hard reject of the program. Thus -EFAULT is
17678                  * propagated in any case.
17679                  */
17680                 subprog = find_subprog(env, i + insn->imm + 1);
17681                 if (subprog < 0) {
17682                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17683                                   i + insn->imm + 1);
17684                         return -EFAULT;
17685                 }
17686                 /* temporarily remember subprog id inside insn instead of
17687                  * aux_data, since next loop will split up all insns into funcs
17688                  */
17689                 insn->off = subprog;
17690                 /* remember original imm in case JIT fails and fallback
17691                  * to interpreter will be needed
17692                  */
17693                 env->insn_aux_data[i].call_imm = insn->imm;
17694                 /* point imm to __bpf_call_base+1 from JITs point of view */
17695                 insn->imm = 1;
17696                 if (bpf_pseudo_func(insn))
17697                         /* jit (e.g. x86_64) may emit fewer instructions
17698                          * if it learns a u32 imm is the same as a u64 imm.
17699                          * Force a non zero here.
17700                          */
17701                         insn[1].imm = 1;
17702         }
17703
17704         err = bpf_prog_alloc_jited_linfo(prog);
17705         if (err)
17706                 goto out_undo_insn;
17707
17708         err = -ENOMEM;
17709         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17710         if (!func)
17711                 goto out_undo_insn;
17712
17713         for (i = 0; i < env->subprog_cnt; i++) {
17714                 subprog_start = subprog_end;
17715                 subprog_end = env->subprog_info[i + 1].start;
17716
17717                 len = subprog_end - subprog_start;
17718                 /* bpf_prog_run() doesn't call subprogs directly,
17719                  * hence main prog stats include the runtime of subprogs.
17720                  * subprogs don't have IDs and not reachable via prog_get_next_id
17721                  * func[i]->stats will never be accessed and stays NULL
17722                  */
17723                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17724                 if (!func[i])
17725                         goto out_free;
17726                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17727                        len * sizeof(struct bpf_insn));
17728                 func[i]->type = prog->type;
17729                 func[i]->len = len;
17730                 if (bpf_prog_calc_tag(func[i]))
17731                         goto out_free;
17732                 func[i]->is_func = 1;
17733                 func[i]->aux->func_idx = i;
17734                 /* Below members will be freed only at prog->aux */
17735                 func[i]->aux->btf = prog->aux->btf;
17736                 func[i]->aux->func_info = prog->aux->func_info;
17737                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17738                 func[i]->aux->poke_tab = prog->aux->poke_tab;
17739                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17740
17741                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17742                         struct bpf_jit_poke_descriptor *poke;
17743
17744                         poke = &prog->aux->poke_tab[j];
17745                         if (poke->insn_idx < subprog_end &&
17746                             poke->insn_idx >= subprog_start)
17747                                 poke->aux = func[i]->aux;
17748                 }
17749
17750                 func[i]->aux->name[0] = 'F';
17751                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17752                 func[i]->jit_requested = 1;
17753                 func[i]->blinding_requested = prog->blinding_requested;
17754                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17755                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17756                 func[i]->aux->linfo = prog->aux->linfo;
17757                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17758                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17759                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17760                 num_exentries = 0;
17761                 insn = func[i]->insnsi;
17762                 for (j = 0; j < func[i]->len; j++, insn++) {
17763                         if (BPF_CLASS(insn->code) == BPF_LDX &&
17764                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
17765                                 num_exentries++;
17766                 }
17767                 func[i]->aux->num_exentries = num_exentries;
17768                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17769                 func[i] = bpf_int_jit_compile(func[i]);
17770                 if (!func[i]->jited) {
17771                         err = -ENOTSUPP;
17772                         goto out_free;
17773                 }
17774                 cond_resched();
17775         }
17776
17777         /* at this point all bpf functions were successfully JITed
17778          * now populate all bpf_calls with correct addresses and
17779          * run last pass of JIT
17780          */
17781         for (i = 0; i < env->subprog_cnt; i++) {
17782                 insn = func[i]->insnsi;
17783                 for (j = 0; j < func[i]->len; j++, insn++) {
17784                         if (bpf_pseudo_func(insn)) {
17785                                 subprog = insn->off;
17786                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17787                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17788                                 continue;
17789                         }
17790                         if (!bpf_pseudo_call(insn))
17791                                 continue;
17792                         subprog = insn->off;
17793                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17794                 }
17795
17796                 /* we use the aux data to keep a list of the start addresses
17797                  * of the JITed images for each function in the program
17798                  *
17799                  * for some architectures, such as powerpc64, the imm field
17800                  * might not be large enough to hold the offset of the start
17801                  * address of the callee's JITed image from __bpf_call_base
17802                  *
17803                  * in such cases, we can lookup the start address of a callee
17804                  * by using its subprog id, available from the off field of
17805                  * the call instruction, as an index for this list
17806                  */
17807                 func[i]->aux->func = func;
17808                 func[i]->aux->func_cnt = env->subprog_cnt;
17809         }
17810         for (i = 0; i < env->subprog_cnt; i++) {
17811                 old_bpf_func = func[i]->bpf_func;
17812                 tmp = bpf_int_jit_compile(func[i]);
17813                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17814                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17815                         err = -ENOTSUPP;
17816                         goto out_free;
17817                 }
17818                 cond_resched();
17819         }
17820
17821         /* finally lock prog and jit images for all functions and
17822          * populate kallsysm. Begin at the first subprogram, since
17823          * bpf_prog_load will add the kallsyms for the main program.
17824          */
17825         for (i = 1; i < env->subprog_cnt; i++) {
17826                 bpf_prog_lock_ro(func[i]);
17827                 bpf_prog_kallsyms_add(func[i]);
17828         }
17829
17830         /* Last step: make now unused interpreter insns from main
17831          * prog consistent for later dump requests, so they can
17832          * later look the same as if they were interpreted only.
17833          */
17834         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17835                 if (bpf_pseudo_func(insn)) {
17836                         insn[0].imm = env->insn_aux_data[i].call_imm;
17837                         insn[1].imm = insn->off;
17838                         insn->off = 0;
17839                         continue;
17840                 }
17841                 if (!bpf_pseudo_call(insn))
17842                         continue;
17843                 insn->off = env->insn_aux_data[i].call_imm;
17844                 subprog = find_subprog(env, i + insn->off + 1);
17845                 insn->imm = subprog;
17846         }
17847
17848         prog->jited = 1;
17849         prog->bpf_func = func[0]->bpf_func;
17850         prog->jited_len = func[0]->jited_len;
17851         prog->aux->extable = func[0]->aux->extable;
17852         prog->aux->num_exentries = func[0]->aux->num_exentries;
17853         prog->aux->func = func;
17854         prog->aux->func_cnt = env->subprog_cnt;
17855         bpf_prog_jit_attempt_done(prog);
17856         return 0;
17857 out_free:
17858         /* We failed JIT'ing, so at this point we need to unregister poke
17859          * descriptors from subprogs, so that kernel is not attempting to
17860          * patch it anymore as we're freeing the subprog JIT memory.
17861          */
17862         for (i = 0; i < prog->aux->size_poke_tab; i++) {
17863                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17864                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17865         }
17866         /* At this point we're guaranteed that poke descriptors are not
17867          * live anymore. We can just unlink its descriptor table as it's
17868          * released with the main prog.
17869          */
17870         for (i = 0; i < env->subprog_cnt; i++) {
17871                 if (!func[i])
17872                         continue;
17873                 func[i]->aux->poke_tab = NULL;
17874                 bpf_jit_free(func[i]);
17875         }
17876         kfree(func);
17877 out_undo_insn:
17878         /* cleanup main prog to be interpreted */
17879         prog->jit_requested = 0;
17880         prog->blinding_requested = 0;
17881         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17882                 if (!bpf_pseudo_call(insn))
17883                         continue;
17884                 insn->off = 0;
17885                 insn->imm = env->insn_aux_data[i].call_imm;
17886         }
17887         bpf_prog_jit_attempt_done(prog);
17888         return err;
17889 }
17890
17891 static int fixup_call_args(struct bpf_verifier_env *env)
17892 {
17893 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17894         struct bpf_prog *prog = env->prog;
17895         struct bpf_insn *insn = prog->insnsi;
17896         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17897         int i, depth;
17898 #endif
17899         int err = 0;
17900
17901         if (env->prog->jit_requested &&
17902             !bpf_prog_is_offloaded(env->prog->aux)) {
17903                 err = jit_subprogs(env);
17904                 if (err == 0)
17905                         return 0;
17906                 if (err == -EFAULT)
17907                         return err;
17908         }
17909 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17910         if (has_kfunc_call) {
17911                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17912                 return -EINVAL;
17913         }
17914         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17915                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
17916                  * have to be rejected, since interpreter doesn't support them yet.
17917                  */
17918                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17919                 return -EINVAL;
17920         }
17921         for (i = 0; i < prog->len; i++, insn++) {
17922                 if (bpf_pseudo_func(insn)) {
17923                         /* When JIT fails the progs with callback calls
17924                          * have to be rejected, since interpreter doesn't support them yet.
17925                          */
17926                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
17927                         return -EINVAL;
17928                 }
17929
17930                 if (!bpf_pseudo_call(insn))
17931                         continue;
17932                 depth = get_callee_stack_depth(env, insn, i);
17933                 if (depth < 0)
17934                         return depth;
17935                 bpf_patch_call_args(insn, depth);
17936         }
17937         err = 0;
17938 #endif
17939         return err;
17940 }
17941
17942 /* replace a generic kfunc with a specialized version if necessary */
17943 static void specialize_kfunc(struct bpf_verifier_env *env,
17944                              u32 func_id, u16 offset, unsigned long *addr)
17945 {
17946         struct bpf_prog *prog = env->prog;
17947         bool seen_direct_write;
17948         void *xdp_kfunc;
17949         bool is_rdonly;
17950
17951         if (bpf_dev_bound_kfunc_id(func_id)) {
17952                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17953                 if (xdp_kfunc) {
17954                         *addr = (unsigned long)xdp_kfunc;
17955                         return;
17956                 }
17957                 /* fallback to default kfunc when not supported by netdev */
17958         }
17959
17960         if (offset)
17961                 return;
17962
17963         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17964                 seen_direct_write = env->seen_direct_write;
17965                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17966
17967                 if (is_rdonly)
17968                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17969
17970                 /* restore env->seen_direct_write to its original value, since
17971                  * may_access_direct_pkt_data mutates it
17972                  */
17973                 env->seen_direct_write = seen_direct_write;
17974         }
17975 }
17976
17977 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17978                                             u16 struct_meta_reg,
17979                                             u16 node_offset_reg,
17980                                             struct bpf_insn *insn,
17981                                             struct bpf_insn *insn_buf,
17982                                             int *cnt)
17983 {
17984         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17985         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17986
17987         insn_buf[0] = addr[0];
17988         insn_buf[1] = addr[1];
17989         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17990         insn_buf[3] = *insn;
17991         *cnt = 4;
17992 }
17993
17994 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17995                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17996 {
17997         const struct bpf_kfunc_desc *desc;
17998
17999         if (!insn->imm) {
18000                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18001                 return -EINVAL;
18002         }
18003
18004         *cnt = 0;
18005
18006         /* insn->imm has the btf func_id. Replace it with an offset relative to
18007          * __bpf_call_base, unless the JIT needs to call functions that are
18008          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18009          */
18010         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18011         if (!desc) {
18012                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18013                         insn->imm);
18014                 return -EFAULT;
18015         }
18016
18017         if (!bpf_jit_supports_far_kfunc_call())
18018                 insn->imm = BPF_CALL_IMM(desc->addr);
18019         if (insn->off)
18020                 return 0;
18021         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18022                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18023                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18024                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18025
18026                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18027                 insn_buf[1] = addr[0];
18028                 insn_buf[2] = addr[1];
18029                 insn_buf[3] = *insn;
18030                 *cnt = 4;
18031         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18032                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18033                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18034                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18035
18036                 insn_buf[0] = addr[0];
18037                 insn_buf[1] = addr[1];
18038                 insn_buf[2] = *insn;
18039                 *cnt = 3;
18040         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18041                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18042                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18043                 int struct_meta_reg = BPF_REG_3;
18044                 int node_offset_reg = BPF_REG_4;
18045
18046                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18047                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18048                         struct_meta_reg = BPF_REG_4;
18049                         node_offset_reg = BPF_REG_5;
18050                 }
18051
18052                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18053                                                 node_offset_reg, insn, insn_buf, cnt);
18054         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18055                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18056                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18057                 *cnt = 1;
18058         }
18059         return 0;
18060 }
18061
18062 /* Do various post-verification rewrites in a single program pass.
18063  * These rewrites simplify JIT and interpreter implementations.
18064  */
18065 static int do_misc_fixups(struct bpf_verifier_env *env)
18066 {
18067         struct bpf_prog *prog = env->prog;
18068         enum bpf_attach_type eatype = prog->expected_attach_type;
18069         enum bpf_prog_type prog_type = resolve_prog_type(prog);
18070         struct bpf_insn *insn = prog->insnsi;
18071         const struct bpf_func_proto *fn;
18072         const int insn_cnt = prog->len;
18073         const struct bpf_map_ops *ops;
18074         struct bpf_insn_aux_data *aux;
18075         struct bpf_insn insn_buf[16];
18076         struct bpf_prog *new_prog;
18077         struct bpf_map *map_ptr;
18078         int i, ret, cnt, delta = 0;
18079
18080         for (i = 0; i < insn_cnt; i++, insn++) {
18081                 /* Make divide-by-zero exceptions impossible. */
18082                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18083                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18084                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18085                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18086                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18087                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18088                         struct bpf_insn *patchlet;
18089                         struct bpf_insn chk_and_div[] = {
18090                                 /* [R,W]x div 0 -> 0 */
18091                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18092                                              BPF_JNE | BPF_K, insn->src_reg,
18093                                              0, 2, 0),
18094                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18095                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18096                                 *insn,
18097                         };
18098                         struct bpf_insn chk_and_mod[] = {
18099                                 /* [R,W]x mod 0 -> [R,W]x */
18100                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18101                                              BPF_JEQ | BPF_K, insn->src_reg,
18102                                              0, 1 + (is64 ? 0 : 1), 0),
18103                                 *insn,
18104                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18105                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18106                         };
18107
18108                         patchlet = isdiv ? chk_and_div : chk_and_mod;
18109                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18110                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18111
18112                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18113                         if (!new_prog)
18114                                 return -ENOMEM;
18115
18116                         delta    += cnt - 1;
18117                         env->prog = prog = new_prog;
18118                         insn      = new_prog->insnsi + i + delta;
18119                         continue;
18120                 }
18121
18122                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18123                 if (BPF_CLASS(insn->code) == BPF_LD &&
18124                     (BPF_MODE(insn->code) == BPF_ABS ||
18125                      BPF_MODE(insn->code) == BPF_IND)) {
18126                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
18127                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18128                                 verbose(env, "bpf verifier is misconfigured\n");
18129                                 return -EINVAL;
18130                         }
18131
18132                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18133                         if (!new_prog)
18134                                 return -ENOMEM;
18135
18136                         delta    += cnt - 1;
18137                         env->prog = prog = new_prog;
18138                         insn      = new_prog->insnsi + i + delta;
18139                         continue;
18140                 }
18141
18142                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18143                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18144                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18145                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18146                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18147                         struct bpf_insn *patch = &insn_buf[0];
18148                         bool issrc, isneg, isimm;
18149                         u32 off_reg;
18150
18151                         aux = &env->insn_aux_data[i + delta];
18152                         if (!aux->alu_state ||
18153                             aux->alu_state == BPF_ALU_NON_POINTER)
18154                                 continue;
18155
18156                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18157                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18158                                 BPF_ALU_SANITIZE_SRC;
18159                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18160
18161                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
18162                         if (isimm) {
18163                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18164                         } else {
18165                                 if (isneg)
18166                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18167                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18168                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18169                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18170                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18171                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18172                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18173                         }
18174                         if (!issrc)
18175                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18176                         insn->src_reg = BPF_REG_AX;
18177                         if (isneg)
18178                                 insn->code = insn->code == code_add ?
18179                                              code_sub : code_add;
18180                         *patch++ = *insn;
18181                         if (issrc && isneg && !isimm)
18182                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18183                         cnt = patch - insn_buf;
18184
18185                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18186                         if (!new_prog)
18187                                 return -ENOMEM;
18188
18189                         delta    += cnt - 1;
18190                         env->prog = prog = new_prog;
18191                         insn      = new_prog->insnsi + i + delta;
18192                         continue;
18193                 }
18194
18195                 if (insn->code != (BPF_JMP | BPF_CALL))
18196                         continue;
18197                 if (insn->src_reg == BPF_PSEUDO_CALL)
18198                         continue;
18199                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18200                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18201                         if (ret)
18202                                 return ret;
18203                         if (cnt == 0)
18204                                 continue;
18205
18206                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18207                         if (!new_prog)
18208                                 return -ENOMEM;
18209
18210                         delta    += cnt - 1;
18211                         env->prog = prog = new_prog;
18212                         insn      = new_prog->insnsi + i + delta;
18213                         continue;
18214                 }
18215
18216                 if (insn->imm == BPF_FUNC_get_route_realm)
18217                         prog->dst_needed = 1;
18218                 if (insn->imm == BPF_FUNC_get_prandom_u32)
18219                         bpf_user_rnd_init_once();
18220                 if (insn->imm == BPF_FUNC_override_return)
18221                         prog->kprobe_override = 1;
18222                 if (insn->imm == BPF_FUNC_tail_call) {
18223                         /* If we tail call into other programs, we
18224                          * cannot make any assumptions since they can
18225                          * be replaced dynamically during runtime in
18226                          * the program array.
18227                          */
18228                         prog->cb_access = 1;
18229                         if (!allow_tail_call_in_subprogs(env))
18230                                 prog->aux->stack_depth = MAX_BPF_STACK;
18231                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18232
18233                         /* mark bpf_tail_call as different opcode to avoid
18234                          * conditional branch in the interpreter for every normal
18235                          * call and to prevent accidental JITing by JIT compiler
18236                          * that doesn't support bpf_tail_call yet
18237                          */
18238                         insn->imm = 0;
18239                         insn->code = BPF_JMP | BPF_TAIL_CALL;
18240
18241                         aux = &env->insn_aux_data[i + delta];
18242                         if (env->bpf_capable && !prog->blinding_requested &&
18243                             prog->jit_requested &&
18244                             !bpf_map_key_poisoned(aux) &&
18245                             !bpf_map_ptr_poisoned(aux) &&
18246                             !bpf_map_ptr_unpriv(aux)) {
18247                                 struct bpf_jit_poke_descriptor desc = {
18248                                         .reason = BPF_POKE_REASON_TAIL_CALL,
18249                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18250                                         .tail_call.key = bpf_map_key_immediate(aux),
18251                                         .insn_idx = i + delta,
18252                                 };
18253
18254                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18255                                 if (ret < 0) {
18256                                         verbose(env, "adding tail call poke descriptor failed\n");
18257                                         return ret;
18258                                 }
18259
18260                                 insn->imm = ret + 1;
18261                                 continue;
18262                         }
18263
18264                         if (!bpf_map_ptr_unpriv(aux))
18265                                 continue;
18266
18267                         /* instead of changing every JIT dealing with tail_call
18268                          * emit two extra insns:
18269                          * if (index >= max_entries) goto out;
18270                          * index &= array->index_mask;
18271                          * to avoid out-of-bounds cpu speculation
18272                          */
18273                         if (bpf_map_ptr_poisoned(aux)) {
18274                                 verbose(env, "tail_call abusing map_ptr\n");
18275                                 return -EINVAL;
18276                         }
18277
18278                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18279                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18280                                                   map_ptr->max_entries, 2);
18281                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18282                                                     container_of(map_ptr,
18283                                                                  struct bpf_array,
18284                                                                  map)->index_mask);
18285                         insn_buf[2] = *insn;
18286                         cnt = 3;
18287                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18288                         if (!new_prog)
18289                                 return -ENOMEM;
18290
18291                         delta    += cnt - 1;
18292                         env->prog = prog = new_prog;
18293                         insn      = new_prog->insnsi + i + delta;
18294                         continue;
18295                 }
18296
18297                 if (insn->imm == BPF_FUNC_timer_set_callback) {
18298                         /* The verifier will process callback_fn as many times as necessary
18299                          * with different maps and the register states prepared by
18300                          * set_timer_callback_state will be accurate.
18301                          *
18302                          * The following use case is valid:
18303                          *   map1 is shared by prog1, prog2, prog3.
18304                          *   prog1 calls bpf_timer_init for some map1 elements
18305                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
18306                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
18307                          *   prog3 calls bpf_timer_start for some map1 elements.
18308                          *     Those that were not both bpf_timer_init-ed and
18309                          *     bpf_timer_set_callback-ed will return -EINVAL.
18310                          */
18311                         struct bpf_insn ld_addrs[2] = {
18312                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18313                         };
18314
18315                         insn_buf[0] = ld_addrs[0];
18316                         insn_buf[1] = ld_addrs[1];
18317                         insn_buf[2] = *insn;
18318                         cnt = 3;
18319
18320                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18321                         if (!new_prog)
18322                                 return -ENOMEM;
18323
18324                         delta    += cnt - 1;
18325                         env->prog = prog = new_prog;
18326                         insn      = new_prog->insnsi + i + delta;
18327                         goto patch_call_imm;
18328                 }
18329
18330                 if (is_storage_get_function(insn->imm)) {
18331                         if (!env->prog->aux->sleepable ||
18332                             env->insn_aux_data[i + delta].storage_get_func_atomic)
18333                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18334                         else
18335                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18336                         insn_buf[1] = *insn;
18337                         cnt = 2;
18338
18339                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18340                         if (!new_prog)
18341                                 return -ENOMEM;
18342
18343                         delta += cnt - 1;
18344                         env->prog = prog = new_prog;
18345                         insn = new_prog->insnsi + i + delta;
18346                         goto patch_call_imm;
18347                 }
18348
18349                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18350                  * and other inlining handlers are currently limited to 64 bit
18351                  * only.
18352                  */
18353                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18354                     (insn->imm == BPF_FUNC_map_lookup_elem ||
18355                      insn->imm == BPF_FUNC_map_update_elem ||
18356                      insn->imm == BPF_FUNC_map_delete_elem ||
18357                      insn->imm == BPF_FUNC_map_push_elem   ||
18358                      insn->imm == BPF_FUNC_map_pop_elem    ||
18359                      insn->imm == BPF_FUNC_map_peek_elem   ||
18360                      insn->imm == BPF_FUNC_redirect_map    ||
18361                      insn->imm == BPF_FUNC_for_each_map_elem ||
18362                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18363                         aux = &env->insn_aux_data[i + delta];
18364                         if (bpf_map_ptr_poisoned(aux))
18365                                 goto patch_call_imm;
18366
18367                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18368                         ops = map_ptr->ops;
18369                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
18370                             ops->map_gen_lookup) {
18371                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18372                                 if (cnt == -EOPNOTSUPP)
18373                                         goto patch_map_ops_generic;
18374                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18375                                         verbose(env, "bpf verifier is misconfigured\n");
18376                                         return -EINVAL;
18377                                 }
18378
18379                                 new_prog = bpf_patch_insn_data(env, i + delta,
18380                                                                insn_buf, cnt);
18381                                 if (!new_prog)
18382                                         return -ENOMEM;
18383
18384                                 delta    += cnt - 1;
18385                                 env->prog = prog = new_prog;
18386                                 insn      = new_prog->insnsi + i + delta;
18387                                 continue;
18388                         }
18389
18390                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18391                                      (void *(*)(struct bpf_map *map, void *key))NULL));
18392                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18393                                      (long (*)(struct bpf_map *map, void *key))NULL));
18394                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18395                                      (long (*)(struct bpf_map *map, void *key, void *value,
18396                                               u64 flags))NULL));
18397                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18398                                      (long (*)(struct bpf_map *map, void *value,
18399                                               u64 flags))NULL));
18400                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18401                                      (long (*)(struct bpf_map *map, void *value))NULL));
18402                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18403                                      (long (*)(struct bpf_map *map, void *value))NULL));
18404                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
18405                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18406                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18407                                      (long (*)(struct bpf_map *map,
18408                                               bpf_callback_t callback_fn,
18409                                               void *callback_ctx,
18410                                               u64 flags))NULL));
18411                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18412                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18413
18414 patch_map_ops_generic:
18415                         switch (insn->imm) {
18416                         case BPF_FUNC_map_lookup_elem:
18417                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18418                                 continue;
18419                         case BPF_FUNC_map_update_elem:
18420                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18421                                 continue;
18422                         case BPF_FUNC_map_delete_elem:
18423                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18424                                 continue;
18425                         case BPF_FUNC_map_push_elem:
18426                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18427                                 continue;
18428                         case BPF_FUNC_map_pop_elem:
18429                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18430                                 continue;
18431                         case BPF_FUNC_map_peek_elem:
18432                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18433                                 continue;
18434                         case BPF_FUNC_redirect_map:
18435                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18436                                 continue;
18437                         case BPF_FUNC_for_each_map_elem:
18438                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18439                                 continue;
18440                         case BPF_FUNC_map_lookup_percpu_elem:
18441                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18442                                 continue;
18443                         }
18444
18445                         goto patch_call_imm;
18446                 }
18447
18448                 /* Implement bpf_jiffies64 inline. */
18449                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18450                     insn->imm == BPF_FUNC_jiffies64) {
18451                         struct bpf_insn ld_jiffies_addr[2] = {
18452                                 BPF_LD_IMM64(BPF_REG_0,
18453                                              (unsigned long)&jiffies),
18454                         };
18455
18456                         insn_buf[0] = ld_jiffies_addr[0];
18457                         insn_buf[1] = ld_jiffies_addr[1];
18458                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18459                                                   BPF_REG_0, 0);
18460                         cnt = 3;
18461
18462                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18463                                                        cnt);
18464                         if (!new_prog)
18465                                 return -ENOMEM;
18466
18467                         delta    += cnt - 1;
18468                         env->prog = prog = new_prog;
18469                         insn      = new_prog->insnsi + i + delta;
18470                         continue;
18471                 }
18472
18473                 /* Implement bpf_get_func_arg inline. */
18474                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18475                     insn->imm == BPF_FUNC_get_func_arg) {
18476                         /* Load nr_args from ctx - 8 */
18477                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18478                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18479                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18480                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18481                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18482                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18483                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18484                         insn_buf[7] = BPF_JMP_A(1);
18485                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18486                         cnt = 9;
18487
18488                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18489                         if (!new_prog)
18490                                 return -ENOMEM;
18491
18492                         delta    += cnt - 1;
18493                         env->prog = prog = new_prog;
18494                         insn      = new_prog->insnsi + i + delta;
18495                         continue;
18496                 }
18497
18498                 /* Implement bpf_get_func_ret inline. */
18499                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18500                     insn->imm == BPF_FUNC_get_func_ret) {
18501                         if (eatype == BPF_TRACE_FEXIT ||
18502                             eatype == BPF_MODIFY_RETURN) {
18503                                 /* Load nr_args from ctx - 8 */
18504                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18505                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18506                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18507                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18508                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18509                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18510                                 cnt = 6;
18511                         } else {
18512                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18513                                 cnt = 1;
18514                         }
18515
18516                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18517                         if (!new_prog)
18518                                 return -ENOMEM;
18519
18520                         delta    += cnt - 1;
18521                         env->prog = prog = new_prog;
18522                         insn      = new_prog->insnsi + i + delta;
18523                         continue;
18524                 }
18525
18526                 /* Implement get_func_arg_cnt inline. */
18527                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18528                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
18529                         /* Load nr_args from ctx - 8 */
18530                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18531
18532                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18533                         if (!new_prog)
18534                                 return -ENOMEM;
18535
18536                         env->prog = prog = new_prog;
18537                         insn      = new_prog->insnsi + i + delta;
18538                         continue;
18539                 }
18540
18541                 /* Implement bpf_get_func_ip inline. */
18542                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18543                     insn->imm == BPF_FUNC_get_func_ip) {
18544                         /* Load IP address from ctx - 16 */
18545                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18546
18547                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18548                         if (!new_prog)
18549                                 return -ENOMEM;
18550
18551                         env->prog = prog = new_prog;
18552                         insn      = new_prog->insnsi + i + delta;
18553                         continue;
18554                 }
18555
18556 patch_call_imm:
18557                 fn = env->ops->get_func_proto(insn->imm, env->prog);
18558                 /* all functions that have prototype and verifier allowed
18559                  * programs to call them, must be real in-kernel functions
18560                  */
18561                 if (!fn->func) {
18562                         verbose(env,
18563                                 "kernel subsystem misconfigured func %s#%d\n",
18564                                 func_id_name(insn->imm), insn->imm);
18565                         return -EFAULT;
18566                 }
18567                 insn->imm = fn->func - __bpf_call_base;
18568         }
18569
18570         /* Since poke tab is now finalized, publish aux to tracker. */
18571         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18572                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18573                 if (!map_ptr->ops->map_poke_track ||
18574                     !map_ptr->ops->map_poke_untrack ||
18575                     !map_ptr->ops->map_poke_run) {
18576                         verbose(env, "bpf verifier is misconfigured\n");
18577                         return -EINVAL;
18578                 }
18579
18580                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18581                 if (ret < 0) {
18582                         verbose(env, "tracking tail call prog failed\n");
18583                         return ret;
18584                 }
18585         }
18586
18587         sort_kfunc_descs_by_imm_off(env->prog);
18588
18589         return 0;
18590 }
18591
18592 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18593                                         int position,
18594                                         s32 stack_base,
18595                                         u32 callback_subprogno,
18596                                         u32 *cnt)
18597 {
18598         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18599         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18600         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18601         int reg_loop_max = BPF_REG_6;
18602         int reg_loop_cnt = BPF_REG_7;
18603         int reg_loop_ctx = BPF_REG_8;
18604
18605         struct bpf_prog *new_prog;
18606         u32 callback_start;
18607         u32 call_insn_offset;
18608         s32 callback_offset;
18609
18610         /* This represents an inlined version of bpf_iter.c:bpf_loop,
18611          * be careful to modify this code in sync.
18612          */
18613         struct bpf_insn insn_buf[] = {
18614                 /* Return error and jump to the end of the patch if
18615                  * expected number of iterations is too big.
18616                  */
18617                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18618                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18619                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18620                 /* spill R6, R7, R8 to use these as loop vars */
18621                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18622                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18623                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18624                 /* initialize loop vars */
18625                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18626                 BPF_MOV32_IMM(reg_loop_cnt, 0),
18627                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18628                 /* loop header,
18629                  * if reg_loop_cnt >= reg_loop_max skip the loop body
18630                  */
18631                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18632                 /* callback call,
18633                  * correct callback offset would be set after patching
18634                  */
18635                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18636                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18637                 BPF_CALL_REL(0),
18638                 /* increment loop counter */
18639                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18640                 /* jump to loop header if callback returned 0 */
18641                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18642                 /* return value of bpf_loop,
18643                  * set R0 to the number of iterations
18644                  */
18645                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18646                 /* restore original values of R6, R7, R8 */
18647                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18648                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18649                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18650         };
18651
18652         *cnt = ARRAY_SIZE(insn_buf);
18653         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18654         if (!new_prog)
18655                 return new_prog;
18656
18657         /* callback start is known only after patching */
18658         callback_start = env->subprog_info[callback_subprogno].start;
18659         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18660         call_insn_offset = position + 12;
18661         callback_offset = callback_start - call_insn_offset - 1;
18662         new_prog->insnsi[call_insn_offset].imm = callback_offset;
18663
18664         return new_prog;
18665 }
18666
18667 static bool is_bpf_loop_call(struct bpf_insn *insn)
18668 {
18669         return insn->code == (BPF_JMP | BPF_CALL) &&
18670                 insn->src_reg == 0 &&
18671                 insn->imm == BPF_FUNC_loop;
18672 }
18673
18674 /* For all sub-programs in the program (including main) check
18675  * insn_aux_data to see if there are bpf_loop calls that require
18676  * inlining. If such calls are found the calls are replaced with a
18677  * sequence of instructions produced by `inline_bpf_loop` function and
18678  * subprog stack_depth is increased by the size of 3 registers.
18679  * This stack space is used to spill values of the R6, R7, R8.  These
18680  * registers are used to store the loop bound, counter and context
18681  * variables.
18682  */
18683 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18684 {
18685         struct bpf_subprog_info *subprogs = env->subprog_info;
18686         int i, cur_subprog = 0, cnt, delta = 0;
18687         struct bpf_insn *insn = env->prog->insnsi;
18688         int insn_cnt = env->prog->len;
18689         u16 stack_depth = subprogs[cur_subprog].stack_depth;
18690         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18691         u16 stack_depth_extra = 0;
18692
18693         for (i = 0; i < insn_cnt; i++, insn++) {
18694                 struct bpf_loop_inline_state *inline_state =
18695                         &env->insn_aux_data[i + delta].loop_inline_state;
18696
18697                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18698                         struct bpf_prog *new_prog;
18699
18700                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18701                         new_prog = inline_bpf_loop(env,
18702                                                    i + delta,
18703                                                    -(stack_depth + stack_depth_extra),
18704                                                    inline_state->callback_subprogno,
18705                                                    &cnt);
18706                         if (!new_prog)
18707                                 return -ENOMEM;
18708
18709                         delta     += cnt - 1;
18710                         env->prog  = new_prog;
18711                         insn       = new_prog->insnsi + i + delta;
18712                 }
18713
18714                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18715                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
18716                         cur_subprog++;
18717                         stack_depth = subprogs[cur_subprog].stack_depth;
18718                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18719                         stack_depth_extra = 0;
18720                 }
18721         }
18722
18723         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18724
18725         return 0;
18726 }
18727
18728 static void free_states(struct bpf_verifier_env *env)
18729 {
18730         struct bpf_verifier_state_list *sl, *sln;
18731         int i;
18732
18733         sl = env->free_list;
18734         while (sl) {
18735                 sln = sl->next;
18736                 free_verifier_state(&sl->state, false);
18737                 kfree(sl);
18738                 sl = sln;
18739         }
18740         env->free_list = NULL;
18741
18742         if (!env->explored_states)
18743                 return;
18744
18745         for (i = 0; i < state_htab_size(env); i++) {
18746                 sl = env->explored_states[i];
18747
18748                 while (sl) {
18749                         sln = sl->next;
18750                         free_verifier_state(&sl->state, false);
18751                         kfree(sl);
18752                         sl = sln;
18753                 }
18754                 env->explored_states[i] = NULL;
18755         }
18756 }
18757
18758 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18759 {
18760         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18761         struct bpf_verifier_state *state;
18762         struct bpf_reg_state *regs;
18763         int ret, i;
18764
18765         env->prev_linfo = NULL;
18766         env->pass_cnt++;
18767
18768         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18769         if (!state)
18770                 return -ENOMEM;
18771         state->curframe = 0;
18772         state->speculative = false;
18773         state->branches = 1;
18774         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18775         if (!state->frame[0]) {
18776                 kfree(state);
18777                 return -ENOMEM;
18778         }
18779         env->cur_state = state;
18780         init_func_state(env, state->frame[0],
18781                         BPF_MAIN_FUNC /* callsite */,
18782                         0 /* frameno */,
18783                         subprog);
18784         state->first_insn_idx = env->subprog_info[subprog].start;
18785         state->last_insn_idx = -1;
18786
18787         regs = state->frame[state->curframe]->regs;
18788         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18789                 ret = btf_prepare_func_args(env, subprog, regs);
18790                 if (ret)
18791                         goto out;
18792                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18793                         if (regs[i].type == PTR_TO_CTX)
18794                                 mark_reg_known_zero(env, regs, i);
18795                         else if (regs[i].type == SCALAR_VALUE)
18796                                 mark_reg_unknown(env, regs, i);
18797                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
18798                                 const u32 mem_size = regs[i].mem_size;
18799
18800                                 mark_reg_known_zero(env, regs, i);
18801                                 regs[i].mem_size = mem_size;
18802                                 regs[i].id = ++env->id_gen;
18803                         }
18804                 }
18805         } else {
18806                 /* 1st arg to a function */
18807                 regs[BPF_REG_1].type = PTR_TO_CTX;
18808                 mark_reg_known_zero(env, regs, BPF_REG_1);
18809                 ret = btf_check_subprog_arg_match(env, subprog, regs);
18810                 if (ret == -EFAULT)
18811                         /* unlikely verifier bug. abort.
18812                          * ret == 0 and ret < 0 are sadly acceptable for
18813                          * main() function due to backward compatibility.
18814                          * Like socket filter program may be written as:
18815                          * int bpf_prog(struct pt_regs *ctx)
18816                          * and never dereference that ctx in the program.
18817                          * 'struct pt_regs' is a type mismatch for socket
18818                          * filter that should be using 'struct __sk_buff'.
18819                          */
18820                         goto out;
18821         }
18822
18823         ret = do_check(env);
18824 out:
18825         /* check for NULL is necessary, since cur_state can be freed inside
18826          * do_check() under memory pressure.
18827          */
18828         if (env->cur_state) {
18829                 free_verifier_state(env->cur_state, true);
18830                 env->cur_state = NULL;
18831         }
18832         while (!pop_stack(env, NULL, NULL, false));
18833         if (!ret && pop_log)
18834                 bpf_vlog_reset(&env->log, 0);
18835         free_states(env);
18836         return ret;
18837 }
18838
18839 /* Verify all global functions in a BPF program one by one based on their BTF.
18840  * All global functions must pass verification. Otherwise the whole program is rejected.
18841  * Consider:
18842  * int bar(int);
18843  * int foo(int f)
18844  * {
18845  *    return bar(f);
18846  * }
18847  * int bar(int b)
18848  * {
18849  *    ...
18850  * }
18851  * foo() will be verified first for R1=any_scalar_value. During verification it
18852  * will be assumed that bar() already verified successfully and call to bar()
18853  * from foo() will be checked for type match only. Later bar() will be verified
18854  * independently to check that it's safe for R1=any_scalar_value.
18855  */
18856 static int do_check_subprogs(struct bpf_verifier_env *env)
18857 {
18858         struct bpf_prog_aux *aux = env->prog->aux;
18859         int i, ret;
18860
18861         if (!aux->func_info)
18862                 return 0;
18863
18864         for (i = 1; i < env->subprog_cnt; i++) {
18865                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18866                         continue;
18867                 env->insn_idx = env->subprog_info[i].start;
18868                 WARN_ON_ONCE(env->insn_idx == 0);
18869                 ret = do_check_common(env, i);
18870                 if (ret) {
18871                         return ret;
18872                 } else if (env->log.level & BPF_LOG_LEVEL) {
18873                         verbose(env,
18874                                 "Func#%d is safe for any args that match its prototype\n",
18875                                 i);
18876                 }
18877         }
18878         return 0;
18879 }
18880
18881 static int do_check_main(struct bpf_verifier_env *env)
18882 {
18883         int ret;
18884
18885         env->insn_idx = 0;
18886         ret = do_check_common(env, 0);
18887         if (!ret)
18888                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18889         return ret;
18890 }
18891
18892
18893 static void print_verification_stats(struct bpf_verifier_env *env)
18894 {
18895         int i;
18896
18897         if (env->log.level & BPF_LOG_STATS) {
18898                 verbose(env, "verification time %lld usec\n",
18899                         div_u64(env->verification_time, 1000));
18900                 verbose(env, "stack depth ");
18901                 for (i = 0; i < env->subprog_cnt; i++) {
18902                         u32 depth = env->subprog_info[i].stack_depth;
18903
18904                         verbose(env, "%d", depth);
18905                         if (i + 1 < env->subprog_cnt)
18906                                 verbose(env, "+");
18907                 }
18908                 verbose(env, "\n");
18909         }
18910         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18911                 "total_states %d peak_states %d mark_read %d\n",
18912                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18913                 env->max_states_per_insn, env->total_states,
18914                 env->peak_states, env->longest_mark_read_walk);
18915 }
18916
18917 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18918 {
18919         const struct btf_type *t, *func_proto;
18920         const struct bpf_struct_ops *st_ops;
18921         const struct btf_member *member;
18922         struct bpf_prog *prog = env->prog;
18923         u32 btf_id, member_idx;
18924         const char *mname;
18925
18926         if (!prog->gpl_compatible) {
18927                 verbose(env, "struct ops programs must have a GPL compatible license\n");
18928                 return -EINVAL;
18929         }
18930
18931         btf_id = prog->aux->attach_btf_id;
18932         st_ops = bpf_struct_ops_find(btf_id);
18933         if (!st_ops) {
18934                 verbose(env, "attach_btf_id %u is not a supported struct\n",
18935                         btf_id);
18936                 return -ENOTSUPP;
18937         }
18938
18939         t = st_ops->type;
18940         member_idx = prog->expected_attach_type;
18941         if (member_idx >= btf_type_vlen(t)) {
18942                 verbose(env, "attach to invalid member idx %u of struct %s\n",
18943                         member_idx, st_ops->name);
18944                 return -EINVAL;
18945         }
18946
18947         member = &btf_type_member(t)[member_idx];
18948         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18949         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18950                                                NULL);
18951         if (!func_proto) {
18952                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18953                         mname, member_idx, st_ops->name);
18954                 return -EINVAL;
18955         }
18956
18957         if (st_ops->check_member) {
18958                 int err = st_ops->check_member(t, member, prog);
18959
18960                 if (err) {
18961                         verbose(env, "attach to unsupported member %s of struct %s\n",
18962                                 mname, st_ops->name);
18963                         return err;
18964                 }
18965         }
18966
18967         prog->aux->attach_func_proto = func_proto;
18968         prog->aux->attach_func_name = mname;
18969         env->ops = st_ops->verifier_ops;
18970
18971         return 0;
18972 }
18973 #define SECURITY_PREFIX "security_"
18974
18975 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18976 {
18977         if (within_error_injection_list(addr) ||
18978             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18979                 return 0;
18980
18981         return -EINVAL;
18982 }
18983
18984 /* list of non-sleepable functions that are otherwise on
18985  * ALLOW_ERROR_INJECTION list
18986  */
18987 BTF_SET_START(btf_non_sleepable_error_inject)
18988 /* Three functions below can be called from sleepable and non-sleepable context.
18989  * Assume non-sleepable from bpf safety point of view.
18990  */
18991 BTF_ID(func, __filemap_add_folio)
18992 BTF_ID(func, should_fail_alloc_page)
18993 BTF_ID(func, should_failslab)
18994 BTF_SET_END(btf_non_sleepable_error_inject)
18995
18996 static int check_non_sleepable_error_inject(u32 btf_id)
18997 {
18998         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18999 }
19000
19001 int bpf_check_attach_target(struct bpf_verifier_log *log,
19002                             const struct bpf_prog *prog,
19003                             const struct bpf_prog *tgt_prog,
19004                             u32 btf_id,
19005                             struct bpf_attach_target_info *tgt_info)
19006 {
19007         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19008         const char prefix[] = "btf_trace_";
19009         int ret = 0, subprog = -1, i;
19010         const struct btf_type *t;
19011         bool conservative = true;
19012         const char *tname;
19013         struct btf *btf;
19014         long addr = 0;
19015         struct module *mod = NULL;
19016
19017         if (!btf_id) {
19018                 bpf_log(log, "Tracing programs must provide btf_id\n");
19019                 return -EINVAL;
19020         }
19021         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19022         if (!btf) {
19023                 bpf_log(log,
19024                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19025                 return -EINVAL;
19026         }
19027         t = btf_type_by_id(btf, btf_id);
19028         if (!t) {
19029                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19030                 return -EINVAL;
19031         }
19032         tname = btf_name_by_offset(btf, t->name_off);
19033         if (!tname) {
19034                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19035                 return -EINVAL;
19036         }
19037         if (tgt_prog) {
19038                 struct bpf_prog_aux *aux = tgt_prog->aux;
19039
19040                 if (bpf_prog_is_dev_bound(prog->aux) &&
19041                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19042                         bpf_log(log, "Target program bound device mismatch");
19043                         return -EINVAL;
19044                 }
19045
19046                 for (i = 0; i < aux->func_info_cnt; i++)
19047                         if (aux->func_info[i].type_id == btf_id) {
19048                                 subprog = i;
19049                                 break;
19050                         }
19051                 if (subprog == -1) {
19052                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
19053                         return -EINVAL;
19054                 }
19055                 conservative = aux->func_info_aux[subprog].unreliable;
19056                 if (prog_extension) {
19057                         if (conservative) {
19058                                 bpf_log(log,
19059                                         "Cannot replace static functions\n");
19060                                 return -EINVAL;
19061                         }
19062                         if (!prog->jit_requested) {
19063                                 bpf_log(log,
19064                                         "Extension programs should be JITed\n");
19065                                 return -EINVAL;
19066                         }
19067                 }
19068                 if (!tgt_prog->jited) {
19069                         bpf_log(log, "Can attach to only JITed progs\n");
19070                         return -EINVAL;
19071                 }
19072                 if (tgt_prog->type == prog->type) {
19073                         /* Cannot fentry/fexit another fentry/fexit program.
19074                          * Cannot attach program extension to another extension.
19075                          * It's ok to attach fentry/fexit to extension program.
19076                          */
19077                         bpf_log(log, "Cannot recursively attach\n");
19078                         return -EINVAL;
19079                 }
19080                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19081                     prog_extension &&
19082                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19083                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19084                         /* Program extensions can extend all program types
19085                          * except fentry/fexit. The reason is the following.
19086                          * The fentry/fexit programs are used for performance
19087                          * analysis, stats and can be attached to any program
19088                          * type except themselves. When extension program is
19089                          * replacing XDP function it is necessary to allow
19090                          * performance analysis of all functions. Both original
19091                          * XDP program and its program extension. Hence
19092                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19093                          * allowed. If extending of fentry/fexit was allowed it
19094                          * would be possible to create long call chain
19095                          * fentry->extension->fentry->extension beyond
19096                          * reasonable stack size. Hence extending fentry is not
19097                          * allowed.
19098                          */
19099                         bpf_log(log, "Cannot extend fentry/fexit\n");
19100                         return -EINVAL;
19101                 }
19102         } else {
19103                 if (prog_extension) {
19104                         bpf_log(log, "Cannot replace kernel functions\n");
19105                         return -EINVAL;
19106                 }
19107         }
19108
19109         switch (prog->expected_attach_type) {
19110         case BPF_TRACE_RAW_TP:
19111                 if (tgt_prog) {
19112                         bpf_log(log,
19113                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19114                         return -EINVAL;
19115                 }
19116                 if (!btf_type_is_typedef(t)) {
19117                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
19118                                 btf_id);
19119                         return -EINVAL;
19120                 }
19121                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19122                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19123                                 btf_id, tname);
19124                         return -EINVAL;
19125                 }
19126                 tname += sizeof(prefix) - 1;
19127                 t = btf_type_by_id(btf, t->type);
19128                 if (!btf_type_is_ptr(t))
19129                         /* should never happen in valid vmlinux build */
19130                         return -EINVAL;
19131                 t = btf_type_by_id(btf, t->type);
19132                 if (!btf_type_is_func_proto(t))
19133                         /* should never happen in valid vmlinux build */
19134                         return -EINVAL;
19135
19136                 break;
19137         case BPF_TRACE_ITER:
19138                 if (!btf_type_is_func(t)) {
19139                         bpf_log(log, "attach_btf_id %u is not a function\n",
19140                                 btf_id);
19141                         return -EINVAL;
19142                 }
19143                 t = btf_type_by_id(btf, t->type);
19144                 if (!btf_type_is_func_proto(t))
19145                         return -EINVAL;
19146                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19147                 if (ret)
19148                         return ret;
19149                 break;
19150         default:
19151                 if (!prog_extension)
19152                         return -EINVAL;
19153                 fallthrough;
19154         case BPF_MODIFY_RETURN:
19155         case BPF_LSM_MAC:
19156         case BPF_LSM_CGROUP:
19157         case BPF_TRACE_FENTRY:
19158         case BPF_TRACE_FEXIT:
19159                 if (!btf_type_is_func(t)) {
19160                         bpf_log(log, "attach_btf_id %u is not a function\n",
19161                                 btf_id);
19162                         return -EINVAL;
19163                 }
19164                 if (prog_extension &&
19165                     btf_check_type_match(log, prog, btf, t))
19166                         return -EINVAL;
19167                 t = btf_type_by_id(btf, t->type);
19168                 if (!btf_type_is_func_proto(t))
19169                         return -EINVAL;
19170
19171                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19172                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19173                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19174                         return -EINVAL;
19175
19176                 if (tgt_prog && conservative)
19177                         t = NULL;
19178
19179                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19180                 if (ret < 0)
19181                         return ret;
19182
19183                 if (tgt_prog) {
19184                         if (subprog == 0)
19185                                 addr = (long) tgt_prog->bpf_func;
19186                         else
19187                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19188                 } else {
19189                         if (btf_is_module(btf)) {
19190                                 mod = btf_try_get_module(btf);
19191                                 if (mod)
19192                                         addr = find_kallsyms_symbol_value(mod, tname);
19193                                 else
19194                                         addr = 0;
19195                         } else {
19196                                 addr = kallsyms_lookup_name(tname);
19197                         }
19198                         if (!addr) {
19199                                 module_put(mod);
19200                                 bpf_log(log,
19201                                         "The address of function %s cannot be found\n",
19202                                         tname);
19203                                 return -ENOENT;
19204                         }
19205                 }
19206
19207                 if (prog->aux->sleepable) {
19208                         ret = -EINVAL;
19209                         switch (prog->type) {
19210                         case BPF_PROG_TYPE_TRACING:
19211
19212                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19213                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19214                                  */
19215                                 if (!check_non_sleepable_error_inject(btf_id) &&
19216                                     within_error_injection_list(addr))
19217                                         ret = 0;
19218                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19219                                  * in the fmodret id set with the KF_SLEEPABLE flag.
19220                                  */
19221                                 else {
19222                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19223                                                                                 prog);
19224
19225                                         if (flags && (*flags & KF_SLEEPABLE))
19226                                                 ret = 0;
19227                                 }
19228                                 break;
19229                         case BPF_PROG_TYPE_LSM:
19230                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19231                                  * Only some of them are sleepable.
19232                                  */
19233                                 if (bpf_lsm_is_sleepable_hook(btf_id))
19234                                         ret = 0;
19235                                 break;
19236                         default:
19237                                 break;
19238                         }
19239                         if (ret) {
19240                                 module_put(mod);
19241                                 bpf_log(log, "%s is not sleepable\n", tname);
19242                                 return ret;
19243                         }
19244                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19245                         if (tgt_prog) {
19246                                 module_put(mod);
19247                                 bpf_log(log, "can't modify return codes of BPF programs\n");
19248                                 return -EINVAL;
19249                         }
19250                         ret = -EINVAL;
19251                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19252                             !check_attach_modify_return(addr, tname))
19253                                 ret = 0;
19254                         if (ret) {
19255                                 module_put(mod);
19256                                 bpf_log(log, "%s() is not modifiable\n", tname);
19257                                 return ret;
19258                         }
19259                 }
19260
19261                 break;
19262         }
19263         tgt_info->tgt_addr = addr;
19264         tgt_info->tgt_name = tname;
19265         tgt_info->tgt_type = t;
19266         tgt_info->tgt_mod = mod;
19267         return 0;
19268 }
19269
19270 BTF_SET_START(btf_id_deny)
19271 BTF_ID_UNUSED
19272 #ifdef CONFIG_SMP
19273 BTF_ID(func, migrate_disable)
19274 BTF_ID(func, migrate_enable)
19275 #endif
19276 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19277 BTF_ID(func, rcu_read_unlock_strict)
19278 #endif
19279 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19280 BTF_ID(func, preempt_count_add)
19281 BTF_ID(func, preempt_count_sub)
19282 #endif
19283 #ifdef CONFIG_PREEMPT_RCU
19284 BTF_ID(func, __rcu_read_lock)
19285 BTF_ID(func, __rcu_read_unlock)
19286 #endif
19287 BTF_SET_END(btf_id_deny)
19288
19289 static bool can_be_sleepable(struct bpf_prog *prog)
19290 {
19291         if (prog->type == BPF_PROG_TYPE_TRACING) {
19292                 switch (prog->expected_attach_type) {
19293                 case BPF_TRACE_FENTRY:
19294                 case BPF_TRACE_FEXIT:
19295                 case BPF_MODIFY_RETURN:
19296                 case BPF_TRACE_ITER:
19297                         return true;
19298                 default:
19299                         return false;
19300                 }
19301         }
19302         return prog->type == BPF_PROG_TYPE_LSM ||
19303                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19304                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19305 }
19306
19307 static int check_attach_btf_id(struct bpf_verifier_env *env)
19308 {
19309         struct bpf_prog *prog = env->prog;
19310         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19311         struct bpf_attach_target_info tgt_info = {};
19312         u32 btf_id = prog->aux->attach_btf_id;
19313         struct bpf_trampoline *tr;
19314         int ret;
19315         u64 key;
19316
19317         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19318                 if (prog->aux->sleepable)
19319                         /* attach_btf_id checked to be zero already */
19320                         return 0;
19321                 verbose(env, "Syscall programs can only be sleepable\n");
19322                 return -EINVAL;
19323         }
19324
19325         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19326                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19327                 return -EINVAL;
19328         }
19329
19330         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19331                 return check_struct_ops_btf_id(env);
19332
19333         if (prog->type != BPF_PROG_TYPE_TRACING &&
19334             prog->type != BPF_PROG_TYPE_LSM &&
19335             prog->type != BPF_PROG_TYPE_EXT)
19336                 return 0;
19337
19338         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19339         if (ret)
19340                 return ret;
19341
19342         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19343                 /* to make freplace equivalent to their targets, they need to
19344                  * inherit env->ops and expected_attach_type for the rest of the
19345                  * verification
19346                  */
19347                 env->ops = bpf_verifier_ops[tgt_prog->type];
19348                 prog->expected_attach_type = tgt_prog->expected_attach_type;
19349         }
19350
19351         /* store info about the attachment target that will be used later */
19352         prog->aux->attach_func_proto = tgt_info.tgt_type;
19353         prog->aux->attach_func_name = tgt_info.tgt_name;
19354         prog->aux->mod = tgt_info.tgt_mod;
19355
19356         if (tgt_prog) {
19357                 prog->aux->saved_dst_prog_type = tgt_prog->type;
19358                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19359         }
19360
19361         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19362                 prog->aux->attach_btf_trace = true;
19363                 return 0;
19364         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19365                 if (!bpf_iter_prog_supported(prog))
19366                         return -EINVAL;
19367                 return 0;
19368         }
19369
19370         if (prog->type == BPF_PROG_TYPE_LSM) {
19371                 ret = bpf_lsm_verify_prog(&env->log, prog);
19372                 if (ret < 0)
19373                         return ret;
19374         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19375                    btf_id_set_contains(&btf_id_deny, btf_id)) {
19376                 return -EINVAL;
19377         }
19378
19379         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19380         tr = bpf_trampoline_get(key, &tgt_info);
19381         if (!tr)
19382                 return -ENOMEM;
19383
19384         prog->aux->dst_trampoline = tr;
19385         return 0;
19386 }
19387
19388 struct btf *bpf_get_btf_vmlinux(void)
19389 {
19390         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19391                 mutex_lock(&bpf_verifier_lock);
19392                 if (!btf_vmlinux)
19393                         btf_vmlinux = btf_parse_vmlinux();
19394                 mutex_unlock(&bpf_verifier_lock);
19395         }
19396         return btf_vmlinux;
19397 }
19398
19399 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19400 {
19401         u64 start_time = ktime_get_ns();
19402         struct bpf_verifier_env *env;
19403         int i, len, ret = -EINVAL, err;
19404         u32 log_true_size;
19405         bool is_priv;
19406
19407         /* no program is valid */
19408         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19409                 return -EINVAL;
19410
19411         /* 'struct bpf_verifier_env' can be global, but since it's not small,
19412          * allocate/free it every time bpf_check() is called
19413          */
19414         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19415         if (!env)
19416                 return -ENOMEM;
19417
19418         env->bt.env = env;
19419
19420         len = (*prog)->len;
19421         env->insn_aux_data =
19422                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19423         ret = -ENOMEM;
19424         if (!env->insn_aux_data)
19425                 goto err_free_env;
19426         for (i = 0; i < len; i++)
19427                 env->insn_aux_data[i].orig_idx = i;
19428         env->prog = *prog;
19429         env->ops = bpf_verifier_ops[env->prog->type];
19430         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19431         is_priv = bpf_capable();
19432
19433         bpf_get_btf_vmlinux();
19434
19435         /* grab the mutex to protect few globals used by verifier */
19436         if (!is_priv)
19437                 mutex_lock(&bpf_verifier_lock);
19438
19439         /* user could have requested verbose verifier output
19440          * and supplied buffer to store the verification trace
19441          */
19442         ret = bpf_vlog_init(&env->log, attr->log_level,
19443                             (char __user *) (unsigned long) attr->log_buf,
19444                             attr->log_size);
19445         if (ret)
19446                 goto err_unlock;
19447
19448         mark_verifier_state_clean(env);
19449
19450         if (IS_ERR(btf_vmlinux)) {
19451                 /* Either gcc or pahole or kernel are broken. */
19452                 verbose(env, "in-kernel BTF is malformed\n");
19453                 ret = PTR_ERR(btf_vmlinux);
19454                 goto skip_full_check;
19455         }
19456
19457         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19458         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19459                 env->strict_alignment = true;
19460         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19461                 env->strict_alignment = false;
19462
19463         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19464         env->allow_uninit_stack = bpf_allow_uninit_stack();
19465         env->bypass_spec_v1 = bpf_bypass_spec_v1();
19466         env->bypass_spec_v4 = bpf_bypass_spec_v4();
19467         env->bpf_capable = bpf_capable();
19468
19469         if (is_priv)
19470                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19471
19472         env->explored_states = kvcalloc(state_htab_size(env),
19473                                        sizeof(struct bpf_verifier_state_list *),
19474                                        GFP_USER);
19475         ret = -ENOMEM;
19476         if (!env->explored_states)
19477                 goto skip_full_check;
19478
19479         ret = add_subprog_and_kfunc(env);
19480         if (ret < 0)
19481                 goto skip_full_check;
19482
19483         ret = check_subprogs(env);
19484         if (ret < 0)
19485                 goto skip_full_check;
19486
19487         ret = check_btf_info(env, attr, uattr);
19488         if (ret < 0)
19489                 goto skip_full_check;
19490
19491         ret = check_attach_btf_id(env);
19492         if (ret)
19493                 goto skip_full_check;
19494
19495         ret = resolve_pseudo_ldimm64(env);
19496         if (ret < 0)
19497                 goto skip_full_check;
19498
19499         if (bpf_prog_is_offloaded(env->prog->aux)) {
19500                 ret = bpf_prog_offload_verifier_prep(env->prog);
19501                 if (ret)
19502                         goto skip_full_check;
19503         }
19504
19505         ret = check_cfg(env);
19506         if (ret < 0)
19507                 goto skip_full_check;
19508
19509         ret = do_check_subprogs(env);
19510         ret = ret ?: do_check_main(env);
19511
19512         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19513                 ret = bpf_prog_offload_finalize(env);
19514
19515 skip_full_check:
19516         kvfree(env->explored_states);
19517
19518         if (ret == 0)
19519                 ret = check_max_stack_depth(env);
19520
19521         /* instruction rewrites happen after this point */
19522         if (ret == 0)
19523                 ret = optimize_bpf_loop(env);
19524
19525         if (is_priv) {
19526                 if (ret == 0)
19527                         opt_hard_wire_dead_code_branches(env);
19528                 if (ret == 0)
19529                         ret = opt_remove_dead_code(env);
19530                 if (ret == 0)
19531                         ret = opt_remove_nops(env);
19532         } else {
19533                 if (ret == 0)
19534                         sanitize_dead_code(env);
19535         }
19536
19537         if (ret == 0)
19538                 /* program is valid, convert *(u32*)(ctx + off) accesses */
19539                 ret = convert_ctx_accesses(env);
19540
19541         if (ret == 0)
19542                 ret = do_misc_fixups(env);
19543
19544         /* do 32-bit optimization after insn patching has done so those patched
19545          * insns could be handled correctly.
19546          */
19547         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19548                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19549                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19550                                                                      : false;
19551         }
19552
19553         if (ret == 0)
19554                 ret = fixup_call_args(env);
19555
19556         env->verification_time = ktime_get_ns() - start_time;
19557         print_verification_stats(env);
19558         env->prog->aux->verified_insns = env->insn_processed;
19559
19560         /* preserve original error even if log finalization is successful */
19561         err = bpf_vlog_finalize(&env->log, &log_true_size);
19562         if (err)
19563                 ret = err;
19564
19565         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19566             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19567                                   &log_true_size, sizeof(log_true_size))) {
19568                 ret = -EFAULT;
19569                 goto err_release_maps;
19570         }
19571
19572         if (ret)
19573                 goto err_release_maps;
19574
19575         if (env->used_map_cnt) {
19576                 /* if program passed verifier, update used_maps in bpf_prog_info */
19577                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19578                                                           sizeof(env->used_maps[0]),
19579                                                           GFP_KERNEL);
19580
19581                 if (!env->prog->aux->used_maps) {
19582                         ret = -ENOMEM;
19583                         goto err_release_maps;
19584                 }
19585
19586                 memcpy(env->prog->aux->used_maps, env->used_maps,
19587                        sizeof(env->used_maps[0]) * env->used_map_cnt);
19588                 env->prog->aux->used_map_cnt = env->used_map_cnt;
19589         }
19590         if (env->used_btf_cnt) {
19591                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19592                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19593                                                           sizeof(env->used_btfs[0]),
19594                                                           GFP_KERNEL);
19595                 if (!env->prog->aux->used_btfs) {
19596                         ret = -ENOMEM;
19597                         goto err_release_maps;
19598                 }
19599
19600                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19601                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19602                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19603         }
19604         if (env->used_map_cnt || env->used_btf_cnt) {
19605                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19606                  * bpf_ld_imm64 instructions
19607                  */
19608                 convert_pseudo_ld_imm64(env);
19609         }
19610
19611         adjust_btf_func(env);
19612
19613 err_release_maps:
19614         if (!env->prog->aux->used_maps)
19615                 /* if we didn't copy map pointers into bpf_prog_info, release
19616                  * them now. Otherwise free_used_maps() will release them.
19617                  */
19618                 release_maps(env);
19619         if (!env->prog->aux->used_btfs)
19620                 release_btfs(env);
19621
19622         /* extension progs temporarily inherit the attach_type of their targets
19623            for verification purposes, so set it back to zero before returning
19624          */
19625         if (env->prog->type == BPF_PROG_TYPE_EXT)
19626                 env->prog->expected_attach_type = 0;
19627
19628         *prog = env->prog;
19629 err_unlock:
19630         if (!is_priv)
19631                 mutex_unlock(&bpf_verifier_lock);
19632         vfree(env->insn_aux_data);
19633 err_free_env:
19634         kfree(env);
19635         return ret;
19636 }