bpf: move explored_state() closer to the beginning of verifier.c
[platform/kernel/linux-starfive.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30
31 #include "disasm.h"
32
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35         [_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171         /* verifer state is 'st'
172          * before processing instruction 'insn_idx'
173          * and after processing instruction 'prev_insn_idx'
174          */
175         struct bpf_verifier_state st;
176         int insn_idx;
177         int prev_insn_idx;
178         struct bpf_verifier_stack_elem *next;
179         /* length of verifier log at the time this state was pushed on stack */
180         u32 log_pos;
181 };
182
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
184 #define BPF_COMPLEXITY_LIMIT_STATES     64
185
186 #define BPF_MAP_KEY_POISON      (1ULL << 63)
187 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
188
189 #define BPF_MAP_PTR_UNPRIV      1UL
190 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
191                                           POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199                               struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201                              u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215                               const struct bpf_map *map, bool unpriv)
216 {
217         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218         unpriv |= bpf_map_ptr_unpriv(aux);
219         aux->map_ptr_state = (unsigned long)map |
220                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240         bool poisoned = bpf_map_key_poisoned(aux);
241
242         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248         return insn->code == (BPF_JMP | BPF_CALL) &&
249                insn->src_reg == 0;
250 }
251
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254         return insn->code == (BPF_JMP | BPF_CALL) &&
255                insn->src_reg == BPF_PSEUDO_CALL;
256 }
257
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260         return insn->code == (BPF_JMP | BPF_CALL) &&
261                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263
264 struct bpf_call_arg_meta {
265         struct bpf_map *map_ptr;
266         bool raw_mode;
267         bool pkt_access;
268         u8 release_regno;
269         int regno;
270         int access_size;
271         int mem_size;
272         u64 msize_max_value;
273         int ref_obj_id;
274         int dynptr_id;
275         int map_uid;
276         int func_id;
277         struct btf *btf;
278         u32 btf_id;
279         struct btf *ret_btf;
280         u32 ret_btf_id;
281         u32 subprogno;
282         struct btf_field *kptr_field;
283 };
284
285 struct bpf_kfunc_call_arg_meta {
286         /* In parameters */
287         struct btf *btf;
288         u32 func_id;
289         u32 kfunc_flags;
290         const struct btf_type *func_proto;
291         const char *func_name;
292         /* Out parameters */
293         u32 ref_obj_id;
294         u8 release_regno;
295         bool r0_rdonly;
296         u32 ret_btf_id;
297         u64 r0_size;
298         u32 subprogno;
299         struct {
300                 u64 value;
301                 bool found;
302         } arg_constant;
303
304         /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305          * generally to pass info about user-defined local kptr types to later
306          * verification logic
307          *   bpf_obj_drop
308          *     Record the local kptr type to be drop'd
309          *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310          *     Record the local kptr type to be refcount_incr'd and use
311          *     arg_owning_ref to determine whether refcount_acquire should be
312          *     fallible
313          */
314         struct btf *arg_btf;
315         u32 arg_btf_id;
316         bool arg_owning_ref;
317
318         struct {
319                 struct btf_field *field;
320         } arg_list_head;
321         struct {
322                 struct btf_field *field;
323         } arg_rbtree_root;
324         struct {
325                 enum bpf_dynptr_type type;
326                 u32 id;
327                 u32 ref_obj_id;
328         } initialized_dynptr;
329         struct {
330                 u8 spi;
331                 u8 frameno;
332         } iter;
333         u64 mem_size;
334 };
335
336 struct btf *btf_vmlinux;
337
338 static DEFINE_MUTEX(bpf_verifier_lock);
339
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343         const struct bpf_line_info *linfo;
344         const struct bpf_prog *prog;
345         u32 i, nr_linfo;
346
347         prog = env->prog;
348         nr_linfo = prog->aux->nr_linfo;
349
350         if (!nr_linfo || insn_off >= prog->len)
351                 return NULL;
352
353         linfo = prog->aux->linfo;
354         for (i = 1; i < nr_linfo; i++)
355                 if (insn_off < linfo[i].insn_off)
356                         break;
357
358         return &linfo[i - 1];
359 }
360
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363         struct bpf_verifier_env *env = private_data;
364         va_list args;
365
366         if (!bpf_verifier_log_needed(&env->log))
367                 return;
368
369         va_start(args, fmt);
370         bpf_verifier_vlog(&env->log, fmt, args);
371         va_end(args);
372 }
373
374 static const char *ltrim(const char *s)
375 {
376         while (isspace(*s))
377                 s++;
378
379         return s;
380 }
381
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383                                          u32 insn_off,
384                                          const char *prefix_fmt, ...)
385 {
386         const struct bpf_line_info *linfo;
387
388         if (!bpf_verifier_log_needed(&env->log))
389                 return;
390
391         linfo = find_linfo(env, insn_off);
392         if (!linfo || linfo == env->prev_linfo)
393                 return;
394
395         if (prefix_fmt) {
396                 va_list args;
397
398                 va_start(args, prefix_fmt);
399                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
400                 va_end(args);
401         }
402
403         verbose(env, "%s\n",
404                 ltrim(btf_name_by_offset(env->prog->aux->btf,
405                                          linfo->line_off)));
406
407         env->prev_linfo = linfo;
408 }
409
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411                                    struct bpf_reg_state *reg,
412                                    struct tnum *range, const char *ctx,
413                                    const char *reg_name)
414 {
415         char tn_buf[48];
416
417         verbose(env, "At %s the register %s ", ctx, reg_name);
418         if (!tnum_is_unknown(reg->var_off)) {
419                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420                 verbose(env, "has value %s", tn_buf);
421         } else {
422                 verbose(env, "has unknown scalar value");
423         }
424         tnum_strn(tn_buf, sizeof(tn_buf), *range);
425         verbose(env, " should have been in %s\n", tn_buf);
426 }
427
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430         type = base_type(type);
431         return type == PTR_TO_PACKET ||
432                type == PTR_TO_PACKET_META;
433 }
434
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437         return type == PTR_TO_SOCKET ||
438                 type == PTR_TO_SOCK_COMMON ||
439                 type == PTR_TO_TCP_SOCK ||
440                 type == PTR_TO_XDP_SOCK;
441 }
442
443 static bool type_may_be_null(u32 type)
444 {
445         return type & PTR_MAYBE_NULL;
446 }
447
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450         enum bpf_reg_type type;
451
452         type = reg->type;
453         if (type_may_be_null(type))
454                 return false;
455
456         type = base_type(type);
457         return type == PTR_TO_SOCKET ||
458                 type == PTR_TO_TCP_SOCK ||
459                 type == PTR_TO_MAP_VALUE ||
460                 type == PTR_TO_MAP_KEY ||
461                 type == PTR_TO_SOCK_COMMON ||
462                 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463                 type == PTR_TO_MEM;
464 }
465
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470
471 static bool type_is_non_owning_ref(u32 type)
472 {
473         return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478         struct btf_record *rec = NULL;
479         struct btf_struct_meta *meta;
480
481         if (reg->type == PTR_TO_MAP_VALUE) {
482                 rec = reg->map_ptr->record;
483         } else if (type_is_ptr_alloc_obj(reg->type)) {
484                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485                 if (meta)
486                         rec = meta->record;
487         }
488         return rec;
489 }
490
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493         struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494
495         return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502
503 static bool type_is_rdonly_mem(u32 type)
504 {
505         return type & MEM_RDONLY;
506 }
507
508 static bool is_acquire_function(enum bpf_func_id func_id,
509                                 const struct bpf_map *map)
510 {
511         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512
513         if (func_id == BPF_FUNC_sk_lookup_tcp ||
514             func_id == BPF_FUNC_sk_lookup_udp ||
515             func_id == BPF_FUNC_skc_lookup_tcp ||
516             func_id == BPF_FUNC_ringbuf_reserve ||
517             func_id == BPF_FUNC_kptr_xchg)
518                 return true;
519
520         if (func_id == BPF_FUNC_map_lookup_elem &&
521             (map_type == BPF_MAP_TYPE_SOCKMAP ||
522              map_type == BPF_MAP_TYPE_SOCKHASH))
523                 return true;
524
525         return false;
526 }
527
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530         return func_id == BPF_FUNC_tcp_sock ||
531                 func_id == BPF_FUNC_sk_fullsock ||
532                 func_id == BPF_FUNC_skc_to_tcp_sock ||
533                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
534                 func_id == BPF_FUNC_skc_to_udp6_sock ||
535                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
536                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542         return func_id == BPF_FUNC_dynptr_data;
543 }
544
545 static bool is_callback_calling_kfunc(u32 btf_id);
546
547 static bool is_callback_calling_function(enum bpf_func_id func_id)
548 {
549         return func_id == BPF_FUNC_for_each_map_elem ||
550                func_id == BPF_FUNC_timer_set_callback ||
551                func_id == BPF_FUNC_find_vma ||
552                func_id == BPF_FUNC_loop ||
553                func_id == BPF_FUNC_user_ringbuf_drain;
554 }
555
556 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
557 {
558         return func_id == BPF_FUNC_timer_set_callback;
559 }
560
561 static bool is_storage_get_function(enum bpf_func_id func_id)
562 {
563         return func_id == BPF_FUNC_sk_storage_get ||
564                func_id == BPF_FUNC_inode_storage_get ||
565                func_id == BPF_FUNC_task_storage_get ||
566                func_id == BPF_FUNC_cgrp_storage_get;
567 }
568
569 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
570                                         const struct bpf_map *map)
571 {
572         int ref_obj_uses = 0;
573
574         if (is_ptr_cast_function(func_id))
575                 ref_obj_uses++;
576         if (is_acquire_function(func_id, map))
577                 ref_obj_uses++;
578         if (is_dynptr_ref_function(func_id))
579                 ref_obj_uses++;
580
581         return ref_obj_uses > 1;
582 }
583
584 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
585 {
586         return BPF_CLASS(insn->code) == BPF_STX &&
587                BPF_MODE(insn->code) == BPF_ATOMIC &&
588                insn->imm == BPF_CMPXCHG;
589 }
590
591 /* string representation of 'enum bpf_reg_type'
592  *
593  * Note that reg_type_str() can not appear more than once in a single verbose()
594  * statement.
595  */
596 static const char *reg_type_str(struct bpf_verifier_env *env,
597                                 enum bpf_reg_type type)
598 {
599         char postfix[16] = {0}, prefix[64] = {0};
600         static const char * const str[] = {
601                 [NOT_INIT]              = "?",
602                 [SCALAR_VALUE]          = "scalar",
603                 [PTR_TO_CTX]            = "ctx",
604                 [CONST_PTR_TO_MAP]      = "map_ptr",
605                 [PTR_TO_MAP_VALUE]      = "map_value",
606                 [PTR_TO_STACK]          = "fp",
607                 [PTR_TO_PACKET]         = "pkt",
608                 [PTR_TO_PACKET_META]    = "pkt_meta",
609                 [PTR_TO_PACKET_END]     = "pkt_end",
610                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
611                 [PTR_TO_SOCKET]         = "sock",
612                 [PTR_TO_SOCK_COMMON]    = "sock_common",
613                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
614                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
615                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
616                 [PTR_TO_BTF_ID]         = "ptr_",
617                 [PTR_TO_MEM]            = "mem",
618                 [PTR_TO_BUF]            = "buf",
619                 [PTR_TO_FUNC]           = "func",
620                 [PTR_TO_MAP_KEY]        = "map_key",
621                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
622         };
623
624         if (type & PTR_MAYBE_NULL) {
625                 if (base_type(type) == PTR_TO_BTF_ID)
626                         strncpy(postfix, "or_null_", 16);
627                 else
628                         strncpy(postfix, "_or_null", 16);
629         }
630
631         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
632                  type & MEM_RDONLY ? "rdonly_" : "",
633                  type & MEM_RINGBUF ? "ringbuf_" : "",
634                  type & MEM_USER ? "user_" : "",
635                  type & MEM_PERCPU ? "percpu_" : "",
636                  type & MEM_RCU ? "rcu_" : "",
637                  type & PTR_UNTRUSTED ? "untrusted_" : "",
638                  type & PTR_TRUSTED ? "trusted_" : ""
639         );
640
641         snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
642                  prefix, str[base_type(type)], postfix);
643         return env->tmp_str_buf;
644 }
645
646 static char slot_type_char[] = {
647         [STACK_INVALID] = '?',
648         [STACK_SPILL]   = 'r',
649         [STACK_MISC]    = 'm',
650         [STACK_ZERO]    = '0',
651         [STACK_DYNPTR]  = 'd',
652         [STACK_ITER]    = 'i',
653 };
654
655 static void print_liveness(struct bpf_verifier_env *env,
656                            enum bpf_reg_liveness live)
657 {
658         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
659             verbose(env, "_");
660         if (live & REG_LIVE_READ)
661                 verbose(env, "r");
662         if (live & REG_LIVE_WRITTEN)
663                 verbose(env, "w");
664         if (live & REG_LIVE_DONE)
665                 verbose(env, "D");
666 }
667
668 static int __get_spi(s32 off)
669 {
670         return (-off - 1) / BPF_REG_SIZE;
671 }
672
673 static struct bpf_func_state *func(struct bpf_verifier_env *env,
674                                    const struct bpf_reg_state *reg)
675 {
676         struct bpf_verifier_state *cur = env->cur_state;
677
678         return cur->frame[reg->frameno];
679 }
680
681 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
682 {
683        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
684
685        /* We need to check that slots between [spi - nr_slots + 1, spi] are
686         * within [0, allocated_stack).
687         *
688         * Please note that the spi grows downwards. For example, a dynptr
689         * takes the size of two stack slots; the first slot will be at
690         * spi and the second slot will be at spi - 1.
691         */
692        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
693 }
694
695 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
696                                   const char *obj_kind, int nr_slots)
697 {
698         int off, spi;
699
700         if (!tnum_is_const(reg->var_off)) {
701                 verbose(env, "%s has to be at a constant offset\n", obj_kind);
702                 return -EINVAL;
703         }
704
705         off = reg->off + reg->var_off.value;
706         if (off % BPF_REG_SIZE) {
707                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
708                 return -EINVAL;
709         }
710
711         spi = __get_spi(off);
712         if (spi + 1 < nr_slots) {
713                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
714                 return -EINVAL;
715         }
716
717         if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
718                 return -ERANGE;
719         return spi;
720 }
721
722 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
723 {
724         return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
725 }
726
727 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
728 {
729         return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
730 }
731
732 static const char *btf_type_name(const struct btf *btf, u32 id)
733 {
734         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
735 }
736
737 static const char *dynptr_type_str(enum bpf_dynptr_type type)
738 {
739         switch (type) {
740         case BPF_DYNPTR_TYPE_LOCAL:
741                 return "local";
742         case BPF_DYNPTR_TYPE_RINGBUF:
743                 return "ringbuf";
744         case BPF_DYNPTR_TYPE_SKB:
745                 return "skb";
746         case BPF_DYNPTR_TYPE_XDP:
747                 return "xdp";
748         case BPF_DYNPTR_TYPE_INVALID:
749                 return "<invalid>";
750         default:
751                 WARN_ONCE(1, "unknown dynptr type %d\n", type);
752                 return "<unknown>";
753         }
754 }
755
756 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
757 {
758         if (!btf || btf_id == 0)
759                 return "<invalid>";
760
761         /* we already validated that type is valid and has conforming name */
762         return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
763 }
764
765 static const char *iter_state_str(enum bpf_iter_state state)
766 {
767         switch (state) {
768         case BPF_ITER_STATE_ACTIVE:
769                 return "active";
770         case BPF_ITER_STATE_DRAINED:
771                 return "drained";
772         case BPF_ITER_STATE_INVALID:
773                 return "<invalid>";
774         default:
775                 WARN_ONCE(1, "unknown iter state %d\n", state);
776                 return "<unknown>";
777         }
778 }
779
780 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
781 {
782         env->scratched_regs |= 1U << regno;
783 }
784
785 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
786 {
787         env->scratched_stack_slots |= 1ULL << spi;
788 }
789
790 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
791 {
792         return (env->scratched_regs >> regno) & 1;
793 }
794
795 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
796 {
797         return (env->scratched_stack_slots >> regno) & 1;
798 }
799
800 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
801 {
802         return env->scratched_regs || env->scratched_stack_slots;
803 }
804
805 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
806 {
807         env->scratched_regs = 0U;
808         env->scratched_stack_slots = 0ULL;
809 }
810
811 /* Used for printing the entire verifier state. */
812 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
813 {
814         env->scratched_regs = ~0U;
815         env->scratched_stack_slots = ~0ULL;
816 }
817
818 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
819 {
820         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
821         case DYNPTR_TYPE_LOCAL:
822                 return BPF_DYNPTR_TYPE_LOCAL;
823         case DYNPTR_TYPE_RINGBUF:
824                 return BPF_DYNPTR_TYPE_RINGBUF;
825         case DYNPTR_TYPE_SKB:
826                 return BPF_DYNPTR_TYPE_SKB;
827         case DYNPTR_TYPE_XDP:
828                 return BPF_DYNPTR_TYPE_XDP;
829         default:
830                 return BPF_DYNPTR_TYPE_INVALID;
831         }
832 }
833
834 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
835 {
836         switch (type) {
837         case BPF_DYNPTR_TYPE_LOCAL:
838                 return DYNPTR_TYPE_LOCAL;
839         case BPF_DYNPTR_TYPE_RINGBUF:
840                 return DYNPTR_TYPE_RINGBUF;
841         case BPF_DYNPTR_TYPE_SKB:
842                 return DYNPTR_TYPE_SKB;
843         case BPF_DYNPTR_TYPE_XDP:
844                 return DYNPTR_TYPE_XDP;
845         default:
846                 return 0;
847         }
848 }
849
850 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
851 {
852         return type == BPF_DYNPTR_TYPE_RINGBUF;
853 }
854
855 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
856                               enum bpf_dynptr_type type,
857                               bool first_slot, int dynptr_id);
858
859 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
860                                 struct bpf_reg_state *reg);
861
862 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
863                                    struct bpf_reg_state *sreg1,
864                                    struct bpf_reg_state *sreg2,
865                                    enum bpf_dynptr_type type)
866 {
867         int id = ++env->id_gen;
868
869         __mark_dynptr_reg(sreg1, type, true, id);
870         __mark_dynptr_reg(sreg2, type, false, id);
871 }
872
873 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
874                                struct bpf_reg_state *reg,
875                                enum bpf_dynptr_type type)
876 {
877         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
878 }
879
880 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
881                                         struct bpf_func_state *state, int spi);
882
883 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
884                                    enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
885 {
886         struct bpf_func_state *state = func(env, reg);
887         enum bpf_dynptr_type type;
888         int spi, i, err;
889
890         spi = dynptr_get_spi(env, reg);
891         if (spi < 0)
892                 return spi;
893
894         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
895          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
896          * to ensure that for the following example:
897          *      [d1][d1][d2][d2]
898          * spi    3   2   1   0
899          * So marking spi = 2 should lead to destruction of both d1 and d2. In
900          * case they do belong to same dynptr, second call won't see slot_type
901          * as STACK_DYNPTR and will simply skip destruction.
902          */
903         err = destroy_if_dynptr_stack_slot(env, state, spi);
904         if (err)
905                 return err;
906         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
907         if (err)
908                 return err;
909
910         for (i = 0; i < BPF_REG_SIZE; i++) {
911                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
912                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
913         }
914
915         type = arg_to_dynptr_type(arg_type);
916         if (type == BPF_DYNPTR_TYPE_INVALID)
917                 return -EINVAL;
918
919         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
920                                &state->stack[spi - 1].spilled_ptr, type);
921
922         if (dynptr_type_refcounted(type)) {
923                 /* The id is used to track proper releasing */
924                 int id;
925
926                 if (clone_ref_obj_id)
927                         id = clone_ref_obj_id;
928                 else
929                         id = acquire_reference_state(env, insn_idx);
930
931                 if (id < 0)
932                         return id;
933
934                 state->stack[spi].spilled_ptr.ref_obj_id = id;
935                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
936         }
937
938         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
939         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
940
941         return 0;
942 }
943
944 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
945 {
946         int i;
947
948         for (i = 0; i < BPF_REG_SIZE; i++) {
949                 state->stack[spi].slot_type[i] = STACK_INVALID;
950                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
951         }
952
953         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
954         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
955
956         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
957          *
958          * While we don't allow reading STACK_INVALID, it is still possible to
959          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
960          * helpers or insns can do partial read of that part without failing,
961          * but check_stack_range_initialized, check_stack_read_var_off, and
962          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
963          * the slot conservatively. Hence we need to prevent those liveness
964          * marking walks.
965          *
966          * This was not a problem before because STACK_INVALID is only set by
967          * default (where the default reg state has its reg->parent as NULL), or
968          * in clean_live_states after REG_LIVE_DONE (at which point
969          * mark_reg_read won't walk reg->parent chain), but not randomly during
970          * verifier state exploration (like we did above). Hence, for our case
971          * parentage chain will still be live (i.e. reg->parent may be
972          * non-NULL), while earlier reg->parent was NULL, so we need
973          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
974          * done later on reads or by mark_dynptr_read as well to unnecessary
975          * mark registers in verifier state.
976          */
977         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
978         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
979 }
980
981 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
982 {
983         struct bpf_func_state *state = func(env, reg);
984         int spi, ref_obj_id, i;
985
986         spi = dynptr_get_spi(env, reg);
987         if (spi < 0)
988                 return spi;
989
990         if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
991                 invalidate_dynptr(env, state, spi);
992                 return 0;
993         }
994
995         ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
996
997         /* If the dynptr has a ref_obj_id, then we need to invalidate
998          * two things:
999          *
1000          * 1) Any dynptrs with a matching ref_obj_id (clones)
1001          * 2) Any slices derived from this dynptr.
1002          */
1003
1004         /* Invalidate any slices associated with this dynptr */
1005         WARN_ON_ONCE(release_reference(env, ref_obj_id));
1006
1007         /* Invalidate any dynptr clones */
1008         for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1009                 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1010                         continue;
1011
1012                 /* it should always be the case that if the ref obj id
1013                  * matches then the stack slot also belongs to a
1014                  * dynptr
1015                  */
1016                 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1017                         verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1018                         return -EFAULT;
1019                 }
1020                 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1021                         invalidate_dynptr(env, state, i);
1022         }
1023
1024         return 0;
1025 }
1026
1027 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1028                                struct bpf_reg_state *reg);
1029
1030 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1031 {
1032         if (!env->allow_ptr_leaks)
1033                 __mark_reg_not_init(env, reg);
1034         else
1035                 __mark_reg_unknown(env, reg);
1036 }
1037
1038 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1039                                         struct bpf_func_state *state, int spi)
1040 {
1041         struct bpf_func_state *fstate;
1042         struct bpf_reg_state *dreg;
1043         int i, dynptr_id;
1044
1045         /* We always ensure that STACK_DYNPTR is never set partially,
1046          * hence just checking for slot_type[0] is enough. This is
1047          * different for STACK_SPILL, where it may be only set for
1048          * 1 byte, so code has to use is_spilled_reg.
1049          */
1050         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1051                 return 0;
1052
1053         /* Reposition spi to first slot */
1054         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1055                 spi = spi + 1;
1056
1057         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1058                 verbose(env, "cannot overwrite referenced dynptr\n");
1059                 return -EINVAL;
1060         }
1061
1062         mark_stack_slot_scratched(env, spi);
1063         mark_stack_slot_scratched(env, spi - 1);
1064
1065         /* Writing partially to one dynptr stack slot destroys both. */
1066         for (i = 0; i < BPF_REG_SIZE; i++) {
1067                 state->stack[spi].slot_type[i] = STACK_INVALID;
1068                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1069         }
1070
1071         dynptr_id = state->stack[spi].spilled_ptr.id;
1072         /* Invalidate any slices associated with this dynptr */
1073         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1074                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1075                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1076                         continue;
1077                 if (dreg->dynptr_id == dynptr_id)
1078                         mark_reg_invalid(env, dreg);
1079         }));
1080
1081         /* Do not release reference state, we are destroying dynptr on stack,
1082          * not using some helper to release it. Just reset register.
1083          */
1084         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1085         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1086
1087         /* Same reason as unmark_stack_slots_dynptr above */
1088         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1090
1091         return 0;
1092 }
1093
1094 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1095 {
1096         int spi;
1097
1098         if (reg->type == CONST_PTR_TO_DYNPTR)
1099                 return false;
1100
1101         spi = dynptr_get_spi(env, reg);
1102
1103         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1104          * error because this just means the stack state hasn't been updated yet.
1105          * We will do check_mem_access to check and update stack bounds later.
1106          */
1107         if (spi < 0 && spi != -ERANGE)
1108                 return false;
1109
1110         /* We don't need to check if the stack slots are marked by previous
1111          * dynptr initializations because we allow overwriting existing unreferenced
1112          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1113          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1114          * touching are completely destructed before we reinitialize them for a new
1115          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1116          * instead of delaying it until the end where the user will get "Unreleased
1117          * reference" error.
1118          */
1119         return true;
1120 }
1121
1122 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1123 {
1124         struct bpf_func_state *state = func(env, reg);
1125         int i, spi;
1126
1127         /* This already represents first slot of initialized bpf_dynptr.
1128          *
1129          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1130          * check_func_arg_reg_off's logic, so we don't need to check its
1131          * offset and alignment.
1132          */
1133         if (reg->type == CONST_PTR_TO_DYNPTR)
1134                 return true;
1135
1136         spi = dynptr_get_spi(env, reg);
1137         if (spi < 0)
1138                 return false;
1139         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1140                 return false;
1141
1142         for (i = 0; i < BPF_REG_SIZE; i++) {
1143                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1144                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1145                         return false;
1146         }
1147
1148         return true;
1149 }
1150
1151 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1152                                     enum bpf_arg_type arg_type)
1153 {
1154         struct bpf_func_state *state = func(env, reg);
1155         enum bpf_dynptr_type dynptr_type;
1156         int spi;
1157
1158         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1159         if (arg_type == ARG_PTR_TO_DYNPTR)
1160                 return true;
1161
1162         dynptr_type = arg_to_dynptr_type(arg_type);
1163         if (reg->type == CONST_PTR_TO_DYNPTR) {
1164                 return reg->dynptr.type == dynptr_type;
1165         } else {
1166                 spi = dynptr_get_spi(env, reg);
1167                 if (spi < 0)
1168                         return false;
1169                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1170         }
1171 }
1172
1173 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1174
1175 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1176                                  struct bpf_reg_state *reg, int insn_idx,
1177                                  struct btf *btf, u32 btf_id, int nr_slots)
1178 {
1179         struct bpf_func_state *state = func(env, reg);
1180         int spi, i, j, id;
1181
1182         spi = iter_get_spi(env, reg, nr_slots);
1183         if (spi < 0)
1184                 return spi;
1185
1186         id = acquire_reference_state(env, insn_idx);
1187         if (id < 0)
1188                 return id;
1189
1190         for (i = 0; i < nr_slots; i++) {
1191                 struct bpf_stack_state *slot = &state->stack[spi - i];
1192                 struct bpf_reg_state *st = &slot->spilled_ptr;
1193
1194                 __mark_reg_known_zero(st);
1195                 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1196                 st->live |= REG_LIVE_WRITTEN;
1197                 st->ref_obj_id = i == 0 ? id : 0;
1198                 st->iter.btf = btf;
1199                 st->iter.btf_id = btf_id;
1200                 st->iter.state = BPF_ITER_STATE_ACTIVE;
1201                 st->iter.depth = 0;
1202
1203                 for (j = 0; j < BPF_REG_SIZE; j++)
1204                         slot->slot_type[j] = STACK_ITER;
1205
1206                 mark_stack_slot_scratched(env, spi - i);
1207         }
1208
1209         return 0;
1210 }
1211
1212 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1213                                    struct bpf_reg_state *reg, int nr_slots)
1214 {
1215         struct bpf_func_state *state = func(env, reg);
1216         int spi, i, j;
1217
1218         spi = iter_get_spi(env, reg, nr_slots);
1219         if (spi < 0)
1220                 return spi;
1221
1222         for (i = 0; i < nr_slots; i++) {
1223                 struct bpf_stack_state *slot = &state->stack[spi - i];
1224                 struct bpf_reg_state *st = &slot->spilled_ptr;
1225
1226                 if (i == 0)
1227                         WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1228
1229                 __mark_reg_not_init(env, st);
1230
1231                 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1232                 st->live |= REG_LIVE_WRITTEN;
1233
1234                 for (j = 0; j < BPF_REG_SIZE; j++)
1235                         slot->slot_type[j] = STACK_INVALID;
1236
1237                 mark_stack_slot_scratched(env, spi - i);
1238         }
1239
1240         return 0;
1241 }
1242
1243 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1244                                      struct bpf_reg_state *reg, int nr_slots)
1245 {
1246         struct bpf_func_state *state = func(env, reg);
1247         int spi, i, j;
1248
1249         /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1250          * will do check_mem_access to check and update stack bounds later, so
1251          * return true for that case.
1252          */
1253         spi = iter_get_spi(env, reg, nr_slots);
1254         if (spi == -ERANGE)
1255                 return true;
1256         if (spi < 0)
1257                 return false;
1258
1259         for (i = 0; i < nr_slots; i++) {
1260                 struct bpf_stack_state *slot = &state->stack[spi - i];
1261
1262                 for (j = 0; j < BPF_REG_SIZE; j++)
1263                         if (slot->slot_type[j] == STACK_ITER)
1264                                 return false;
1265         }
1266
1267         return true;
1268 }
1269
1270 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1271                                    struct btf *btf, u32 btf_id, int nr_slots)
1272 {
1273         struct bpf_func_state *state = func(env, reg);
1274         int spi, i, j;
1275
1276         spi = iter_get_spi(env, reg, nr_slots);
1277         if (spi < 0)
1278                 return false;
1279
1280         for (i = 0; i < nr_slots; i++) {
1281                 struct bpf_stack_state *slot = &state->stack[spi - i];
1282                 struct bpf_reg_state *st = &slot->spilled_ptr;
1283
1284                 /* only main (first) slot has ref_obj_id set */
1285                 if (i == 0 && !st->ref_obj_id)
1286                         return false;
1287                 if (i != 0 && st->ref_obj_id)
1288                         return false;
1289                 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1290                         return false;
1291
1292                 for (j = 0; j < BPF_REG_SIZE; j++)
1293                         if (slot->slot_type[j] != STACK_ITER)
1294                                 return false;
1295         }
1296
1297         return true;
1298 }
1299
1300 /* Check if given stack slot is "special":
1301  *   - spilled register state (STACK_SPILL);
1302  *   - dynptr state (STACK_DYNPTR);
1303  *   - iter state (STACK_ITER).
1304  */
1305 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1306 {
1307         enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1308
1309         switch (type) {
1310         case STACK_SPILL:
1311         case STACK_DYNPTR:
1312         case STACK_ITER:
1313                 return true;
1314         case STACK_INVALID:
1315         case STACK_MISC:
1316         case STACK_ZERO:
1317                 return false;
1318         default:
1319                 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1320                 return true;
1321         }
1322 }
1323
1324 /* The reg state of a pointer or a bounded scalar was saved when
1325  * it was spilled to the stack.
1326  */
1327 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1328 {
1329         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1330 }
1331
1332 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1333 {
1334         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1335                stack->spilled_ptr.type == SCALAR_VALUE;
1336 }
1337
1338 static void scrub_spilled_slot(u8 *stype)
1339 {
1340         if (*stype != STACK_INVALID)
1341                 *stype = STACK_MISC;
1342 }
1343
1344 static void print_verifier_state(struct bpf_verifier_env *env,
1345                                  const struct bpf_func_state *state,
1346                                  bool print_all)
1347 {
1348         const struct bpf_reg_state *reg;
1349         enum bpf_reg_type t;
1350         int i;
1351
1352         if (state->frameno)
1353                 verbose(env, " frame%d:", state->frameno);
1354         for (i = 0; i < MAX_BPF_REG; i++) {
1355                 reg = &state->regs[i];
1356                 t = reg->type;
1357                 if (t == NOT_INIT)
1358                         continue;
1359                 if (!print_all && !reg_scratched(env, i))
1360                         continue;
1361                 verbose(env, " R%d", i);
1362                 print_liveness(env, reg->live);
1363                 verbose(env, "=");
1364                 if (t == SCALAR_VALUE && reg->precise)
1365                         verbose(env, "P");
1366                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1367                     tnum_is_const(reg->var_off)) {
1368                         /* reg->off should be 0 for SCALAR_VALUE */
1369                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1370                         verbose(env, "%lld", reg->var_off.value + reg->off);
1371                 } else {
1372                         const char *sep = "";
1373
1374                         verbose(env, "%s", reg_type_str(env, t));
1375                         if (base_type(t) == PTR_TO_BTF_ID)
1376                                 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1377                         verbose(env, "(");
1378 /*
1379  * _a stands for append, was shortened to avoid multiline statements below.
1380  * This macro is used to output a comma separated list of attributes.
1381  */
1382 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1383
1384                         if (reg->id)
1385                                 verbose_a("id=%d", reg->id);
1386                         if (reg->ref_obj_id)
1387                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1388                         if (type_is_non_owning_ref(reg->type))
1389                                 verbose_a("%s", "non_own_ref");
1390                         if (t != SCALAR_VALUE)
1391                                 verbose_a("off=%d", reg->off);
1392                         if (type_is_pkt_pointer(t))
1393                                 verbose_a("r=%d", reg->range);
1394                         else if (base_type(t) == CONST_PTR_TO_MAP ||
1395                                  base_type(t) == PTR_TO_MAP_KEY ||
1396                                  base_type(t) == PTR_TO_MAP_VALUE)
1397                                 verbose_a("ks=%d,vs=%d",
1398                                           reg->map_ptr->key_size,
1399                                           reg->map_ptr->value_size);
1400                         if (tnum_is_const(reg->var_off)) {
1401                                 /* Typically an immediate SCALAR_VALUE, but
1402                                  * could be a pointer whose offset is too big
1403                                  * for reg->off
1404                                  */
1405                                 verbose_a("imm=%llx", reg->var_off.value);
1406                         } else {
1407                                 if (reg->smin_value != reg->umin_value &&
1408                                     reg->smin_value != S64_MIN)
1409                                         verbose_a("smin=%lld", (long long)reg->smin_value);
1410                                 if (reg->smax_value != reg->umax_value &&
1411                                     reg->smax_value != S64_MAX)
1412                                         verbose_a("smax=%lld", (long long)reg->smax_value);
1413                                 if (reg->umin_value != 0)
1414                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1415                                 if (reg->umax_value != U64_MAX)
1416                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1417                                 if (!tnum_is_unknown(reg->var_off)) {
1418                                         char tn_buf[48];
1419
1420                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1421                                         verbose_a("var_off=%s", tn_buf);
1422                                 }
1423                                 if (reg->s32_min_value != reg->smin_value &&
1424                                     reg->s32_min_value != S32_MIN)
1425                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1426                                 if (reg->s32_max_value != reg->smax_value &&
1427                                     reg->s32_max_value != S32_MAX)
1428                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1429                                 if (reg->u32_min_value != reg->umin_value &&
1430                                     reg->u32_min_value != U32_MIN)
1431                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1432                                 if (reg->u32_max_value != reg->umax_value &&
1433                                     reg->u32_max_value != U32_MAX)
1434                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1435                         }
1436 #undef verbose_a
1437
1438                         verbose(env, ")");
1439                 }
1440         }
1441         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1442                 char types_buf[BPF_REG_SIZE + 1];
1443                 bool valid = false;
1444                 int j;
1445
1446                 for (j = 0; j < BPF_REG_SIZE; j++) {
1447                         if (state->stack[i].slot_type[j] != STACK_INVALID)
1448                                 valid = true;
1449                         types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1450                 }
1451                 types_buf[BPF_REG_SIZE] = 0;
1452                 if (!valid)
1453                         continue;
1454                 if (!print_all && !stack_slot_scratched(env, i))
1455                         continue;
1456                 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1457                 case STACK_SPILL:
1458                         reg = &state->stack[i].spilled_ptr;
1459                         t = reg->type;
1460
1461                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1462                         print_liveness(env, reg->live);
1463                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1464                         if (t == SCALAR_VALUE && reg->precise)
1465                                 verbose(env, "P");
1466                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1467                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1468                         break;
1469                 case STACK_DYNPTR:
1470                         i += BPF_DYNPTR_NR_SLOTS - 1;
1471                         reg = &state->stack[i].spilled_ptr;
1472
1473                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1474                         print_liveness(env, reg->live);
1475                         verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1476                         if (reg->ref_obj_id)
1477                                 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1478                         break;
1479                 case STACK_ITER:
1480                         /* only main slot has ref_obj_id set; skip others */
1481                         reg = &state->stack[i].spilled_ptr;
1482                         if (!reg->ref_obj_id)
1483                                 continue;
1484
1485                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1486                         print_liveness(env, reg->live);
1487                         verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1488                                 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1489                                 reg->ref_obj_id, iter_state_str(reg->iter.state),
1490                                 reg->iter.depth);
1491                         break;
1492                 case STACK_MISC:
1493                 case STACK_ZERO:
1494                 default:
1495                         reg = &state->stack[i].spilled_ptr;
1496
1497                         for (j = 0; j < BPF_REG_SIZE; j++)
1498                                 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1499                         types_buf[BPF_REG_SIZE] = 0;
1500
1501                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1502                         print_liveness(env, reg->live);
1503                         verbose(env, "=%s", types_buf);
1504                         break;
1505                 }
1506         }
1507         if (state->acquired_refs && state->refs[0].id) {
1508                 verbose(env, " refs=%d", state->refs[0].id);
1509                 for (i = 1; i < state->acquired_refs; i++)
1510                         if (state->refs[i].id)
1511                                 verbose(env, ",%d", state->refs[i].id);
1512         }
1513         if (state->in_callback_fn)
1514                 verbose(env, " cb");
1515         if (state->in_async_callback_fn)
1516                 verbose(env, " async_cb");
1517         verbose(env, "\n");
1518         if (!print_all)
1519                 mark_verifier_state_clean(env);
1520 }
1521
1522 static inline u32 vlog_alignment(u32 pos)
1523 {
1524         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1525                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1526 }
1527
1528 static void print_insn_state(struct bpf_verifier_env *env,
1529                              const struct bpf_func_state *state)
1530 {
1531         if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1532                 /* remove new line character */
1533                 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1534                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1535         } else {
1536                 verbose(env, "%d:", env->insn_idx);
1537         }
1538         print_verifier_state(env, state, false);
1539 }
1540
1541 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1542  * small to hold src. This is different from krealloc since we don't want to preserve
1543  * the contents of dst.
1544  *
1545  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1546  * not be allocated.
1547  */
1548 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1549 {
1550         size_t alloc_bytes;
1551         void *orig = dst;
1552         size_t bytes;
1553
1554         if (ZERO_OR_NULL_PTR(src))
1555                 goto out;
1556
1557         if (unlikely(check_mul_overflow(n, size, &bytes)))
1558                 return NULL;
1559
1560         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1561         dst = krealloc(orig, alloc_bytes, flags);
1562         if (!dst) {
1563                 kfree(orig);
1564                 return NULL;
1565         }
1566
1567         memcpy(dst, src, bytes);
1568 out:
1569         return dst ? dst : ZERO_SIZE_PTR;
1570 }
1571
1572 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1573  * small to hold new_n items. new items are zeroed out if the array grows.
1574  *
1575  * Contrary to krealloc_array, does not free arr if new_n is zero.
1576  */
1577 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1578 {
1579         size_t alloc_size;
1580         void *new_arr;
1581
1582         if (!new_n || old_n == new_n)
1583                 goto out;
1584
1585         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1586         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1587         if (!new_arr) {
1588                 kfree(arr);
1589                 return NULL;
1590         }
1591         arr = new_arr;
1592
1593         if (new_n > old_n)
1594                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1595
1596 out:
1597         return arr ? arr : ZERO_SIZE_PTR;
1598 }
1599
1600 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1601 {
1602         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1603                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1604         if (!dst->refs)
1605                 return -ENOMEM;
1606
1607         dst->acquired_refs = src->acquired_refs;
1608         return 0;
1609 }
1610
1611 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613         size_t n = src->allocated_stack / BPF_REG_SIZE;
1614
1615         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1616                                 GFP_KERNEL);
1617         if (!dst->stack)
1618                 return -ENOMEM;
1619
1620         dst->allocated_stack = src->allocated_stack;
1621         return 0;
1622 }
1623
1624 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1625 {
1626         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1627                                     sizeof(struct bpf_reference_state));
1628         if (!state->refs)
1629                 return -ENOMEM;
1630
1631         state->acquired_refs = n;
1632         return 0;
1633 }
1634
1635 /* Possibly update state->allocated_stack to be at least size bytes. Also
1636  * possibly update the function's high-water mark in its bpf_subprog_info.
1637  */
1638 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1639 {
1640         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1641
1642         if (old_n >= n)
1643                 return 0;
1644
1645         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1646         if (!state->stack)
1647                 return -ENOMEM;
1648
1649         state->allocated_stack = size;
1650
1651         /* update known max for given subprogram */
1652         if (env->subprog_info[state->subprogno].stack_depth < size)
1653                 env->subprog_info[state->subprogno].stack_depth = size;
1654
1655         return 0;
1656 }
1657
1658 /* Acquire a pointer id from the env and update the state->refs to include
1659  * this new pointer reference.
1660  * On success, returns a valid pointer id to associate with the register
1661  * On failure, returns a negative errno.
1662  */
1663 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1664 {
1665         struct bpf_func_state *state = cur_func(env);
1666         int new_ofs = state->acquired_refs;
1667         int id, err;
1668
1669         err = resize_reference_state(state, state->acquired_refs + 1);
1670         if (err)
1671                 return err;
1672         id = ++env->id_gen;
1673         state->refs[new_ofs].id = id;
1674         state->refs[new_ofs].insn_idx = insn_idx;
1675         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1676
1677         return id;
1678 }
1679
1680 /* release function corresponding to acquire_reference_state(). Idempotent. */
1681 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1682 {
1683         int i, last_idx;
1684
1685         last_idx = state->acquired_refs - 1;
1686         for (i = 0; i < state->acquired_refs; i++) {
1687                 if (state->refs[i].id == ptr_id) {
1688                         /* Cannot release caller references in callbacks */
1689                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1690                                 return -EINVAL;
1691                         if (last_idx && i != last_idx)
1692                                 memcpy(&state->refs[i], &state->refs[last_idx],
1693                                        sizeof(*state->refs));
1694                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1695                         state->acquired_refs--;
1696                         return 0;
1697                 }
1698         }
1699         return -EINVAL;
1700 }
1701
1702 static void free_func_state(struct bpf_func_state *state)
1703 {
1704         if (!state)
1705                 return;
1706         kfree(state->refs);
1707         kfree(state->stack);
1708         kfree(state);
1709 }
1710
1711 static void clear_jmp_history(struct bpf_verifier_state *state)
1712 {
1713         kfree(state->jmp_history);
1714         state->jmp_history = NULL;
1715         state->jmp_history_cnt = 0;
1716 }
1717
1718 static void free_verifier_state(struct bpf_verifier_state *state,
1719                                 bool free_self)
1720 {
1721         int i;
1722
1723         for (i = 0; i <= state->curframe; i++) {
1724                 free_func_state(state->frame[i]);
1725                 state->frame[i] = NULL;
1726         }
1727         clear_jmp_history(state);
1728         if (free_self)
1729                 kfree(state);
1730 }
1731
1732 /* copy verifier state from src to dst growing dst stack space
1733  * when necessary to accommodate larger src stack
1734  */
1735 static int copy_func_state(struct bpf_func_state *dst,
1736                            const struct bpf_func_state *src)
1737 {
1738         int err;
1739
1740         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1741         err = copy_reference_state(dst, src);
1742         if (err)
1743                 return err;
1744         return copy_stack_state(dst, src);
1745 }
1746
1747 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1748                                const struct bpf_verifier_state *src)
1749 {
1750         struct bpf_func_state *dst;
1751         int i, err;
1752
1753         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1754                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1755                                             GFP_USER);
1756         if (!dst_state->jmp_history)
1757                 return -ENOMEM;
1758         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1759
1760         /* if dst has more stack frames then src frame, free them */
1761         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1762                 free_func_state(dst_state->frame[i]);
1763                 dst_state->frame[i] = NULL;
1764         }
1765         dst_state->speculative = src->speculative;
1766         dst_state->active_rcu_lock = src->active_rcu_lock;
1767         dst_state->curframe = src->curframe;
1768         dst_state->active_lock.ptr = src->active_lock.ptr;
1769         dst_state->active_lock.id = src->active_lock.id;
1770         dst_state->branches = src->branches;
1771         dst_state->parent = src->parent;
1772         dst_state->first_insn_idx = src->first_insn_idx;
1773         dst_state->last_insn_idx = src->last_insn_idx;
1774         for (i = 0; i <= src->curframe; i++) {
1775                 dst = dst_state->frame[i];
1776                 if (!dst) {
1777                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1778                         if (!dst)
1779                                 return -ENOMEM;
1780                         dst_state->frame[i] = dst;
1781                 }
1782                 err = copy_func_state(dst, src->frame[i]);
1783                 if (err)
1784                         return err;
1785         }
1786         return 0;
1787 }
1788
1789 static u32 state_htab_size(struct bpf_verifier_env *env)
1790 {
1791         return env->prog->len;
1792 }
1793
1794 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1795 {
1796         struct bpf_verifier_state *cur = env->cur_state;
1797         struct bpf_func_state *state = cur->frame[cur->curframe];
1798
1799         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1800 }
1801
1802 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1803 {
1804         while (st) {
1805                 u32 br = --st->branches;
1806
1807                 /* WARN_ON(br > 1) technically makes sense here,
1808                  * but see comment in push_stack(), hence:
1809                  */
1810                 WARN_ONCE((int)br < 0,
1811                           "BUG update_branch_counts:branches_to_explore=%d\n",
1812                           br);
1813                 if (br)
1814                         break;
1815                 st = st->parent;
1816         }
1817 }
1818
1819 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1820                      int *insn_idx, bool pop_log)
1821 {
1822         struct bpf_verifier_state *cur = env->cur_state;
1823         struct bpf_verifier_stack_elem *elem, *head = env->head;
1824         int err;
1825
1826         if (env->head == NULL)
1827                 return -ENOENT;
1828
1829         if (cur) {
1830                 err = copy_verifier_state(cur, &head->st);
1831                 if (err)
1832                         return err;
1833         }
1834         if (pop_log)
1835                 bpf_vlog_reset(&env->log, head->log_pos);
1836         if (insn_idx)
1837                 *insn_idx = head->insn_idx;
1838         if (prev_insn_idx)
1839                 *prev_insn_idx = head->prev_insn_idx;
1840         elem = head->next;
1841         free_verifier_state(&head->st, false);
1842         kfree(head);
1843         env->head = elem;
1844         env->stack_size--;
1845         return 0;
1846 }
1847
1848 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1849                                              int insn_idx, int prev_insn_idx,
1850                                              bool speculative)
1851 {
1852         struct bpf_verifier_state *cur = env->cur_state;
1853         struct bpf_verifier_stack_elem *elem;
1854         int err;
1855
1856         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1857         if (!elem)
1858                 goto err;
1859
1860         elem->insn_idx = insn_idx;
1861         elem->prev_insn_idx = prev_insn_idx;
1862         elem->next = env->head;
1863         elem->log_pos = env->log.end_pos;
1864         env->head = elem;
1865         env->stack_size++;
1866         err = copy_verifier_state(&elem->st, cur);
1867         if (err)
1868                 goto err;
1869         elem->st.speculative |= speculative;
1870         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1871                 verbose(env, "The sequence of %d jumps is too complex.\n",
1872                         env->stack_size);
1873                 goto err;
1874         }
1875         if (elem->st.parent) {
1876                 ++elem->st.parent->branches;
1877                 /* WARN_ON(branches > 2) technically makes sense here,
1878                  * but
1879                  * 1. speculative states will bump 'branches' for non-branch
1880                  * instructions
1881                  * 2. is_state_visited() heuristics may decide not to create
1882                  * a new state for a sequence of branches and all such current
1883                  * and cloned states will be pointing to a single parent state
1884                  * which might have large 'branches' count.
1885                  */
1886         }
1887         return &elem->st;
1888 err:
1889         free_verifier_state(env->cur_state, true);
1890         env->cur_state = NULL;
1891         /* pop all elements and return */
1892         while (!pop_stack(env, NULL, NULL, false));
1893         return NULL;
1894 }
1895
1896 #define CALLER_SAVED_REGS 6
1897 static const int caller_saved[CALLER_SAVED_REGS] = {
1898         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1899 };
1900
1901 /* This helper doesn't clear reg->id */
1902 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1903 {
1904         reg->var_off = tnum_const(imm);
1905         reg->smin_value = (s64)imm;
1906         reg->smax_value = (s64)imm;
1907         reg->umin_value = imm;
1908         reg->umax_value = imm;
1909
1910         reg->s32_min_value = (s32)imm;
1911         reg->s32_max_value = (s32)imm;
1912         reg->u32_min_value = (u32)imm;
1913         reg->u32_max_value = (u32)imm;
1914 }
1915
1916 /* Mark the unknown part of a register (variable offset or scalar value) as
1917  * known to have the value @imm.
1918  */
1919 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1920 {
1921         /* Clear off and union(map_ptr, range) */
1922         memset(((u8 *)reg) + sizeof(reg->type), 0,
1923                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1924         reg->id = 0;
1925         reg->ref_obj_id = 0;
1926         ___mark_reg_known(reg, imm);
1927 }
1928
1929 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1930 {
1931         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1932         reg->s32_min_value = (s32)imm;
1933         reg->s32_max_value = (s32)imm;
1934         reg->u32_min_value = (u32)imm;
1935         reg->u32_max_value = (u32)imm;
1936 }
1937
1938 /* Mark the 'variable offset' part of a register as zero.  This should be
1939  * used only on registers holding a pointer type.
1940  */
1941 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1942 {
1943         __mark_reg_known(reg, 0);
1944 }
1945
1946 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1947 {
1948         __mark_reg_known(reg, 0);
1949         reg->type = SCALAR_VALUE;
1950 }
1951
1952 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1953                                 struct bpf_reg_state *regs, u32 regno)
1954 {
1955         if (WARN_ON(regno >= MAX_BPF_REG)) {
1956                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1957                 /* Something bad happened, let's kill all regs */
1958                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1959                         __mark_reg_not_init(env, regs + regno);
1960                 return;
1961         }
1962         __mark_reg_known_zero(regs + regno);
1963 }
1964
1965 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1966                               bool first_slot, int dynptr_id)
1967 {
1968         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1969          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1970          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1971          */
1972         __mark_reg_known_zero(reg);
1973         reg->type = CONST_PTR_TO_DYNPTR;
1974         /* Give each dynptr a unique id to uniquely associate slices to it. */
1975         reg->id = dynptr_id;
1976         reg->dynptr.type = type;
1977         reg->dynptr.first_slot = first_slot;
1978 }
1979
1980 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1981 {
1982         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1983                 const struct bpf_map *map = reg->map_ptr;
1984
1985                 if (map->inner_map_meta) {
1986                         reg->type = CONST_PTR_TO_MAP;
1987                         reg->map_ptr = map->inner_map_meta;
1988                         /* transfer reg's id which is unique for every map_lookup_elem
1989                          * as UID of the inner map.
1990                          */
1991                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1992                                 reg->map_uid = reg->id;
1993                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1994                         reg->type = PTR_TO_XDP_SOCK;
1995                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1996                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1997                         reg->type = PTR_TO_SOCKET;
1998                 } else {
1999                         reg->type = PTR_TO_MAP_VALUE;
2000                 }
2001                 return;
2002         }
2003
2004         reg->type &= ~PTR_MAYBE_NULL;
2005 }
2006
2007 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2008                                 struct btf_field_graph_root *ds_head)
2009 {
2010         __mark_reg_known_zero(&regs[regno]);
2011         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2012         regs[regno].btf = ds_head->btf;
2013         regs[regno].btf_id = ds_head->value_btf_id;
2014         regs[regno].off = ds_head->node_offset;
2015 }
2016
2017 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2018 {
2019         return type_is_pkt_pointer(reg->type);
2020 }
2021
2022 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2023 {
2024         return reg_is_pkt_pointer(reg) ||
2025                reg->type == PTR_TO_PACKET_END;
2026 }
2027
2028 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2029 {
2030         return base_type(reg->type) == PTR_TO_MEM &&
2031                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2032 }
2033
2034 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2035 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2036                                     enum bpf_reg_type which)
2037 {
2038         /* The register can already have a range from prior markings.
2039          * This is fine as long as it hasn't been advanced from its
2040          * origin.
2041          */
2042         return reg->type == which &&
2043                reg->id == 0 &&
2044                reg->off == 0 &&
2045                tnum_equals_const(reg->var_off, 0);
2046 }
2047
2048 /* Reset the min/max bounds of a register */
2049 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2050 {
2051         reg->smin_value = S64_MIN;
2052         reg->smax_value = S64_MAX;
2053         reg->umin_value = 0;
2054         reg->umax_value = U64_MAX;
2055
2056         reg->s32_min_value = S32_MIN;
2057         reg->s32_max_value = S32_MAX;
2058         reg->u32_min_value = 0;
2059         reg->u32_max_value = U32_MAX;
2060 }
2061
2062 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2063 {
2064         reg->smin_value = S64_MIN;
2065         reg->smax_value = S64_MAX;
2066         reg->umin_value = 0;
2067         reg->umax_value = U64_MAX;
2068 }
2069
2070 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2071 {
2072         reg->s32_min_value = S32_MIN;
2073         reg->s32_max_value = S32_MAX;
2074         reg->u32_min_value = 0;
2075         reg->u32_max_value = U32_MAX;
2076 }
2077
2078 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2079 {
2080         struct tnum var32_off = tnum_subreg(reg->var_off);
2081
2082         /* min signed is max(sign bit) | min(other bits) */
2083         reg->s32_min_value = max_t(s32, reg->s32_min_value,
2084                         var32_off.value | (var32_off.mask & S32_MIN));
2085         /* max signed is min(sign bit) | max(other bits) */
2086         reg->s32_max_value = min_t(s32, reg->s32_max_value,
2087                         var32_off.value | (var32_off.mask & S32_MAX));
2088         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2089         reg->u32_max_value = min(reg->u32_max_value,
2090                                  (u32)(var32_off.value | var32_off.mask));
2091 }
2092
2093 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2094 {
2095         /* min signed is max(sign bit) | min(other bits) */
2096         reg->smin_value = max_t(s64, reg->smin_value,
2097                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2098         /* max signed is min(sign bit) | max(other bits) */
2099         reg->smax_value = min_t(s64, reg->smax_value,
2100                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2101         reg->umin_value = max(reg->umin_value, reg->var_off.value);
2102         reg->umax_value = min(reg->umax_value,
2103                               reg->var_off.value | reg->var_off.mask);
2104 }
2105
2106 static void __update_reg_bounds(struct bpf_reg_state *reg)
2107 {
2108         __update_reg32_bounds(reg);
2109         __update_reg64_bounds(reg);
2110 }
2111
2112 /* Uses signed min/max values to inform unsigned, and vice-versa */
2113 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2114 {
2115         /* Learn sign from signed bounds.
2116          * If we cannot cross the sign boundary, then signed and unsigned bounds
2117          * are the same, so combine.  This works even in the negative case, e.g.
2118          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2119          */
2120         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2121                 reg->s32_min_value = reg->u32_min_value =
2122                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2123                 reg->s32_max_value = reg->u32_max_value =
2124                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2125                 return;
2126         }
2127         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2128          * boundary, so we must be careful.
2129          */
2130         if ((s32)reg->u32_max_value >= 0) {
2131                 /* Positive.  We can't learn anything from the smin, but smax
2132                  * is positive, hence safe.
2133                  */
2134                 reg->s32_min_value = reg->u32_min_value;
2135                 reg->s32_max_value = reg->u32_max_value =
2136                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2137         } else if ((s32)reg->u32_min_value < 0) {
2138                 /* Negative.  We can't learn anything from the smax, but smin
2139                  * is negative, hence safe.
2140                  */
2141                 reg->s32_min_value = reg->u32_min_value =
2142                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2143                 reg->s32_max_value = reg->u32_max_value;
2144         }
2145 }
2146
2147 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2148 {
2149         /* Learn sign from signed bounds.
2150          * If we cannot cross the sign boundary, then signed and unsigned bounds
2151          * are the same, so combine.  This works even in the negative case, e.g.
2152          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2153          */
2154         if (reg->smin_value >= 0 || reg->smax_value < 0) {
2155                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2156                                                           reg->umin_value);
2157                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2158                                                           reg->umax_value);
2159                 return;
2160         }
2161         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2162          * boundary, so we must be careful.
2163          */
2164         if ((s64)reg->umax_value >= 0) {
2165                 /* Positive.  We can't learn anything from the smin, but smax
2166                  * is positive, hence safe.
2167                  */
2168                 reg->smin_value = reg->umin_value;
2169                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2170                                                           reg->umax_value);
2171         } else if ((s64)reg->umin_value < 0) {
2172                 /* Negative.  We can't learn anything from the smax, but smin
2173                  * is negative, hence safe.
2174                  */
2175                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2176                                                           reg->umin_value);
2177                 reg->smax_value = reg->umax_value;
2178         }
2179 }
2180
2181 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2182 {
2183         __reg32_deduce_bounds(reg);
2184         __reg64_deduce_bounds(reg);
2185 }
2186
2187 /* Attempts to improve var_off based on unsigned min/max information */
2188 static void __reg_bound_offset(struct bpf_reg_state *reg)
2189 {
2190         struct tnum var64_off = tnum_intersect(reg->var_off,
2191                                                tnum_range(reg->umin_value,
2192                                                           reg->umax_value));
2193         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2194                                                tnum_range(reg->u32_min_value,
2195                                                           reg->u32_max_value));
2196
2197         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2198 }
2199
2200 static void reg_bounds_sync(struct bpf_reg_state *reg)
2201 {
2202         /* We might have learned new bounds from the var_off. */
2203         __update_reg_bounds(reg);
2204         /* We might have learned something about the sign bit. */
2205         __reg_deduce_bounds(reg);
2206         /* We might have learned some bits from the bounds. */
2207         __reg_bound_offset(reg);
2208         /* Intersecting with the old var_off might have improved our bounds
2209          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2210          * then new var_off is (0; 0x7f...fc) which improves our umax.
2211          */
2212         __update_reg_bounds(reg);
2213 }
2214
2215 static bool __reg32_bound_s64(s32 a)
2216 {
2217         return a >= 0 && a <= S32_MAX;
2218 }
2219
2220 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2221 {
2222         reg->umin_value = reg->u32_min_value;
2223         reg->umax_value = reg->u32_max_value;
2224
2225         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2226          * be positive otherwise set to worse case bounds and refine later
2227          * from tnum.
2228          */
2229         if (__reg32_bound_s64(reg->s32_min_value) &&
2230             __reg32_bound_s64(reg->s32_max_value)) {
2231                 reg->smin_value = reg->s32_min_value;
2232                 reg->smax_value = reg->s32_max_value;
2233         } else {
2234                 reg->smin_value = 0;
2235                 reg->smax_value = U32_MAX;
2236         }
2237 }
2238
2239 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2240 {
2241         /* special case when 64-bit register has upper 32-bit register
2242          * zeroed. Typically happens after zext or <<32, >>32 sequence
2243          * allowing us to use 32-bit bounds directly,
2244          */
2245         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2246                 __reg_assign_32_into_64(reg);
2247         } else {
2248                 /* Otherwise the best we can do is push lower 32bit known and
2249                  * unknown bits into register (var_off set from jmp logic)
2250                  * then learn as much as possible from the 64-bit tnum
2251                  * known and unknown bits. The previous smin/smax bounds are
2252                  * invalid here because of jmp32 compare so mark them unknown
2253                  * so they do not impact tnum bounds calculation.
2254                  */
2255                 __mark_reg64_unbounded(reg);
2256         }
2257         reg_bounds_sync(reg);
2258 }
2259
2260 static bool __reg64_bound_s32(s64 a)
2261 {
2262         return a >= S32_MIN && a <= S32_MAX;
2263 }
2264
2265 static bool __reg64_bound_u32(u64 a)
2266 {
2267         return a >= U32_MIN && a <= U32_MAX;
2268 }
2269
2270 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2271 {
2272         __mark_reg32_unbounded(reg);
2273         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2274                 reg->s32_min_value = (s32)reg->smin_value;
2275                 reg->s32_max_value = (s32)reg->smax_value;
2276         }
2277         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2278                 reg->u32_min_value = (u32)reg->umin_value;
2279                 reg->u32_max_value = (u32)reg->umax_value;
2280         }
2281         reg_bounds_sync(reg);
2282 }
2283
2284 /* Mark a register as having a completely unknown (scalar) value. */
2285 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2286                                struct bpf_reg_state *reg)
2287 {
2288         /*
2289          * Clear type, off, and union(map_ptr, range) and
2290          * padding between 'type' and union
2291          */
2292         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2293         reg->type = SCALAR_VALUE;
2294         reg->id = 0;
2295         reg->ref_obj_id = 0;
2296         reg->var_off = tnum_unknown;
2297         reg->frameno = 0;
2298         reg->precise = !env->bpf_capable;
2299         __mark_reg_unbounded(reg);
2300 }
2301
2302 static void mark_reg_unknown(struct bpf_verifier_env *env,
2303                              struct bpf_reg_state *regs, u32 regno)
2304 {
2305         if (WARN_ON(regno >= MAX_BPF_REG)) {
2306                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2307                 /* Something bad happened, let's kill all regs except FP */
2308                 for (regno = 0; regno < BPF_REG_FP; regno++)
2309                         __mark_reg_not_init(env, regs + regno);
2310                 return;
2311         }
2312         __mark_reg_unknown(env, regs + regno);
2313 }
2314
2315 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2316                                 struct bpf_reg_state *reg)
2317 {
2318         __mark_reg_unknown(env, reg);
2319         reg->type = NOT_INIT;
2320 }
2321
2322 static void mark_reg_not_init(struct bpf_verifier_env *env,
2323                               struct bpf_reg_state *regs, u32 regno)
2324 {
2325         if (WARN_ON(regno >= MAX_BPF_REG)) {
2326                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2327                 /* Something bad happened, let's kill all regs except FP */
2328                 for (regno = 0; regno < BPF_REG_FP; regno++)
2329                         __mark_reg_not_init(env, regs + regno);
2330                 return;
2331         }
2332         __mark_reg_not_init(env, regs + regno);
2333 }
2334
2335 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2336                             struct bpf_reg_state *regs, u32 regno,
2337                             enum bpf_reg_type reg_type,
2338                             struct btf *btf, u32 btf_id,
2339                             enum bpf_type_flag flag)
2340 {
2341         if (reg_type == SCALAR_VALUE) {
2342                 mark_reg_unknown(env, regs, regno);
2343                 return;
2344         }
2345         mark_reg_known_zero(env, regs, regno);
2346         regs[regno].type = PTR_TO_BTF_ID | flag;
2347         regs[regno].btf = btf;
2348         regs[regno].btf_id = btf_id;
2349 }
2350
2351 #define DEF_NOT_SUBREG  (0)
2352 static void init_reg_state(struct bpf_verifier_env *env,
2353                            struct bpf_func_state *state)
2354 {
2355         struct bpf_reg_state *regs = state->regs;
2356         int i;
2357
2358         for (i = 0; i < MAX_BPF_REG; i++) {
2359                 mark_reg_not_init(env, regs, i);
2360                 regs[i].live = REG_LIVE_NONE;
2361                 regs[i].parent = NULL;
2362                 regs[i].subreg_def = DEF_NOT_SUBREG;
2363         }
2364
2365         /* frame pointer */
2366         regs[BPF_REG_FP].type = PTR_TO_STACK;
2367         mark_reg_known_zero(env, regs, BPF_REG_FP);
2368         regs[BPF_REG_FP].frameno = state->frameno;
2369 }
2370
2371 #define BPF_MAIN_FUNC (-1)
2372 static void init_func_state(struct bpf_verifier_env *env,
2373                             struct bpf_func_state *state,
2374                             int callsite, int frameno, int subprogno)
2375 {
2376         state->callsite = callsite;
2377         state->frameno = frameno;
2378         state->subprogno = subprogno;
2379         state->callback_ret_range = tnum_range(0, 0);
2380         init_reg_state(env, state);
2381         mark_verifier_state_scratched(env);
2382 }
2383
2384 /* Similar to push_stack(), but for async callbacks */
2385 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2386                                                 int insn_idx, int prev_insn_idx,
2387                                                 int subprog)
2388 {
2389         struct bpf_verifier_stack_elem *elem;
2390         struct bpf_func_state *frame;
2391
2392         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2393         if (!elem)
2394                 goto err;
2395
2396         elem->insn_idx = insn_idx;
2397         elem->prev_insn_idx = prev_insn_idx;
2398         elem->next = env->head;
2399         elem->log_pos = env->log.end_pos;
2400         env->head = elem;
2401         env->stack_size++;
2402         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2403                 verbose(env,
2404                         "The sequence of %d jumps is too complex for async cb.\n",
2405                         env->stack_size);
2406                 goto err;
2407         }
2408         /* Unlike push_stack() do not copy_verifier_state().
2409          * The caller state doesn't matter.
2410          * This is async callback. It starts in a fresh stack.
2411          * Initialize it similar to do_check_common().
2412          */
2413         elem->st.branches = 1;
2414         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2415         if (!frame)
2416                 goto err;
2417         init_func_state(env, frame,
2418                         BPF_MAIN_FUNC /* callsite */,
2419                         0 /* frameno within this callchain */,
2420                         subprog /* subprog number within this prog */);
2421         elem->st.frame[0] = frame;
2422         return &elem->st;
2423 err:
2424         free_verifier_state(env->cur_state, true);
2425         env->cur_state = NULL;
2426         /* pop all elements and return */
2427         while (!pop_stack(env, NULL, NULL, false));
2428         return NULL;
2429 }
2430
2431
2432 enum reg_arg_type {
2433         SRC_OP,         /* register is used as source operand */
2434         DST_OP,         /* register is used as destination operand */
2435         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2436 };
2437
2438 static int cmp_subprogs(const void *a, const void *b)
2439 {
2440         return ((struct bpf_subprog_info *)a)->start -
2441                ((struct bpf_subprog_info *)b)->start;
2442 }
2443
2444 static int find_subprog(struct bpf_verifier_env *env, int off)
2445 {
2446         struct bpf_subprog_info *p;
2447
2448         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2449                     sizeof(env->subprog_info[0]), cmp_subprogs);
2450         if (!p)
2451                 return -ENOENT;
2452         return p - env->subprog_info;
2453
2454 }
2455
2456 static int add_subprog(struct bpf_verifier_env *env, int off)
2457 {
2458         int insn_cnt = env->prog->len;
2459         int ret;
2460
2461         if (off >= insn_cnt || off < 0) {
2462                 verbose(env, "call to invalid destination\n");
2463                 return -EINVAL;
2464         }
2465         ret = find_subprog(env, off);
2466         if (ret >= 0)
2467                 return ret;
2468         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2469                 verbose(env, "too many subprograms\n");
2470                 return -E2BIG;
2471         }
2472         /* determine subprog starts. The end is one before the next starts */
2473         env->subprog_info[env->subprog_cnt++].start = off;
2474         sort(env->subprog_info, env->subprog_cnt,
2475              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2476         return env->subprog_cnt - 1;
2477 }
2478
2479 #define MAX_KFUNC_DESCS 256
2480 #define MAX_KFUNC_BTFS  256
2481
2482 struct bpf_kfunc_desc {
2483         struct btf_func_model func_model;
2484         u32 func_id;
2485         s32 imm;
2486         u16 offset;
2487         unsigned long addr;
2488 };
2489
2490 struct bpf_kfunc_btf {
2491         struct btf *btf;
2492         struct module *module;
2493         u16 offset;
2494 };
2495
2496 struct bpf_kfunc_desc_tab {
2497         /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2498          * verification. JITs do lookups by bpf_insn, where func_id may not be
2499          * available, therefore at the end of verification do_misc_fixups()
2500          * sorts this by imm and offset.
2501          */
2502         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2503         u32 nr_descs;
2504 };
2505
2506 struct bpf_kfunc_btf_tab {
2507         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2508         u32 nr_descs;
2509 };
2510
2511 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2512 {
2513         const struct bpf_kfunc_desc *d0 = a;
2514         const struct bpf_kfunc_desc *d1 = b;
2515
2516         /* func_id is not greater than BTF_MAX_TYPE */
2517         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2518 }
2519
2520 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2521 {
2522         const struct bpf_kfunc_btf *d0 = a;
2523         const struct bpf_kfunc_btf *d1 = b;
2524
2525         return d0->offset - d1->offset;
2526 }
2527
2528 static const struct bpf_kfunc_desc *
2529 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2530 {
2531         struct bpf_kfunc_desc desc = {
2532                 .func_id = func_id,
2533                 .offset = offset,
2534         };
2535         struct bpf_kfunc_desc_tab *tab;
2536
2537         tab = prog->aux->kfunc_tab;
2538         return bsearch(&desc, tab->descs, tab->nr_descs,
2539                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2540 }
2541
2542 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2543                        u16 btf_fd_idx, u8 **func_addr)
2544 {
2545         const struct bpf_kfunc_desc *desc;
2546
2547         desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2548         if (!desc)
2549                 return -EFAULT;
2550
2551         *func_addr = (u8 *)desc->addr;
2552         return 0;
2553 }
2554
2555 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2556                                          s16 offset)
2557 {
2558         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2559         struct bpf_kfunc_btf_tab *tab;
2560         struct bpf_kfunc_btf *b;
2561         struct module *mod;
2562         struct btf *btf;
2563         int btf_fd;
2564
2565         tab = env->prog->aux->kfunc_btf_tab;
2566         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2567                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2568         if (!b) {
2569                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2570                         verbose(env, "too many different module BTFs\n");
2571                         return ERR_PTR(-E2BIG);
2572                 }
2573
2574                 if (bpfptr_is_null(env->fd_array)) {
2575                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2576                         return ERR_PTR(-EPROTO);
2577                 }
2578
2579                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2580                                             offset * sizeof(btf_fd),
2581                                             sizeof(btf_fd)))
2582                         return ERR_PTR(-EFAULT);
2583
2584                 btf = btf_get_by_fd(btf_fd);
2585                 if (IS_ERR(btf)) {
2586                         verbose(env, "invalid module BTF fd specified\n");
2587                         return btf;
2588                 }
2589
2590                 if (!btf_is_module(btf)) {
2591                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2592                         btf_put(btf);
2593                         return ERR_PTR(-EINVAL);
2594                 }
2595
2596                 mod = btf_try_get_module(btf);
2597                 if (!mod) {
2598                         btf_put(btf);
2599                         return ERR_PTR(-ENXIO);
2600                 }
2601
2602                 b = &tab->descs[tab->nr_descs++];
2603                 b->btf = btf;
2604                 b->module = mod;
2605                 b->offset = offset;
2606
2607                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2608                      kfunc_btf_cmp_by_off, NULL);
2609         }
2610         return b->btf;
2611 }
2612
2613 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2614 {
2615         if (!tab)
2616                 return;
2617
2618         while (tab->nr_descs--) {
2619                 module_put(tab->descs[tab->nr_descs].module);
2620                 btf_put(tab->descs[tab->nr_descs].btf);
2621         }
2622         kfree(tab);
2623 }
2624
2625 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2626 {
2627         if (offset) {
2628                 if (offset < 0) {
2629                         /* In the future, this can be allowed to increase limit
2630                          * of fd index into fd_array, interpreted as u16.
2631                          */
2632                         verbose(env, "negative offset disallowed for kernel module function call\n");
2633                         return ERR_PTR(-EINVAL);
2634                 }
2635
2636                 return __find_kfunc_desc_btf(env, offset);
2637         }
2638         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2639 }
2640
2641 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2642 {
2643         const struct btf_type *func, *func_proto;
2644         struct bpf_kfunc_btf_tab *btf_tab;
2645         struct bpf_kfunc_desc_tab *tab;
2646         struct bpf_prog_aux *prog_aux;
2647         struct bpf_kfunc_desc *desc;
2648         const char *func_name;
2649         struct btf *desc_btf;
2650         unsigned long call_imm;
2651         unsigned long addr;
2652         int err;
2653
2654         prog_aux = env->prog->aux;
2655         tab = prog_aux->kfunc_tab;
2656         btf_tab = prog_aux->kfunc_btf_tab;
2657         if (!tab) {
2658                 if (!btf_vmlinux) {
2659                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2660                         return -ENOTSUPP;
2661                 }
2662
2663                 if (!env->prog->jit_requested) {
2664                         verbose(env, "JIT is required for calling kernel function\n");
2665                         return -ENOTSUPP;
2666                 }
2667
2668                 if (!bpf_jit_supports_kfunc_call()) {
2669                         verbose(env, "JIT does not support calling kernel function\n");
2670                         return -ENOTSUPP;
2671                 }
2672
2673                 if (!env->prog->gpl_compatible) {
2674                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2675                         return -EINVAL;
2676                 }
2677
2678                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2679                 if (!tab)
2680                         return -ENOMEM;
2681                 prog_aux->kfunc_tab = tab;
2682         }
2683
2684         /* func_id == 0 is always invalid, but instead of returning an error, be
2685          * conservative and wait until the code elimination pass before returning
2686          * error, so that invalid calls that get pruned out can be in BPF programs
2687          * loaded from userspace.  It is also required that offset be untouched
2688          * for such calls.
2689          */
2690         if (!func_id && !offset)
2691                 return 0;
2692
2693         if (!btf_tab && offset) {
2694                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2695                 if (!btf_tab)
2696                         return -ENOMEM;
2697                 prog_aux->kfunc_btf_tab = btf_tab;
2698         }
2699
2700         desc_btf = find_kfunc_desc_btf(env, offset);
2701         if (IS_ERR(desc_btf)) {
2702                 verbose(env, "failed to find BTF for kernel function\n");
2703                 return PTR_ERR(desc_btf);
2704         }
2705
2706         if (find_kfunc_desc(env->prog, func_id, offset))
2707                 return 0;
2708
2709         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2710                 verbose(env, "too many different kernel function calls\n");
2711                 return -E2BIG;
2712         }
2713
2714         func = btf_type_by_id(desc_btf, func_id);
2715         if (!func || !btf_type_is_func(func)) {
2716                 verbose(env, "kernel btf_id %u is not a function\n",
2717                         func_id);
2718                 return -EINVAL;
2719         }
2720         func_proto = btf_type_by_id(desc_btf, func->type);
2721         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2722                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2723                         func_id);
2724                 return -EINVAL;
2725         }
2726
2727         func_name = btf_name_by_offset(desc_btf, func->name_off);
2728         addr = kallsyms_lookup_name(func_name);
2729         if (!addr) {
2730                 verbose(env, "cannot find address for kernel function %s\n",
2731                         func_name);
2732                 return -EINVAL;
2733         }
2734         specialize_kfunc(env, func_id, offset, &addr);
2735
2736         if (bpf_jit_supports_far_kfunc_call()) {
2737                 call_imm = func_id;
2738         } else {
2739                 call_imm = BPF_CALL_IMM(addr);
2740                 /* Check whether the relative offset overflows desc->imm */
2741                 if ((unsigned long)(s32)call_imm != call_imm) {
2742                         verbose(env, "address of kernel function %s is out of range\n",
2743                                 func_name);
2744                         return -EINVAL;
2745                 }
2746         }
2747
2748         if (bpf_dev_bound_kfunc_id(func_id)) {
2749                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2750                 if (err)
2751                         return err;
2752         }
2753
2754         desc = &tab->descs[tab->nr_descs++];
2755         desc->func_id = func_id;
2756         desc->imm = call_imm;
2757         desc->offset = offset;
2758         desc->addr = addr;
2759         err = btf_distill_func_proto(&env->log, desc_btf,
2760                                      func_proto, func_name,
2761                                      &desc->func_model);
2762         if (!err)
2763                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2764                      kfunc_desc_cmp_by_id_off, NULL);
2765         return err;
2766 }
2767
2768 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2769 {
2770         const struct bpf_kfunc_desc *d0 = a;
2771         const struct bpf_kfunc_desc *d1 = b;
2772
2773         if (d0->imm != d1->imm)
2774                 return d0->imm < d1->imm ? -1 : 1;
2775         if (d0->offset != d1->offset)
2776                 return d0->offset < d1->offset ? -1 : 1;
2777         return 0;
2778 }
2779
2780 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2781 {
2782         struct bpf_kfunc_desc_tab *tab;
2783
2784         tab = prog->aux->kfunc_tab;
2785         if (!tab)
2786                 return;
2787
2788         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2789              kfunc_desc_cmp_by_imm_off, NULL);
2790 }
2791
2792 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2793 {
2794         return !!prog->aux->kfunc_tab;
2795 }
2796
2797 const struct btf_func_model *
2798 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2799                          const struct bpf_insn *insn)
2800 {
2801         const struct bpf_kfunc_desc desc = {
2802                 .imm = insn->imm,
2803                 .offset = insn->off,
2804         };
2805         const struct bpf_kfunc_desc *res;
2806         struct bpf_kfunc_desc_tab *tab;
2807
2808         tab = prog->aux->kfunc_tab;
2809         res = bsearch(&desc, tab->descs, tab->nr_descs,
2810                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2811
2812         return res ? &res->func_model : NULL;
2813 }
2814
2815 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2816 {
2817         struct bpf_subprog_info *subprog = env->subprog_info;
2818         struct bpf_insn *insn = env->prog->insnsi;
2819         int i, ret, insn_cnt = env->prog->len;
2820
2821         /* Add entry function. */
2822         ret = add_subprog(env, 0);
2823         if (ret)
2824                 return ret;
2825
2826         for (i = 0; i < insn_cnt; i++, insn++) {
2827                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2828                     !bpf_pseudo_kfunc_call(insn))
2829                         continue;
2830
2831                 if (!env->bpf_capable) {
2832                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2833                         return -EPERM;
2834                 }
2835
2836                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2837                         ret = add_subprog(env, i + insn->imm + 1);
2838                 else
2839                         ret = add_kfunc_call(env, insn->imm, insn->off);
2840
2841                 if (ret < 0)
2842                         return ret;
2843         }
2844
2845         /* Add a fake 'exit' subprog which could simplify subprog iteration
2846          * logic. 'subprog_cnt' should not be increased.
2847          */
2848         subprog[env->subprog_cnt].start = insn_cnt;
2849
2850         if (env->log.level & BPF_LOG_LEVEL2)
2851                 for (i = 0; i < env->subprog_cnt; i++)
2852                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2853
2854         return 0;
2855 }
2856
2857 static int check_subprogs(struct bpf_verifier_env *env)
2858 {
2859         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2860         struct bpf_subprog_info *subprog = env->subprog_info;
2861         struct bpf_insn *insn = env->prog->insnsi;
2862         int insn_cnt = env->prog->len;
2863
2864         /* now check that all jumps are within the same subprog */
2865         subprog_start = subprog[cur_subprog].start;
2866         subprog_end = subprog[cur_subprog + 1].start;
2867         for (i = 0; i < insn_cnt; i++) {
2868                 u8 code = insn[i].code;
2869
2870                 if (code == (BPF_JMP | BPF_CALL) &&
2871                     insn[i].src_reg == 0 &&
2872                     insn[i].imm == BPF_FUNC_tail_call)
2873                         subprog[cur_subprog].has_tail_call = true;
2874                 if (BPF_CLASS(code) == BPF_LD &&
2875                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2876                         subprog[cur_subprog].has_ld_abs = true;
2877                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2878                         goto next;
2879                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2880                         goto next;
2881                 if (code == (BPF_JMP32 | BPF_JA))
2882                         off = i + insn[i].imm + 1;
2883                 else
2884                         off = i + insn[i].off + 1;
2885                 if (off < subprog_start || off >= subprog_end) {
2886                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2887                         return -EINVAL;
2888                 }
2889 next:
2890                 if (i == subprog_end - 1) {
2891                         /* to avoid fall-through from one subprog into another
2892                          * the last insn of the subprog should be either exit
2893                          * or unconditional jump back
2894                          */
2895                         if (code != (BPF_JMP | BPF_EXIT) &&
2896                             code != (BPF_JMP32 | BPF_JA) &&
2897                             code != (BPF_JMP | BPF_JA)) {
2898                                 verbose(env, "last insn is not an exit or jmp\n");
2899                                 return -EINVAL;
2900                         }
2901                         subprog_start = subprog_end;
2902                         cur_subprog++;
2903                         if (cur_subprog < env->subprog_cnt)
2904                                 subprog_end = subprog[cur_subprog + 1].start;
2905                 }
2906         }
2907         return 0;
2908 }
2909
2910 /* Parentage chain of this register (or stack slot) should take care of all
2911  * issues like callee-saved registers, stack slot allocation time, etc.
2912  */
2913 static int mark_reg_read(struct bpf_verifier_env *env,
2914                          const struct bpf_reg_state *state,
2915                          struct bpf_reg_state *parent, u8 flag)
2916 {
2917         bool writes = parent == state->parent; /* Observe write marks */
2918         int cnt = 0;
2919
2920         while (parent) {
2921                 /* if read wasn't screened by an earlier write ... */
2922                 if (writes && state->live & REG_LIVE_WRITTEN)
2923                         break;
2924                 if (parent->live & REG_LIVE_DONE) {
2925                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2926                                 reg_type_str(env, parent->type),
2927                                 parent->var_off.value, parent->off);
2928                         return -EFAULT;
2929                 }
2930                 /* The first condition is more likely to be true than the
2931                  * second, checked it first.
2932                  */
2933                 if ((parent->live & REG_LIVE_READ) == flag ||
2934                     parent->live & REG_LIVE_READ64)
2935                         /* The parentage chain never changes and
2936                          * this parent was already marked as LIVE_READ.
2937                          * There is no need to keep walking the chain again and
2938                          * keep re-marking all parents as LIVE_READ.
2939                          * This case happens when the same register is read
2940                          * multiple times without writes into it in-between.
2941                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2942                          * then no need to set the weak REG_LIVE_READ32.
2943                          */
2944                         break;
2945                 /* ... then we depend on parent's value */
2946                 parent->live |= flag;
2947                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2948                 if (flag == REG_LIVE_READ64)
2949                         parent->live &= ~REG_LIVE_READ32;
2950                 state = parent;
2951                 parent = state->parent;
2952                 writes = true;
2953                 cnt++;
2954         }
2955
2956         if (env->longest_mark_read_walk < cnt)
2957                 env->longest_mark_read_walk = cnt;
2958         return 0;
2959 }
2960
2961 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2962 {
2963         struct bpf_func_state *state = func(env, reg);
2964         int spi, ret;
2965
2966         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2967          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2968          * check_kfunc_call.
2969          */
2970         if (reg->type == CONST_PTR_TO_DYNPTR)
2971                 return 0;
2972         spi = dynptr_get_spi(env, reg);
2973         if (spi < 0)
2974                 return spi;
2975         /* Caller ensures dynptr is valid and initialized, which means spi is in
2976          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2977          * read.
2978          */
2979         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2980                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2981         if (ret)
2982                 return ret;
2983         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2984                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2985 }
2986
2987 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2988                           int spi, int nr_slots)
2989 {
2990         struct bpf_func_state *state = func(env, reg);
2991         int err, i;
2992
2993         for (i = 0; i < nr_slots; i++) {
2994                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2995
2996                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2997                 if (err)
2998                         return err;
2999
3000                 mark_stack_slot_scratched(env, spi - i);
3001         }
3002
3003         return 0;
3004 }
3005
3006 /* This function is supposed to be used by the following 32-bit optimization
3007  * code only. It returns TRUE if the source or destination register operates
3008  * on 64-bit, otherwise return FALSE.
3009  */
3010 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3011                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3012 {
3013         u8 code, class, op;
3014
3015         code = insn->code;
3016         class = BPF_CLASS(code);
3017         op = BPF_OP(code);
3018         if (class == BPF_JMP) {
3019                 /* BPF_EXIT for "main" will reach here. Return TRUE
3020                  * conservatively.
3021                  */
3022                 if (op == BPF_EXIT)
3023                         return true;
3024                 if (op == BPF_CALL) {
3025                         /* BPF to BPF call will reach here because of marking
3026                          * caller saved clobber with DST_OP_NO_MARK for which we
3027                          * don't care the register def because they are anyway
3028                          * marked as NOT_INIT already.
3029                          */
3030                         if (insn->src_reg == BPF_PSEUDO_CALL)
3031                                 return false;
3032                         /* Helper call will reach here because of arg type
3033                          * check, conservatively return TRUE.
3034                          */
3035                         if (t == SRC_OP)
3036                                 return true;
3037
3038                         return false;
3039                 }
3040         }
3041
3042         if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3043                 return false;
3044
3045         if (class == BPF_ALU64 || class == BPF_JMP ||
3046             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3047                 return true;
3048
3049         if (class == BPF_ALU || class == BPF_JMP32)
3050                 return false;
3051
3052         if (class == BPF_LDX) {
3053                 if (t != SRC_OP)
3054                         return BPF_SIZE(code) == BPF_DW;
3055                 /* LDX source must be ptr. */
3056                 return true;
3057         }
3058
3059         if (class == BPF_STX) {
3060                 /* BPF_STX (including atomic variants) has multiple source
3061                  * operands, one of which is a ptr. Check whether the caller is
3062                  * asking about it.
3063                  */
3064                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3065                         return true;
3066                 return BPF_SIZE(code) == BPF_DW;
3067         }
3068
3069         if (class == BPF_LD) {
3070                 u8 mode = BPF_MODE(code);
3071
3072                 /* LD_IMM64 */
3073                 if (mode == BPF_IMM)
3074                         return true;
3075
3076                 /* Both LD_IND and LD_ABS return 32-bit data. */
3077                 if (t != SRC_OP)
3078                         return  false;
3079
3080                 /* Implicit ctx ptr. */
3081                 if (regno == BPF_REG_6)
3082                         return true;
3083
3084                 /* Explicit source could be any width. */
3085                 return true;
3086         }
3087
3088         if (class == BPF_ST)
3089                 /* The only source register for BPF_ST is a ptr. */
3090                 return true;
3091
3092         /* Conservatively return true at default. */
3093         return true;
3094 }
3095
3096 /* Return the regno defined by the insn, or -1. */
3097 static int insn_def_regno(const struct bpf_insn *insn)
3098 {
3099         switch (BPF_CLASS(insn->code)) {
3100         case BPF_JMP:
3101         case BPF_JMP32:
3102         case BPF_ST:
3103                 return -1;
3104         case BPF_STX:
3105                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3106                     (insn->imm & BPF_FETCH)) {
3107                         if (insn->imm == BPF_CMPXCHG)
3108                                 return BPF_REG_0;
3109                         else
3110                                 return insn->src_reg;
3111                 } else {
3112                         return -1;
3113                 }
3114         default:
3115                 return insn->dst_reg;
3116         }
3117 }
3118
3119 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3120 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3121 {
3122         int dst_reg = insn_def_regno(insn);
3123
3124         if (dst_reg == -1)
3125                 return false;
3126
3127         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3128 }
3129
3130 static void mark_insn_zext(struct bpf_verifier_env *env,
3131                            struct bpf_reg_state *reg)
3132 {
3133         s32 def_idx = reg->subreg_def;
3134
3135         if (def_idx == DEF_NOT_SUBREG)
3136                 return;
3137
3138         env->insn_aux_data[def_idx - 1].zext_dst = true;
3139         /* The dst will be zero extended, so won't be sub-register anymore. */
3140         reg->subreg_def = DEF_NOT_SUBREG;
3141 }
3142
3143 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3144                          enum reg_arg_type t)
3145 {
3146         struct bpf_verifier_state *vstate = env->cur_state;
3147         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3148         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3149         struct bpf_reg_state *reg, *regs = state->regs;
3150         bool rw64;
3151
3152         if (regno >= MAX_BPF_REG) {
3153                 verbose(env, "R%d is invalid\n", regno);
3154                 return -EINVAL;
3155         }
3156
3157         mark_reg_scratched(env, regno);
3158
3159         reg = &regs[regno];
3160         rw64 = is_reg64(env, insn, regno, reg, t);
3161         if (t == SRC_OP) {
3162                 /* check whether register used as source operand can be read */
3163                 if (reg->type == NOT_INIT) {
3164                         verbose(env, "R%d !read_ok\n", regno);
3165                         return -EACCES;
3166                 }
3167                 /* We don't need to worry about FP liveness because it's read-only */
3168                 if (regno == BPF_REG_FP)
3169                         return 0;
3170
3171                 if (rw64)
3172                         mark_insn_zext(env, reg);
3173
3174                 return mark_reg_read(env, reg, reg->parent,
3175                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3176         } else {
3177                 /* check whether register used as dest operand can be written to */
3178                 if (regno == BPF_REG_FP) {
3179                         verbose(env, "frame pointer is read only\n");
3180                         return -EACCES;
3181                 }
3182                 reg->live |= REG_LIVE_WRITTEN;
3183                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3184                 if (t == DST_OP)
3185                         mark_reg_unknown(env, regs, regno);
3186         }
3187         return 0;
3188 }
3189
3190 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3191 {
3192         env->insn_aux_data[idx].jmp_point = true;
3193 }
3194
3195 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3196 {
3197         return env->insn_aux_data[insn_idx].jmp_point;
3198 }
3199
3200 /* for any branch, call, exit record the history of jmps in the given state */
3201 static int push_jmp_history(struct bpf_verifier_env *env,
3202                             struct bpf_verifier_state *cur)
3203 {
3204         u32 cnt = cur->jmp_history_cnt;
3205         struct bpf_idx_pair *p;
3206         size_t alloc_size;
3207
3208         if (!is_jmp_point(env, env->insn_idx))
3209                 return 0;
3210
3211         cnt++;
3212         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3213         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3214         if (!p)
3215                 return -ENOMEM;
3216         p[cnt - 1].idx = env->insn_idx;
3217         p[cnt - 1].prev_idx = env->prev_insn_idx;
3218         cur->jmp_history = p;
3219         cur->jmp_history_cnt = cnt;
3220         return 0;
3221 }
3222
3223 /* Backtrack one insn at a time. If idx is not at the top of recorded
3224  * history then previous instruction came from straight line execution.
3225  * Return -ENOENT if we exhausted all instructions within given state.
3226  *
3227  * It's legal to have a bit of a looping with the same starting and ending
3228  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3229  * instruction index is the same as state's first_idx doesn't mean we are
3230  * done. If there is still some jump history left, we should keep going. We
3231  * need to take into account that we might have a jump history between given
3232  * state's parent and itself, due to checkpointing. In this case, we'll have
3233  * history entry recording a jump from last instruction of parent state and
3234  * first instruction of given state.
3235  */
3236 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3237                              u32 *history)
3238 {
3239         u32 cnt = *history;
3240
3241         if (i == st->first_insn_idx) {
3242                 if (cnt == 0)
3243                         return -ENOENT;
3244                 if (cnt == 1 && st->jmp_history[0].idx == i)
3245                         return -ENOENT;
3246         }
3247
3248         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3249                 i = st->jmp_history[cnt - 1].prev_idx;
3250                 (*history)--;
3251         } else {
3252                 i--;
3253         }
3254         return i;
3255 }
3256
3257 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3258 {
3259         const struct btf_type *func;
3260         struct btf *desc_btf;
3261
3262         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3263                 return NULL;
3264
3265         desc_btf = find_kfunc_desc_btf(data, insn->off);
3266         if (IS_ERR(desc_btf))
3267                 return "<error>";
3268
3269         func = btf_type_by_id(desc_btf, insn->imm);
3270         return btf_name_by_offset(desc_btf, func->name_off);
3271 }
3272
3273 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3274 {
3275         bt->frame = frame;
3276 }
3277
3278 static inline void bt_reset(struct backtrack_state *bt)
3279 {
3280         struct bpf_verifier_env *env = bt->env;
3281
3282         memset(bt, 0, sizeof(*bt));
3283         bt->env = env;
3284 }
3285
3286 static inline u32 bt_empty(struct backtrack_state *bt)
3287 {
3288         u64 mask = 0;
3289         int i;
3290
3291         for (i = 0; i <= bt->frame; i++)
3292                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3293
3294         return mask == 0;
3295 }
3296
3297 static inline int bt_subprog_enter(struct backtrack_state *bt)
3298 {
3299         if (bt->frame == MAX_CALL_FRAMES - 1) {
3300                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3301                 WARN_ONCE(1, "verifier backtracking bug");
3302                 return -EFAULT;
3303         }
3304         bt->frame++;
3305         return 0;
3306 }
3307
3308 static inline int bt_subprog_exit(struct backtrack_state *bt)
3309 {
3310         if (bt->frame == 0) {
3311                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3312                 WARN_ONCE(1, "verifier backtracking bug");
3313                 return -EFAULT;
3314         }
3315         bt->frame--;
3316         return 0;
3317 }
3318
3319 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3320 {
3321         bt->reg_masks[frame] |= 1 << reg;
3322 }
3323
3324 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3325 {
3326         bt->reg_masks[frame] &= ~(1 << reg);
3327 }
3328
3329 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3330 {
3331         bt_set_frame_reg(bt, bt->frame, reg);
3332 }
3333
3334 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3335 {
3336         bt_clear_frame_reg(bt, bt->frame, reg);
3337 }
3338
3339 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3340 {
3341         bt->stack_masks[frame] |= 1ull << slot;
3342 }
3343
3344 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3345 {
3346         bt->stack_masks[frame] &= ~(1ull << slot);
3347 }
3348
3349 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3350 {
3351         bt_set_frame_slot(bt, bt->frame, slot);
3352 }
3353
3354 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3355 {
3356         bt_clear_frame_slot(bt, bt->frame, slot);
3357 }
3358
3359 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3360 {
3361         return bt->reg_masks[frame];
3362 }
3363
3364 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3365 {
3366         return bt->reg_masks[bt->frame];
3367 }
3368
3369 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3370 {
3371         return bt->stack_masks[frame];
3372 }
3373
3374 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3375 {
3376         return bt->stack_masks[bt->frame];
3377 }
3378
3379 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3380 {
3381         return bt->reg_masks[bt->frame] & (1 << reg);
3382 }
3383
3384 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3385 {
3386         return bt->stack_masks[bt->frame] & (1ull << slot);
3387 }
3388
3389 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3390 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3391 {
3392         DECLARE_BITMAP(mask, 64);
3393         bool first = true;
3394         int i, n;
3395
3396         buf[0] = '\0';
3397
3398         bitmap_from_u64(mask, reg_mask);
3399         for_each_set_bit(i, mask, 32) {
3400                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3401                 first = false;
3402                 buf += n;
3403                 buf_sz -= n;
3404                 if (buf_sz < 0)
3405                         break;
3406         }
3407 }
3408 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3409 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3410 {
3411         DECLARE_BITMAP(mask, 64);
3412         bool first = true;
3413         int i, n;
3414
3415         buf[0] = '\0';
3416
3417         bitmap_from_u64(mask, stack_mask);
3418         for_each_set_bit(i, mask, 64) {
3419                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3420                 first = false;
3421                 buf += n;
3422                 buf_sz -= n;
3423                 if (buf_sz < 0)
3424                         break;
3425         }
3426 }
3427
3428 /* For given verifier state backtrack_insn() is called from the last insn to
3429  * the first insn. Its purpose is to compute a bitmask of registers and
3430  * stack slots that needs precision in the parent verifier state.
3431  *
3432  * @idx is an index of the instruction we are currently processing;
3433  * @subseq_idx is an index of the subsequent instruction that:
3434  *   - *would be* executed next, if jump history is viewed in forward order;
3435  *   - *was* processed previously during backtracking.
3436  */
3437 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3438                           struct backtrack_state *bt)
3439 {
3440         const struct bpf_insn_cbs cbs = {
3441                 .cb_call        = disasm_kfunc_name,
3442                 .cb_print       = verbose,
3443                 .private_data   = env,
3444         };
3445         struct bpf_insn *insn = env->prog->insnsi + idx;
3446         u8 class = BPF_CLASS(insn->code);
3447         u8 opcode = BPF_OP(insn->code);
3448         u8 mode = BPF_MODE(insn->code);
3449         u32 dreg = insn->dst_reg;
3450         u32 sreg = insn->src_reg;
3451         u32 spi, i;
3452
3453         if (insn->code == 0)
3454                 return 0;
3455         if (env->log.level & BPF_LOG_LEVEL2) {
3456                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3457                 verbose(env, "mark_precise: frame%d: regs=%s ",
3458                         bt->frame, env->tmp_str_buf);
3459                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3460                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3461                 verbose(env, "%d: ", idx);
3462                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3463         }
3464
3465         if (class == BPF_ALU || class == BPF_ALU64) {
3466                 if (!bt_is_reg_set(bt, dreg))
3467                         return 0;
3468                 if (opcode == BPF_END || opcode == BPF_NEG) {
3469                         /* sreg is reserved and unused
3470                          * dreg still need precision before this insn
3471                          */
3472                         return 0;
3473                 } else if (opcode == BPF_MOV) {
3474                         if (BPF_SRC(insn->code) == BPF_X) {
3475                                 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3476                                  * dreg needs precision after this insn
3477                                  * sreg needs precision before this insn
3478                                  */
3479                                 bt_clear_reg(bt, dreg);
3480                                 bt_set_reg(bt, sreg);
3481                         } else {
3482                                 /* dreg = K
3483                                  * dreg needs precision after this insn.
3484                                  * Corresponding register is already marked
3485                                  * as precise=true in this verifier state.
3486                                  * No further markings in parent are necessary
3487                                  */
3488                                 bt_clear_reg(bt, dreg);
3489                         }
3490                 } else {
3491                         if (BPF_SRC(insn->code) == BPF_X) {
3492                                 /* dreg += sreg
3493                                  * both dreg and sreg need precision
3494                                  * before this insn
3495                                  */
3496                                 bt_set_reg(bt, sreg);
3497                         } /* else dreg += K
3498                            * dreg still needs precision before this insn
3499                            */
3500                 }
3501         } else if (class == BPF_LDX) {
3502                 if (!bt_is_reg_set(bt, dreg))
3503                         return 0;
3504                 bt_clear_reg(bt, dreg);
3505
3506                 /* scalars can only be spilled into stack w/o losing precision.
3507                  * Load from any other memory can be zero extended.
3508                  * The desire to keep that precision is already indicated
3509                  * by 'precise' mark in corresponding register of this state.
3510                  * No further tracking necessary.
3511                  */
3512                 if (insn->src_reg != BPF_REG_FP)
3513                         return 0;
3514
3515                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3516                  * that [fp - off] slot contains scalar that needs to be
3517                  * tracked with precision
3518                  */
3519                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3520                 if (spi >= 64) {
3521                         verbose(env, "BUG spi %d\n", spi);
3522                         WARN_ONCE(1, "verifier backtracking bug");
3523                         return -EFAULT;
3524                 }
3525                 bt_set_slot(bt, spi);
3526         } else if (class == BPF_STX || class == BPF_ST) {
3527                 if (bt_is_reg_set(bt, dreg))
3528                         /* stx & st shouldn't be using _scalar_ dst_reg
3529                          * to access memory. It means backtracking
3530                          * encountered a case of pointer subtraction.
3531                          */
3532                         return -ENOTSUPP;
3533                 /* scalars can only be spilled into stack */
3534                 if (insn->dst_reg != BPF_REG_FP)
3535                         return 0;
3536                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3537                 if (spi >= 64) {
3538                         verbose(env, "BUG spi %d\n", spi);
3539                         WARN_ONCE(1, "verifier backtracking bug");
3540                         return -EFAULT;
3541                 }
3542                 if (!bt_is_slot_set(bt, spi))
3543                         return 0;
3544                 bt_clear_slot(bt, spi);
3545                 if (class == BPF_STX)
3546                         bt_set_reg(bt, sreg);
3547         } else if (class == BPF_JMP || class == BPF_JMP32) {
3548                 if (bpf_pseudo_call(insn)) {
3549                         int subprog_insn_idx, subprog;
3550
3551                         subprog_insn_idx = idx + insn->imm + 1;
3552                         subprog = find_subprog(env, subprog_insn_idx);
3553                         if (subprog < 0)
3554                                 return -EFAULT;
3555
3556                         if (subprog_is_global(env, subprog)) {
3557                                 /* check that jump history doesn't have any
3558                                  * extra instructions from subprog; the next
3559                                  * instruction after call to global subprog
3560                                  * should be literally next instruction in
3561                                  * caller program
3562                                  */
3563                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3564                                 /* r1-r5 are invalidated after subprog call,
3565                                  * so for global func call it shouldn't be set
3566                                  * anymore
3567                                  */
3568                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3569                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3570                                         WARN_ONCE(1, "verifier backtracking bug");
3571                                         return -EFAULT;
3572                                 }
3573                                 /* global subprog always sets R0 */
3574                                 bt_clear_reg(bt, BPF_REG_0);
3575                                 return 0;
3576                         } else {
3577                                 /* static subprog call instruction, which
3578                                  * means that we are exiting current subprog,
3579                                  * so only r1-r5 could be still requested as
3580                                  * precise, r0 and r6-r10 or any stack slot in
3581                                  * the current frame should be zero by now
3582                                  */
3583                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3584                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3585                                         WARN_ONCE(1, "verifier backtracking bug");
3586                                         return -EFAULT;
3587                                 }
3588                                 /* we don't track register spills perfectly,
3589                                  * so fallback to force-precise instead of failing */
3590                                 if (bt_stack_mask(bt) != 0)
3591                                         return -ENOTSUPP;
3592                                 /* propagate r1-r5 to the caller */
3593                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3594                                         if (bt_is_reg_set(bt, i)) {
3595                                                 bt_clear_reg(bt, i);
3596                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3597                                         }
3598                                 }
3599                                 if (bt_subprog_exit(bt))
3600                                         return -EFAULT;
3601                                 return 0;
3602                         }
3603                 } else if ((bpf_helper_call(insn) &&
3604                             is_callback_calling_function(insn->imm) &&
3605                             !is_async_callback_calling_function(insn->imm)) ||
3606                            (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3607                         /* callback-calling helper or kfunc call, which means
3608                          * we are exiting from subprog, but unlike the subprog
3609                          * call handling above, we shouldn't propagate
3610                          * precision of r1-r5 (if any requested), as they are
3611                          * not actually arguments passed directly to callback
3612                          * subprogs
3613                          */
3614                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3615                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3616                                 WARN_ONCE(1, "verifier backtracking bug");
3617                                 return -EFAULT;
3618                         }
3619                         if (bt_stack_mask(bt) != 0)
3620                                 return -ENOTSUPP;
3621                         /* clear r1-r5 in callback subprog's mask */
3622                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3623                                 bt_clear_reg(bt, i);
3624                         if (bt_subprog_exit(bt))
3625                                 return -EFAULT;
3626                         return 0;
3627                 } else if (opcode == BPF_CALL) {
3628                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3629                          * catch this error later. Make backtracking conservative
3630                          * with ENOTSUPP.
3631                          */
3632                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3633                                 return -ENOTSUPP;
3634                         /* regular helper call sets R0 */
3635                         bt_clear_reg(bt, BPF_REG_0);
3636                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3637                                 /* if backtracing was looking for registers R1-R5
3638                                  * they should have been found already.
3639                                  */
3640                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3641                                 WARN_ONCE(1, "verifier backtracking bug");
3642                                 return -EFAULT;
3643                         }
3644                 } else if (opcode == BPF_EXIT) {
3645                         bool r0_precise;
3646
3647                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3648                                 /* if backtracing was looking for registers R1-R5
3649                                  * they should have been found already.
3650                                  */
3651                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3652                                 WARN_ONCE(1, "verifier backtracking bug");
3653                                 return -EFAULT;
3654                         }
3655
3656                         /* BPF_EXIT in subprog or callback always returns
3657                          * right after the call instruction, so by checking
3658                          * whether the instruction at subseq_idx-1 is subprog
3659                          * call or not we can distinguish actual exit from
3660                          * *subprog* from exit from *callback*. In the former
3661                          * case, we need to propagate r0 precision, if
3662                          * necessary. In the former we never do that.
3663                          */
3664                         r0_precise = subseq_idx - 1 >= 0 &&
3665                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3666                                      bt_is_reg_set(bt, BPF_REG_0);
3667
3668                         bt_clear_reg(bt, BPF_REG_0);
3669                         if (bt_subprog_enter(bt))
3670                                 return -EFAULT;
3671
3672                         if (r0_precise)
3673                                 bt_set_reg(bt, BPF_REG_0);
3674                         /* r6-r9 and stack slots will stay set in caller frame
3675                          * bitmasks until we return back from callee(s)
3676                          */
3677                         return 0;
3678                 } else if (BPF_SRC(insn->code) == BPF_X) {
3679                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3680                                 return 0;
3681                         /* dreg <cond> sreg
3682                          * Both dreg and sreg need precision before
3683                          * this insn. If only sreg was marked precise
3684                          * before it would be equally necessary to
3685                          * propagate it to dreg.
3686                          */
3687                         bt_set_reg(bt, dreg);
3688                         bt_set_reg(bt, sreg);
3689                          /* else dreg <cond> K
3690                           * Only dreg still needs precision before
3691                           * this insn, so for the K-based conditional
3692                           * there is nothing new to be marked.
3693                           */
3694                 }
3695         } else if (class == BPF_LD) {
3696                 if (!bt_is_reg_set(bt, dreg))
3697                         return 0;
3698                 bt_clear_reg(bt, dreg);
3699                 /* It's ld_imm64 or ld_abs or ld_ind.
3700                  * For ld_imm64 no further tracking of precision
3701                  * into parent is necessary
3702                  */
3703                 if (mode == BPF_IND || mode == BPF_ABS)
3704                         /* to be analyzed */
3705                         return -ENOTSUPP;
3706         }
3707         return 0;
3708 }
3709
3710 /* the scalar precision tracking algorithm:
3711  * . at the start all registers have precise=false.
3712  * . scalar ranges are tracked as normal through alu and jmp insns.
3713  * . once precise value of the scalar register is used in:
3714  *   .  ptr + scalar alu
3715  *   . if (scalar cond K|scalar)
3716  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3717  *   backtrack through the verifier states and mark all registers and
3718  *   stack slots with spilled constants that these scalar regisers
3719  *   should be precise.
3720  * . during state pruning two registers (or spilled stack slots)
3721  *   are equivalent if both are not precise.
3722  *
3723  * Note the verifier cannot simply walk register parentage chain,
3724  * since many different registers and stack slots could have been
3725  * used to compute single precise scalar.
3726  *
3727  * The approach of starting with precise=true for all registers and then
3728  * backtrack to mark a register as not precise when the verifier detects
3729  * that program doesn't care about specific value (e.g., when helper
3730  * takes register as ARG_ANYTHING parameter) is not safe.
3731  *
3732  * It's ok to walk single parentage chain of the verifier states.
3733  * It's possible that this backtracking will go all the way till 1st insn.
3734  * All other branches will be explored for needing precision later.
3735  *
3736  * The backtracking needs to deal with cases like:
3737  *   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)
3738  * r9 -= r8
3739  * r5 = r9
3740  * if r5 > 0x79f goto pc+7
3741  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3742  * r5 += 1
3743  * ...
3744  * call bpf_perf_event_output#25
3745  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3746  *
3747  * and this case:
3748  * r6 = 1
3749  * call foo // uses callee's r6 inside to compute r0
3750  * r0 += r6
3751  * if r0 == 0 goto
3752  *
3753  * to track above reg_mask/stack_mask needs to be independent for each frame.
3754  *
3755  * Also if parent's curframe > frame where backtracking started,
3756  * the verifier need to mark registers in both frames, otherwise callees
3757  * may incorrectly prune callers. This is similar to
3758  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3759  *
3760  * For now backtracking falls back into conservative marking.
3761  */
3762 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3763                                      struct bpf_verifier_state *st)
3764 {
3765         struct bpf_func_state *func;
3766         struct bpf_reg_state *reg;
3767         int i, j;
3768
3769         if (env->log.level & BPF_LOG_LEVEL2) {
3770                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3771                         st->curframe);
3772         }
3773
3774         /* big hammer: mark all scalars precise in this path.
3775          * pop_stack may still get !precise scalars.
3776          * We also skip current state and go straight to first parent state,
3777          * because precision markings in current non-checkpointed state are
3778          * not needed. See why in the comment in __mark_chain_precision below.
3779          */
3780         for (st = st->parent; st; st = st->parent) {
3781                 for (i = 0; i <= st->curframe; i++) {
3782                         func = st->frame[i];
3783                         for (j = 0; j < BPF_REG_FP; j++) {
3784                                 reg = &func->regs[j];
3785                                 if (reg->type != SCALAR_VALUE || reg->precise)
3786                                         continue;
3787                                 reg->precise = true;
3788                                 if (env->log.level & BPF_LOG_LEVEL2) {
3789                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3790                                                 i, j);
3791                                 }
3792                         }
3793                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3794                                 if (!is_spilled_reg(&func->stack[j]))
3795                                         continue;
3796                                 reg = &func->stack[j].spilled_ptr;
3797                                 if (reg->type != SCALAR_VALUE || reg->precise)
3798                                         continue;
3799                                 reg->precise = true;
3800                                 if (env->log.level & BPF_LOG_LEVEL2) {
3801                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3802                                                 i, -(j + 1) * 8);
3803                                 }
3804                         }
3805                 }
3806         }
3807 }
3808
3809 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3810 {
3811         struct bpf_func_state *func;
3812         struct bpf_reg_state *reg;
3813         int i, j;
3814
3815         for (i = 0; i <= st->curframe; i++) {
3816                 func = st->frame[i];
3817                 for (j = 0; j < BPF_REG_FP; j++) {
3818                         reg = &func->regs[j];
3819                         if (reg->type != SCALAR_VALUE)
3820                                 continue;
3821                         reg->precise = false;
3822                 }
3823                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3824                         if (!is_spilled_reg(&func->stack[j]))
3825                                 continue;
3826                         reg = &func->stack[j].spilled_ptr;
3827                         if (reg->type != SCALAR_VALUE)
3828                                 continue;
3829                         reg->precise = false;
3830                 }
3831         }
3832 }
3833
3834 static bool idset_contains(struct bpf_idset *s, u32 id)
3835 {
3836         u32 i;
3837
3838         for (i = 0; i < s->count; ++i)
3839                 if (s->ids[i] == id)
3840                         return true;
3841
3842         return false;
3843 }
3844
3845 static int idset_push(struct bpf_idset *s, u32 id)
3846 {
3847         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3848                 return -EFAULT;
3849         s->ids[s->count++] = id;
3850         return 0;
3851 }
3852
3853 static void idset_reset(struct bpf_idset *s)
3854 {
3855         s->count = 0;
3856 }
3857
3858 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3859  * Mark all registers with these IDs as precise.
3860  */
3861 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3862 {
3863         struct bpf_idset *precise_ids = &env->idset_scratch;
3864         struct backtrack_state *bt = &env->bt;
3865         struct bpf_func_state *func;
3866         struct bpf_reg_state *reg;
3867         DECLARE_BITMAP(mask, 64);
3868         int i, fr;
3869
3870         idset_reset(precise_ids);
3871
3872         for (fr = bt->frame; fr >= 0; fr--) {
3873                 func = st->frame[fr];
3874
3875                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3876                 for_each_set_bit(i, mask, 32) {
3877                         reg = &func->regs[i];
3878                         if (!reg->id || reg->type != SCALAR_VALUE)
3879                                 continue;
3880                         if (idset_push(precise_ids, reg->id))
3881                                 return -EFAULT;
3882                 }
3883
3884                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3885                 for_each_set_bit(i, mask, 64) {
3886                         if (i >= func->allocated_stack / BPF_REG_SIZE)
3887                                 break;
3888                         if (!is_spilled_scalar_reg(&func->stack[i]))
3889                                 continue;
3890                         reg = &func->stack[i].spilled_ptr;
3891                         if (!reg->id)
3892                                 continue;
3893                         if (idset_push(precise_ids, reg->id))
3894                                 return -EFAULT;
3895                 }
3896         }
3897
3898         for (fr = 0; fr <= st->curframe; ++fr) {
3899                 func = st->frame[fr];
3900
3901                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3902                         reg = &func->regs[i];
3903                         if (!reg->id)
3904                                 continue;
3905                         if (!idset_contains(precise_ids, reg->id))
3906                                 continue;
3907                         bt_set_frame_reg(bt, fr, i);
3908                 }
3909                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3910                         if (!is_spilled_scalar_reg(&func->stack[i]))
3911                                 continue;
3912                         reg = &func->stack[i].spilled_ptr;
3913                         if (!reg->id)
3914                                 continue;
3915                         if (!idset_contains(precise_ids, reg->id))
3916                                 continue;
3917                         bt_set_frame_slot(bt, fr, i);
3918                 }
3919         }
3920
3921         return 0;
3922 }
3923
3924 /*
3925  * __mark_chain_precision() backtracks BPF program instruction sequence and
3926  * chain of verifier states making sure that register *regno* (if regno >= 0)
3927  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3928  * SCALARS, as well as any other registers and slots that contribute to
3929  * a tracked state of given registers/stack slots, depending on specific BPF
3930  * assembly instructions (see backtrack_insns() for exact instruction handling
3931  * logic). This backtracking relies on recorded jmp_history and is able to
3932  * traverse entire chain of parent states. This process ends only when all the
3933  * necessary registers/slots and their transitive dependencies are marked as
3934  * precise.
3935  *
3936  * One important and subtle aspect is that precise marks *do not matter* in
3937  * the currently verified state (current state). It is important to understand
3938  * why this is the case.
3939  *
3940  * First, note that current state is the state that is not yet "checkpointed",
3941  * i.e., it is not yet put into env->explored_states, and it has no children
3942  * states as well. It's ephemeral, and can end up either a) being discarded if
3943  * compatible explored state is found at some point or BPF_EXIT instruction is
3944  * reached or b) checkpointed and put into env->explored_states, branching out
3945  * into one or more children states.
3946  *
3947  * In the former case, precise markings in current state are completely
3948  * ignored by state comparison code (see regsafe() for details). Only
3949  * checkpointed ("old") state precise markings are important, and if old
3950  * state's register/slot is precise, regsafe() assumes current state's
3951  * register/slot as precise and checks value ranges exactly and precisely. If
3952  * states turn out to be compatible, current state's necessary precise
3953  * markings and any required parent states' precise markings are enforced
3954  * after the fact with propagate_precision() logic, after the fact. But it's
3955  * important to realize that in this case, even after marking current state
3956  * registers/slots as precise, we immediately discard current state. So what
3957  * actually matters is any of the precise markings propagated into current
3958  * state's parent states, which are always checkpointed (due to b) case above).
3959  * As such, for scenario a) it doesn't matter if current state has precise
3960  * markings set or not.
3961  *
3962  * Now, for the scenario b), checkpointing and forking into child(ren)
3963  * state(s). Note that before current state gets to checkpointing step, any
3964  * processed instruction always assumes precise SCALAR register/slot
3965  * knowledge: if precise value or range is useful to prune jump branch, BPF
3966  * verifier takes this opportunity enthusiastically. Similarly, when
3967  * register's value is used to calculate offset or memory address, exact
3968  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3969  * what we mentioned above about state comparison ignoring precise markings
3970  * during state comparison, BPF verifier ignores and also assumes precise
3971  * markings *at will* during instruction verification process. But as verifier
3972  * assumes precision, it also propagates any precision dependencies across
3973  * parent states, which are not yet finalized, so can be further restricted
3974  * based on new knowledge gained from restrictions enforced by their children
3975  * states. This is so that once those parent states are finalized, i.e., when
3976  * they have no more active children state, state comparison logic in
3977  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3978  * required for correctness.
3979  *
3980  * To build a bit more intuition, note also that once a state is checkpointed,
3981  * the path we took to get to that state is not important. This is crucial
3982  * property for state pruning. When state is checkpointed and finalized at
3983  * some instruction index, it can be correctly and safely used to "short
3984  * circuit" any *compatible* state that reaches exactly the same instruction
3985  * index. I.e., if we jumped to that instruction from a completely different
3986  * code path than original finalized state was derived from, it doesn't
3987  * matter, current state can be discarded because from that instruction
3988  * forward having a compatible state will ensure we will safely reach the
3989  * exit. States describe preconditions for further exploration, but completely
3990  * forget the history of how we got here.
3991  *
3992  * This also means that even if we needed precise SCALAR range to get to
3993  * finalized state, but from that point forward *that same* SCALAR register is
3994  * never used in a precise context (i.e., it's precise value is not needed for
3995  * correctness), it's correct and safe to mark such register as "imprecise"
3996  * (i.e., precise marking set to false). This is what we rely on when we do
3997  * not set precise marking in current state. If no child state requires
3998  * precision for any given SCALAR register, it's safe to dictate that it can
3999  * be imprecise. If any child state does require this register to be precise,
4000  * we'll mark it precise later retroactively during precise markings
4001  * propagation from child state to parent states.
4002  *
4003  * Skipping precise marking setting in current state is a mild version of
4004  * relying on the above observation. But we can utilize this property even
4005  * more aggressively by proactively forgetting any precise marking in the
4006  * current state (which we inherited from the parent state), right before we
4007  * checkpoint it and branch off into new child state. This is done by
4008  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4009  * finalized states which help in short circuiting more future states.
4010  */
4011 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4012 {
4013         struct backtrack_state *bt = &env->bt;
4014         struct bpf_verifier_state *st = env->cur_state;
4015         int first_idx = st->first_insn_idx;
4016         int last_idx = env->insn_idx;
4017         int subseq_idx = -1;
4018         struct bpf_func_state *func;
4019         struct bpf_reg_state *reg;
4020         bool skip_first = true;
4021         int i, fr, err;
4022
4023         if (!env->bpf_capable)
4024                 return 0;
4025
4026         /* set frame number from which we are starting to backtrack */
4027         bt_init(bt, env->cur_state->curframe);
4028
4029         /* Do sanity checks against current state of register and/or stack
4030          * slot, but don't set precise flag in current state, as precision
4031          * tracking in the current state is unnecessary.
4032          */
4033         func = st->frame[bt->frame];
4034         if (regno >= 0) {
4035                 reg = &func->regs[regno];
4036                 if (reg->type != SCALAR_VALUE) {
4037                         WARN_ONCE(1, "backtracing misuse");
4038                         return -EFAULT;
4039                 }
4040                 bt_set_reg(bt, regno);
4041         }
4042
4043         if (bt_empty(bt))
4044                 return 0;
4045
4046         for (;;) {
4047                 DECLARE_BITMAP(mask, 64);
4048                 u32 history = st->jmp_history_cnt;
4049
4050                 if (env->log.level & BPF_LOG_LEVEL2) {
4051                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4052                                 bt->frame, last_idx, first_idx, subseq_idx);
4053                 }
4054
4055                 /* If some register with scalar ID is marked as precise,
4056                  * make sure that all registers sharing this ID are also precise.
4057                  * This is needed to estimate effect of find_equal_scalars().
4058                  * Do this at the last instruction of each state,
4059                  * bpf_reg_state::id fields are valid for these instructions.
4060                  *
4061                  * Allows to track precision in situation like below:
4062                  *
4063                  *     r2 = unknown value
4064                  *     ...
4065                  *   --- state #0 ---
4066                  *     ...
4067                  *     r1 = r2                 // r1 and r2 now share the same ID
4068                  *     ...
4069                  *   --- state #1 {r1.id = A, r2.id = A} ---
4070                  *     ...
4071                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4072                  *     ...
4073                  *   --- state #2 {r1.id = A, r2.id = A} ---
4074                  *     r3 = r10
4075                  *     r3 += r1                // need to mark both r1 and r2
4076                  */
4077                 if (mark_precise_scalar_ids(env, st))
4078                         return -EFAULT;
4079
4080                 if (last_idx < 0) {
4081                         /* we are at the entry into subprog, which
4082                          * is expected for global funcs, but only if
4083                          * requested precise registers are R1-R5
4084                          * (which are global func's input arguments)
4085                          */
4086                         if (st->curframe == 0 &&
4087                             st->frame[0]->subprogno > 0 &&
4088                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4089                             bt_stack_mask(bt) == 0 &&
4090                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4091                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4092                                 for_each_set_bit(i, mask, 32) {
4093                                         reg = &st->frame[0]->regs[i];
4094                                         bt_clear_reg(bt, i);
4095                                         if (reg->type == SCALAR_VALUE)
4096                                                 reg->precise = true;
4097                                 }
4098                                 return 0;
4099                         }
4100
4101                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4102                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4103                         WARN_ONCE(1, "verifier backtracking bug");
4104                         return -EFAULT;
4105                 }
4106
4107                 for (i = last_idx;;) {
4108                         if (skip_first) {
4109                                 err = 0;
4110                                 skip_first = false;
4111                         } else {
4112                                 err = backtrack_insn(env, i, subseq_idx, bt);
4113                         }
4114                         if (err == -ENOTSUPP) {
4115                                 mark_all_scalars_precise(env, env->cur_state);
4116                                 bt_reset(bt);
4117                                 return 0;
4118                         } else if (err) {
4119                                 return err;
4120                         }
4121                         if (bt_empty(bt))
4122                                 /* Found assignment(s) into tracked register in this state.
4123                                  * Since this state is already marked, just return.
4124                                  * Nothing to be tracked further in the parent state.
4125                                  */
4126                                 return 0;
4127                         subseq_idx = i;
4128                         i = get_prev_insn_idx(st, i, &history);
4129                         if (i == -ENOENT)
4130                                 break;
4131                         if (i >= env->prog->len) {
4132                                 /* This can happen if backtracking reached insn 0
4133                                  * and there are still reg_mask or stack_mask
4134                                  * to backtrack.
4135                                  * It means the backtracking missed the spot where
4136                                  * particular register was initialized with a constant.
4137                                  */
4138                                 verbose(env, "BUG backtracking idx %d\n", i);
4139                                 WARN_ONCE(1, "verifier backtracking bug");
4140                                 return -EFAULT;
4141                         }
4142                 }
4143                 st = st->parent;
4144                 if (!st)
4145                         break;
4146
4147                 for (fr = bt->frame; fr >= 0; fr--) {
4148                         func = st->frame[fr];
4149                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4150                         for_each_set_bit(i, mask, 32) {
4151                                 reg = &func->regs[i];
4152                                 if (reg->type != SCALAR_VALUE) {
4153                                         bt_clear_frame_reg(bt, fr, i);
4154                                         continue;
4155                                 }
4156                                 if (reg->precise)
4157                                         bt_clear_frame_reg(bt, fr, i);
4158                                 else
4159                                         reg->precise = true;
4160                         }
4161
4162                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4163                         for_each_set_bit(i, mask, 64) {
4164                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4165                                         /* the sequence of instructions:
4166                                          * 2: (bf) r3 = r10
4167                                          * 3: (7b) *(u64 *)(r3 -8) = r0
4168                                          * 4: (79) r4 = *(u64 *)(r10 -8)
4169                                          * doesn't contain jmps. It's backtracked
4170                                          * as a single block.
4171                                          * During backtracking insn 3 is not recognized as
4172                                          * stack access, so at the end of backtracking
4173                                          * stack slot fp-8 is still marked in stack_mask.
4174                                          * However the parent state may not have accessed
4175                                          * fp-8 and it's "unallocated" stack space.
4176                                          * In such case fallback to conservative.
4177                                          */
4178                                         mark_all_scalars_precise(env, env->cur_state);
4179                                         bt_reset(bt);
4180                                         return 0;
4181                                 }
4182
4183                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4184                                         bt_clear_frame_slot(bt, fr, i);
4185                                         continue;
4186                                 }
4187                                 reg = &func->stack[i].spilled_ptr;
4188                                 if (reg->precise)
4189                                         bt_clear_frame_slot(bt, fr, i);
4190                                 else
4191                                         reg->precise = true;
4192                         }
4193                         if (env->log.level & BPF_LOG_LEVEL2) {
4194                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4195                                              bt_frame_reg_mask(bt, fr));
4196                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4197                                         fr, env->tmp_str_buf);
4198                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4199                                                bt_frame_stack_mask(bt, fr));
4200                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4201                                 print_verifier_state(env, func, true);
4202                         }
4203                 }
4204
4205                 if (bt_empty(bt))
4206                         return 0;
4207
4208                 subseq_idx = first_idx;
4209                 last_idx = st->last_insn_idx;
4210                 first_idx = st->first_insn_idx;
4211         }
4212
4213         /* if we still have requested precise regs or slots, we missed
4214          * something (e.g., stack access through non-r10 register), so
4215          * fallback to marking all precise
4216          */
4217         if (!bt_empty(bt)) {
4218                 mark_all_scalars_precise(env, env->cur_state);
4219                 bt_reset(bt);
4220         }
4221
4222         return 0;
4223 }
4224
4225 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4226 {
4227         return __mark_chain_precision(env, regno);
4228 }
4229
4230 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4231  * desired reg and stack masks across all relevant frames
4232  */
4233 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4234 {
4235         return __mark_chain_precision(env, -1);
4236 }
4237
4238 static bool is_spillable_regtype(enum bpf_reg_type type)
4239 {
4240         switch (base_type(type)) {
4241         case PTR_TO_MAP_VALUE:
4242         case PTR_TO_STACK:
4243         case PTR_TO_CTX:
4244         case PTR_TO_PACKET:
4245         case PTR_TO_PACKET_META:
4246         case PTR_TO_PACKET_END:
4247         case PTR_TO_FLOW_KEYS:
4248         case CONST_PTR_TO_MAP:
4249         case PTR_TO_SOCKET:
4250         case PTR_TO_SOCK_COMMON:
4251         case PTR_TO_TCP_SOCK:
4252         case PTR_TO_XDP_SOCK:
4253         case PTR_TO_BTF_ID:
4254         case PTR_TO_BUF:
4255         case PTR_TO_MEM:
4256         case PTR_TO_FUNC:
4257         case PTR_TO_MAP_KEY:
4258                 return true;
4259         default:
4260                 return false;
4261         }
4262 }
4263
4264 /* Does this register contain a constant zero? */
4265 static bool register_is_null(struct bpf_reg_state *reg)
4266 {
4267         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4268 }
4269
4270 static bool register_is_const(struct bpf_reg_state *reg)
4271 {
4272         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4273 }
4274
4275 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4276 {
4277         return tnum_is_unknown(reg->var_off) &&
4278                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4279                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4280                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4281                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4282 }
4283
4284 static bool register_is_bounded(struct bpf_reg_state *reg)
4285 {
4286         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4287 }
4288
4289 static bool __is_pointer_value(bool allow_ptr_leaks,
4290                                const struct bpf_reg_state *reg)
4291 {
4292         if (allow_ptr_leaks)
4293                 return false;
4294
4295         return reg->type != SCALAR_VALUE;
4296 }
4297
4298 /* Copy src state preserving dst->parent and dst->live fields */
4299 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4300 {
4301         struct bpf_reg_state *parent = dst->parent;
4302         enum bpf_reg_liveness live = dst->live;
4303
4304         *dst = *src;
4305         dst->parent = parent;
4306         dst->live = live;
4307 }
4308
4309 static void save_register_state(struct bpf_func_state *state,
4310                                 int spi, struct bpf_reg_state *reg,
4311                                 int size)
4312 {
4313         int i;
4314
4315         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4316         if (size == BPF_REG_SIZE)
4317                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4318
4319         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4320                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4321
4322         /* size < 8 bytes spill */
4323         for (; i; i--)
4324                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4325 }
4326
4327 static bool is_bpf_st_mem(struct bpf_insn *insn)
4328 {
4329         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4330 }
4331
4332 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4333  * stack boundary and alignment are checked in check_mem_access()
4334  */
4335 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4336                                        /* stack frame we're writing to */
4337                                        struct bpf_func_state *state,
4338                                        int off, int size, int value_regno,
4339                                        int insn_idx)
4340 {
4341         struct bpf_func_state *cur; /* state of the current function */
4342         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4343         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4344         struct bpf_reg_state *reg = NULL;
4345         u32 dst_reg = insn->dst_reg;
4346
4347         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4348          * so it's aligned access and [off, off + size) are within stack limits
4349          */
4350         if (!env->allow_ptr_leaks &&
4351             is_spilled_reg(&state->stack[spi]) &&
4352             size != BPF_REG_SIZE) {
4353                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4354                 return -EACCES;
4355         }
4356
4357         cur = env->cur_state->frame[env->cur_state->curframe];
4358         if (value_regno >= 0)
4359                 reg = &cur->regs[value_regno];
4360         if (!env->bypass_spec_v4) {
4361                 bool sanitize = reg && is_spillable_regtype(reg->type);
4362
4363                 for (i = 0; i < size; i++) {
4364                         u8 type = state->stack[spi].slot_type[i];
4365
4366                         if (type != STACK_MISC && type != STACK_ZERO) {
4367                                 sanitize = true;
4368                                 break;
4369                         }
4370                 }
4371
4372                 if (sanitize)
4373                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4374         }
4375
4376         err = destroy_if_dynptr_stack_slot(env, state, spi);
4377         if (err)
4378                 return err;
4379
4380         mark_stack_slot_scratched(env, spi);
4381         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4382             !register_is_null(reg) && env->bpf_capable) {
4383                 if (dst_reg != BPF_REG_FP) {
4384                         /* The backtracking logic can only recognize explicit
4385                          * stack slot address like [fp - 8]. Other spill of
4386                          * scalar via different register has to be conservative.
4387                          * Backtrack from here and mark all registers as precise
4388                          * that contributed into 'reg' being a constant.
4389                          */
4390                         err = mark_chain_precision(env, value_regno);
4391                         if (err)
4392                                 return err;
4393                 }
4394                 save_register_state(state, spi, reg, size);
4395                 /* Break the relation on a narrowing spill. */
4396                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4397                         state->stack[spi].spilled_ptr.id = 0;
4398         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4399                    insn->imm != 0 && env->bpf_capable) {
4400                 struct bpf_reg_state fake_reg = {};
4401
4402                 __mark_reg_known(&fake_reg, insn->imm);
4403                 fake_reg.type = SCALAR_VALUE;
4404                 save_register_state(state, spi, &fake_reg, size);
4405         } else if (reg && is_spillable_regtype(reg->type)) {
4406                 /* register containing pointer is being spilled into stack */
4407                 if (size != BPF_REG_SIZE) {
4408                         verbose_linfo(env, insn_idx, "; ");
4409                         verbose(env, "invalid size of register spill\n");
4410                         return -EACCES;
4411                 }
4412                 if (state != cur && reg->type == PTR_TO_STACK) {
4413                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4414                         return -EINVAL;
4415                 }
4416                 save_register_state(state, spi, reg, size);
4417         } else {
4418                 u8 type = STACK_MISC;
4419
4420                 /* regular write of data into stack destroys any spilled ptr */
4421                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4422                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4423                 if (is_stack_slot_special(&state->stack[spi]))
4424                         for (i = 0; i < BPF_REG_SIZE; i++)
4425                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4426
4427                 /* only mark the slot as written if all 8 bytes were written
4428                  * otherwise read propagation may incorrectly stop too soon
4429                  * when stack slots are partially written.
4430                  * This heuristic means that read propagation will be
4431                  * conservative, since it will add reg_live_read marks
4432                  * to stack slots all the way to first state when programs
4433                  * writes+reads less than 8 bytes
4434                  */
4435                 if (size == BPF_REG_SIZE)
4436                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4437
4438                 /* when we zero initialize stack slots mark them as such */
4439                 if ((reg && register_is_null(reg)) ||
4440                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4441                         /* backtracking doesn't work for STACK_ZERO yet. */
4442                         err = mark_chain_precision(env, value_regno);
4443                         if (err)
4444                                 return err;
4445                         type = STACK_ZERO;
4446                 }
4447
4448                 /* Mark slots affected by this stack write. */
4449                 for (i = 0; i < size; i++)
4450                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4451                                 type;
4452         }
4453         return 0;
4454 }
4455
4456 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4457  * known to contain a variable offset.
4458  * This function checks whether the write is permitted and conservatively
4459  * tracks the effects of the write, considering that each stack slot in the
4460  * dynamic range is potentially written to.
4461  *
4462  * 'off' includes 'regno->off'.
4463  * 'value_regno' can be -1, meaning that an unknown value is being written to
4464  * the stack.
4465  *
4466  * Spilled pointers in range are not marked as written because we don't know
4467  * what's going to be actually written. This means that read propagation for
4468  * future reads cannot be terminated by this write.
4469  *
4470  * For privileged programs, uninitialized stack slots are considered
4471  * initialized by this write (even though we don't know exactly what offsets
4472  * are going to be written to). The idea is that we don't want the verifier to
4473  * reject future reads that access slots written to through variable offsets.
4474  */
4475 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4476                                      /* func where register points to */
4477                                      struct bpf_func_state *state,
4478                                      int ptr_regno, int off, int size,
4479                                      int value_regno, int insn_idx)
4480 {
4481         struct bpf_func_state *cur; /* state of the current function */
4482         int min_off, max_off;
4483         int i, err;
4484         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4485         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4486         bool writing_zero = false;
4487         /* set if the fact that we're writing a zero is used to let any
4488          * stack slots remain STACK_ZERO
4489          */
4490         bool zero_used = false;
4491
4492         cur = env->cur_state->frame[env->cur_state->curframe];
4493         ptr_reg = &cur->regs[ptr_regno];
4494         min_off = ptr_reg->smin_value + off;
4495         max_off = ptr_reg->smax_value + off + size;
4496         if (value_regno >= 0)
4497                 value_reg = &cur->regs[value_regno];
4498         if ((value_reg && register_is_null(value_reg)) ||
4499             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4500                 writing_zero = true;
4501
4502         for (i = min_off; i < max_off; i++) {
4503                 int spi;
4504
4505                 spi = __get_spi(i);
4506                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4507                 if (err)
4508                         return err;
4509         }
4510
4511         /* Variable offset writes destroy any spilled pointers in range. */
4512         for (i = min_off; i < max_off; i++) {
4513                 u8 new_type, *stype;
4514                 int slot, spi;
4515
4516                 slot = -i - 1;
4517                 spi = slot / BPF_REG_SIZE;
4518                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4519                 mark_stack_slot_scratched(env, spi);
4520
4521                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4522                         /* Reject the write if range we may write to has not
4523                          * been initialized beforehand. If we didn't reject
4524                          * here, the ptr status would be erased below (even
4525                          * though not all slots are actually overwritten),
4526                          * possibly opening the door to leaks.
4527                          *
4528                          * We do however catch STACK_INVALID case below, and
4529                          * only allow reading possibly uninitialized memory
4530                          * later for CAP_PERFMON, as the write may not happen to
4531                          * that slot.
4532                          */
4533                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4534                                 insn_idx, i);
4535                         return -EINVAL;
4536                 }
4537
4538                 /* Erase all spilled pointers. */
4539                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4540
4541                 /* Update the slot type. */
4542                 new_type = STACK_MISC;
4543                 if (writing_zero && *stype == STACK_ZERO) {
4544                         new_type = STACK_ZERO;
4545                         zero_used = true;
4546                 }
4547                 /* If the slot is STACK_INVALID, we check whether it's OK to
4548                  * pretend that it will be initialized by this write. The slot
4549                  * might not actually be written to, and so if we mark it as
4550                  * initialized future reads might leak uninitialized memory.
4551                  * For privileged programs, we will accept such reads to slots
4552                  * that may or may not be written because, if we're reject
4553                  * them, the error would be too confusing.
4554                  */
4555                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4556                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4557                                         insn_idx, i);
4558                         return -EINVAL;
4559                 }
4560                 *stype = new_type;
4561         }
4562         if (zero_used) {
4563                 /* backtracking doesn't work for STACK_ZERO yet. */
4564                 err = mark_chain_precision(env, value_regno);
4565                 if (err)
4566                         return err;
4567         }
4568         return 0;
4569 }
4570
4571 /* When register 'dst_regno' is assigned some values from stack[min_off,
4572  * max_off), we set the register's type according to the types of the
4573  * respective stack slots. If all the stack values are known to be zeros, then
4574  * so is the destination reg. Otherwise, the register is considered to be
4575  * SCALAR. This function does not deal with register filling; the caller must
4576  * ensure that all spilled registers in the stack range have been marked as
4577  * read.
4578  */
4579 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4580                                 /* func where src register points to */
4581                                 struct bpf_func_state *ptr_state,
4582                                 int min_off, int max_off, int dst_regno)
4583 {
4584         struct bpf_verifier_state *vstate = env->cur_state;
4585         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4586         int i, slot, spi;
4587         u8 *stype;
4588         int zeros = 0;
4589
4590         for (i = min_off; i < max_off; i++) {
4591                 slot = -i - 1;
4592                 spi = slot / BPF_REG_SIZE;
4593                 mark_stack_slot_scratched(env, spi);
4594                 stype = ptr_state->stack[spi].slot_type;
4595                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4596                         break;
4597                 zeros++;
4598         }
4599         if (zeros == max_off - min_off) {
4600                 /* any access_size read into register is zero extended,
4601                  * so the whole register == const_zero
4602                  */
4603                 __mark_reg_const_zero(&state->regs[dst_regno]);
4604                 /* backtracking doesn't support STACK_ZERO yet,
4605                  * so mark it precise here, so that later
4606                  * backtracking can stop here.
4607                  * Backtracking may not need this if this register
4608                  * doesn't participate in pointer adjustment.
4609                  * Forward propagation of precise flag is not
4610                  * necessary either. This mark is only to stop
4611                  * backtracking. Any register that contributed
4612                  * to const 0 was marked precise before spill.
4613                  */
4614                 state->regs[dst_regno].precise = true;
4615         } else {
4616                 /* have read misc data from the stack */
4617                 mark_reg_unknown(env, state->regs, dst_regno);
4618         }
4619         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4620 }
4621
4622 /* Read the stack at 'off' and put the results into the register indicated by
4623  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4624  * spilled reg.
4625  *
4626  * 'dst_regno' can be -1, meaning that the read value is not going to a
4627  * register.
4628  *
4629  * The access is assumed to be within the current stack bounds.
4630  */
4631 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4632                                       /* func where src register points to */
4633                                       struct bpf_func_state *reg_state,
4634                                       int off, int size, int dst_regno)
4635 {
4636         struct bpf_verifier_state *vstate = env->cur_state;
4637         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4638         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4639         struct bpf_reg_state *reg;
4640         u8 *stype, type;
4641
4642         stype = reg_state->stack[spi].slot_type;
4643         reg = &reg_state->stack[spi].spilled_ptr;
4644
4645         mark_stack_slot_scratched(env, spi);
4646
4647         if (is_spilled_reg(&reg_state->stack[spi])) {
4648                 u8 spill_size = 1;
4649
4650                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4651                         spill_size++;
4652
4653                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4654                         if (reg->type != SCALAR_VALUE) {
4655                                 verbose_linfo(env, env->insn_idx, "; ");
4656                                 verbose(env, "invalid size of register fill\n");
4657                                 return -EACCES;
4658                         }
4659
4660                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4661                         if (dst_regno < 0)
4662                                 return 0;
4663
4664                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4665                                 /* The earlier check_reg_arg() has decided the
4666                                  * subreg_def for this insn.  Save it first.
4667                                  */
4668                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4669
4670                                 copy_register_state(&state->regs[dst_regno], reg);
4671                                 state->regs[dst_regno].subreg_def = subreg_def;
4672                         } else {
4673                                 for (i = 0; i < size; i++) {
4674                                         type = stype[(slot - i) % BPF_REG_SIZE];
4675                                         if (type == STACK_SPILL)
4676                                                 continue;
4677                                         if (type == STACK_MISC)
4678                                                 continue;
4679                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4680                                                 continue;
4681                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4682                                                 off, i, size);
4683                                         return -EACCES;
4684                                 }
4685                                 mark_reg_unknown(env, state->regs, dst_regno);
4686                         }
4687                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4688                         return 0;
4689                 }
4690
4691                 if (dst_regno >= 0) {
4692                         /* restore register state from stack */
4693                         copy_register_state(&state->regs[dst_regno], reg);
4694                         /* mark reg as written since spilled pointer state likely
4695                          * has its liveness marks cleared by is_state_visited()
4696                          * which resets stack/reg liveness for state transitions
4697                          */
4698                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4699                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4700                         /* If dst_regno==-1, the caller is asking us whether
4701                          * it is acceptable to use this value as a SCALAR_VALUE
4702                          * (e.g. for XADD).
4703                          * We must not allow unprivileged callers to do that
4704                          * with spilled pointers.
4705                          */
4706                         verbose(env, "leaking pointer from stack off %d\n",
4707                                 off);
4708                         return -EACCES;
4709                 }
4710                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4711         } else {
4712                 for (i = 0; i < size; i++) {
4713                         type = stype[(slot - i) % BPF_REG_SIZE];
4714                         if (type == STACK_MISC)
4715                                 continue;
4716                         if (type == STACK_ZERO)
4717                                 continue;
4718                         if (type == STACK_INVALID && env->allow_uninit_stack)
4719                                 continue;
4720                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4721                                 off, i, size);
4722                         return -EACCES;
4723                 }
4724                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4725                 if (dst_regno >= 0)
4726                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4727         }
4728         return 0;
4729 }
4730
4731 enum bpf_access_src {
4732         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4733         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4734 };
4735
4736 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4737                                          int regno, int off, int access_size,
4738                                          bool zero_size_allowed,
4739                                          enum bpf_access_src type,
4740                                          struct bpf_call_arg_meta *meta);
4741
4742 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4743 {
4744         return cur_regs(env) + regno;
4745 }
4746
4747 /* Read the stack at 'ptr_regno + off' and put the result into the register
4748  * 'dst_regno'.
4749  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4750  * but not its variable offset.
4751  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4752  *
4753  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4754  * filling registers (i.e. reads of spilled register cannot be detected when
4755  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4756  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4757  * offset; for a fixed offset check_stack_read_fixed_off should be used
4758  * instead.
4759  */
4760 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4761                                     int ptr_regno, int off, int size, int dst_regno)
4762 {
4763         /* The state of the source register. */
4764         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4765         struct bpf_func_state *ptr_state = func(env, reg);
4766         int err;
4767         int min_off, max_off;
4768
4769         /* Note that we pass a NULL meta, so raw access will not be permitted.
4770          */
4771         err = check_stack_range_initialized(env, ptr_regno, off, size,
4772                                             false, ACCESS_DIRECT, NULL);
4773         if (err)
4774                 return err;
4775
4776         min_off = reg->smin_value + off;
4777         max_off = reg->smax_value + off;
4778         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4779         return 0;
4780 }
4781
4782 /* check_stack_read dispatches to check_stack_read_fixed_off or
4783  * check_stack_read_var_off.
4784  *
4785  * The caller must ensure that the offset falls within the allocated stack
4786  * bounds.
4787  *
4788  * 'dst_regno' is a register which will receive the value from the stack. It
4789  * can be -1, meaning that the read value is not going to a register.
4790  */
4791 static int check_stack_read(struct bpf_verifier_env *env,
4792                             int ptr_regno, int off, int size,
4793                             int dst_regno)
4794 {
4795         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4796         struct bpf_func_state *state = func(env, reg);
4797         int err;
4798         /* Some accesses are only permitted with a static offset. */
4799         bool var_off = !tnum_is_const(reg->var_off);
4800
4801         /* The offset is required to be static when reads don't go to a
4802          * register, in order to not leak pointers (see
4803          * check_stack_read_fixed_off).
4804          */
4805         if (dst_regno < 0 && var_off) {
4806                 char tn_buf[48];
4807
4808                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4809                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4810                         tn_buf, off, size);
4811                 return -EACCES;
4812         }
4813         /* Variable offset is prohibited for unprivileged mode for simplicity
4814          * since it requires corresponding support in Spectre masking for stack
4815          * ALU. See also retrieve_ptr_limit(). The check in
4816          * check_stack_access_for_ptr_arithmetic() called by
4817          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4818          * with variable offsets, therefore no check is required here. Further,
4819          * just checking it here would be insufficient as speculative stack
4820          * writes could still lead to unsafe speculative behaviour.
4821          */
4822         if (!var_off) {
4823                 off += reg->var_off.value;
4824                 err = check_stack_read_fixed_off(env, state, off, size,
4825                                                  dst_regno);
4826         } else {
4827                 /* Variable offset stack reads need more conservative handling
4828                  * than fixed offset ones. Note that dst_regno >= 0 on this
4829                  * branch.
4830                  */
4831                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4832                                                dst_regno);
4833         }
4834         return err;
4835 }
4836
4837
4838 /* check_stack_write dispatches to check_stack_write_fixed_off or
4839  * check_stack_write_var_off.
4840  *
4841  * 'ptr_regno' is the register used as a pointer into the stack.
4842  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4843  * 'value_regno' is the register whose value we're writing to the stack. It can
4844  * be -1, meaning that we're not writing from a register.
4845  *
4846  * The caller must ensure that the offset falls within the maximum stack size.
4847  */
4848 static int check_stack_write(struct bpf_verifier_env *env,
4849                              int ptr_regno, int off, int size,
4850                              int value_regno, int insn_idx)
4851 {
4852         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4853         struct bpf_func_state *state = func(env, reg);
4854         int err;
4855
4856         if (tnum_is_const(reg->var_off)) {
4857                 off += reg->var_off.value;
4858                 err = check_stack_write_fixed_off(env, state, off, size,
4859                                                   value_regno, insn_idx);
4860         } else {
4861                 /* Variable offset stack reads need more conservative handling
4862                  * than fixed offset ones.
4863                  */
4864                 err = check_stack_write_var_off(env, state,
4865                                                 ptr_regno, off, size,
4866                                                 value_regno, insn_idx);
4867         }
4868         return err;
4869 }
4870
4871 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4872                                  int off, int size, enum bpf_access_type type)
4873 {
4874         struct bpf_reg_state *regs = cur_regs(env);
4875         struct bpf_map *map = regs[regno].map_ptr;
4876         u32 cap = bpf_map_flags_to_cap(map);
4877
4878         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4879                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4880                         map->value_size, off, size);
4881                 return -EACCES;
4882         }
4883
4884         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4885                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4886                         map->value_size, off, size);
4887                 return -EACCES;
4888         }
4889
4890         return 0;
4891 }
4892
4893 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4894 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4895                               int off, int size, u32 mem_size,
4896                               bool zero_size_allowed)
4897 {
4898         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4899         struct bpf_reg_state *reg;
4900
4901         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4902                 return 0;
4903
4904         reg = &cur_regs(env)[regno];
4905         switch (reg->type) {
4906         case PTR_TO_MAP_KEY:
4907                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4908                         mem_size, off, size);
4909                 break;
4910         case PTR_TO_MAP_VALUE:
4911                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4912                         mem_size, off, size);
4913                 break;
4914         case PTR_TO_PACKET:
4915         case PTR_TO_PACKET_META:
4916         case PTR_TO_PACKET_END:
4917                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4918                         off, size, regno, reg->id, off, mem_size);
4919                 break;
4920         case PTR_TO_MEM:
4921         default:
4922                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4923                         mem_size, off, size);
4924         }
4925
4926         return -EACCES;
4927 }
4928
4929 /* check read/write into a memory region with possible variable offset */
4930 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4931                                    int off, int size, u32 mem_size,
4932                                    bool zero_size_allowed)
4933 {
4934         struct bpf_verifier_state *vstate = env->cur_state;
4935         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4936         struct bpf_reg_state *reg = &state->regs[regno];
4937         int err;
4938
4939         /* We may have adjusted the register pointing to memory region, so we
4940          * need to try adding each of min_value and max_value to off
4941          * to make sure our theoretical access will be safe.
4942          *
4943          * The minimum value is only important with signed
4944          * comparisons where we can't assume the floor of a
4945          * value is 0.  If we are using signed variables for our
4946          * index'es we need to make sure that whatever we use
4947          * will have a set floor within our range.
4948          */
4949         if (reg->smin_value < 0 &&
4950             (reg->smin_value == S64_MIN ||
4951              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4952               reg->smin_value + off < 0)) {
4953                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4954                         regno);
4955                 return -EACCES;
4956         }
4957         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4958                                  mem_size, zero_size_allowed);
4959         if (err) {
4960                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4961                         regno);
4962                 return err;
4963         }
4964
4965         /* If we haven't set a max value then we need to bail since we can't be
4966          * sure we won't do bad things.
4967          * If reg->umax_value + off could overflow, treat that as unbounded too.
4968          */
4969         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4970                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4971                         regno);
4972                 return -EACCES;
4973         }
4974         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4975                                  mem_size, zero_size_allowed);
4976         if (err) {
4977                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4978                         regno);
4979                 return err;
4980         }
4981
4982         return 0;
4983 }
4984
4985 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4986                                const struct bpf_reg_state *reg, int regno,
4987                                bool fixed_off_ok)
4988 {
4989         /* Access to this pointer-typed register or passing it to a helper
4990          * is only allowed in its original, unmodified form.
4991          */
4992
4993         if (reg->off < 0) {
4994                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4995                         reg_type_str(env, reg->type), regno, reg->off);
4996                 return -EACCES;
4997         }
4998
4999         if (!fixed_off_ok && reg->off) {
5000                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5001                         reg_type_str(env, reg->type), regno, reg->off);
5002                 return -EACCES;
5003         }
5004
5005         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5006                 char tn_buf[48];
5007
5008                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5009                 verbose(env, "variable %s access var_off=%s disallowed\n",
5010                         reg_type_str(env, reg->type), tn_buf);
5011                 return -EACCES;
5012         }
5013
5014         return 0;
5015 }
5016
5017 int check_ptr_off_reg(struct bpf_verifier_env *env,
5018                       const struct bpf_reg_state *reg, int regno)
5019 {
5020         return __check_ptr_off_reg(env, reg, regno, false);
5021 }
5022
5023 static int map_kptr_match_type(struct bpf_verifier_env *env,
5024                                struct btf_field *kptr_field,
5025                                struct bpf_reg_state *reg, u32 regno)
5026 {
5027         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5028         int perm_flags;
5029         const char *reg_name = "";
5030
5031         if (btf_is_kernel(reg->btf)) {
5032                 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5033
5034                 /* Only unreferenced case accepts untrusted pointers */
5035                 if (kptr_field->type == BPF_KPTR_UNREF)
5036                         perm_flags |= PTR_UNTRUSTED;
5037         } else {
5038                 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5039         }
5040
5041         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5042                 goto bad_type;
5043
5044         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5045         reg_name = btf_type_name(reg->btf, reg->btf_id);
5046
5047         /* For ref_ptr case, release function check should ensure we get one
5048          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5049          * normal store of unreferenced kptr, we must ensure var_off is zero.
5050          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5051          * reg->off and reg->ref_obj_id are not needed here.
5052          */
5053         if (__check_ptr_off_reg(env, reg, regno, true))
5054                 return -EACCES;
5055
5056         /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5057          * we also need to take into account the reg->off.
5058          *
5059          * We want to support cases like:
5060          *
5061          * struct foo {
5062          *         struct bar br;
5063          *         struct baz bz;
5064          * };
5065          *
5066          * struct foo *v;
5067          * v = func();        // PTR_TO_BTF_ID
5068          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5069          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5070          *                    // first member type of struct after comparison fails
5071          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5072          *                    // to match type
5073          *
5074          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5075          * is zero. We must also ensure that btf_struct_ids_match does not walk
5076          * the struct to match type against first member of struct, i.e. reject
5077          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5078          * strict mode to true for type match.
5079          */
5080         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5081                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5082                                   kptr_field->type == BPF_KPTR_REF))
5083                 goto bad_type;
5084         return 0;
5085 bad_type:
5086         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5087                 reg_type_str(env, reg->type), reg_name);
5088         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5089         if (kptr_field->type == BPF_KPTR_UNREF)
5090                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5091                         targ_name);
5092         else
5093                 verbose(env, "\n");
5094         return -EINVAL;
5095 }
5096
5097 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5098  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5099  */
5100 static bool in_rcu_cs(struct bpf_verifier_env *env)
5101 {
5102         return env->cur_state->active_rcu_lock ||
5103                env->cur_state->active_lock.ptr ||
5104                !env->prog->aux->sleepable;
5105 }
5106
5107 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5108 BTF_SET_START(rcu_protected_types)
5109 BTF_ID(struct, prog_test_ref_kfunc)
5110 BTF_ID(struct, cgroup)
5111 BTF_ID(struct, bpf_cpumask)
5112 BTF_ID(struct, task_struct)
5113 BTF_SET_END(rcu_protected_types)
5114
5115 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5116 {
5117         if (!btf_is_kernel(btf))
5118                 return false;
5119         return btf_id_set_contains(&rcu_protected_types, btf_id);
5120 }
5121
5122 static bool rcu_safe_kptr(const struct btf_field *field)
5123 {
5124         const struct btf_field_kptr *kptr = &field->kptr;
5125
5126         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5127 }
5128
5129 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5130                                  int value_regno, int insn_idx,
5131                                  struct btf_field *kptr_field)
5132 {
5133         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5134         int class = BPF_CLASS(insn->code);
5135         struct bpf_reg_state *val_reg;
5136
5137         /* Things we already checked for in check_map_access and caller:
5138          *  - Reject cases where variable offset may touch kptr
5139          *  - size of access (must be BPF_DW)
5140          *  - tnum_is_const(reg->var_off)
5141          *  - kptr_field->offset == off + reg->var_off.value
5142          */
5143         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5144         if (BPF_MODE(insn->code) != BPF_MEM) {
5145                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5146                 return -EACCES;
5147         }
5148
5149         /* We only allow loading referenced kptr, since it will be marked as
5150          * untrusted, similar to unreferenced kptr.
5151          */
5152         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5153                 verbose(env, "store to referenced kptr disallowed\n");
5154                 return -EACCES;
5155         }
5156
5157         if (class == BPF_LDX) {
5158                 val_reg = reg_state(env, value_regno);
5159                 /* We can simply mark the value_regno receiving the pointer
5160                  * value from map as PTR_TO_BTF_ID, with the correct type.
5161                  */
5162                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5163                                 kptr_field->kptr.btf_id,
5164                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5165                                 PTR_MAYBE_NULL | MEM_RCU :
5166                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5167                 /* For mark_ptr_or_null_reg */
5168                 val_reg->id = ++env->id_gen;
5169         } else if (class == BPF_STX) {
5170                 val_reg = reg_state(env, value_regno);
5171                 if (!register_is_null(val_reg) &&
5172                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5173                         return -EACCES;
5174         } else if (class == BPF_ST) {
5175                 if (insn->imm) {
5176                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5177                                 kptr_field->offset);
5178                         return -EACCES;
5179                 }
5180         } else {
5181                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5182                 return -EACCES;
5183         }
5184         return 0;
5185 }
5186
5187 /* check read/write into a map element with possible variable offset */
5188 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5189                             int off, int size, bool zero_size_allowed,
5190                             enum bpf_access_src src)
5191 {
5192         struct bpf_verifier_state *vstate = env->cur_state;
5193         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5194         struct bpf_reg_state *reg = &state->regs[regno];
5195         struct bpf_map *map = reg->map_ptr;
5196         struct btf_record *rec;
5197         int err, i;
5198
5199         err = check_mem_region_access(env, regno, off, size, map->value_size,
5200                                       zero_size_allowed);
5201         if (err)
5202                 return err;
5203
5204         if (IS_ERR_OR_NULL(map->record))
5205                 return 0;
5206         rec = map->record;
5207         for (i = 0; i < rec->cnt; i++) {
5208                 struct btf_field *field = &rec->fields[i];
5209                 u32 p = field->offset;
5210
5211                 /* If any part of a field  can be touched by load/store, reject
5212                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5213                  * it is sufficient to check x1 < y2 && y1 < x2.
5214                  */
5215                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5216                     p < reg->umax_value + off + size) {
5217                         switch (field->type) {
5218                         case BPF_KPTR_UNREF:
5219                         case BPF_KPTR_REF:
5220                                 if (src != ACCESS_DIRECT) {
5221                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5222                                         return -EACCES;
5223                                 }
5224                                 if (!tnum_is_const(reg->var_off)) {
5225                                         verbose(env, "kptr access cannot have variable offset\n");
5226                                         return -EACCES;
5227                                 }
5228                                 if (p != off + reg->var_off.value) {
5229                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5230                                                 p, off + reg->var_off.value);
5231                                         return -EACCES;
5232                                 }
5233                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5234                                         verbose(env, "kptr access size must be BPF_DW\n");
5235                                         return -EACCES;
5236                                 }
5237                                 break;
5238                         default:
5239                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5240                                         btf_field_type_name(field->type));
5241                                 return -EACCES;
5242                         }
5243                 }
5244         }
5245         return 0;
5246 }
5247
5248 #define MAX_PACKET_OFF 0xffff
5249
5250 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5251                                        const struct bpf_call_arg_meta *meta,
5252                                        enum bpf_access_type t)
5253 {
5254         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5255
5256         switch (prog_type) {
5257         /* Program types only with direct read access go here! */
5258         case BPF_PROG_TYPE_LWT_IN:
5259         case BPF_PROG_TYPE_LWT_OUT:
5260         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5261         case BPF_PROG_TYPE_SK_REUSEPORT:
5262         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5263         case BPF_PROG_TYPE_CGROUP_SKB:
5264                 if (t == BPF_WRITE)
5265                         return false;
5266                 fallthrough;
5267
5268         /* Program types with direct read + write access go here! */
5269         case BPF_PROG_TYPE_SCHED_CLS:
5270         case BPF_PROG_TYPE_SCHED_ACT:
5271         case BPF_PROG_TYPE_XDP:
5272         case BPF_PROG_TYPE_LWT_XMIT:
5273         case BPF_PROG_TYPE_SK_SKB:
5274         case BPF_PROG_TYPE_SK_MSG:
5275                 if (meta)
5276                         return meta->pkt_access;
5277
5278                 env->seen_direct_write = true;
5279                 return true;
5280
5281         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5282                 if (t == BPF_WRITE)
5283                         env->seen_direct_write = true;
5284
5285                 return true;
5286
5287         default:
5288                 return false;
5289         }
5290 }
5291
5292 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5293                                int size, bool zero_size_allowed)
5294 {
5295         struct bpf_reg_state *regs = cur_regs(env);
5296         struct bpf_reg_state *reg = &regs[regno];
5297         int err;
5298
5299         /* We may have added a variable offset to the packet pointer; but any
5300          * reg->range we have comes after that.  We are only checking the fixed
5301          * offset.
5302          */
5303
5304         /* We don't allow negative numbers, because we aren't tracking enough
5305          * detail to prove they're safe.
5306          */
5307         if (reg->smin_value < 0) {
5308                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5309                         regno);
5310                 return -EACCES;
5311         }
5312
5313         err = reg->range < 0 ? -EINVAL :
5314               __check_mem_access(env, regno, off, size, reg->range,
5315                                  zero_size_allowed);
5316         if (err) {
5317                 verbose(env, "R%d offset is outside of the packet\n", regno);
5318                 return err;
5319         }
5320
5321         /* __check_mem_access has made sure "off + size - 1" is within u16.
5322          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5323          * otherwise find_good_pkt_pointers would have refused to set range info
5324          * that __check_mem_access would have rejected this pkt access.
5325          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5326          */
5327         env->prog->aux->max_pkt_offset =
5328                 max_t(u32, env->prog->aux->max_pkt_offset,
5329                       off + reg->umax_value + size - 1);
5330
5331         return err;
5332 }
5333
5334 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5335 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5336                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5337                             struct btf **btf, u32 *btf_id)
5338 {
5339         struct bpf_insn_access_aux info = {
5340                 .reg_type = *reg_type,
5341                 .log = &env->log,
5342         };
5343
5344         if (env->ops->is_valid_access &&
5345             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5346                 /* A non zero info.ctx_field_size indicates that this field is a
5347                  * candidate for later verifier transformation to load the whole
5348                  * field and then apply a mask when accessed with a narrower
5349                  * access than actual ctx access size. A zero info.ctx_field_size
5350                  * will only allow for whole field access and rejects any other
5351                  * type of narrower access.
5352                  */
5353                 *reg_type = info.reg_type;
5354
5355                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5356                         *btf = info.btf;
5357                         *btf_id = info.btf_id;
5358                 } else {
5359                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5360                 }
5361                 /* remember the offset of last byte accessed in ctx */
5362                 if (env->prog->aux->max_ctx_offset < off + size)
5363                         env->prog->aux->max_ctx_offset = off + size;
5364                 return 0;
5365         }
5366
5367         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5368         return -EACCES;
5369 }
5370
5371 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5372                                   int size)
5373 {
5374         if (size < 0 || off < 0 ||
5375             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5376                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5377                         off, size);
5378                 return -EACCES;
5379         }
5380         return 0;
5381 }
5382
5383 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5384                              u32 regno, int off, int size,
5385                              enum bpf_access_type t)
5386 {
5387         struct bpf_reg_state *regs = cur_regs(env);
5388         struct bpf_reg_state *reg = &regs[regno];
5389         struct bpf_insn_access_aux info = {};
5390         bool valid;
5391
5392         if (reg->smin_value < 0) {
5393                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5394                         regno);
5395                 return -EACCES;
5396         }
5397
5398         switch (reg->type) {
5399         case PTR_TO_SOCK_COMMON:
5400                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5401                 break;
5402         case PTR_TO_SOCKET:
5403                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5404                 break;
5405         case PTR_TO_TCP_SOCK:
5406                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5407                 break;
5408         case PTR_TO_XDP_SOCK:
5409                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5410                 break;
5411         default:
5412                 valid = false;
5413         }
5414
5415
5416         if (valid) {
5417                 env->insn_aux_data[insn_idx].ctx_field_size =
5418                         info.ctx_field_size;
5419                 return 0;
5420         }
5421
5422         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5423                 regno, reg_type_str(env, reg->type), off, size);
5424
5425         return -EACCES;
5426 }
5427
5428 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5429 {
5430         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5431 }
5432
5433 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5434 {
5435         const struct bpf_reg_state *reg = reg_state(env, regno);
5436
5437         return reg->type == PTR_TO_CTX;
5438 }
5439
5440 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5441 {
5442         const struct bpf_reg_state *reg = reg_state(env, regno);
5443
5444         return type_is_sk_pointer(reg->type);
5445 }
5446
5447 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5448 {
5449         const struct bpf_reg_state *reg = reg_state(env, regno);
5450
5451         return type_is_pkt_pointer(reg->type);
5452 }
5453
5454 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5455 {
5456         const struct bpf_reg_state *reg = reg_state(env, regno);
5457
5458         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5459         return reg->type == PTR_TO_FLOW_KEYS;
5460 }
5461
5462 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5463 #ifdef CONFIG_NET
5464         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5465         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5466         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5467 #endif
5468         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5469 };
5470
5471 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5472 {
5473         /* A referenced register is always trusted. */
5474         if (reg->ref_obj_id)
5475                 return true;
5476
5477         /* Types listed in the reg2btf_ids are always trusted */
5478         if (reg2btf_ids[base_type(reg->type)])
5479                 return true;
5480
5481         /* If a register is not referenced, it is trusted if it has the
5482          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5483          * other type modifiers may be safe, but we elect to take an opt-in
5484          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5485          * not.
5486          *
5487          * Eventually, we should make PTR_TRUSTED the single source of truth
5488          * for whether a register is trusted.
5489          */
5490         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5491                !bpf_type_has_unsafe_modifiers(reg->type);
5492 }
5493
5494 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5495 {
5496         return reg->type & MEM_RCU;
5497 }
5498
5499 static void clear_trusted_flags(enum bpf_type_flag *flag)
5500 {
5501         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5502 }
5503
5504 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5505                                    const struct bpf_reg_state *reg,
5506                                    int off, int size, bool strict)
5507 {
5508         struct tnum reg_off;
5509         int ip_align;
5510
5511         /* Byte size accesses are always allowed. */
5512         if (!strict || size == 1)
5513                 return 0;
5514
5515         /* For platforms that do not have a Kconfig enabling
5516          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5517          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5518          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5519          * to this code only in strict mode where we want to emulate
5520          * the NET_IP_ALIGN==2 checking.  Therefore use an
5521          * unconditional IP align value of '2'.
5522          */
5523         ip_align = 2;
5524
5525         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5526         if (!tnum_is_aligned(reg_off, size)) {
5527                 char tn_buf[48];
5528
5529                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5530                 verbose(env,
5531                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5532                         ip_align, tn_buf, reg->off, off, size);
5533                 return -EACCES;
5534         }
5535
5536         return 0;
5537 }
5538
5539 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5540                                        const struct bpf_reg_state *reg,
5541                                        const char *pointer_desc,
5542                                        int off, int size, bool strict)
5543 {
5544         struct tnum reg_off;
5545
5546         /* Byte size accesses are always allowed. */
5547         if (!strict || size == 1)
5548                 return 0;
5549
5550         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5551         if (!tnum_is_aligned(reg_off, size)) {
5552                 char tn_buf[48];
5553
5554                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5555                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5556                         pointer_desc, tn_buf, reg->off, off, size);
5557                 return -EACCES;
5558         }
5559
5560         return 0;
5561 }
5562
5563 static int check_ptr_alignment(struct bpf_verifier_env *env,
5564                                const struct bpf_reg_state *reg, int off,
5565                                int size, bool strict_alignment_once)
5566 {
5567         bool strict = env->strict_alignment || strict_alignment_once;
5568         const char *pointer_desc = "";
5569
5570         switch (reg->type) {
5571         case PTR_TO_PACKET:
5572         case PTR_TO_PACKET_META:
5573                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5574                  * right in front, treat it the very same way.
5575                  */
5576                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5577         case PTR_TO_FLOW_KEYS:
5578                 pointer_desc = "flow keys ";
5579                 break;
5580         case PTR_TO_MAP_KEY:
5581                 pointer_desc = "key ";
5582                 break;
5583         case PTR_TO_MAP_VALUE:
5584                 pointer_desc = "value ";
5585                 break;
5586         case PTR_TO_CTX:
5587                 pointer_desc = "context ";
5588                 break;
5589         case PTR_TO_STACK:
5590                 pointer_desc = "stack ";
5591                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5592                  * and check_stack_read_fixed_off() relies on stack accesses being
5593                  * aligned.
5594                  */
5595                 strict = true;
5596                 break;
5597         case PTR_TO_SOCKET:
5598                 pointer_desc = "sock ";
5599                 break;
5600         case PTR_TO_SOCK_COMMON:
5601                 pointer_desc = "sock_common ";
5602                 break;
5603         case PTR_TO_TCP_SOCK:
5604                 pointer_desc = "tcp_sock ";
5605                 break;
5606         case PTR_TO_XDP_SOCK:
5607                 pointer_desc = "xdp_sock ";
5608                 break;
5609         default:
5610                 break;
5611         }
5612         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5613                                            strict);
5614 }
5615
5616 /* starting from main bpf function walk all instructions of the function
5617  * and recursively walk all callees that given function can call.
5618  * Ignore jump and exit insns.
5619  * Since recursion is prevented by check_cfg() this algorithm
5620  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5621  */
5622 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5623 {
5624         struct bpf_subprog_info *subprog = env->subprog_info;
5625         struct bpf_insn *insn = env->prog->insnsi;
5626         int depth = 0, frame = 0, i, subprog_end;
5627         bool tail_call_reachable = false;
5628         int ret_insn[MAX_CALL_FRAMES];
5629         int ret_prog[MAX_CALL_FRAMES];
5630         int j;
5631
5632         i = subprog[idx].start;
5633 process_func:
5634         /* protect against potential stack overflow that might happen when
5635          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5636          * depth for such case down to 256 so that the worst case scenario
5637          * would result in 8k stack size (32 which is tailcall limit * 256 =
5638          * 8k).
5639          *
5640          * To get the idea what might happen, see an example:
5641          * func1 -> sub rsp, 128
5642          *  subfunc1 -> sub rsp, 256
5643          *  tailcall1 -> add rsp, 256
5644          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5645          *   subfunc2 -> sub rsp, 64
5646          *   subfunc22 -> sub rsp, 128
5647          *   tailcall2 -> add rsp, 128
5648          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5649          *
5650          * tailcall will unwind the current stack frame but it will not get rid
5651          * of caller's stack as shown on the example above.
5652          */
5653         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5654                 verbose(env,
5655                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5656                         depth);
5657                 return -EACCES;
5658         }
5659         /* round up to 32-bytes, since this is granularity
5660          * of interpreter stack size
5661          */
5662         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5663         if (depth > MAX_BPF_STACK) {
5664                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5665                         frame + 1, depth);
5666                 return -EACCES;
5667         }
5668 continue_func:
5669         subprog_end = subprog[idx + 1].start;
5670         for (; i < subprog_end; i++) {
5671                 int next_insn, sidx;
5672
5673                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5674                         continue;
5675                 /* remember insn and function to return to */
5676                 ret_insn[frame] = i + 1;
5677                 ret_prog[frame] = idx;
5678
5679                 /* find the callee */
5680                 next_insn = i + insn[i].imm + 1;
5681                 sidx = find_subprog(env, next_insn);
5682                 if (sidx < 0) {
5683                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5684                                   next_insn);
5685                         return -EFAULT;
5686                 }
5687                 if (subprog[sidx].is_async_cb) {
5688                         if (subprog[sidx].has_tail_call) {
5689                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5690                                 return -EFAULT;
5691                         }
5692                         /* async callbacks don't increase bpf prog stack size unless called directly */
5693                         if (!bpf_pseudo_call(insn + i))
5694                                 continue;
5695                 }
5696                 i = next_insn;
5697                 idx = sidx;
5698
5699                 if (subprog[idx].has_tail_call)
5700                         tail_call_reachable = true;
5701
5702                 frame++;
5703                 if (frame >= MAX_CALL_FRAMES) {
5704                         verbose(env, "the call stack of %d frames is too deep !\n",
5705                                 frame);
5706                         return -E2BIG;
5707                 }
5708                 goto process_func;
5709         }
5710         /* if tail call got detected across bpf2bpf calls then mark each of the
5711          * currently present subprog frames as tail call reachable subprogs;
5712          * this info will be utilized by JIT so that we will be preserving the
5713          * tail call counter throughout bpf2bpf calls combined with tailcalls
5714          */
5715         if (tail_call_reachable)
5716                 for (j = 0; j < frame; j++)
5717                         subprog[ret_prog[j]].tail_call_reachable = true;
5718         if (subprog[0].tail_call_reachable)
5719                 env->prog->aux->tail_call_reachable = true;
5720
5721         /* end of for() loop means the last insn of the 'subprog'
5722          * was reached. Doesn't matter whether it was JA or EXIT
5723          */
5724         if (frame == 0)
5725                 return 0;
5726         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5727         frame--;
5728         i = ret_insn[frame];
5729         idx = ret_prog[frame];
5730         goto continue_func;
5731 }
5732
5733 static int check_max_stack_depth(struct bpf_verifier_env *env)
5734 {
5735         struct bpf_subprog_info *si = env->subprog_info;
5736         int ret;
5737
5738         for (int i = 0; i < env->subprog_cnt; i++) {
5739                 if (!i || si[i].is_async_cb) {
5740                         ret = check_max_stack_depth_subprog(env, i);
5741                         if (ret < 0)
5742                                 return ret;
5743                 }
5744                 continue;
5745         }
5746         return 0;
5747 }
5748
5749 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5750 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5751                                   const struct bpf_insn *insn, int idx)
5752 {
5753         int start = idx + insn->imm + 1, subprog;
5754
5755         subprog = find_subprog(env, start);
5756         if (subprog < 0) {
5757                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5758                           start);
5759                 return -EFAULT;
5760         }
5761         return env->subprog_info[subprog].stack_depth;
5762 }
5763 #endif
5764
5765 static int __check_buffer_access(struct bpf_verifier_env *env,
5766                                  const char *buf_info,
5767                                  const struct bpf_reg_state *reg,
5768                                  int regno, int off, int size)
5769 {
5770         if (off < 0) {
5771                 verbose(env,
5772                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5773                         regno, buf_info, off, size);
5774                 return -EACCES;
5775         }
5776         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5777                 char tn_buf[48];
5778
5779                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5780                 verbose(env,
5781                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5782                         regno, off, tn_buf);
5783                 return -EACCES;
5784         }
5785
5786         return 0;
5787 }
5788
5789 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5790                                   const struct bpf_reg_state *reg,
5791                                   int regno, int off, int size)
5792 {
5793         int err;
5794
5795         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5796         if (err)
5797                 return err;
5798
5799         if (off + size > env->prog->aux->max_tp_access)
5800                 env->prog->aux->max_tp_access = off + size;
5801
5802         return 0;
5803 }
5804
5805 static int check_buffer_access(struct bpf_verifier_env *env,
5806                                const struct bpf_reg_state *reg,
5807                                int regno, int off, int size,
5808                                bool zero_size_allowed,
5809                                u32 *max_access)
5810 {
5811         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5812         int err;
5813
5814         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5815         if (err)
5816                 return err;
5817
5818         if (off + size > *max_access)
5819                 *max_access = off + size;
5820
5821         return 0;
5822 }
5823
5824 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5825 static void zext_32_to_64(struct bpf_reg_state *reg)
5826 {
5827         reg->var_off = tnum_subreg(reg->var_off);
5828         __reg_assign_32_into_64(reg);
5829 }
5830
5831 /* truncate register to smaller size (in bytes)
5832  * must be called with size < BPF_REG_SIZE
5833  */
5834 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5835 {
5836         u64 mask;
5837
5838         /* clear high bits in bit representation */
5839         reg->var_off = tnum_cast(reg->var_off, size);
5840
5841         /* fix arithmetic bounds */
5842         mask = ((u64)1 << (size * 8)) - 1;
5843         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5844                 reg->umin_value &= mask;
5845                 reg->umax_value &= mask;
5846         } else {
5847                 reg->umin_value = 0;
5848                 reg->umax_value = mask;
5849         }
5850         reg->smin_value = reg->umin_value;
5851         reg->smax_value = reg->umax_value;
5852
5853         /* If size is smaller than 32bit register the 32bit register
5854          * values are also truncated so we push 64-bit bounds into
5855          * 32-bit bounds. Above were truncated < 32-bits already.
5856          */
5857         if (size >= 4)
5858                 return;
5859         __reg_combine_64_into_32(reg);
5860 }
5861
5862 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5863 {
5864         if (size == 1) {
5865                 reg->smin_value = reg->s32_min_value = S8_MIN;
5866                 reg->smax_value = reg->s32_max_value = S8_MAX;
5867         } else if (size == 2) {
5868                 reg->smin_value = reg->s32_min_value = S16_MIN;
5869                 reg->smax_value = reg->s32_max_value = S16_MAX;
5870         } else {
5871                 /* size == 4 */
5872                 reg->smin_value = reg->s32_min_value = S32_MIN;
5873                 reg->smax_value = reg->s32_max_value = S32_MAX;
5874         }
5875         reg->umin_value = reg->u32_min_value = 0;
5876         reg->umax_value = U64_MAX;
5877         reg->u32_max_value = U32_MAX;
5878         reg->var_off = tnum_unknown;
5879 }
5880
5881 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5882 {
5883         s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5884         u64 top_smax_value, top_smin_value;
5885         u64 num_bits = size * 8;
5886
5887         if (tnum_is_const(reg->var_off)) {
5888                 u64_cval = reg->var_off.value;
5889                 if (size == 1)
5890                         reg->var_off = tnum_const((s8)u64_cval);
5891                 else if (size == 2)
5892                         reg->var_off = tnum_const((s16)u64_cval);
5893                 else
5894                         /* size == 4 */
5895                         reg->var_off = tnum_const((s32)u64_cval);
5896
5897                 u64_cval = reg->var_off.value;
5898                 reg->smax_value = reg->smin_value = u64_cval;
5899                 reg->umax_value = reg->umin_value = u64_cval;
5900                 reg->s32_max_value = reg->s32_min_value = u64_cval;
5901                 reg->u32_max_value = reg->u32_min_value = u64_cval;
5902                 return;
5903         }
5904
5905         top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5906         top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5907
5908         if (top_smax_value != top_smin_value)
5909                 goto out;
5910
5911         /* find the s64_min and s64_min after sign extension */
5912         if (size == 1) {
5913                 init_s64_max = (s8)reg->smax_value;
5914                 init_s64_min = (s8)reg->smin_value;
5915         } else if (size == 2) {
5916                 init_s64_max = (s16)reg->smax_value;
5917                 init_s64_min = (s16)reg->smin_value;
5918         } else {
5919                 init_s64_max = (s32)reg->smax_value;
5920                 init_s64_min = (s32)reg->smin_value;
5921         }
5922
5923         s64_max = max(init_s64_max, init_s64_min);
5924         s64_min = min(init_s64_max, init_s64_min);
5925
5926         /* both of s64_max/s64_min positive or negative */
5927         if ((s64_max >= 0) == (s64_min >= 0)) {
5928                 reg->smin_value = reg->s32_min_value = s64_min;
5929                 reg->smax_value = reg->s32_max_value = s64_max;
5930                 reg->umin_value = reg->u32_min_value = s64_min;
5931                 reg->umax_value = reg->u32_max_value = s64_max;
5932                 reg->var_off = tnum_range(s64_min, s64_max);
5933                 return;
5934         }
5935
5936 out:
5937         set_sext64_default_val(reg, size);
5938 }
5939
5940 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5941 {
5942         if (size == 1) {
5943                 reg->s32_min_value = S8_MIN;
5944                 reg->s32_max_value = S8_MAX;
5945         } else {
5946                 /* size == 2 */
5947                 reg->s32_min_value = S16_MIN;
5948                 reg->s32_max_value = S16_MAX;
5949         }
5950         reg->u32_min_value = 0;
5951         reg->u32_max_value = U32_MAX;
5952 }
5953
5954 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5955 {
5956         s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5957         u32 top_smax_value, top_smin_value;
5958         u32 num_bits = size * 8;
5959
5960         if (tnum_is_const(reg->var_off)) {
5961                 u32_val = reg->var_off.value;
5962                 if (size == 1)
5963                         reg->var_off = tnum_const((s8)u32_val);
5964                 else
5965                         reg->var_off = tnum_const((s16)u32_val);
5966
5967                 u32_val = reg->var_off.value;
5968                 reg->s32_min_value = reg->s32_max_value = u32_val;
5969                 reg->u32_min_value = reg->u32_max_value = u32_val;
5970                 return;
5971         }
5972
5973         top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5974         top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5975
5976         if (top_smax_value != top_smin_value)
5977                 goto out;
5978
5979         /* find the s32_min and s32_min after sign extension */
5980         if (size == 1) {
5981                 init_s32_max = (s8)reg->s32_max_value;
5982                 init_s32_min = (s8)reg->s32_min_value;
5983         } else {
5984                 /* size == 2 */
5985                 init_s32_max = (s16)reg->s32_max_value;
5986                 init_s32_min = (s16)reg->s32_min_value;
5987         }
5988         s32_max = max(init_s32_max, init_s32_min);
5989         s32_min = min(init_s32_max, init_s32_min);
5990
5991         if ((s32_min >= 0) == (s32_max >= 0)) {
5992                 reg->s32_min_value = s32_min;
5993                 reg->s32_max_value = s32_max;
5994                 reg->u32_min_value = (u32)s32_min;
5995                 reg->u32_max_value = (u32)s32_max;
5996                 return;
5997         }
5998
5999 out:
6000         set_sext32_default_val(reg, size);
6001 }
6002
6003 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6004 {
6005         /* A map is considered read-only if the following condition are true:
6006          *
6007          * 1) BPF program side cannot change any of the map content. The
6008          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6009          *    and was set at map creation time.
6010          * 2) The map value(s) have been initialized from user space by a
6011          *    loader and then "frozen", such that no new map update/delete
6012          *    operations from syscall side are possible for the rest of
6013          *    the map's lifetime from that point onwards.
6014          * 3) Any parallel/pending map update/delete operations from syscall
6015          *    side have been completed. Only after that point, it's safe to
6016          *    assume that map value(s) are immutable.
6017          */
6018         return (map->map_flags & BPF_F_RDONLY_PROG) &&
6019                READ_ONCE(map->frozen) &&
6020                !bpf_map_write_active(map);
6021 }
6022
6023 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6024                                bool is_ldsx)
6025 {
6026         void *ptr;
6027         u64 addr;
6028         int err;
6029
6030         err = map->ops->map_direct_value_addr(map, &addr, off);
6031         if (err)
6032                 return err;
6033         ptr = (void *)(long)addr + off;
6034
6035         switch (size) {
6036         case sizeof(u8):
6037                 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6038                 break;
6039         case sizeof(u16):
6040                 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6041                 break;
6042         case sizeof(u32):
6043                 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6044                 break;
6045         case sizeof(u64):
6046                 *val = *(u64 *)ptr;
6047                 break;
6048         default:
6049                 return -EINVAL;
6050         }
6051         return 0;
6052 }
6053
6054 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6055 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6056 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6057
6058 /*
6059  * Allow list few fields as RCU trusted or full trusted.
6060  * This logic doesn't allow mix tagging and will be removed once GCC supports
6061  * btf_type_tag.
6062  */
6063
6064 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6065 BTF_TYPE_SAFE_RCU(struct task_struct) {
6066         const cpumask_t *cpus_ptr;
6067         struct css_set __rcu *cgroups;
6068         struct task_struct __rcu *real_parent;
6069         struct task_struct *group_leader;
6070 };
6071
6072 BTF_TYPE_SAFE_RCU(struct cgroup) {
6073         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6074         struct kernfs_node *kn;
6075 };
6076
6077 BTF_TYPE_SAFE_RCU(struct css_set) {
6078         struct cgroup *dfl_cgrp;
6079 };
6080
6081 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6082 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6083         struct file __rcu *exe_file;
6084 };
6085
6086 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6087  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6088  */
6089 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6090         struct sock *sk;
6091 };
6092
6093 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6094         struct sock *sk;
6095 };
6096
6097 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6098 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6099         struct seq_file *seq;
6100 };
6101
6102 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6103         struct bpf_iter_meta *meta;
6104         struct task_struct *task;
6105 };
6106
6107 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6108         struct file *file;
6109 };
6110
6111 BTF_TYPE_SAFE_TRUSTED(struct file) {
6112         struct inode *f_inode;
6113 };
6114
6115 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6116         /* no negative dentry-s in places where bpf can see it */
6117         struct inode *d_inode;
6118 };
6119
6120 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6121         struct sock *sk;
6122 };
6123
6124 static bool type_is_rcu(struct bpf_verifier_env *env,
6125                         struct bpf_reg_state *reg,
6126                         const char *field_name, u32 btf_id)
6127 {
6128         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6129         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6130         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6131
6132         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6133 }
6134
6135 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6136                                 struct bpf_reg_state *reg,
6137                                 const char *field_name, u32 btf_id)
6138 {
6139         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6140         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6141         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6142
6143         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6144 }
6145
6146 static bool type_is_trusted(struct bpf_verifier_env *env,
6147                             struct bpf_reg_state *reg,
6148                             const char *field_name, u32 btf_id)
6149 {
6150         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6151         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6152         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6153         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6154         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6155         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6156
6157         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6158 }
6159
6160 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6161                                    struct bpf_reg_state *regs,
6162                                    int regno, int off, int size,
6163                                    enum bpf_access_type atype,
6164                                    int value_regno)
6165 {
6166         struct bpf_reg_state *reg = regs + regno;
6167         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6168         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6169         const char *field_name = NULL;
6170         enum bpf_type_flag flag = 0;
6171         u32 btf_id = 0;
6172         int ret;
6173
6174         if (!env->allow_ptr_leaks) {
6175                 verbose(env,
6176                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6177                         tname);
6178                 return -EPERM;
6179         }
6180         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6181                 verbose(env,
6182                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6183                         tname);
6184                 return -EINVAL;
6185         }
6186         if (off < 0) {
6187                 verbose(env,
6188                         "R%d is ptr_%s invalid negative access: off=%d\n",
6189                         regno, tname, off);
6190                 return -EACCES;
6191         }
6192         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6193                 char tn_buf[48];
6194
6195                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6196                 verbose(env,
6197                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6198                         regno, tname, off, tn_buf);
6199                 return -EACCES;
6200         }
6201
6202         if (reg->type & MEM_USER) {
6203                 verbose(env,
6204                         "R%d is ptr_%s access user memory: off=%d\n",
6205                         regno, tname, off);
6206                 return -EACCES;
6207         }
6208
6209         if (reg->type & MEM_PERCPU) {
6210                 verbose(env,
6211                         "R%d is ptr_%s access percpu memory: off=%d\n",
6212                         regno, tname, off);
6213                 return -EACCES;
6214         }
6215
6216         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6217                 if (!btf_is_kernel(reg->btf)) {
6218                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6219                         return -EFAULT;
6220                 }
6221                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6222         } else {
6223                 /* Writes are permitted with default btf_struct_access for
6224                  * program allocated objects (which always have ref_obj_id > 0),
6225                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6226                  */
6227                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6228                         verbose(env, "only read is supported\n");
6229                         return -EACCES;
6230                 }
6231
6232                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6233                     !reg->ref_obj_id) {
6234                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6235                         return -EFAULT;
6236                 }
6237
6238                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6239         }
6240
6241         if (ret < 0)
6242                 return ret;
6243
6244         if (ret != PTR_TO_BTF_ID) {
6245                 /* just mark; */
6246
6247         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6248                 /* If this is an untrusted pointer, all pointers formed by walking it
6249                  * also inherit the untrusted flag.
6250                  */
6251                 flag = PTR_UNTRUSTED;
6252
6253         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6254                 /* By default any pointer obtained from walking a trusted pointer is no
6255                  * longer trusted, unless the field being accessed has explicitly been
6256                  * marked as inheriting its parent's state of trust (either full or RCU).
6257                  * For example:
6258                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6259                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6260                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6261                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6262                  *
6263                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6264                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6265                  */
6266                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6267                         flag |= PTR_TRUSTED;
6268                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6269                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6270                                 /* ignore __rcu tag and mark it MEM_RCU */
6271                                 flag |= MEM_RCU;
6272                         } else if (flag & MEM_RCU ||
6273                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6274                                 /* __rcu tagged pointers can be NULL */
6275                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6276
6277                                 /* We always trust them */
6278                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6279                                     flag & PTR_UNTRUSTED)
6280                                         flag &= ~PTR_UNTRUSTED;
6281                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6282                                 /* keep as-is */
6283                         } else {
6284                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6285                                 clear_trusted_flags(&flag);
6286                         }
6287                 } else {
6288                         /*
6289                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6290                          * aggressively mark as untrusted otherwise such
6291                          * pointers will be plain PTR_TO_BTF_ID without flags
6292                          * and will be allowed to be passed into helpers for
6293                          * compat reasons.
6294                          */
6295                         flag = PTR_UNTRUSTED;
6296                 }
6297         } else {
6298                 /* Old compat. Deprecated */
6299                 clear_trusted_flags(&flag);
6300         }
6301
6302         if (atype == BPF_READ && value_regno >= 0)
6303                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6304
6305         return 0;
6306 }
6307
6308 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6309                                    struct bpf_reg_state *regs,
6310                                    int regno, int off, int size,
6311                                    enum bpf_access_type atype,
6312                                    int value_regno)
6313 {
6314         struct bpf_reg_state *reg = regs + regno;
6315         struct bpf_map *map = reg->map_ptr;
6316         struct bpf_reg_state map_reg;
6317         enum bpf_type_flag flag = 0;
6318         const struct btf_type *t;
6319         const char *tname;
6320         u32 btf_id;
6321         int ret;
6322
6323         if (!btf_vmlinux) {
6324                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6325                 return -ENOTSUPP;
6326         }
6327
6328         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6329                 verbose(env, "map_ptr access not supported for map type %d\n",
6330                         map->map_type);
6331                 return -ENOTSUPP;
6332         }
6333
6334         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6335         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6336
6337         if (!env->allow_ptr_leaks) {
6338                 verbose(env,
6339                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6340                         tname);
6341                 return -EPERM;
6342         }
6343
6344         if (off < 0) {
6345                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6346                         regno, tname, off);
6347                 return -EACCES;
6348         }
6349
6350         if (atype != BPF_READ) {
6351                 verbose(env, "only read from %s is supported\n", tname);
6352                 return -EACCES;
6353         }
6354
6355         /* Simulate access to a PTR_TO_BTF_ID */
6356         memset(&map_reg, 0, sizeof(map_reg));
6357         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6358         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6359         if (ret < 0)
6360                 return ret;
6361
6362         if (value_regno >= 0)
6363                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6364
6365         return 0;
6366 }
6367
6368 /* Check that the stack access at the given offset is within bounds. The
6369  * maximum valid offset is -1.
6370  *
6371  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6372  * -state->allocated_stack for reads.
6373  */
6374 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6375                                           s64 off,
6376                                           struct bpf_func_state *state,
6377                                           enum bpf_access_type t)
6378 {
6379         int min_valid_off;
6380
6381         if (t == BPF_WRITE || env->allow_uninit_stack)
6382                 min_valid_off = -MAX_BPF_STACK;
6383         else
6384                 min_valid_off = -state->allocated_stack;
6385
6386         if (off < min_valid_off || off > -1)
6387                 return -EACCES;
6388         return 0;
6389 }
6390
6391 /* Check that the stack access at 'regno + off' falls within the maximum stack
6392  * bounds.
6393  *
6394  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6395  */
6396 static int check_stack_access_within_bounds(
6397                 struct bpf_verifier_env *env,
6398                 int regno, int off, int access_size,
6399                 enum bpf_access_src src, enum bpf_access_type type)
6400 {
6401         struct bpf_reg_state *regs = cur_regs(env);
6402         struct bpf_reg_state *reg = regs + regno;
6403         struct bpf_func_state *state = func(env, reg);
6404         s64 min_off, max_off;
6405         int err;
6406         char *err_extra;
6407
6408         if (src == ACCESS_HELPER)
6409                 /* We don't know if helpers are reading or writing (or both). */
6410                 err_extra = " indirect access to";
6411         else if (type == BPF_READ)
6412                 err_extra = " read from";
6413         else
6414                 err_extra = " write to";
6415
6416         if (tnum_is_const(reg->var_off)) {
6417                 min_off = (s64)reg->var_off.value + off;
6418                 max_off = min_off + access_size;
6419         } else {
6420                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6421                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6422                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6423                                 err_extra, regno);
6424                         return -EACCES;
6425                 }
6426                 min_off = reg->smin_value + off;
6427                 max_off = reg->smax_value + off + access_size;
6428         }
6429
6430         err = check_stack_slot_within_bounds(env, min_off, state, type);
6431         if (!err && max_off > 0)
6432                 err = -EINVAL; /* out of stack access into non-negative offsets */
6433
6434         if (err) {
6435                 if (tnum_is_const(reg->var_off)) {
6436                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6437                                 err_extra, regno, off, access_size);
6438                 } else {
6439                         char tn_buf[48];
6440
6441                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6442                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6443                                 err_extra, regno, tn_buf, access_size);
6444                 }
6445                 return err;
6446         }
6447
6448         return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6449 }
6450
6451 /* check whether memory at (regno + off) is accessible for t = (read | write)
6452  * if t==write, value_regno is a register which value is stored into memory
6453  * if t==read, value_regno is a register which will receive the value from memory
6454  * if t==write && value_regno==-1, some unknown value is stored into memory
6455  * if t==read && value_regno==-1, don't care what we read from memory
6456  */
6457 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6458                             int off, int bpf_size, enum bpf_access_type t,
6459                             int value_regno, bool strict_alignment_once, bool is_ldsx)
6460 {
6461         struct bpf_reg_state *regs = cur_regs(env);
6462         struct bpf_reg_state *reg = regs + regno;
6463         int size, err = 0;
6464
6465         size = bpf_size_to_bytes(bpf_size);
6466         if (size < 0)
6467                 return size;
6468
6469         /* alignment checks will add in reg->off themselves */
6470         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6471         if (err)
6472                 return err;
6473
6474         /* for access checks, reg->off is just part of off */
6475         off += reg->off;
6476
6477         if (reg->type == PTR_TO_MAP_KEY) {
6478                 if (t == BPF_WRITE) {
6479                         verbose(env, "write to change key R%d not allowed\n", regno);
6480                         return -EACCES;
6481                 }
6482
6483                 err = check_mem_region_access(env, regno, off, size,
6484                                               reg->map_ptr->key_size, false);
6485                 if (err)
6486                         return err;
6487                 if (value_regno >= 0)
6488                         mark_reg_unknown(env, regs, value_regno);
6489         } else if (reg->type == PTR_TO_MAP_VALUE) {
6490                 struct btf_field *kptr_field = NULL;
6491
6492                 if (t == BPF_WRITE && value_regno >= 0 &&
6493                     is_pointer_value(env, value_regno)) {
6494                         verbose(env, "R%d leaks addr into map\n", value_regno);
6495                         return -EACCES;
6496                 }
6497                 err = check_map_access_type(env, regno, off, size, t);
6498                 if (err)
6499                         return err;
6500                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6501                 if (err)
6502                         return err;
6503                 if (tnum_is_const(reg->var_off))
6504                         kptr_field = btf_record_find(reg->map_ptr->record,
6505                                                      off + reg->var_off.value, BPF_KPTR);
6506                 if (kptr_field) {
6507                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6508                 } else if (t == BPF_READ && value_regno >= 0) {
6509                         struct bpf_map *map = reg->map_ptr;
6510
6511                         /* if map is read-only, track its contents as scalars */
6512                         if (tnum_is_const(reg->var_off) &&
6513                             bpf_map_is_rdonly(map) &&
6514                             map->ops->map_direct_value_addr) {
6515                                 int map_off = off + reg->var_off.value;
6516                                 u64 val = 0;
6517
6518                                 err = bpf_map_direct_read(map, map_off, size,
6519                                                           &val, is_ldsx);
6520                                 if (err)
6521                                         return err;
6522
6523                                 regs[value_regno].type = SCALAR_VALUE;
6524                                 __mark_reg_known(&regs[value_regno], val);
6525                         } else {
6526                                 mark_reg_unknown(env, regs, value_regno);
6527                         }
6528                 }
6529         } else if (base_type(reg->type) == PTR_TO_MEM) {
6530                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6531
6532                 if (type_may_be_null(reg->type)) {
6533                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6534                                 reg_type_str(env, reg->type));
6535                         return -EACCES;
6536                 }
6537
6538                 if (t == BPF_WRITE && rdonly_mem) {
6539                         verbose(env, "R%d cannot write into %s\n",
6540                                 regno, reg_type_str(env, reg->type));
6541                         return -EACCES;
6542                 }
6543
6544                 if (t == BPF_WRITE && value_regno >= 0 &&
6545                     is_pointer_value(env, value_regno)) {
6546                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6547                         return -EACCES;
6548                 }
6549
6550                 err = check_mem_region_access(env, regno, off, size,
6551                                               reg->mem_size, false);
6552                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6553                         mark_reg_unknown(env, regs, value_regno);
6554         } else if (reg->type == PTR_TO_CTX) {
6555                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6556                 struct btf *btf = NULL;
6557                 u32 btf_id = 0;
6558
6559                 if (t == BPF_WRITE && value_regno >= 0 &&
6560                     is_pointer_value(env, value_regno)) {
6561                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6562                         return -EACCES;
6563                 }
6564
6565                 err = check_ptr_off_reg(env, reg, regno);
6566                 if (err < 0)
6567                         return err;
6568
6569                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6570                                        &btf_id);
6571                 if (err)
6572                         verbose_linfo(env, insn_idx, "; ");
6573                 if (!err && t == BPF_READ && value_regno >= 0) {
6574                         /* ctx access returns either a scalar, or a
6575                          * PTR_TO_PACKET[_META,_END]. In the latter
6576                          * case, we know the offset is zero.
6577                          */
6578                         if (reg_type == SCALAR_VALUE) {
6579                                 mark_reg_unknown(env, regs, value_regno);
6580                         } else {
6581                                 mark_reg_known_zero(env, regs,
6582                                                     value_regno);
6583                                 if (type_may_be_null(reg_type))
6584                                         regs[value_regno].id = ++env->id_gen;
6585                                 /* A load of ctx field could have different
6586                                  * actual load size with the one encoded in the
6587                                  * insn. When the dst is PTR, it is for sure not
6588                                  * a sub-register.
6589                                  */
6590                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6591                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6592                                         regs[value_regno].btf = btf;
6593                                         regs[value_regno].btf_id = btf_id;
6594                                 }
6595                         }
6596                         regs[value_regno].type = reg_type;
6597                 }
6598
6599         } else if (reg->type == PTR_TO_STACK) {
6600                 /* Basic bounds checks. */
6601                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6602                 if (err)
6603                         return err;
6604
6605                 if (t == BPF_READ)
6606                         err = check_stack_read(env, regno, off, size,
6607                                                value_regno);
6608                 else
6609                         err = check_stack_write(env, regno, off, size,
6610                                                 value_regno, insn_idx);
6611         } else if (reg_is_pkt_pointer(reg)) {
6612                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6613                         verbose(env, "cannot write into packet\n");
6614                         return -EACCES;
6615                 }
6616                 if (t == BPF_WRITE && value_regno >= 0 &&
6617                     is_pointer_value(env, value_regno)) {
6618                         verbose(env, "R%d leaks addr into packet\n",
6619                                 value_regno);
6620                         return -EACCES;
6621                 }
6622                 err = check_packet_access(env, regno, off, size, false);
6623                 if (!err && t == BPF_READ && value_regno >= 0)
6624                         mark_reg_unknown(env, regs, value_regno);
6625         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6626                 if (t == BPF_WRITE && value_regno >= 0 &&
6627                     is_pointer_value(env, value_regno)) {
6628                         verbose(env, "R%d leaks addr into flow keys\n",
6629                                 value_regno);
6630                         return -EACCES;
6631                 }
6632
6633                 err = check_flow_keys_access(env, off, size);
6634                 if (!err && t == BPF_READ && value_regno >= 0)
6635                         mark_reg_unknown(env, regs, value_regno);
6636         } else if (type_is_sk_pointer(reg->type)) {
6637                 if (t == BPF_WRITE) {
6638                         verbose(env, "R%d cannot write into %s\n",
6639                                 regno, reg_type_str(env, reg->type));
6640                         return -EACCES;
6641                 }
6642                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6643                 if (!err && value_regno >= 0)
6644                         mark_reg_unknown(env, regs, value_regno);
6645         } else if (reg->type == PTR_TO_TP_BUFFER) {
6646                 err = check_tp_buffer_access(env, reg, regno, off, size);
6647                 if (!err && t == BPF_READ && value_regno >= 0)
6648                         mark_reg_unknown(env, regs, value_regno);
6649         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6650                    !type_may_be_null(reg->type)) {
6651                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6652                                               value_regno);
6653         } else if (reg->type == CONST_PTR_TO_MAP) {
6654                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6655                                               value_regno);
6656         } else if (base_type(reg->type) == PTR_TO_BUF) {
6657                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6658                 u32 *max_access;
6659
6660                 if (rdonly_mem) {
6661                         if (t == BPF_WRITE) {
6662                                 verbose(env, "R%d cannot write into %s\n",
6663                                         regno, reg_type_str(env, reg->type));
6664                                 return -EACCES;
6665                         }
6666                         max_access = &env->prog->aux->max_rdonly_access;
6667                 } else {
6668                         max_access = &env->prog->aux->max_rdwr_access;
6669                 }
6670
6671                 err = check_buffer_access(env, reg, regno, off, size, false,
6672                                           max_access);
6673
6674                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6675                         mark_reg_unknown(env, regs, value_regno);
6676         } else {
6677                 verbose(env, "R%d invalid mem access '%s'\n", regno,
6678                         reg_type_str(env, reg->type));
6679                 return -EACCES;
6680         }
6681
6682         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6683             regs[value_regno].type == SCALAR_VALUE) {
6684                 if (!is_ldsx)
6685                         /* b/h/w load zero-extends, mark upper bits as known 0 */
6686                         coerce_reg_to_size(&regs[value_regno], size);
6687                 else
6688                         coerce_reg_to_size_sx(&regs[value_regno], size);
6689         }
6690         return err;
6691 }
6692
6693 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6694 {
6695         int load_reg;
6696         int err;
6697
6698         switch (insn->imm) {
6699         case BPF_ADD:
6700         case BPF_ADD | BPF_FETCH:
6701         case BPF_AND:
6702         case BPF_AND | BPF_FETCH:
6703         case BPF_OR:
6704         case BPF_OR | BPF_FETCH:
6705         case BPF_XOR:
6706         case BPF_XOR | BPF_FETCH:
6707         case BPF_XCHG:
6708         case BPF_CMPXCHG:
6709                 break;
6710         default:
6711                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6712                 return -EINVAL;
6713         }
6714
6715         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6716                 verbose(env, "invalid atomic operand size\n");
6717                 return -EINVAL;
6718         }
6719
6720         /* check src1 operand */
6721         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6722         if (err)
6723                 return err;
6724
6725         /* check src2 operand */
6726         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6727         if (err)
6728                 return err;
6729
6730         if (insn->imm == BPF_CMPXCHG) {
6731                 /* Check comparison of R0 with memory location */
6732                 const u32 aux_reg = BPF_REG_0;
6733
6734                 err = check_reg_arg(env, aux_reg, SRC_OP);
6735                 if (err)
6736                         return err;
6737
6738                 if (is_pointer_value(env, aux_reg)) {
6739                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6740                         return -EACCES;
6741                 }
6742         }
6743
6744         if (is_pointer_value(env, insn->src_reg)) {
6745                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6746                 return -EACCES;
6747         }
6748
6749         if (is_ctx_reg(env, insn->dst_reg) ||
6750             is_pkt_reg(env, insn->dst_reg) ||
6751             is_flow_key_reg(env, insn->dst_reg) ||
6752             is_sk_reg(env, insn->dst_reg)) {
6753                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6754                         insn->dst_reg,
6755                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6756                 return -EACCES;
6757         }
6758
6759         if (insn->imm & BPF_FETCH) {
6760                 if (insn->imm == BPF_CMPXCHG)
6761                         load_reg = BPF_REG_0;
6762                 else
6763                         load_reg = insn->src_reg;
6764
6765                 /* check and record load of old value */
6766                 err = check_reg_arg(env, load_reg, DST_OP);
6767                 if (err)
6768                         return err;
6769         } else {
6770                 /* This instruction accesses a memory location but doesn't
6771                  * actually load it into a register.
6772                  */
6773                 load_reg = -1;
6774         }
6775
6776         /* Check whether we can read the memory, with second call for fetch
6777          * case to simulate the register fill.
6778          */
6779         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6780                                BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6781         if (!err && load_reg >= 0)
6782                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6783                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
6784                                        true, false);
6785         if (err)
6786                 return err;
6787
6788         /* Check whether we can write into the same memory. */
6789         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6790                                BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6791         if (err)
6792                 return err;
6793
6794         return 0;
6795 }
6796
6797 /* When register 'regno' is used to read the stack (either directly or through
6798  * a helper function) make sure that it's within stack boundary and, depending
6799  * on the access type and privileges, that all elements of the stack are
6800  * initialized.
6801  *
6802  * 'off' includes 'regno->off', but not its dynamic part (if any).
6803  *
6804  * All registers that have been spilled on the stack in the slots within the
6805  * read offsets are marked as read.
6806  */
6807 static int check_stack_range_initialized(
6808                 struct bpf_verifier_env *env, int regno, int off,
6809                 int access_size, bool zero_size_allowed,
6810                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6811 {
6812         struct bpf_reg_state *reg = reg_state(env, regno);
6813         struct bpf_func_state *state = func(env, reg);
6814         int err, min_off, max_off, i, j, slot, spi;
6815         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6816         enum bpf_access_type bounds_check_type;
6817         /* Some accesses can write anything into the stack, others are
6818          * read-only.
6819          */
6820         bool clobber = false;
6821
6822         if (access_size == 0 && !zero_size_allowed) {
6823                 verbose(env, "invalid zero-sized read\n");
6824                 return -EACCES;
6825         }
6826
6827         if (type == ACCESS_HELPER) {
6828                 /* The bounds checks for writes are more permissive than for
6829                  * reads. However, if raw_mode is not set, we'll do extra
6830                  * checks below.
6831                  */
6832                 bounds_check_type = BPF_WRITE;
6833                 clobber = true;
6834         } else {
6835                 bounds_check_type = BPF_READ;
6836         }
6837         err = check_stack_access_within_bounds(env, regno, off, access_size,
6838                                                type, bounds_check_type);
6839         if (err)
6840                 return err;
6841
6842
6843         if (tnum_is_const(reg->var_off)) {
6844                 min_off = max_off = reg->var_off.value + off;
6845         } else {
6846                 /* Variable offset is prohibited for unprivileged mode for
6847                  * simplicity since it requires corresponding support in
6848                  * Spectre masking for stack ALU.
6849                  * See also retrieve_ptr_limit().
6850                  */
6851                 if (!env->bypass_spec_v1) {
6852                         char tn_buf[48];
6853
6854                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6855                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6856                                 regno, err_extra, tn_buf);
6857                         return -EACCES;
6858                 }
6859                 /* Only initialized buffer on stack is allowed to be accessed
6860                  * with variable offset. With uninitialized buffer it's hard to
6861                  * guarantee that whole memory is marked as initialized on
6862                  * helper return since specific bounds are unknown what may
6863                  * cause uninitialized stack leaking.
6864                  */
6865                 if (meta && meta->raw_mode)
6866                         meta = NULL;
6867
6868                 min_off = reg->smin_value + off;
6869                 max_off = reg->smax_value + off;
6870         }
6871
6872         if (meta && meta->raw_mode) {
6873                 /* Ensure we won't be overwriting dynptrs when simulating byte
6874                  * by byte access in check_helper_call using meta.access_size.
6875                  * This would be a problem if we have a helper in the future
6876                  * which takes:
6877                  *
6878                  *      helper(uninit_mem, len, dynptr)
6879                  *
6880                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6881                  * may end up writing to dynptr itself when touching memory from
6882                  * arg 1. This can be relaxed on a case by case basis for known
6883                  * safe cases, but reject due to the possibilitiy of aliasing by
6884                  * default.
6885                  */
6886                 for (i = min_off; i < max_off + access_size; i++) {
6887                         int stack_off = -i - 1;
6888
6889                         spi = __get_spi(i);
6890                         /* raw_mode may write past allocated_stack */
6891                         if (state->allocated_stack <= stack_off)
6892                                 continue;
6893                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6894                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6895                                 return -EACCES;
6896                         }
6897                 }
6898                 meta->access_size = access_size;
6899                 meta->regno = regno;
6900                 return 0;
6901         }
6902
6903         for (i = min_off; i < max_off + access_size; i++) {
6904                 u8 *stype;
6905
6906                 slot = -i - 1;
6907                 spi = slot / BPF_REG_SIZE;
6908                 if (state->allocated_stack <= slot) {
6909                         verbose(env, "verifier bug: allocated_stack too small");
6910                         return -EFAULT;
6911                 }
6912
6913                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6914                 if (*stype == STACK_MISC)
6915                         goto mark;
6916                 if ((*stype == STACK_ZERO) ||
6917                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6918                         if (clobber) {
6919                                 /* helper can write anything into the stack */
6920                                 *stype = STACK_MISC;
6921                         }
6922                         goto mark;
6923                 }
6924
6925                 if (is_spilled_reg(&state->stack[spi]) &&
6926                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6927                      env->allow_ptr_leaks)) {
6928                         if (clobber) {
6929                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6930                                 for (j = 0; j < BPF_REG_SIZE; j++)
6931                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6932                         }
6933                         goto mark;
6934                 }
6935
6936                 if (tnum_is_const(reg->var_off)) {
6937                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6938                                 err_extra, regno, min_off, i - min_off, access_size);
6939                 } else {
6940                         char tn_buf[48];
6941
6942                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6943                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6944                                 err_extra, regno, tn_buf, i - min_off, access_size);
6945                 }
6946                 return -EACCES;
6947 mark:
6948                 /* reading any byte out of 8-byte 'spill_slot' will cause
6949                  * the whole slot to be marked as 'read'
6950                  */
6951                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6952                               state->stack[spi].spilled_ptr.parent,
6953                               REG_LIVE_READ64);
6954                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6955                  * be sure that whether stack slot is written to or not. Hence,
6956                  * we must still conservatively propagate reads upwards even if
6957                  * helper may write to the entire memory range.
6958                  */
6959         }
6960         return 0;
6961 }
6962
6963 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6964                                    int access_size, bool zero_size_allowed,
6965                                    struct bpf_call_arg_meta *meta)
6966 {
6967         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6968         u32 *max_access;
6969
6970         switch (base_type(reg->type)) {
6971         case PTR_TO_PACKET:
6972         case PTR_TO_PACKET_META:
6973                 return check_packet_access(env, regno, reg->off, access_size,
6974                                            zero_size_allowed);
6975         case PTR_TO_MAP_KEY:
6976                 if (meta && meta->raw_mode) {
6977                         verbose(env, "R%d cannot write into %s\n", regno,
6978                                 reg_type_str(env, reg->type));
6979                         return -EACCES;
6980                 }
6981                 return check_mem_region_access(env, regno, reg->off, access_size,
6982                                                reg->map_ptr->key_size, false);
6983         case PTR_TO_MAP_VALUE:
6984                 if (check_map_access_type(env, regno, reg->off, access_size,
6985                                           meta && meta->raw_mode ? BPF_WRITE :
6986                                           BPF_READ))
6987                         return -EACCES;
6988                 return check_map_access(env, regno, reg->off, access_size,
6989                                         zero_size_allowed, ACCESS_HELPER);
6990         case PTR_TO_MEM:
6991                 if (type_is_rdonly_mem(reg->type)) {
6992                         if (meta && meta->raw_mode) {
6993                                 verbose(env, "R%d cannot write into %s\n", regno,
6994                                         reg_type_str(env, reg->type));
6995                                 return -EACCES;
6996                         }
6997                 }
6998                 return check_mem_region_access(env, regno, reg->off,
6999                                                access_size, reg->mem_size,
7000                                                zero_size_allowed);
7001         case PTR_TO_BUF:
7002                 if (type_is_rdonly_mem(reg->type)) {
7003                         if (meta && meta->raw_mode) {
7004                                 verbose(env, "R%d cannot write into %s\n", regno,
7005                                         reg_type_str(env, reg->type));
7006                                 return -EACCES;
7007                         }
7008
7009                         max_access = &env->prog->aux->max_rdonly_access;
7010                 } else {
7011                         max_access = &env->prog->aux->max_rdwr_access;
7012                 }
7013                 return check_buffer_access(env, reg, regno, reg->off,
7014                                            access_size, zero_size_allowed,
7015                                            max_access);
7016         case PTR_TO_STACK:
7017                 return check_stack_range_initialized(
7018                                 env,
7019                                 regno, reg->off, access_size,
7020                                 zero_size_allowed, ACCESS_HELPER, meta);
7021         case PTR_TO_BTF_ID:
7022                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7023                                                access_size, BPF_READ, -1);
7024         case PTR_TO_CTX:
7025                 /* in case the function doesn't know how to access the context,
7026                  * (because we are in a program of type SYSCALL for example), we
7027                  * can not statically check its size.
7028                  * Dynamically check it now.
7029                  */
7030                 if (!env->ops->convert_ctx_access) {
7031                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7032                         int offset = access_size - 1;
7033
7034                         /* Allow zero-byte read from PTR_TO_CTX */
7035                         if (access_size == 0)
7036                                 return zero_size_allowed ? 0 : -EACCES;
7037
7038                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7039                                                 atype, -1, false, false);
7040                 }
7041
7042                 fallthrough;
7043         default: /* scalar_value or invalid ptr */
7044                 /* Allow zero-byte read from NULL, regardless of pointer type */
7045                 if (zero_size_allowed && access_size == 0 &&
7046                     register_is_null(reg))
7047                         return 0;
7048
7049                 verbose(env, "R%d type=%s ", regno,
7050                         reg_type_str(env, reg->type));
7051                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7052                 return -EACCES;
7053         }
7054 }
7055
7056 static int check_mem_size_reg(struct bpf_verifier_env *env,
7057                               struct bpf_reg_state *reg, u32 regno,
7058                               bool zero_size_allowed,
7059                               struct bpf_call_arg_meta *meta)
7060 {
7061         int err;
7062
7063         /* This is used to refine r0 return value bounds for helpers
7064          * that enforce this value as an upper bound on return values.
7065          * See do_refine_retval_range() for helpers that can refine
7066          * the return value. C type of helper is u32 so we pull register
7067          * bound from umax_value however, if negative verifier errors
7068          * out. Only upper bounds can be learned because retval is an
7069          * int type and negative retvals are allowed.
7070          */
7071         meta->msize_max_value = reg->umax_value;
7072
7073         /* The register is SCALAR_VALUE; the access check
7074          * happens using its boundaries.
7075          */
7076         if (!tnum_is_const(reg->var_off))
7077                 /* For unprivileged variable accesses, disable raw
7078                  * mode so that the program is required to
7079                  * initialize all the memory that the helper could
7080                  * just partially fill up.
7081                  */
7082                 meta = NULL;
7083
7084         if (reg->smin_value < 0) {
7085                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7086                         regno);
7087                 return -EACCES;
7088         }
7089
7090         if (reg->umin_value == 0) {
7091                 err = check_helper_mem_access(env, regno - 1, 0,
7092                                               zero_size_allowed,
7093                                               meta);
7094                 if (err)
7095                         return err;
7096         }
7097
7098         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7099                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7100                         regno);
7101                 return -EACCES;
7102         }
7103         err = check_helper_mem_access(env, regno - 1,
7104                                       reg->umax_value,
7105                                       zero_size_allowed, meta);
7106         if (!err)
7107                 err = mark_chain_precision(env, regno);
7108         return err;
7109 }
7110
7111 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7112                    u32 regno, u32 mem_size)
7113 {
7114         bool may_be_null = type_may_be_null(reg->type);
7115         struct bpf_reg_state saved_reg;
7116         struct bpf_call_arg_meta meta;
7117         int err;
7118
7119         if (register_is_null(reg))
7120                 return 0;
7121
7122         memset(&meta, 0, sizeof(meta));
7123         /* Assuming that the register contains a value check if the memory
7124          * access is safe. Temporarily save and restore the register's state as
7125          * the conversion shouldn't be visible to a caller.
7126          */
7127         if (may_be_null) {
7128                 saved_reg = *reg;
7129                 mark_ptr_not_null_reg(reg);
7130         }
7131
7132         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7133         /* Check access for BPF_WRITE */
7134         meta.raw_mode = true;
7135         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7136
7137         if (may_be_null)
7138                 *reg = saved_reg;
7139
7140         return err;
7141 }
7142
7143 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7144                                     u32 regno)
7145 {
7146         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7147         bool may_be_null = type_may_be_null(mem_reg->type);
7148         struct bpf_reg_state saved_reg;
7149         struct bpf_call_arg_meta meta;
7150         int err;
7151
7152         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7153
7154         memset(&meta, 0, sizeof(meta));
7155
7156         if (may_be_null) {
7157                 saved_reg = *mem_reg;
7158                 mark_ptr_not_null_reg(mem_reg);
7159         }
7160
7161         err = check_mem_size_reg(env, reg, regno, true, &meta);
7162         /* Check access for BPF_WRITE */
7163         meta.raw_mode = true;
7164         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7165
7166         if (may_be_null)
7167                 *mem_reg = saved_reg;
7168         return err;
7169 }
7170
7171 /* Implementation details:
7172  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7173  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7174  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7175  * Two separate bpf_obj_new will also have different reg->id.
7176  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7177  * clears reg->id after value_or_null->value transition, since the verifier only
7178  * cares about the range of access to valid map value pointer and doesn't care
7179  * about actual address of the map element.
7180  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7181  * reg->id > 0 after value_or_null->value transition. By doing so
7182  * two bpf_map_lookups will be considered two different pointers that
7183  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7184  * returned from bpf_obj_new.
7185  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7186  * dead-locks.
7187  * Since only one bpf_spin_lock is allowed the checks are simpler than
7188  * reg_is_refcounted() logic. The verifier needs to remember only
7189  * one spin_lock instead of array of acquired_refs.
7190  * cur_state->active_lock remembers which map value element or allocated
7191  * object got locked and clears it after bpf_spin_unlock.
7192  */
7193 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7194                              bool is_lock)
7195 {
7196         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7197         struct bpf_verifier_state *cur = env->cur_state;
7198         bool is_const = tnum_is_const(reg->var_off);
7199         u64 val = reg->var_off.value;
7200         struct bpf_map *map = NULL;
7201         struct btf *btf = NULL;
7202         struct btf_record *rec;
7203
7204         if (!is_const) {
7205                 verbose(env,
7206                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7207                         regno);
7208                 return -EINVAL;
7209         }
7210         if (reg->type == PTR_TO_MAP_VALUE) {
7211                 map = reg->map_ptr;
7212                 if (!map->btf) {
7213                         verbose(env,
7214                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7215                                 map->name);
7216                         return -EINVAL;
7217                 }
7218         } else {
7219                 btf = reg->btf;
7220         }
7221
7222         rec = reg_btf_record(reg);
7223         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7224                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7225                         map ? map->name : "kptr");
7226                 return -EINVAL;
7227         }
7228         if (rec->spin_lock_off != val + reg->off) {
7229                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7230                         val + reg->off, rec->spin_lock_off);
7231                 return -EINVAL;
7232         }
7233         if (is_lock) {
7234                 if (cur->active_lock.ptr) {
7235                         verbose(env,
7236                                 "Locking two bpf_spin_locks are not allowed\n");
7237                         return -EINVAL;
7238                 }
7239                 if (map)
7240                         cur->active_lock.ptr = map;
7241                 else
7242                         cur->active_lock.ptr = btf;
7243                 cur->active_lock.id = reg->id;
7244         } else {
7245                 void *ptr;
7246
7247                 if (map)
7248                         ptr = map;
7249                 else
7250                         ptr = btf;
7251
7252                 if (!cur->active_lock.ptr) {
7253                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7254                         return -EINVAL;
7255                 }
7256                 if (cur->active_lock.ptr != ptr ||
7257                     cur->active_lock.id != reg->id) {
7258                         verbose(env, "bpf_spin_unlock of different lock\n");
7259                         return -EINVAL;
7260                 }
7261
7262                 invalidate_non_owning_refs(env);
7263
7264                 cur->active_lock.ptr = NULL;
7265                 cur->active_lock.id = 0;
7266         }
7267         return 0;
7268 }
7269
7270 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7271                               struct bpf_call_arg_meta *meta)
7272 {
7273         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7274         bool is_const = tnum_is_const(reg->var_off);
7275         struct bpf_map *map = reg->map_ptr;
7276         u64 val = reg->var_off.value;
7277
7278         if (!is_const) {
7279                 verbose(env,
7280                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7281                         regno);
7282                 return -EINVAL;
7283         }
7284         if (!map->btf) {
7285                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7286                         map->name);
7287                 return -EINVAL;
7288         }
7289         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7290                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7291                 return -EINVAL;
7292         }
7293         if (map->record->timer_off != val + reg->off) {
7294                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7295                         val + reg->off, map->record->timer_off);
7296                 return -EINVAL;
7297         }
7298         if (meta->map_ptr) {
7299                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7300                 return -EFAULT;
7301         }
7302         meta->map_uid = reg->map_uid;
7303         meta->map_ptr = map;
7304         return 0;
7305 }
7306
7307 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7308                              struct bpf_call_arg_meta *meta)
7309 {
7310         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7311         struct bpf_map *map_ptr = reg->map_ptr;
7312         struct btf_field *kptr_field;
7313         u32 kptr_off;
7314
7315         if (!tnum_is_const(reg->var_off)) {
7316                 verbose(env,
7317                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7318                         regno);
7319                 return -EINVAL;
7320         }
7321         if (!map_ptr->btf) {
7322                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7323                         map_ptr->name);
7324                 return -EINVAL;
7325         }
7326         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7327                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7328                 return -EINVAL;
7329         }
7330
7331         meta->map_ptr = map_ptr;
7332         kptr_off = reg->off + reg->var_off.value;
7333         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7334         if (!kptr_field) {
7335                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7336                 return -EACCES;
7337         }
7338         if (kptr_field->type != BPF_KPTR_REF) {
7339                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7340                 return -EACCES;
7341         }
7342         meta->kptr_field = kptr_field;
7343         return 0;
7344 }
7345
7346 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7347  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7348  *
7349  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7350  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7351  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7352  *
7353  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7354  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7355  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7356  * mutate the view of the dynptr and also possibly destroy it. In the latter
7357  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7358  * memory that dynptr points to.
7359  *
7360  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7361  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7362  * readonly dynptr view yet, hence only the first case is tracked and checked.
7363  *
7364  * This is consistent with how C applies the const modifier to a struct object,
7365  * where the pointer itself inside bpf_dynptr becomes const but not what it
7366  * points to.
7367  *
7368  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7369  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7370  */
7371 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7372                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7373 {
7374         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7375         int err;
7376
7377         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7378          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7379          */
7380         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7381                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7382                 return -EFAULT;
7383         }
7384
7385         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7386          *               constructing a mutable bpf_dynptr object.
7387          *
7388          *               Currently, this is only possible with PTR_TO_STACK
7389          *               pointing to a region of at least 16 bytes which doesn't
7390          *               contain an existing bpf_dynptr.
7391          *
7392          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7393          *               mutated or destroyed. However, the memory it points to
7394          *               may be mutated.
7395          *
7396          *  None       - Points to a initialized dynptr that can be mutated and
7397          *               destroyed, including mutation of the memory it points
7398          *               to.
7399          */
7400         if (arg_type & MEM_UNINIT) {
7401                 int i;
7402
7403                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7404                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7405                         return -EINVAL;
7406                 }
7407
7408                 /* we write BPF_DW bits (8 bytes) at a time */
7409                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7410                         err = check_mem_access(env, insn_idx, regno,
7411                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7412                         if (err)
7413                                 return err;
7414                 }
7415
7416                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7417         } else /* MEM_RDONLY and None case from above */ {
7418                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7419                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7420                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7421                         return -EINVAL;
7422                 }
7423
7424                 if (!is_dynptr_reg_valid_init(env, reg)) {
7425                         verbose(env,
7426                                 "Expected an initialized dynptr as arg #%d\n",
7427                                 regno);
7428                         return -EINVAL;
7429                 }
7430
7431                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7432                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7433                         verbose(env,
7434                                 "Expected a dynptr of type %s as arg #%d\n",
7435                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7436                         return -EINVAL;
7437                 }
7438
7439                 err = mark_dynptr_read(env, reg);
7440         }
7441         return err;
7442 }
7443
7444 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7445 {
7446         struct bpf_func_state *state = func(env, reg);
7447
7448         return state->stack[spi].spilled_ptr.ref_obj_id;
7449 }
7450
7451 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7452 {
7453         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7454 }
7455
7456 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7457 {
7458         return meta->kfunc_flags & KF_ITER_NEW;
7459 }
7460
7461 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7462 {
7463         return meta->kfunc_flags & KF_ITER_NEXT;
7464 }
7465
7466 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7467 {
7468         return meta->kfunc_flags & KF_ITER_DESTROY;
7469 }
7470
7471 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7472 {
7473         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7474          * kfunc is iter state pointer
7475          */
7476         return arg == 0 && is_iter_kfunc(meta);
7477 }
7478
7479 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7480                             struct bpf_kfunc_call_arg_meta *meta)
7481 {
7482         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7483         const struct btf_type *t;
7484         const struct btf_param *arg;
7485         int spi, err, i, nr_slots;
7486         u32 btf_id;
7487
7488         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7489         arg = &btf_params(meta->func_proto)[0];
7490         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7491         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7492         nr_slots = t->size / BPF_REG_SIZE;
7493
7494         if (is_iter_new_kfunc(meta)) {
7495                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7496                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7497                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7498                                 iter_type_str(meta->btf, btf_id), regno);
7499                         return -EINVAL;
7500                 }
7501
7502                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7503                         err = check_mem_access(env, insn_idx, regno,
7504                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7505                         if (err)
7506                                 return err;
7507                 }
7508
7509                 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7510                 if (err)
7511                         return err;
7512         } else {
7513                 /* iter_next() or iter_destroy() expect initialized iter state*/
7514                 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7515                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7516                                 iter_type_str(meta->btf, btf_id), regno);
7517                         return -EINVAL;
7518                 }
7519
7520                 spi = iter_get_spi(env, reg, nr_slots);
7521                 if (spi < 0)
7522                         return spi;
7523
7524                 err = mark_iter_read(env, reg, spi, nr_slots);
7525                 if (err)
7526                         return err;
7527
7528                 /* remember meta->iter info for process_iter_next_call() */
7529                 meta->iter.spi = spi;
7530                 meta->iter.frameno = reg->frameno;
7531                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7532
7533                 if (is_iter_destroy_kfunc(meta)) {
7534                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7535                         if (err)
7536                                 return err;
7537                 }
7538         }
7539
7540         return 0;
7541 }
7542
7543 /* process_iter_next_call() is called when verifier gets to iterator's next
7544  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7545  * to it as just "iter_next()" in comments below.
7546  *
7547  * BPF verifier relies on a crucial contract for any iter_next()
7548  * implementation: it should *eventually* return NULL, and once that happens
7549  * it should keep returning NULL. That is, once iterator exhausts elements to
7550  * iterate, it should never reset or spuriously return new elements.
7551  *
7552  * With the assumption of such contract, process_iter_next_call() simulates
7553  * a fork in the verifier state to validate loop logic correctness and safety
7554  * without having to simulate infinite amount of iterations.
7555  *
7556  * In current state, we first assume that iter_next() returned NULL and
7557  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7558  * conditions we should not form an infinite loop and should eventually reach
7559  * exit.
7560  *
7561  * Besides that, we also fork current state and enqueue it for later
7562  * verification. In a forked state we keep iterator state as ACTIVE
7563  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7564  * also bump iteration depth to prevent erroneous infinite loop detection
7565  * later on (see iter_active_depths_differ() comment for details). In this
7566  * state we assume that we'll eventually loop back to another iter_next()
7567  * calls (it could be in exactly same location or in some other instruction,
7568  * it doesn't matter, we don't make any unnecessary assumptions about this,
7569  * everything revolves around iterator state in a stack slot, not which
7570  * instruction is calling iter_next()). When that happens, we either will come
7571  * to iter_next() with equivalent state and can conclude that next iteration
7572  * will proceed in exactly the same way as we just verified, so it's safe to
7573  * assume that loop converges. If not, we'll go on another iteration
7574  * simulation with a different input state, until all possible starting states
7575  * are validated or we reach maximum number of instructions limit.
7576  *
7577  * This way, we will either exhaustively discover all possible input states
7578  * that iterator loop can start with and eventually will converge, or we'll
7579  * effectively regress into bounded loop simulation logic and either reach
7580  * maximum number of instructions if loop is not provably convergent, or there
7581  * is some statically known limit on number of iterations (e.g., if there is
7582  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7583  *
7584  * One very subtle but very important aspect is that we *always* simulate NULL
7585  * condition first (as the current state) before we simulate non-NULL case.
7586  * This has to do with intricacies of scalar precision tracking. By simulating
7587  * "exit condition" of iter_next() returning NULL first, we make sure all the
7588  * relevant precision marks *that will be set **after** we exit iterator loop*
7589  * are propagated backwards to common parent state of NULL and non-NULL
7590  * branches. Thanks to that, state equivalence checks done later in forked
7591  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7592  * precision marks are finalized and won't change. Because simulating another
7593  * ACTIVE iterator iteration won't change them (because given same input
7594  * states we'll end up with exactly same output states which we are currently
7595  * comparing; and verification after the loop already propagated back what
7596  * needs to be **additionally** tracked as precise). It's subtle, grok
7597  * precision tracking for more intuitive understanding.
7598  */
7599 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7600                                   struct bpf_kfunc_call_arg_meta *meta)
7601 {
7602         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7603         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7604         struct bpf_reg_state *cur_iter, *queued_iter;
7605         int iter_frameno = meta->iter.frameno;
7606         int iter_spi = meta->iter.spi;
7607
7608         BTF_TYPE_EMIT(struct bpf_iter);
7609
7610         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7611
7612         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7613             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7614                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7615                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7616                 return -EFAULT;
7617         }
7618
7619         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7620                 /* branch out active iter state */
7621                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7622                 if (!queued_st)
7623                         return -ENOMEM;
7624
7625                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7626                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7627                 queued_iter->iter.depth++;
7628
7629                 queued_fr = queued_st->frame[queued_st->curframe];
7630                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7631         }
7632
7633         /* switch to DRAINED state, but keep the depth unchanged */
7634         /* mark current iter state as drained and assume returned NULL */
7635         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7636         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7637
7638         return 0;
7639 }
7640
7641 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7642 {
7643         return type == ARG_CONST_SIZE ||
7644                type == ARG_CONST_SIZE_OR_ZERO;
7645 }
7646
7647 static bool arg_type_is_release(enum bpf_arg_type type)
7648 {
7649         return type & OBJ_RELEASE;
7650 }
7651
7652 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7653 {
7654         return base_type(type) == ARG_PTR_TO_DYNPTR;
7655 }
7656
7657 static int int_ptr_type_to_size(enum bpf_arg_type type)
7658 {
7659         if (type == ARG_PTR_TO_INT)
7660                 return sizeof(u32);
7661         else if (type == ARG_PTR_TO_LONG)
7662                 return sizeof(u64);
7663
7664         return -EINVAL;
7665 }
7666
7667 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7668                                  const struct bpf_call_arg_meta *meta,
7669                                  enum bpf_arg_type *arg_type)
7670 {
7671         if (!meta->map_ptr) {
7672                 /* kernel subsystem misconfigured verifier */
7673                 verbose(env, "invalid map_ptr to access map->type\n");
7674                 return -EACCES;
7675         }
7676
7677         switch (meta->map_ptr->map_type) {
7678         case BPF_MAP_TYPE_SOCKMAP:
7679         case BPF_MAP_TYPE_SOCKHASH:
7680                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7681                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7682                 } else {
7683                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
7684                         return -EINVAL;
7685                 }
7686                 break;
7687         case BPF_MAP_TYPE_BLOOM_FILTER:
7688                 if (meta->func_id == BPF_FUNC_map_peek_elem)
7689                         *arg_type = ARG_PTR_TO_MAP_VALUE;
7690                 break;
7691         default:
7692                 break;
7693         }
7694         return 0;
7695 }
7696
7697 struct bpf_reg_types {
7698         const enum bpf_reg_type types[10];
7699         u32 *btf_id;
7700 };
7701
7702 static const struct bpf_reg_types sock_types = {
7703         .types = {
7704                 PTR_TO_SOCK_COMMON,
7705                 PTR_TO_SOCKET,
7706                 PTR_TO_TCP_SOCK,
7707                 PTR_TO_XDP_SOCK,
7708         },
7709 };
7710
7711 #ifdef CONFIG_NET
7712 static const struct bpf_reg_types btf_id_sock_common_types = {
7713         .types = {
7714                 PTR_TO_SOCK_COMMON,
7715                 PTR_TO_SOCKET,
7716                 PTR_TO_TCP_SOCK,
7717                 PTR_TO_XDP_SOCK,
7718                 PTR_TO_BTF_ID,
7719                 PTR_TO_BTF_ID | PTR_TRUSTED,
7720         },
7721         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7722 };
7723 #endif
7724
7725 static const struct bpf_reg_types mem_types = {
7726         .types = {
7727                 PTR_TO_STACK,
7728                 PTR_TO_PACKET,
7729                 PTR_TO_PACKET_META,
7730                 PTR_TO_MAP_KEY,
7731                 PTR_TO_MAP_VALUE,
7732                 PTR_TO_MEM,
7733                 PTR_TO_MEM | MEM_RINGBUF,
7734                 PTR_TO_BUF,
7735                 PTR_TO_BTF_ID | PTR_TRUSTED,
7736         },
7737 };
7738
7739 static const struct bpf_reg_types int_ptr_types = {
7740         .types = {
7741                 PTR_TO_STACK,
7742                 PTR_TO_PACKET,
7743                 PTR_TO_PACKET_META,
7744                 PTR_TO_MAP_KEY,
7745                 PTR_TO_MAP_VALUE,
7746         },
7747 };
7748
7749 static const struct bpf_reg_types spin_lock_types = {
7750         .types = {
7751                 PTR_TO_MAP_VALUE,
7752                 PTR_TO_BTF_ID | MEM_ALLOC,
7753         }
7754 };
7755
7756 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7757 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7758 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7759 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7760 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7761 static const struct bpf_reg_types btf_ptr_types = {
7762         .types = {
7763                 PTR_TO_BTF_ID,
7764                 PTR_TO_BTF_ID | PTR_TRUSTED,
7765                 PTR_TO_BTF_ID | MEM_RCU,
7766         },
7767 };
7768 static const struct bpf_reg_types percpu_btf_ptr_types = {
7769         .types = {
7770                 PTR_TO_BTF_ID | MEM_PERCPU,
7771                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7772         }
7773 };
7774 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7775 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7776 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7777 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7778 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7779 static const struct bpf_reg_types dynptr_types = {
7780         .types = {
7781                 PTR_TO_STACK,
7782                 CONST_PTR_TO_DYNPTR,
7783         }
7784 };
7785
7786 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7787         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
7788         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
7789         [ARG_CONST_SIZE]                = &scalar_types,
7790         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
7791         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
7792         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
7793         [ARG_PTR_TO_CTX]                = &context_types,
7794         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
7795 #ifdef CONFIG_NET
7796         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7797 #endif
7798         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
7799         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
7800         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
7801         [ARG_PTR_TO_MEM]                = &mem_types,
7802         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
7803         [ARG_PTR_TO_INT]                = &int_ptr_types,
7804         [ARG_PTR_TO_LONG]               = &int_ptr_types,
7805         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
7806         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
7807         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
7808         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
7809         [ARG_PTR_TO_TIMER]              = &timer_types,
7810         [ARG_PTR_TO_KPTR]               = &kptr_types,
7811         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
7812 };
7813
7814 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7815                           enum bpf_arg_type arg_type,
7816                           const u32 *arg_btf_id,
7817                           struct bpf_call_arg_meta *meta)
7818 {
7819         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7820         enum bpf_reg_type expected, type = reg->type;
7821         const struct bpf_reg_types *compatible;
7822         int i, j;
7823
7824         compatible = compatible_reg_types[base_type(arg_type)];
7825         if (!compatible) {
7826                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7827                 return -EFAULT;
7828         }
7829
7830         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7831          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7832          *
7833          * Same for MAYBE_NULL:
7834          *
7835          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7836          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7837          *
7838          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7839          *
7840          * Therefore we fold these flags depending on the arg_type before comparison.
7841          */
7842         if (arg_type & MEM_RDONLY)
7843                 type &= ~MEM_RDONLY;
7844         if (arg_type & PTR_MAYBE_NULL)
7845                 type &= ~PTR_MAYBE_NULL;
7846         if (base_type(arg_type) == ARG_PTR_TO_MEM)
7847                 type &= ~DYNPTR_TYPE_FLAG_MASK;
7848
7849         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7850                 type &= ~MEM_ALLOC;
7851
7852         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7853                 expected = compatible->types[i];
7854                 if (expected == NOT_INIT)
7855                         break;
7856
7857                 if (type == expected)
7858                         goto found;
7859         }
7860
7861         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7862         for (j = 0; j + 1 < i; j++)
7863                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7864         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7865         return -EACCES;
7866
7867 found:
7868         if (base_type(reg->type) != PTR_TO_BTF_ID)
7869                 return 0;
7870
7871         if (compatible == &mem_types) {
7872                 if (!(arg_type & MEM_RDONLY)) {
7873                         verbose(env,
7874                                 "%s() may write into memory pointed by R%d type=%s\n",
7875                                 func_id_name(meta->func_id),
7876                                 regno, reg_type_str(env, reg->type));
7877                         return -EACCES;
7878                 }
7879                 return 0;
7880         }
7881
7882         switch ((int)reg->type) {
7883         case PTR_TO_BTF_ID:
7884         case PTR_TO_BTF_ID | PTR_TRUSTED:
7885         case PTR_TO_BTF_ID | MEM_RCU:
7886         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7887         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7888         {
7889                 /* For bpf_sk_release, it needs to match against first member
7890                  * 'struct sock_common', hence make an exception for it. This
7891                  * allows bpf_sk_release to work for multiple socket types.
7892                  */
7893                 bool strict_type_match = arg_type_is_release(arg_type) &&
7894                                          meta->func_id != BPF_FUNC_sk_release;
7895
7896                 if (type_may_be_null(reg->type) &&
7897                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7898                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7899                         return -EACCES;
7900                 }
7901
7902                 if (!arg_btf_id) {
7903                         if (!compatible->btf_id) {
7904                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7905                                 return -EFAULT;
7906                         }
7907                         arg_btf_id = compatible->btf_id;
7908                 }
7909
7910                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7911                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7912                                 return -EACCES;
7913                 } else {
7914                         if (arg_btf_id == BPF_PTR_POISON) {
7915                                 verbose(env, "verifier internal error:");
7916                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7917                                         regno);
7918                                 return -EACCES;
7919                         }
7920
7921                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7922                                                   btf_vmlinux, *arg_btf_id,
7923                                                   strict_type_match)) {
7924                                 verbose(env, "R%d is of type %s but %s is expected\n",
7925                                         regno, btf_type_name(reg->btf, reg->btf_id),
7926                                         btf_type_name(btf_vmlinux, *arg_btf_id));
7927                                 return -EACCES;
7928                         }
7929                 }
7930                 break;
7931         }
7932         case PTR_TO_BTF_ID | MEM_ALLOC:
7933                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7934                     meta->func_id != BPF_FUNC_kptr_xchg) {
7935                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7936                         return -EFAULT;
7937                 }
7938                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7939                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7940                                 return -EACCES;
7941                 }
7942                 break;
7943         case PTR_TO_BTF_ID | MEM_PERCPU:
7944         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7945                 /* Handled by helper specific checks */
7946                 break;
7947         default:
7948                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7949                 return -EFAULT;
7950         }
7951         return 0;
7952 }
7953
7954 static struct btf_field *
7955 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7956 {
7957         struct btf_field *field;
7958         struct btf_record *rec;
7959
7960         rec = reg_btf_record(reg);
7961         if (!rec)
7962                 return NULL;
7963
7964         field = btf_record_find(rec, off, fields);
7965         if (!field)
7966                 return NULL;
7967
7968         return field;
7969 }
7970
7971 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7972                            const struct bpf_reg_state *reg, int regno,
7973                            enum bpf_arg_type arg_type)
7974 {
7975         u32 type = reg->type;
7976
7977         /* When referenced register is passed to release function, its fixed
7978          * offset must be 0.
7979          *
7980          * We will check arg_type_is_release reg has ref_obj_id when storing
7981          * meta->release_regno.
7982          */
7983         if (arg_type_is_release(arg_type)) {
7984                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7985                  * may not directly point to the object being released, but to
7986                  * dynptr pointing to such object, which might be at some offset
7987                  * on the stack. In that case, we simply to fallback to the
7988                  * default handling.
7989                  */
7990                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7991                         return 0;
7992
7993                 /* Doing check_ptr_off_reg check for the offset will catch this
7994                  * because fixed_off_ok is false, but checking here allows us
7995                  * to give the user a better error message.
7996                  */
7997                 if (reg->off) {
7998                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7999                                 regno);
8000                         return -EINVAL;
8001                 }
8002                 return __check_ptr_off_reg(env, reg, regno, false);
8003         }
8004
8005         switch (type) {
8006         /* Pointer types where both fixed and variable offset is explicitly allowed: */
8007         case PTR_TO_STACK:
8008         case PTR_TO_PACKET:
8009         case PTR_TO_PACKET_META:
8010         case PTR_TO_MAP_KEY:
8011         case PTR_TO_MAP_VALUE:
8012         case PTR_TO_MEM:
8013         case PTR_TO_MEM | MEM_RDONLY:
8014         case PTR_TO_MEM | MEM_RINGBUF:
8015         case PTR_TO_BUF:
8016         case PTR_TO_BUF | MEM_RDONLY:
8017         case SCALAR_VALUE:
8018                 return 0;
8019         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8020          * fixed offset.
8021          */
8022         case PTR_TO_BTF_ID:
8023         case PTR_TO_BTF_ID | MEM_ALLOC:
8024         case PTR_TO_BTF_ID | PTR_TRUSTED:
8025         case PTR_TO_BTF_ID | MEM_RCU:
8026         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8027         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8028                 /* When referenced PTR_TO_BTF_ID is passed to release function,
8029                  * its fixed offset must be 0. In the other cases, fixed offset
8030                  * can be non-zero. This was already checked above. So pass
8031                  * fixed_off_ok as true to allow fixed offset for all other
8032                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8033                  * still need to do checks instead of returning.
8034                  */
8035                 return __check_ptr_off_reg(env, reg, regno, true);
8036         default:
8037                 return __check_ptr_off_reg(env, reg, regno, false);
8038         }
8039 }
8040
8041 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8042                                                 const struct bpf_func_proto *fn,
8043                                                 struct bpf_reg_state *regs)
8044 {
8045         struct bpf_reg_state *state = NULL;
8046         int i;
8047
8048         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8049                 if (arg_type_is_dynptr(fn->arg_type[i])) {
8050                         if (state) {
8051                                 verbose(env, "verifier internal error: multiple dynptr args\n");
8052                                 return NULL;
8053                         }
8054                         state = &regs[BPF_REG_1 + i];
8055                 }
8056
8057         if (!state)
8058                 verbose(env, "verifier internal error: no dynptr arg found\n");
8059
8060         return state;
8061 }
8062
8063 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8064 {
8065         struct bpf_func_state *state = func(env, reg);
8066         int spi;
8067
8068         if (reg->type == CONST_PTR_TO_DYNPTR)
8069                 return reg->id;
8070         spi = dynptr_get_spi(env, reg);
8071         if (spi < 0)
8072                 return spi;
8073         return state->stack[spi].spilled_ptr.id;
8074 }
8075
8076 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8077 {
8078         struct bpf_func_state *state = func(env, reg);
8079         int spi;
8080
8081         if (reg->type == CONST_PTR_TO_DYNPTR)
8082                 return reg->ref_obj_id;
8083         spi = dynptr_get_spi(env, reg);
8084         if (spi < 0)
8085                 return spi;
8086         return state->stack[spi].spilled_ptr.ref_obj_id;
8087 }
8088
8089 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8090                                             struct bpf_reg_state *reg)
8091 {
8092         struct bpf_func_state *state = func(env, reg);
8093         int spi;
8094
8095         if (reg->type == CONST_PTR_TO_DYNPTR)
8096                 return reg->dynptr.type;
8097
8098         spi = __get_spi(reg->off);
8099         if (spi < 0) {
8100                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8101                 return BPF_DYNPTR_TYPE_INVALID;
8102         }
8103
8104         return state->stack[spi].spilled_ptr.dynptr.type;
8105 }
8106
8107 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8108                           struct bpf_call_arg_meta *meta,
8109                           const struct bpf_func_proto *fn,
8110                           int insn_idx)
8111 {
8112         u32 regno = BPF_REG_1 + arg;
8113         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8114         enum bpf_arg_type arg_type = fn->arg_type[arg];
8115         enum bpf_reg_type type = reg->type;
8116         u32 *arg_btf_id = NULL;
8117         int err = 0;
8118
8119         if (arg_type == ARG_DONTCARE)
8120                 return 0;
8121
8122         err = check_reg_arg(env, regno, SRC_OP);
8123         if (err)
8124                 return err;
8125
8126         if (arg_type == ARG_ANYTHING) {
8127                 if (is_pointer_value(env, regno)) {
8128                         verbose(env, "R%d leaks addr into helper function\n",
8129                                 regno);
8130                         return -EACCES;
8131                 }
8132                 return 0;
8133         }
8134
8135         if (type_is_pkt_pointer(type) &&
8136             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8137                 verbose(env, "helper access to the packet is not allowed\n");
8138                 return -EACCES;
8139         }
8140
8141         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8142                 err = resolve_map_arg_type(env, meta, &arg_type);
8143                 if (err)
8144                         return err;
8145         }
8146
8147         if (register_is_null(reg) && type_may_be_null(arg_type))
8148                 /* A NULL register has a SCALAR_VALUE type, so skip
8149                  * type checking.
8150                  */
8151                 goto skip_type_check;
8152
8153         /* arg_btf_id and arg_size are in a union. */
8154         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8155             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8156                 arg_btf_id = fn->arg_btf_id[arg];
8157
8158         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8159         if (err)
8160                 return err;
8161
8162         err = check_func_arg_reg_off(env, reg, regno, arg_type);
8163         if (err)
8164                 return err;
8165
8166 skip_type_check:
8167         if (arg_type_is_release(arg_type)) {
8168                 if (arg_type_is_dynptr(arg_type)) {
8169                         struct bpf_func_state *state = func(env, reg);
8170                         int spi;
8171
8172                         /* Only dynptr created on stack can be released, thus
8173                          * the get_spi and stack state checks for spilled_ptr
8174                          * should only be done before process_dynptr_func for
8175                          * PTR_TO_STACK.
8176                          */
8177                         if (reg->type == PTR_TO_STACK) {
8178                                 spi = dynptr_get_spi(env, reg);
8179                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8180                                         verbose(env, "arg %d is an unacquired reference\n", regno);
8181                                         return -EINVAL;
8182                                 }
8183                         } else {
8184                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8185                                 return -EINVAL;
8186                         }
8187                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8188                         verbose(env, "R%d must be referenced when passed to release function\n",
8189                                 regno);
8190                         return -EINVAL;
8191                 }
8192                 if (meta->release_regno) {
8193                         verbose(env, "verifier internal error: more than one release argument\n");
8194                         return -EFAULT;
8195                 }
8196                 meta->release_regno = regno;
8197         }
8198
8199         if (reg->ref_obj_id) {
8200                 if (meta->ref_obj_id) {
8201                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8202                                 regno, reg->ref_obj_id,
8203                                 meta->ref_obj_id);
8204                         return -EFAULT;
8205                 }
8206                 meta->ref_obj_id = reg->ref_obj_id;
8207         }
8208
8209         switch (base_type(arg_type)) {
8210         case ARG_CONST_MAP_PTR:
8211                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8212                 if (meta->map_ptr) {
8213                         /* Use map_uid (which is unique id of inner map) to reject:
8214                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8215                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8216                          * if (inner_map1 && inner_map2) {
8217                          *     timer = bpf_map_lookup_elem(inner_map1);
8218                          *     if (timer)
8219                          *         // mismatch would have been allowed
8220                          *         bpf_timer_init(timer, inner_map2);
8221                          * }
8222                          *
8223                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8224                          */
8225                         if (meta->map_ptr != reg->map_ptr ||
8226                             meta->map_uid != reg->map_uid) {
8227                                 verbose(env,
8228                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8229                                         meta->map_uid, reg->map_uid);
8230                                 return -EINVAL;
8231                         }
8232                 }
8233                 meta->map_ptr = reg->map_ptr;
8234                 meta->map_uid = reg->map_uid;
8235                 break;
8236         case ARG_PTR_TO_MAP_KEY:
8237                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8238                  * check that [key, key + map->key_size) are within
8239                  * stack limits and initialized
8240                  */
8241                 if (!meta->map_ptr) {
8242                         /* in function declaration map_ptr must come before
8243                          * map_key, so that it's verified and known before
8244                          * we have to check map_key here. Otherwise it means
8245                          * that kernel subsystem misconfigured verifier
8246                          */
8247                         verbose(env, "invalid map_ptr to access map->key\n");
8248                         return -EACCES;
8249                 }
8250                 err = check_helper_mem_access(env, regno,
8251                                               meta->map_ptr->key_size, false,
8252                                               NULL);
8253                 break;
8254         case ARG_PTR_TO_MAP_VALUE:
8255                 if (type_may_be_null(arg_type) && register_is_null(reg))
8256                         return 0;
8257
8258                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8259                  * check [value, value + map->value_size) validity
8260                  */
8261                 if (!meta->map_ptr) {
8262                         /* kernel subsystem misconfigured verifier */
8263                         verbose(env, "invalid map_ptr to access map->value\n");
8264                         return -EACCES;
8265                 }
8266                 meta->raw_mode = arg_type & MEM_UNINIT;
8267                 err = check_helper_mem_access(env, regno,
8268                                               meta->map_ptr->value_size, false,
8269                                               meta);
8270                 break;
8271         case ARG_PTR_TO_PERCPU_BTF_ID:
8272                 if (!reg->btf_id) {
8273                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8274                         return -EACCES;
8275                 }
8276                 meta->ret_btf = reg->btf;
8277                 meta->ret_btf_id = reg->btf_id;
8278                 break;
8279         case ARG_PTR_TO_SPIN_LOCK:
8280                 if (in_rbtree_lock_required_cb(env)) {
8281                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8282                         return -EACCES;
8283                 }
8284                 if (meta->func_id == BPF_FUNC_spin_lock) {
8285                         err = process_spin_lock(env, regno, true);
8286                         if (err)
8287                                 return err;
8288                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8289                         err = process_spin_lock(env, regno, false);
8290                         if (err)
8291                                 return err;
8292                 } else {
8293                         verbose(env, "verifier internal error\n");
8294                         return -EFAULT;
8295                 }
8296                 break;
8297         case ARG_PTR_TO_TIMER:
8298                 err = process_timer_func(env, regno, meta);
8299                 if (err)
8300                         return err;
8301                 break;
8302         case ARG_PTR_TO_FUNC:
8303                 meta->subprogno = reg->subprogno;
8304                 break;
8305         case ARG_PTR_TO_MEM:
8306                 /* The access to this pointer is only checked when we hit the
8307                  * next is_mem_size argument below.
8308                  */
8309                 meta->raw_mode = arg_type & MEM_UNINIT;
8310                 if (arg_type & MEM_FIXED_SIZE) {
8311                         err = check_helper_mem_access(env, regno,
8312                                                       fn->arg_size[arg], false,
8313                                                       meta);
8314                 }
8315                 break;
8316         case ARG_CONST_SIZE:
8317                 err = check_mem_size_reg(env, reg, regno, false, meta);
8318                 break;
8319         case ARG_CONST_SIZE_OR_ZERO:
8320                 err = check_mem_size_reg(env, reg, regno, true, meta);
8321                 break;
8322         case ARG_PTR_TO_DYNPTR:
8323                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8324                 if (err)
8325                         return err;
8326                 break;
8327         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8328                 if (!tnum_is_const(reg->var_off)) {
8329                         verbose(env, "R%d is not a known constant'\n",
8330                                 regno);
8331                         return -EACCES;
8332                 }
8333                 meta->mem_size = reg->var_off.value;
8334                 err = mark_chain_precision(env, regno);
8335                 if (err)
8336                         return err;
8337                 break;
8338         case ARG_PTR_TO_INT:
8339         case ARG_PTR_TO_LONG:
8340         {
8341                 int size = int_ptr_type_to_size(arg_type);
8342
8343                 err = check_helper_mem_access(env, regno, size, false, meta);
8344                 if (err)
8345                         return err;
8346                 err = check_ptr_alignment(env, reg, 0, size, true);
8347                 break;
8348         }
8349         case ARG_PTR_TO_CONST_STR:
8350         {
8351                 struct bpf_map *map = reg->map_ptr;
8352                 int map_off;
8353                 u64 map_addr;
8354                 char *str_ptr;
8355
8356                 if (!bpf_map_is_rdonly(map)) {
8357                         verbose(env, "R%d does not point to a readonly map'\n", regno);
8358                         return -EACCES;
8359                 }
8360
8361                 if (!tnum_is_const(reg->var_off)) {
8362                         verbose(env, "R%d is not a constant address'\n", regno);
8363                         return -EACCES;
8364                 }
8365
8366                 if (!map->ops->map_direct_value_addr) {
8367                         verbose(env, "no direct value access support for this map type\n");
8368                         return -EACCES;
8369                 }
8370
8371                 err = check_map_access(env, regno, reg->off,
8372                                        map->value_size - reg->off, false,
8373                                        ACCESS_HELPER);
8374                 if (err)
8375                         return err;
8376
8377                 map_off = reg->off + reg->var_off.value;
8378                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8379                 if (err) {
8380                         verbose(env, "direct value access on string failed\n");
8381                         return err;
8382                 }
8383
8384                 str_ptr = (char *)(long)(map_addr);
8385                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8386                         verbose(env, "string is not zero-terminated\n");
8387                         return -EINVAL;
8388                 }
8389                 break;
8390         }
8391         case ARG_PTR_TO_KPTR:
8392                 err = process_kptr_func(env, regno, meta);
8393                 if (err)
8394                         return err;
8395                 break;
8396         }
8397
8398         return err;
8399 }
8400
8401 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8402 {
8403         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8404         enum bpf_prog_type type = resolve_prog_type(env->prog);
8405
8406         if (func_id != BPF_FUNC_map_update_elem)
8407                 return false;
8408
8409         /* It's not possible to get access to a locked struct sock in these
8410          * contexts, so updating is safe.
8411          */
8412         switch (type) {
8413         case BPF_PROG_TYPE_TRACING:
8414                 if (eatype == BPF_TRACE_ITER)
8415                         return true;
8416                 break;
8417         case BPF_PROG_TYPE_SOCKET_FILTER:
8418         case BPF_PROG_TYPE_SCHED_CLS:
8419         case BPF_PROG_TYPE_SCHED_ACT:
8420         case BPF_PROG_TYPE_XDP:
8421         case BPF_PROG_TYPE_SK_REUSEPORT:
8422         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8423         case BPF_PROG_TYPE_SK_LOOKUP:
8424                 return true;
8425         default:
8426                 break;
8427         }
8428
8429         verbose(env, "cannot update sockmap in this context\n");
8430         return false;
8431 }
8432
8433 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8434 {
8435         return env->prog->jit_requested &&
8436                bpf_jit_supports_subprog_tailcalls();
8437 }
8438
8439 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8440                                         struct bpf_map *map, int func_id)
8441 {
8442         if (!map)
8443                 return 0;
8444
8445         /* We need a two way check, first is from map perspective ... */
8446         switch (map->map_type) {
8447         case BPF_MAP_TYPE_PROG_ARRAY:
8448                 if (func_id != BPF_FUNC_tail_call)
8449                         goto error;
8450                 break;
8451         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8452                 if (func_id != BPF_FUNC_perf_event_read &&
8453                     func_id != BPF_FUNC_perf_event_output &&
8454                     func_id != BPF_FUNC_skb_output &&
8455                     func_id != BPF_FUNC_perf_event_read_value &&
8456                     func_id != BPF_FUNC_xdp_output)
8457                         goto error;
8458                 break;
8459         case BPF_MAP_TYPE_RINGBUF:
8460                 if (func_id != BPF_FUNC_ringbuf_output &&
8461                     func_id != BPF_FUNC_ringbuf_reserve &&
8462                     func_id != BPF_FUNC_ringbuf_query &&
8463                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8464                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8465                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8466                         goto error;
8467                 break;
8468         case BPF_MAP_TYPE_USER_RINGBUF:
8469                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8470                         goto error;
8471                 break;
8472         case BPF_MAP_TYPE_STACK_TRACE:
8473                 if (func_id != BPF_FUNC_get_stackid)
8474                         goto error;
8475                 break;
8476         case BPF_MAP_TYPE_CGROUP_ARRAY:
8477                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8478                     func_id != BPF_FUNC_current_task_under_cgroup)
8479                         goto error;
8480                 break;
8481         case BPF_MAP_TYPE_CGROUP_STORAGE:
8482         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8483                 if (func_id != BPF_FUNC_get_local_storage)
8484                         goto error;
8485                 break;
8486         case BPF_MAP_TYPE_DEVMAP:
8487         case BPF_MAP_TYPE_DEVMAP_HASH:
8488                 if (func_id != BPF_FUNC_redirect_map &&
8489                     func_id != BPF_FUNC_map_lookup_elem)
8490                         goto error;
8491                 break;
8492         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8493          * appear.
8494          */
8495         case BPF_MAP_TYPE_CPUMAP:
8496                 if (func_id != BPF_FUNC_redirect_map)
8497                         goto error;
8498                 break;
8499         case BPF_MAP_TYPE_XSKMAP:
8500                 if (func_id != BPF_FUNC_redirect_map &&
8501                     func_id != BPF_FUNC_map_lookup_elem)
8502                         goto error;
8503                 break;
8504         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8505         case BPF_MAP_TYPE_HASH_OF_MAPS:
8506                 if (func_id != BPF_FUNC_map_lookup_elem)
8507                         goto error;
8508                 break;
8509         case BPF_MAP_TYPE_SOCKMAP:
8510                 if (func_id != BPF_FUNC_sk_redirect_map &&
8511                     func_id != BPF_FUNC_sock_map_update &&
8512                     func_id != BPF_FUNC_map_delete_elem &&
8513                     func_id != BPF_FUNC_msg_redirect_map &&
8514                     func_id != BPF_FUNC_sk_select_reuseport &&
8515                     func_id != BPF_FUNC_map_lookup_elem &&
8516                     !may_update_sockmap(env, func_id))
8517                         goto error;
8518                 break;
8519         case BPF_MAP_TYPE_SOCKHASH:
8520                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8521                     func_id != BPF_FUNC_sock_hash_update &&
8522                     func_id != BPF_FUNC_map_delete_elem &&
8523                     func_id != BPF_FUNC_msg_redirect_hash &&
8524                     func_id != BPF_FUNC_sk_select_reuseport &&
8525                     func_id != BPF_FUNC_map_lookup_elem &&
8526                     !may_update_sockmap(env, func_id))
8527                         goto error;
8528                 break;
8529         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8530                 if (func_id != BPF_FUNC_sk_select_reuseport)
8531                         goto error;
8532                 break;
8533         case BPF_MAP_TYPE_QUEUE:
8534         case BPF_MAP_TYPE_STACK:
8535                 if (func_id != BPF_FUNC_map_peek_elem &&
8536                     func_id != BPF_FUNC_map_pop_elem &&
8537                     func_id != BPF_FUNC_map_push_elem)
8538                         goto error;
8539                 break;
8540         case BPF_MAP_TYPE_SK_STORAGE:
8541                 if (func_id != BPF_FUNC_sk_storage_get &&
8542                     func_id != BPF_FUNC_sk_storage_delete &&
8543                     func_id != BPF_FUNC_kptr_xchg)
8544                         goto error;
8545                 break;
8546         case BPF_MAP_TYPE_INODE_STORAGE:
8547                 if (func_id != BPF_FUNC_inode_storage_get &&
8548                     func_id != BPF_FUNC_inode_storage_delete &&
8549                     func_id != BPF_FUNC_kptr_xchg)
8550                         goto error;
8551                 break;
8552         case BPF_MAP_TYPE_TASK_STORAGE:
8553                 if (func_id != BPF_FUNC_task_storage_get &&
8554                     func_id != BPF_FUNC_task_storage_delete &&
8555                     func_id != BPF_FUNC_kptr_xchg)
8556                         goto error;
8557                 break;
8558         case BPF_MAP_TYPE_CGRP_STORAGE:
8559                 if (func_id != BPF_FUNC_cgrp_storage_get &&
8560                     func_id != BPF_FUNC_cgrp_storage_delete &&
8561                     func_id != BPF_FUNC_kptr_xchg)
8562                         goto error;
8563                 break;
8564         case BPF_MAP_TYPE_BLOOM_FILTER:
8565                 if (func_id != BPF_FUNC_map_peek_elem &&
8566                     func_id != BPF_FUNC_map_push_elem)
8567                         goto error;
8568                 break;
8569         default:
8570                 break;
8571         }
8572
8573         /* ... and second from the function itself. */
8574         switch (func_id) {
8575         case BPF_FUNC_tail_call:
8576                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8577                         goto error;
8578                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8579                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8580                         return -EINVAL;
8581                 }
8582                 break;
8583         case BPF_FUNC_perf_event_read:
8584         case BPF_FUNC_perf_event_output:
8585         case BPF_FUNC_perf_event_read_value:
8586         case BPF_FUNC_skb_output:
8587         case BPF_FUNC_xdp_output:
8588                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8589                         goto error;
8590                 break;
8591         case BPF_FUNC_ringbuf_output:
8592         case BPF_FUNC_ringbuf_reserve:
8593         case BPF_FUNC_ringbuf_query:
8594         case BPF_FUNC_ringbuf_reserve_dynptr:
8595         case BPF_FUNC_ringbuf_submit_dynptr:
8596         case BPF_FUNC_ringbuf_discard_dynptr:
8597                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8598                         goto error;
8599                 break;
8600         case BPF_FUNC_user_ringbuf_drain:
8601                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8602                         goto error;
8603                 break;
8604         case BPF_FUNC_get_stackid:
8605                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8606                         goto error;
8607                 break;
8608         case BPF_FUNC_current_task_under_cgroup:
8609         case BPF_FUNC_skb_under_cgroup:
8610                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8611                         goto error;
8612                 break;
8613         case BPF_FUNC_redirect_map:
8614                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8615                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8616                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
8617                     map->map_type != BPF_MAP_TYPE_XSKMAP)
8618                         goto error;
8619                 break;
8620         case BPF_FUNC_sk_redirect_map:
8621         case BPF_FUNC_msg_redirect_map:
8622         case BPF_FUNC_sock_map_update:
8623                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8624                         goto error;
8625                 break;
8626         case BPF_FUNC_sk_redirect_hash:
8627         case BPF_FUNC_msg_redirect_hash:
8628         case BPF_FUNC_sock_hash_update:
8629                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8630                         goto error;
8631                 break;
8632         case BPF_FUNC_get_local_storage:
8633                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8634                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8635                         goto error;
8636                 break;
8637         case BPF_FUNC_sk_select_reuseport:
8638                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8639                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8640                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
8641                         goto error;
8642                 break;
8643         case BPF_FUNC_map_pop_elem:
8644                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8645                     map->map_type != BPF_MAP_TYPE_STACK)
8646                         goto error;
8647                 break;
8648         case BPF_FUNC_map_peek_elem:
8649         case BPF_FUNC_map_push_elem:
8650                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8651                     map->map_type != BPF_MAP_TYPE_STACK &&
8652                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8653                         goto error;
8654                 break;
8655         case BPF_FUNC_map_lookup_percpu_elem:
8656                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8657                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8658                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8659                         goto error;
8660                 break;
8661         case BPF_FUNC_sk_storage_get:
8662         case BPF_FUNC_sk_storage_delete:
8663                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8664                         goto error;
8665                 break;
8666         case BPF_FUNC_inode_storage_get:
8667         case BPF_FUNC_inode_storage_delete:
8668                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8669                         goto error;
8670                 break;
8671         case BPF_FUNC_task_storage_get:
8672         case BPF_FUNC_task_storage_delete:
8673                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8674                         goto error;
8675                 break;
8676         case BPF_FUNC_cgrp_storage_get:
8677         case BPF_FUNC_cgrp_storage_delete:
8678                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8679                         goto error;
8680                 break;
8681         default:
8682                 break;
8683         }
8684
8685         return 0;
8686 error:
8687         verbose(env, "cannot pass map_type %d into func %s#%d\n",
8688                 map->map_type, func_id_name(func_id), func_id);
8689         return -EINVAL;
8690 }
8691
8692 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8693 {
8694         int count = 0;
8695
8696         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8697                 count++;
8698         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8699                 count++;
8700         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8701                 count++;
8702         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8703                 count++;
8704         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8705                 count++;
8706
8707         /* We only support one arg being in raw mode at the moment,
8708          * which is sufficient for the helper functions we have
8709          * right now.
8710          */
8711         return count <= 1;
8712 }
8713
8714 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8715 {
8716         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8717         bool has_size = fn->arg_size[arg] != 0;
8718         bool is_next_size = false;
8719
8720         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8721                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8722
8723         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8724                 return is_next_size;
8725
8726         return has_size == is_next_size || is_next_size == is_fixed;
8727 }
8728
8729 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8730 {
8731         /* bpf_xxx(..., buf, len) call will access 'len'
8732          * bytes from memory 'buf'. Both arg types need
8733          * to be paired, so make sure there's no buggy
8734          * helper function specification.
8735          */
8736         if (arg_type_is_mem_size(fn->arg1_type) ||
8737             check_args_pair_invalid(fn, 0) ||
8738             check_args_pair_invalid(fn, 1) ||
8739             check_args_pair_invalid(fn, 2) ||
8740             check_args_pair_invalid(fn, 3) ||
8741             check_args_pair_invalid(fn, 4))
8742                 return false;
8743
8744         return true;
8745 }
8746
8747 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8748 {
8749         int i;
8750
8751         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8752                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8753                         return !!fn->arg_btf_id[i];
8754                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8755                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
8756                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8757                     /* arg_btf_id and arg_size are in a union. */
8758                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8759                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8760                         return false;
8761         }
8762
8763         return true;
8764 }
8765
8766 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8767 {
8768         return check_raw_mode_ok(fn) &&
8769                check_arg_pair_ok(fn) &&
8770                check_btf_id_ok(fn) ? 0 : -EINVAL;
8771 }
8772
8773 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8774  * are now invalid, so turn them into unknown SCALAR_VALUE.
8775  *
8776  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8777  * since these slices point to packet data.
8778  */
8779 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8780 {
8781         struct bpf_func_state *state;
8782         struct bpf_reg_state *reg;
8783
8784         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8785                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8786                         mark_reg_invalid(env, reg);
8787         }));
8788 }
8789
8790 enum {
8791         AT_PKT_END = -1,
8792         BEYOND_PKT_END = -2,
8793 };
8794
8795 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8796 {
8797         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8798         struct bpf_reg_state *reg = &state->regs[regn];
8799
8800         if (reg->type != PTR_TO_PACKET)
8801                 /* PTR_TO_PACKET_META is not supported yet */
8802                 return;
8803
8804         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8805          * How far beyond pkt_end it goes is unknown.
8806          * if (!range_open) it's the case of pkt >= pkt_end
8807          * if (range_open) it's the case of pkt > pkt_end
8808          * hence this pointer is at least 1 byte bigger than pkt_end
8809          */
8810         if (range_open)
8811                 reg->range = BEYOND_PKT_END;
8812         else
8813                 reg->range = AT_PKT_END;
8814 }
8815
8816 /* The pointer with the specified id has released its reference to kernel
8817  * resources. Identify all copies of the same pointer and clear the reference.
8818  */
8819 static int release_reference(struct bpf_verifier_env *env,
8820                              int ref_obj_id)
8821 {
8822         struct bpf_func_state *state;
8823         struct bpf_reg_state *reg;
8824         int err;
8825
8826         err = release_reference_state(cur_func(env), ref_obj_id);
8827         if (err)
8828                 return err;
8829
8830         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8831                 if (reg->ref_obj_id == ref_obj_id)
8832                         mark_reg_invalid(env, reg);
8833         }));
8834
8835         return 0;
8836 }
8837
8838 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8839 {
8840         struct bpf_func_state *unused;
8841         struct bpf_reg_state *reg;
8842
8843         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8844                 if (type_is_non_owning_ref(reg->type))
8845                         mark_reg_invalid(env, reg);
8846         }));
8847 }
8848
8849 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8850                                     struct bpf_reg_state *regs)
8851 {
8852         int i;
8853
8854         /* after the call registers r0 - r5 were scratched */
8855         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8856                 mark_reg_not_init(env, regs, caller_saved[i]);
8857                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8858         }
8859 }
8860
8861 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8862                                    struct bpf_func_state *caller,
8863                                    struct bpf_func_state *callee,
8864                                    int insn_idx);
8865
8866 static int set_callee_state(struct bpf_verifier_env *env,
8867                             struct bpf_func_state *caller,
8868                             struct bpf_func_state *callee, int insn_idx);
8869
8870 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8871                              int *insn_idx, int subprog,
8872                              set_callee_state_fn set_callee_state_cb)
8873 {
8874         struct bpf_verifier_state *state = env->cur_state;
8875         struct bpf_func_state *caller, *callee;
8876         int err;
8877
8878         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8879                 verbose(env, "the call stack of %d frames is too deep\n",
8880                         state->curframe + 2);
8881                 return -E2BIG;
8882         }
8883
8884         caller = state->frame[state->curframe];
8885         if (state->frame[state->curframe + 1]) {
8886                 verbose(env, "verifier bug. Frame %d already allocated\n",
8887                         state->curframe + 1);
8888                 return -EFAULT;
8889         }
8890
8891         err = btf_check_subprog_call(env, subprog, caller->regs);
8892         if (err == -EFAULT)
8893                 return err;
8894         if (subprog_is_global(env, subprog)) {
8895                 if (err) {
8896                         verbose(env, "Caller passes invalid args into func#%d\n",
8897                                 subprog);
8898                         return err;
8899                 } else {
8900                         if (env->log.level & BPF_LOG_LEVEL)
8901                                 verbose(env,
8902                                         "Func#%d is global and valid. Skipping.\n",
8903                                         subprog);
8904                         clear_caller_saved_regs(env, caller->regs);
8905
8906                         /* All global functions return a 64-bit SCALAR_VALUE */
8907                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
8908                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8909
8910                         /* continue with next insn after call */
8911                         return 0;
8912                 }
8913         }
8914
8915         /* set_callee_state is used for direct subprog calls, but we are
8916          * interested in validating only BPF helpers that can call subprogs as
8917          * callbacks
8918          */
8919         if (set_callee_state_cb != set_callee_state) {
8920                 if (bpf_pseudo_kfunc_call(insn) &&
8921                     !is_callback_calling_kfunc(insn->imm)) {
8922                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8923                                 func_id_name(insn->imm), insn->imm);
8924                         return -EFAULT;
8925                 } else if (!bpf_pseudo_kfunc_call(insn) &&
8926                            !is_callback_calling_function(insn->imm)) { /* helper */
8927                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8928                                 func_id_name(insn->imm), insn->imm);
8929                         return -EFAULT;
8930                 }
8931         }
8932
8933         if (insn->code == (BPF_JMP | BPF_CALL) &&
8934             insn->src_reg == 0 &&
8935             insn->imm == BPF_FUNC_timer_set_callback) {
8936                 struct bpf_verifier_state *async_cb;
8937
8938                 /* there is no real recursion here. timer callbacks are async */
8939                 env->subprog_info[subprog].is_async_cb = true;
8940                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8941                                          *insn_idx, subprog);
8942                 if (!async_cb)
8943                         return -EFAULT;
8944                 callee = async_cb->frame[0];
8945                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8946
8947                 /* Convert bpf_timer_set_callback() args into timer callback args */
8948                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8949                 if (err)
8950                         return err;
8951
8952                 clear_caller_saved_regs(env, caller->regs);
8953                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8954                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8955                 /* continue with next insn after call */
8956                 return 0;
8957         }
8958
8959         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8960         if (!callee)
8961                 return -ENOMEM;
8962         state->frame[state->curframe + 1] = callee;
8963
8964         /* callee cannot access r0, r6 - r9 for reading and has to write
8965          * into its own stack before reading from it.
8966          * callee can read/write into caller's stack
8967          */
8968         init_func_state(env, callee,
8969                         /* remember the callsite, it will be used by bpf_exit */
8970                         *insn_idx /* callsite */,
8971                         state->curframe + 1 /* frameno within this callchain */,
8972                         subprog /* subprog number within this prog */);
8973
8974         /* Transfer references to the callee */
8975         err = copy_reference_state(callee, caller);
8976         if (err)
8977                 goto err_out;
8978
8979         err = set_callee_state_cb(env, caller, callee, *insn_idx);
8980         if (err)
8981                 goto err_out;
8982
8983         clear_caller_saved_regs(env, caller->regs);
8984
8985         /* only increment it after check_reg_arg() finished */
8986         state->curframe++;
8987
8988         /* and go analyze first insn of the callee */
8989         *insn_idx = env->subprog_info[subprog].start - 1;
8990
8991         if (env->log.level & BPF_LOG_LEVEL) {
8992                 verbose(env, "caller:\n");
8993                 print_verifier_state(env, caller, true);
8994                 verbose(env, "callee:\n");
8995                 print_verifier_state(env, callee, true);
8996         }
8997         return 0;
8998
8999 err_out:
9000         free_func_state(callee);
9001         state->frame[state->curframe + 1] = NULL;
9002         return err;
9003 }
9004
9005 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9006                                    struct bpf_func_state *caller,
9007                                    struct bpf_func_state *callee)
9008 {
9009         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9010          *      void *callback_ctx, u64 flags);
9011          * callback_fn(struct bpf_map *map, void *key, void *value,
9012          *      void *callback_ctx);
9013          */
9014         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9015
9016         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9017         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9018         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9019
9020         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9021         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9022         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9023
9024         /* pointer to stack or null */
9025         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9026
9027         /* unused */
9028         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9029         return 0;
9030 }
9031
9032 static int set_callee_state(struct bpf_verifier_env *env,
9033                             struct bpf_func_state *caller,
9034                             struct bpf_func_state *callee, int insn_idx)
9035 {
9036         int i;
9037
9038         /* copy r1 - r5 args that callee can access.  The copy includes parent
9039          * pointers, which connects us up to the liveness chain
9040          */
9041         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9042                 callee->regs[i] = caller->regs[i];
9043         return 0;
9044 }
9045
9046 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9047                            int *insn_idx)
9048 {
9049         int subprog, target_insn;
9050
9051         target_insn = *insn_idx + insn->imm + 1;
9052         subprog = find_subprog(env, target_insn);
9053         if (subprog < 0) {
9054                 verbose(env, "verifier bug. No program starts at insn %d\n",
9055                         target_insn);
9056                 return -EFAULT;
9057         }
9058
9059         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9060 }
9061
9062 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9063                                        struct bpf_func_state *caller,
9064                                        struct bpf_func_state *callee,
9065                                        int insn_idx)
9066 {
9067         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9068         struct bpf_map *map;
9069         int err;
9070
9071         if (bpf_map_ptr_poisoned(insn_aux)) {
9072                 verbose(env, "tail_call abusing map_ptr\n");
9073                 return -EINVAL;
9074         }
9075
9076         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9077         if (!map->ops->map_set_for_each_callback_args ||
9078             !map->ops->map_for_each_callback) {
9079                 verbose(env, "callback function not allowed for map\n");
9080                 return -ENOTSUPP;
9081         }
9082
9083         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9084         if (err)
9085                 return err;
9086
9087         callee->in_callback_fn = true;
9088         callee->callback_ret_range = tnum_range(0, 1);
9089         return 0;
9090 }
9091
9092 static int set_loop_callback_state(struct bpf_verifier_env *env,
9093                                    struct bpf_func_state *caller,
9094                                    struct bpf_func_state *callee,
9095                                    int insn_idx)
9096 {
9097         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9098          *          u64 flags);
9099          * callback_fn(u32 index, void *callback_ctx);
9100          */
9101         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9102         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9103
9104         /* unused */
9105         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9106         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9107         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9108
9109         callee->in_callback_fn = true;
9110         callee->callback_ret_range = tnum_range(0, 1);
9111         return 0;
9112 }
9113
9114 static int set_timer_callback_state(struct bpf_verifier_env *env,
9115                                     struct bpf_func_state *caller,
9116                                     struct bpf_func_state *callee,
9117                                     int insn_idx)
9118 {
9119         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9120
9121         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9122          * callback_fn(struct bpf_map *map, void *key, void *value);
9123          */
9124         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9125         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9126         callee->regs[BPF_REG_1].map_ptr = map_ptr;
9127
9128         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9129         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9130         callee->regs[BPF_REG_2].map_ptr = map_ptr;
9131
9132         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9133         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9134         callee->regs[BPF_REG_3].map_ptr = map_ptr;
9135
9136         /* unused */
9137         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9138         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9139         callee->in_async_callback_fn = true;
9140         callee->callback_ret_range = tnum_range(0, 1);
9141         return 0;
9142 }
9143
9144 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9145                                        struct bpf_func_state *caller,
9146                                        struct bpf_func_state *callee,
9147                                        int insn_idx)
9148 {
9149         /* bpf_find_vma(struct task_struct *task, u64 addr,
9150          *               void *callback_fn, void *callback_ctx, u64 flags)
9151          * (callback_fn)(struct task_struct *task,
9152          *               struct vm_area_struct *vma, void *callback_ctx);
9153          */
9154         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9155
9156         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9157         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9158         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9159         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9160
9161         /* pointer to stack or null */
9162         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9163
9164         /* unused */
9165         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9166         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9167         callee->in_callback_fn = true;
9168         callee->callback_ret_range = tnum_range(0, 1);
9169         return 0;
9170 }
9171
9172 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9173                                            struct bpf_func_state *caller,
9174                                            struct bpf_func_state *callee,
9175                                            int insn_idx)
9176 {
9177         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9178          *                        callback_ctx, u64 flags);
9179          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9180          */
9181         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9182         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9183         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9184
9185         /* unused */
9186         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9187         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9188         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9189
9190         callee->in_callback_fn = true;
9191         callee->callback_ret_range = tnum_range(0, 1);
9192         return 0;
9193 }
9194
9195 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9196                                          struct bpf_func_state *caller,
9197                                          struct bpf_func_state *callee,
9198                                          int insn_idx)
9199 {
9200         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9201          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9202          *
9203          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9204          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9205          * by this point, so look at 'root'
9206          */
9207         struct btf_field *field;
9208
9209         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9210                                       BPF_RB_ROOT);
9211         if (!field || !field->graph_root.value_btf_id)
9212                 return -EFAULT;
9213
9214         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9215         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9216         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9217         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9218
9219         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9220         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9221         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9222         callee->in_callback_fn = true;
9223         callee->callback_ret_range = tnum_range(0, 1);
9224         return 0;
9225 }
9226
9227 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9228
9229 /* Are we currently verifying the callback for a rbtree helper that must
9230  * be called with lock held? If so, no need to complain about unreleased
9231  * lock
9232  */
9233 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9234 {
9235         struct bpf_verifier_state *state = env->cur_state;
9236         struct bpf_insn *insn = env->prog->insnsi;
9237         struct bpf_func_state *callee;
9238         int kfunc_btf_id;
9239
9240         if (!state->curframe)
9241                 return false;
9242
9243         callee = state->frame[state->curframe];
9244
9245         if (!callee->in_callback_fn)
9246                 return false;
9247
9248         kfunc_btf_id = insn[callee->callsite].imm;
9249         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9250 }
9251
9252 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9253 {
9254         struct bpf_verifier_state *state = env->cur_state;
9255         struct bpf_func_state *caller, *callee;
9256         struct bpf_reg_state *r0;
9257         int err;
9258
9259         callee = state->frame[state->curframe];
9260         r0 = &callee->regs[BPF_REG_0];
9261         if (r0->type == PTR_TO_STACK) {
9262                 /* technically it's ok to return caller's stack pointer
9263                  * (or caller's caller's pointer) back to the caller,
9264                  * since these pointers are valid. Only current stack
9265                  * pointer will be invalid as soon as function exits,
9266                  * but let's be conservative
9267                  */
9268                 verbose(env, "cannot return stack pointer to the caller\n");
9269                 return -EINVAL;
9270         }
9271
9272         caller = state->frame[state->curframe - 1];
9273         if (callee->in_callback_fn) {
9274                 /* enforce R0 return value range [0, 1]. */
9275                 struct tnum range = callee->callback_ret_range;
9276
9277                 if (r0->type != SCALAR_VALUE) {
9278                         verbose(env, "R0 not a scalar value\n");
9279                         return -EACCES;
9280                 }
9281
9282                 /* we are going to rely on register's precise value */
9283                 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9284                 err = err ?: mark_chain_precision(env, BPF_REG_0);
9285                 if (err)
9286                         return err;
9287
9288                 if (!tnum_in(range, r0->var_off)) {
9289                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9290                         return -EINVAL;
9291                 }
9292         } else {
9293                 /* return to the caller whatever r0 had in the callee */
9294                 caller->regs[BPF_REG_0] = *r0;
9295         }
9296
9297         /* callback_fn frame should have released its own additions to parent's
9298          * reference state at this point, or check_reference_leak would
9299          * complain, hence it must be the same as the caller. There is no need
9300          * to copy it back.
9301          */
9302         if (!callee->in_callback_fn) {
9303                 /* Transfer references to the caller */
9304                 err = copy_reference_state(caller, callee);
9305                 if (err)
9306                         return err;
9307         }
9308
9309         *insn_idx = callee->callsite + 1;
9310         if (env->log.level & BPF_LOG_LEVEL) {
9311                 verbose(env, "returning from callee:\n");
9312                 print_verifier_state(env, callee, true);
9313                 verbose(env, "to caller at %d:\n", *insn_idx);
9314                 print_verifier_state(env, caller, true);
9315         }
9316         /* clear everything in the callee */
9317         free_func_state(callee);
9318         state->frame[state->curframe--] = NULL;
9319         return 0;
9320 }
9321
9322 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9323                                    int func_id,
9324                                    struct bpf_call_arg_meta *meta)
9325 {
9326         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9327
9328         if (ret_type != RET_INTEGER)
9329                 return;
9330
9331         switch (func_id) {
9332         case BPF_FUNC_get_stack:
9333         case BPF_FUNC_get_task_stack:
9334         case BPF_FUNC_probe_read_str:
9335         case BPF_FUNC_probe_read_kernel_str:
9336         case BPF_FUNC_probe_read_user_str:
9337                 ret_reg->smax_value = meta->msize_max_value;
9338                 ret_reg->s32_max_value = meta->msize_max_value;
9339                 ret_reg->smin_value = -MAX_ERRNO;
9340                 ret_reg->s32_min_value = -MAX_ERRNO;
9341                 reg_bounds_sync(ret_reg);
9342                 break;
9343         case BPF_FUNC_get_smp_processor_id:
9344                 ret_reg->umax_value = nr_cpu_ids - 1;
9345                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9346                 ret_reg->smax_value = nr_cpu_ids - 1;
9347                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9348                 ret_reg->umin_value = 0;
9349                 ret_reg->u32_min_value = 0;
9350                 ret_reg->smin_value = 0;
9351                 ret_reg->s32_min_value = 0;
9352                 reg_bounds_sync(ret_reg);
9353                 break;
9354         }
9355 }
9356
9357 static int
9358 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9359                 int func_id, int insn_idx)
9360 {
9361         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9362         struct bpf_map *map = meta->map_ptr;
9363
9364         if (func_id != BPF_FUNC_tail_call &&
9365             func_id != BPF_FUNC_map_lookup_elem &&
9366             func_id != BPF_FUNC_map_update_elem &&
9367             func_id != BPF_FUNC_map_delete_elem &&
9368             func_id != BPF_FUNC_map_push_elem &&
9369             func_id != BPF_FUNC_map_pop_elem &&
9370             func_id != BPF_FUNC_map_peek_elem &&
9371             func_id != BPF_FUNC_for_each_map_elem &&
9372             func_id != BPF_FUNC_redirect_map &&
9373             func_id != BPF_FUNC_map_lookup_percpu_elem)
9374                 return 0;
9375
9376         if (map == NULL) {
9377                 verbose(env, "kernel subsystem misconfigured verifier\n");
9378                 return -EINVAL;
9379         }
9380
9381         /* In case of read-only, some additional restrictions
9382          * need to be applied in order to prevent altering the
9383          * state of the map from program side.
9384          */
9385         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9386             (func_id == BPF_FUNC_map_delete_elem ||
9387              func_id == BPF_FUNC_map_update_elem ||
9388              func_id == BPF_FUNC_map_push_elem ||
9389              func_id == BPF_FUNC_map_pop_elem)) {
9390                 verbose(env, "write into map forbidden\n");
9391                 return -EACCES;
9392         }
9393
9394         if (!BPF_MAP_PTR(aux->map_ptr_state))
9395                 bpf_map_ptr_store(aux, meta->map_ptr,
9396                                   !meta->map_ptr->bypass_spec_v1);
9397         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9398                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9399                                   !meta->map_ptr->bypass_spec_v1);
9400         return 0;
9401 }
9402
9403 static int
9404 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9405                 int func_id, int insn_idx)
9406 {
9407         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9408         struct bpf_reg_state *regs = cur_regs(env), *reg;
9409         struct bpf_map *map = meta->map_ptr;
9410         u64 val, max;
9411         int err;
9412
9413         if (func_id != BPF_FUNC_tail_call)
9414                 return 0;
9415         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9416                 verbose(env, "kernel subsystem misconfigured verifier\n");
9417                 return -EINVAL;
9418         }
9419
9420         reg = &regs[BPF_REG_3];
9421         val = reg->var_off.value;
9422         max = map->max_entries;
9423
9424         if (!(register_is_const(reg) && val < max)) {
9425                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9426                 return 0;
9427         }
9428
9429         err = mark_chain_precision(env, BPF_REG_3);
9430         if (err)
9431                 return err;
9432         if (bpf_map_key_unseen(aux))
9433                 bpf_map_key_store(aux, val);
9434         else if (!bpf_map_key_poisoned(aux) &&
9435                   bpf_map_key_immediate(aux) != val)
9436                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9437         return 0;
9438 }
9439
9440 static int check_reference_leak(struct bpf_verifier_env *env)
9441 {
9442         struct bpf_func_state *state = cur_func(env);
9443         bool refs_lingering = false;
9444         int i;
9445
9446         if (state->frameno && !state->in_callback_fn)
9447                 return 0;
9448
9449         for (i = 0; i < state->acquired_refs; i++) {
9450                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9451                         continue;
9452                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9453                         state->refs[i].id, state->refs[i].insn_idx);
9454                 refs_lingering = true;
9455         }
9456         return refs_lingering ? -EINVAL : 0;
9457 }
9458
9459 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9460                                    struct bpf_reg_state *regs)
9461 {
9462         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9463         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9464         struct bpf_map *fmt_map = fmt_reg->map_ptr;
9465         struct bpf_bprintf_data data = {};
9466         int err, fmt_map_off, num_args;
9467         u64 fmt_addr;
9468         char *fmt;
9469
9470         /* data must be an array of u64 */
9471         if (data_len_reg->var_off.value % 8)
9472                 return -EINVAL;
9473         num_args = data_len_reg->var_off.value / 8;
9474
9475         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9476          * and map_direct_value_addr is set.
9477          */
9478         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9479         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9480                                                   fmt_map_off);
9481         if (err) {
9482                 verbose(env, "verifier bug\n");
9483                 return -EFAULT;
9484         }
9485         fmt = (char *)(long)fmt_addr + fmt_map_off;
9486
9487         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9488          * can focus on validating the format specifiers.
9489          */
9490         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9491         if (err < 0)
9492                 verbose(env, "Invalid format string\n");
9493
9494         return err;
9495 }
9496
9497 static int check_get_func_ip(struct bpf_verifier_env *env)
9498 {
9499         enum bpf_prog_type type = resolve_prog_type(env->prog);
9500         int func_id = BPF_FUNC_get_func_ip;
9501
9502         if (type == BPF_PROG_TYPE_TRACING) {
9503                 if (!bpf_prog_has_trampoline(env->prog)) {
9504                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9505                                 func_id_name(func_id), func_id);
9506                         return -ENOTSUPP;
9507                 }
9508                 return 0;
9509         } else if (type == BPF_PROG_TYPE_KPROBE) {
9510                 return 0;
9511         }
9512
9513         verbose(env, "func %s#%d not supported for program type %d\n",
9514                 func_id_name(func_id), func_id, type);
9515         return -ENOTSUPP;
9516 }
9517
9518 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9519 {
9520         return &env->insn_aux_data[env->insn_idx];
9521 }
9522
9523 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9524 {
9525         struct bpf_reg_state *regs = cur_regs(env);
9526         struct bpf_reg_state *reg = &regs[BPF_REG_4];
9527         bool reg_is_null = register_is_null(reg);
9528
9529         if (reg_is_null)
9530                 mark_chain_precision(env, BPF_REG_4);
9531
9532         return reg_is_null;
9533 }
9534
9535 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9536 {
9537         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9538
9539         if (!state->initialized) {
9540                 state->initialized = 1;
9541                 state->fit_for_inline = loop_flag_is_zero(env);
9542                 state->callback_subprogno = subprogno;
9543                 return;
9544         }
9545
9546         if (!state->fit_for_inline)
9547                 return;
9548
9549         state->fit_for_inline = (loop_flag_is_zero(env) &&
9550                                  state->callback_subprogno == subprogno);
9551 }
9552
9553 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9554                              int *insn_idx_p)
9555 {
9556         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9557         const struct bpf_func_proto *fn = NULL;
9558         enum bpf_return_type ret_type;
9559         enum bpf_type_flag ret_flag;
9560         struct bpf_reg_state *regs;
9561         struct bpf_call_arg_meta meta;
9562         int insn_idx = *insn_idx_p;
9563         bool changes_data;
9564         int i, err, func_id;
9565
9566         /* find function prototype */
9567         func_id = insn->imm;
9568         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9569                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9570                         func_id);
9571                 return -EINVAL;
9572         }
9573
9574         if (env->ops->get_func_proto)
9575                 fn = env->ops->get_func_proto(func_id, env->prog);
9576         if (!fn) {
9577                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9578                         func_id);
9579                 return -EINVAL;
9580         }
9581
9582         /* eBPF programs must be GPL compatible to use GPL-ed functions */
9583         if (!env->prog->gpl_compatible && fn->gpl_only) {
9584                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9585                 return -EINVAL;
9586         }
9587
9588         if (fn->allowed && !fn->allowed(env->prog)) {
9589                 verbose(env, "helper call is not allowed in probe\n");
9590                 return -EINVAL;
9591         }
9592
9593         if (!env->prog->aux->sleepable && fn->might_sleep) {
9594                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9595                 return -EINVAL;
9596         }
9597
9598         /* With LD_ABS/IND some JITs save/restore skb from r1. */
9599         changes_data = bpf_helper_changes_pkt_data(fn->func);
9600         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9601                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9602                         func_id_name(func_id), func_id);
9603                 return -EINVAL;
9604         }
9605
9606         memset(&meta, 0, sizeof(meta));
9607         meta.pkt_access = fn->pkt_access;
9608
9609         err = check_func_proto(fn, func_id);
9610         if (err) {
9611                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9612                         func_id_name(func_id), func_id);
9613                 return err;
9614         }
9615
9616         if (env->cur_state->active_rcu_lock) {
9617                 if (fn->might_sleep) {
9618                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9619                                 func_id_name(func_id), func_id);
9620                         return -EINVAL;
9621                 }
9622
9623                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9624                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9625         }
9626
9627         meta.func_id = func_id;
9628         /* check args */
9629         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9630                 err = check_func_arg(env, i, &meta, fn, insn_idx);
9631                 if (err)
9632                         return err;
9633         }
9634
9635         err = record_func_map(env, &meta, func_id, insn_idx);
9636         if (err)
9637                 return err;
9638
9639         err = record_func_key(env, &meta, func_id, insn_idx);
9640         if (err)
9641                 return err;
9642
9643         /* Mark slots with STACK_MISC in case of raw mode, stack offset
9644          * is inferred from register state.
9645          */
9646         for (i = 0; i < meta.access_size; i++) {
9647                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9648                                        BPF_WRITE, -1, false, false);
9649                 if (err)
9650                         return err;
9651         }
9652
9653         regs = cur_regs(env);
9654
9655         if (meta.release_regno) {
9656                 err = -EINVAL;
9657                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9658                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9659                  * is safe to do directly.
9660                  */
9661                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9662                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9663                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9664                                 return -EFAULT;
9665                         }
9666                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9667                 } else if (meta.ref_obj_id) {
9668                         err = release_reference(env, meta.ref_obj_id);
9669                 } else if (register_is_null(&regs[meta.release_regno])) {
9670                         /* meta.ref_obj_id can only be 0 if register that is meant to be
9671                          * released is NULL, which must be > R0.
9672                          */
9673                         err = 0;
9674                 }
9675                 if (err) {
9676                         verbose(env, "func %s#%d reference has not been acquired before\n",
9677                                 func_id_name(func_id), func_id);
9678                         return err;
9679                 }
9680         }
9681
9682         switch (func_id) {
9683         case BPF_FUNC_tail_call:
9684                 err = check_reference_leak(env);
9685                 if (err) {
9686                         verbose(env, "tail_call would lead to reference leak\n");
9687                         return err;
9688                 }
9689                 break;
9690         case BPF_FUNC_get_local_storage:
9691                 /* check that flags argument in get_local_storage(map, flags) is 0,
9692                  * this is required because get_local_storage() can't return an error.
9693                  */
9694                 if (!register_is_null(&regs[BPF_REG_2])) {
9695                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9696                         return -EINVAL;
9697                 }
9698                 break;
9699         case BPF_FUNC_for_each_map_elem:
9700                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9701                                         set_map_elem_callback_state);
9702                 break;
9703         case BPF_FUNC_timer_set_callback:
9704                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9705                                         set_timer_callback_state);
9706                 break;
9707         case BPF_FUNC_find_vma:
9708                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9709                                         set_find_vma_callback_state);
9710                 break;
9711         case BPF_FUNC_snprintf:
9712                 err = check_bpf_snprintf_call(env, regs);
9713                 break;
9714         case BPF_FUNC_loop:
9715                 update_loop_inline_state(env, meta.subprogno);
9716                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9717                                         set_loop_callback_state);
9718                 break;
9719         case BPF_FUNC_dynptr_from_mem:
9720                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9721                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9722                                 reg_type_str(env, regs[BPF_REG_1].type));
9723                         return -EACCES;
9724                 }
9725                 break;
9726         case BPF_FUNC_set_retval:
9727                 if (prog_type == BPF_PROG_TYPE_LSM &&
9728                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9729                         if (!env->prog->aux->attach_func_proto->type) {
9730                                 /* Make sure programs that attach to void
9731                                  * hooks don't try to modify return value.
9732                                  */
9733                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9734                                 return -EINVAL;
9735                         }
9736                 }
9737                 break;
9738         case BPF_FUNC_dynptr_data:
9739         {
9740                 struct bpf_reg_state *reg;
9741                 int id, ref_obj_id;
9742
9743                 reg = get_dynptr_arg_reg(env, fn, regs);
9744                 if (!reg)
9745                         return -EFAULT;
9746
9747
9748                 if (meta.dynptr_id) {
9749                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9750                         return -EFAULT;
9751                 }
9752                 if (meta.ref_obj_id) {
9753                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9754                         return -EFAULT;
9755                 }
9756
9757                 id = dynptr_id(env, reg);
9758                 if (id < 0) {
9759                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9760                         return id;
9761                 }
9762
9763                 ref_obj_id = dynptr_ref_obj_id(env, reg);
9764                 if (ref_obj_id < 0) {
9765                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9766                         return ref_obj_id;
9767                 }
9768
9769                 meta.dynptr_id = id;
9770                 meta.ref_obj_id = ref_obj_id;
9771
9772                 break;
9773         }
9774         case BPF_FUNC_dynptr_write:
9775         {
9776                 enum bpf_dynptr_type dynptr_type;
9777                 struct bpf_reg_state *reg;
9778
9779                 reg = get_dynptr_arg_reg(env, fn, regs);
9780                 if (!reg)
9781                         return -EFAULT;
9782
9783                 dynptr_type = dynptr_get_type(env, reg);
9784                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9785                         return -EFAULT;
9786
9787                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9788                         /* this will trigger clear_all_pkt_pointers(), which will
9789                          * invalidate all dynptr slices associated with the skb
9790                          */
9791                         changes_data = true;
9792
9793                 break;
9794         }
9795         case BPF_FUNC_user_ringbuf_drain:
9796                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9797                                         set_user_ringbuf_callback_state);
9798                 break;
9799         }
9800
9801         if (err)
9802                 return err;
9803
9804         /* reset caller saved regs */
9805         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9806                 mark_reg_not_init(env, regs, caller_saved[i]);
9807                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9808         }
9809
9810         /* helper call returns 64-bit value. */
9811         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9812
9813         /* update return register (already marked as written above) */
9814         ret_type = fn->ret_type;
9815         ret_flag = type_flag(ret_type);
9816
9817         switch (base_type(ret_type)) {
9818         case RET_INTEGER:
9819                 /* sets type to SCALAR_VALUE */
9820                 mark_reg_unknown(env, regs, BPF_REG_0);
9821                 break;
9822         case RET_VOID:
9823                 regs[BPF_REG_0].type = NOT_INIT;
9824                 break;
9825         case RET_PTR_TO_MAP_VALUE:
9826                 /* There is no offset yet applied, variable or fixed */
9827                 mark_reg_known_zero(env, regs, BPF_REG_0);
9828                 /* remember map_ptr, so that check_map_access()
9829                  * can check 'value_size' boundary of memory access
9830                  * to map element returned from bpf_map_lookup_elem()
9831                  */
9832                 if (meta.map_ptr == NULL) {
9833                         verbose(env,
9834                                 "kernel subsystem misconfigured verifier\n");
9835                         return -EINVAL;
9836                 }
9837                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9838                 regs[BPF_REG_0].map_uid = meta.map_uid;
9839                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9840                 if (!type_may_be_null(ret_type) &&
9841                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9842                         regs[BPF_REG_0].id = ++env->id_gen;
9843                 }
9844                 break;
9845         case RET_PTR_TO_SOCKET:
9846                 mark_reg_known_zero(env, regs, BPF_REG_0);
9847                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9848                 break;
9849         case RET_PTR_TO_SOCK_COMMON:
9850                 mark_reg_known_zero(env, regs, BPF_REG_0);
9851                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9852                 break;
9853         case RET_PTR_TO_TCP_SOCK:
9854                 mark_reg_known_zero(env, regs, BPF_REG_0);
9855                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9856                 break;
9857         case RET_PTR_TO_MEM:
9858                 mark_reg_known_zero(env, regs, BPF_REG_0);
9859                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9860                 regs[BPF_REG_0].mem_size = meta.mem_size;
9861                 break;
9862         case RET_PTR_TO_MEM_OR_BTF_ID:
9863         {
9864                 const struct btf_type *t;
9865
9866                 mark_reg_known_zero(env, regs, BPF_REG_0);
9867                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9868                 if (!btf_type_is_struct(t)) {
9869                         u32 tsize;
9870                         const struct btf_type *ret;
9871                         const char *tname;
9872
9873                         /* resolve the type size of ksym. */
9874                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9875                         if (IS_ERR(ret)) {
9876                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9877                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9878                                         tname, PTR_ERR(ret));
9879                                 return -EINVAL;
9880                         }
9881                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9882                         regs[BPF_REG_0].mem_size = tsize;
9883                 } else {
9884                         /* MEM_RDONLY may be carried from ret_flag, but it
9885                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9886                          * it will confuse the check of PTR_TO_BTF_ID in
9887                          * check_mem_access().
9888                          */
9889                         ret_flag &= ~MEM_RDONLY;
9890
9891                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9892                         regs[BPF_REG_0].btf = meta.ret_btf;
9893                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9894                 }
9895                 break;
9896         }
9897         case RET_PTR_TO_BTF_ID:
9898         {
9899                 struct btf *ret_btf;
9900                 int ret_btf_id;
9901
9902                 mark_reg_known_zero(env, regs, BPF_REG_0);
9903                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9904                 if (func_id == BPF_FUNC_kptr_xchg) {
9905                         ret_btf = meta.kptr_field->kptr.btf;
9906                         ret_btf_id = meta.kptr_field->kptr.btf_id;
9907                         if (!btf_is_kernel(ret_btf))
9908                                 regs[BPF_REG_0].type |= MEM_ALLOC;
9909                 } else {
9910                         if (fn->ret_btf_id == BPF_PTR_POISON) {
9911                                 verbose(env, "verifier internal error:");
9912                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9913                                         func_id_name(func_id));
9914                                 return -EINVAL;
9915                         }
9916                         ret_btf = btf_vmlinux;
9917                         ret_btf_id = *fn->ret_btf_id;
9918                 }
9919                 if (ret_btf_id == 0) {
9920                         verbose(env, "invalid return type %u of func %s#%d\n",
9921                                 base_type(ret_type), func_id_name(func_id),
9922                                 func_id);
9923                         return -EINVAL;
9924                 }
9925                 regs[BPF_REG_0].btf = ret_btf;
9926                 regs[BPF_REG_0].btf_id = ret_btf_id;
9927                 break;
9928         }
9929         default:
9930                 verbose(env, "unknown return type %u of func %s#%d\n",
9931                         base_type(ret_type), func_id_name(func_id), func_id);
9932                 return -EINVAL;
9933         }
9934
9935         if (type_may_be_null(regs[BPF_REG_0].type))
9936                 regs[BPF_REG_0].id = ++env->id_gen;
9937
9938         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9939                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9940                         func_id_name(func_id), func_id);
9941                 return -EFAULT;
9942         }
9943
9944         if (is_dynptr_ref_function(func_id))
9945                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9946
9947         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9948                 /* For release_reference() */
9949                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9950         } else if (is_acquire_function(func_id, meta.map_ptr)) {
9951                 int id = acquire_reference_state(env, insn_idx);
9952
9953                 if (id < 0)
9954                         return id;
9955                 /* For mark_ptr_or_null_reg() */
9956                 regs[BPF_REG_0].id = id;
9957                 /* For release_reference() */
9958                 regs[BPF_REG_0].ref_obj_id = id;
9959         }
9960
9961         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9962
9963         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9964         if (err)
9965                 return err;
9966
9967         if ((func_id == BPF_FUNC_get_stack ||
9968              func_id == BPF_FUNC_get_task_stack) &&
9969             !env->prog->has_callchain_buf) {
9970                 const char *err_str;
9971
9972 #ifdef CONFIG_PERF_EVENTS
9973                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9974                 err_str = "cannot get callchain buffer for func %s#%d\n";
9975 #else
9976                 err = -ENOTSUPP;
9977                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9978 #endif
9979                 if (err) {
9980                         verbose(env, err_str, func_id_name(func_id), func_id);
9981                         return err;
9982                 }
9983
9984                 env->prog->has_callchain_buf = true;
9985         }
9986
9987         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9988                 env->prog->call_get_stack = true;
9989
9990         if (func_id == BPF_FUNC_get_func_ip) {
9991                 if (check_get_func_ip(env))
9992                         return -ENOTSUPP;
9993                 env->prog->call_get_func_ip = true;
9994         }
9995
9996         if (changes_data)
9997                 clear_all_pkt_pointers(env);
9998         return 0;
9999 }
10000
10001 /* mark_btf_func_reg_size() is used when the reg size is determined by
10002  * the BTF func_proto's return value size and argument.
10003  */
10004 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10005                                    size_t reg_size)
10006 {
10007         struct bpf_reg_state *reg = &cur_regs(env)[regno];
10008
10009         if (regno == BPF_REG_0) {
10010                 /* Function return value */
10011                 reg->live |= REG_LIVE_WRITTEN;
10012                 reg->subreg_def = reg_size == sizeof(u64) ?
10013                         DEF_NOT_SUBREG : env->insn_idx + 1;
10014         } else {
10015                 /* Function argument */
10016                 if (reg_size == sizeof(u64)) {
10017                         mark_insn_zext(env, reg);
10018                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10019                 } else {
10020                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10021                 }
10022         }
10023 }
10024
10025 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10026 {
10027         return meta->kfunc_flags & KF_ACQUIRE;
10028 }
10029
10030 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10031 {
10032         return meta->kfunc_flags & KF_RELEASE;
10033 }
10034
10035 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10036 {
10037         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10038 }
10039
10040 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10041 {
10042         return meta->kfunc_flags & KF_SLEEPABLE;
10043 }
10044
10045 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10046 {
10047         return meta->kfunc_flags & KF_DESTRUCTIVE;
10048 }
10049
10050 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10051 {
10052         return meta->kfunc_flags & KF_RCU;
10053 }
10054
10055 static bool __kfunc_param_match_suffix(const struct btf *btf,
10056                                        const struct btf_param *arg,
10057                                        const char *suffix)
10058 {
10059         int suffix_len = strlen(suffix), len;
10060         const char *param_name;
10061
10062         /* In the future, this can be ported to use BTF tagging */
10063         param_name = btf_name_by_offset(btf, arg->name_off);
10064         if (str_is_empty(param_name))
10065                 return false;
10066         len = strlen(param_name);
10067         if (len < suffix_len)
10068                 return false;
10069         param_name += len - suffix_len;
10070         return !strncmp(param_name, suffix, suffix_len);
10071 }
10072
10073 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10074                                   const struct btf_param *arg,
10075                                   const struct bpf_reg_state *reg)
10076 {
10077         const struct btf_type *t;
10078
10079         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10080         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10081                 return false;
10082
10083         return __kfunc_param_match_suffix(btf, arg, "__sz");
10084 }
10085
10086 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10087                                         const struct btf_param *arg,
10088                                         const struct bpf_reg_state *reg)
10089 {
10090         const struct btf_type *t;
10091
10092         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10093         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10094                 return false;
10095
10096         return __kfunc_param_match_suffix(btf, arg, "__szk");
10097 }
10098
10099 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10100 {
10101         return __kfunc_param_match_suffix(btf, arg, "__opt");
10102 }
10103
10104 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10105 {
10106         return __kfunc_param_match_suffix(btf, arg, "__k");
10107 }
10108
10109 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10110 {
10111         return __kfunc_param_match_suffix(btf, arg, "__ign");
10112 }
10113
10114 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10115 {
10116         return __kfunc_param_match_suffix(btf, arg, "__alloc");
10117 }
10118
10119 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10120 {
10121         return __kfunc_param_match_suffix(btf, arg, "__uninit");
10122 }
10123
10124 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10125 {
10126         return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10127 }
10128
10129 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10130                                           const struct btf_param *arg,
10131                                           const char *name)
10132 {
10133         int len, target_len = strlen(name);
10134         const char *param_name;
10135
10136         param_name = btf_name_by_offset(btf, arg->name_off);
10137         if (str_is_empty(param_name))
10138                 return false;
10139         len = strlen(param_name);
10140         if (len != target_len)
10141                 return false;
10142         if (strcmp(param_name, name))
10143                 return false;
10144
10145         return true;
10146 }
10147
10148 enum {
10149         KF_ARG_DYNPTR_ID,
10150         KF_ARG_LIST_HEAD_ID,
10151         KF_ARG_LIST_NODE_ID,
10152         KF_ARG_RB_ROOT_ID,
10153         KF_ARG_RB_NODE_ID,
10154 };
10155
10156 BTF_ID_LIST(kf_arg_btf_ids)
10157 BTF_ID(struct, bpf_dynptr_kern)
10158 BTF_ID(struct, bpf_list_head)
10159 BTF_ID(struct, bpf_list_node)
10160 BTF_ID(struct, bpf_rb_root)
10161 BTF_ID(struct, bpf_rb_node)
10162
10163 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10164                                     const struct btf_param *arg, int type)
10165 {
10166         const struct btf_type *t;
10167         u32 res_id;
10168
10169         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10170         if (!t)
10171                 return false;
10172         if (!btf_type_is_ptr(t))
10173                 return false;
10174         t = btf_type_skip_modifiers(btf, t->type, &res_id);
10175         if (!t)
10176                 return false;
10177         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10178 }
10179
10180 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10181 {
10182         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10183 }
10184
10185 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10186 {
10187         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10188 }
10189
10190 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10191 {
10192         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10193 }
10194
10195 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10196 {
10197         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10198 }
10199
10200 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10201 {
10202         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10203 }
10204
10205 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10206                                   const struct btf_param *arg)
10207 {
10208         const struct btf_type *t;
10209
10210         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10211         if (!t)
10212                 return false;
10213
10214         return true;
10215 }
10216
10217 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10218 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10219                                         const struct btf *btf,
10220                                         const struct btf_type *t, int rec)
10221 {
10222         const struct btf_type *member_type;
10223         const struct btf_member *member;
10224         u32 i;
10225
10226         if (!btf_type_is_struct(t))
10227                 return false;
10228
10229         for_each_member(i, t, member) {
10230                 const struct btf_array *array;
10231
10232                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10233                 if (btf_type_is_struct(member_type)) {
10234                         if (rec >= 3) {
10235                                 verbose(env, "max struct nesting depth exceeded\n");
10236                                 return false;
10237                         }
10238                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10239                                 return false;
10240                         continue;
10241                 }
10242                 if (btf_type_is_array(member_type)) {
10243                         array = btf_array(member_type);
10244                         if (!array->nelems)
10245                                 return false;
10246                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10247                         if (!btf_type_is_scalar(member_type))
10248                                 return false;
10249                         continue;
10250                 }
10251                 if (!btf_type_is_scalar(member_type))
10252                         return false;
10253         }
10254         return true;
10255 }
10256
10257 enum kfunc_ptr_arg_type {
10258         KF_ARG_PTR_TO_CTX,
10259         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10260         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10261         KF_ARG_PTR_TO_DYNPTR,
10262         KF_ARG_PTR_TO_ITER,
10263         KF_ARG_PTR_TO_LIST_HEAD,
10264         KF_ARG_PTR_TO_LIST_NODE,
10265         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10266         KF_ARG_PTR_TO_MEM,
10267         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10268         KF_ARG_PTR_TO_CALLBACK,
10269         KF_ARG_PTR_TO_RB_ROOT,
10270         KF_ARG_PTR_TO_RB_NODE,
10271 };
10272
10273 enum special_kfunc_type {
10274         KF_bpf_obj_new_impl,
10275         KF_bpf_obj_drop_impl,
10276         KF_bpf_refcount_acquire_impl,
10277         KF_bpf_list_push_front_impl,
10278         KF_bpf_list_push_back_impl,
10279         KF_bpf_list_pop_front,
10280         KF_bpf_list_pop_back,
10281         KF_bpf_cast_to_kern_ctx,
10282         KF_bpf_rdonly_cast,
10283         KF_bpf_rcu_read_lock,
10284         KF_bpf_rcu_read_unlock,
10285         KF_bpf_rbtree_remove,
10286         KF_bpf_rbtree_add_impl,
10287         KF_bpf_rbtree_first,
10288         KF_bpf_dynptr_from_skb,
10289         KF_bpf_dynptr_from_xdp,
10290         KF_bpf_dynptr_slice,
10291         KF_bpf_dynptr_slice_rdwr,
10292         KF_bpf_dynptr_clone,
10293 };
10294
10295 BTF_SET_START(special_kfunc_set)
10296 BTF_ID(func, bpf_obj_new_impl)
10297 BTF_ID(func, bpf_obj_drop_impl)
10298 BTF_ID(func, bpf_refcount_acquire_impl)
10299 BTF_ID(func, bpf_list_push_front_impl)
10300 BTF_ID(func, bpf_list_push_back_impl)
10301 BTF_ID(func, bpf_list_pop_front)
10302 BTF_ID(func, bpf_list_pop_back)
10303 BTF_ID(func, bpf_cast_to_kern_ctx)
10304 BTF_ID(func, bpf_rdonly_cast)
10305 BTF_ID(func, bpf_rbtree_remove)
10306 BTF_ID(func, bpf_rbtree_add_impl)
10307 BTF_ID(func, bpf_rbtree_first)
10308 BTF_ID(func, bpf_dynptr_from_skb)
10309 BTF_ID(func, bpf_dynptr_from_xdp)
10310 BTF_ID(func, bpf_dynptr_slice)
10311 BTF_ID(func, bpf_dynptr_slice_rdwr)
10312 BTF_ID(func, bpf_dynptr_clone)
10313 BTF_SET_END(special_kfunc_set)
10314
10315 BTF_ID_LIST(special_kfunc_list)
10316 BTF_ID(func, bpf_obj_new_impl)
10317 BTF_ID(func, bpf_obj_drop_impl)
10318 BTF_ID(func, bpf_refcount_acquire_impl)
10319 BTF_ID(func, bpf_list_push_front_impl)
10320 BTF_ID(func, bpf_list_push_back_impl)
10321 BTF_ID(func, bpf_list_pop_front)
10322 BTF_ID(func, bpf_list_pop_back)
10323 BTF_ID(func, bpf_cast_to_kern_ctx)
10324 BTF_ID(func, bpf_rdonly_cast)
10325 BTF_ID(func, bpf_rcu_read_lock)
10326 BTF_ID(func, bpf_rcu_read_unlock)
10327 BTF_ID(func, bpf_rbtree_remove)
10328 BTF_ID(func, bpf_rbtree_add_impl)
10329 BTF_ID(func, bpf_rbtree_first)
10330 BTF_ID(func, bpf_dynptr_from_skb)
10331 BTF_ID(func, bpf_dynptr_from_xdp)
10332 BTF_ID(func, bpf_dynptr_slice)
10333 BTF_ID(func, bpf_dynptr_slice_rdwr)
10334 BTF_ID(func, bpf_dynptr_clone)
10335
10336 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10337 {
10338         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10339             meta->arg_owning_ref) {
10340                 return false;
10341         }
10342
10343         return meta->kfunc_flags & KF_RET_NULL;
10344 }
10345
10346 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10347 {
10348         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10349 }
10350
10351 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10352 {
10353         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10354 }
10355
10356 static enum kfunc_ptr_arg_type
10357 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10358                        struct bpf_kfunc_call_arg_meta *meta,
10359                        const struct btf_type *t, const struct btf_type *ref_t,
10360                        const char *ref_tname, const struct btf_param *args,
10361                        int argno, int nargs)
10362 {
10363         u32 regno = argno + 1;
10364         struct bpf_reg_state *regs = cur_regs(env);
10365         struct bpf_reg_state *reg = &regs[regno];
10366         bool arg_mem_size = false;
10367
10368         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10369                 return KF_ARG_PTR_TO_CTX;
10370
10371         /* In this function, we verify the kfunc's BTF as per the argument type,
10372          * leaving the rest of the verification with respect to the register
10373          * type to our caller. When a set of conditions hold in the BTF type of
10374          * arguments, we resolve it to a known kfunc_ptr_arg_type.
10375          */
10376         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10377                 return KF_ARG_PTR_TO_CTX;
10378
10379         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10380                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10381
10382         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10383                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10384
10385         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10386                 return KF_ARG_PTR_TO_DYNPTR;
10387
10388         if (is_kfunc_arg_iter(meta, argno))
10389                 return KF_ARG_PTR_TO_ITER;
10390
10391         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10392                 return KF_ARG_PTR_TO_LIST_HEAD;
10393
10394         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10395                 return KF_ARG_PTR_TO_LIST_NODE;
10396
10397         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10398                 return KF_ARG_PTR_TO_RB_ROOT;
10399
10400         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10401                 return KF_ARG_PTR_TO_RB_NODE;
10402
10403         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10404                 if (!btf_type_is_struct(ref_t)) {
10405                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10406                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10407                         return -EINVAL;
10408                 }
10409                 return KF_ARG_PTR_TO_BTF_ID;
10410         }
10411
10412         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10413                 return KF_ARG_PTR_TO_CALLBACK;
10414
10415
10416         if (argno + 1 < nargs &&
10417             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10418              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10419                 arg_mem_size = true;
10420
10421         /* This is the catch all argument type of register types supported by
10422          * check_helper_mem_access. However, we only allow when argument type is
10423          * pointer to scalar, or struct composed (recursively) of scalars. When
10424          * arg_mem_size is true, the pointer can be void *.
10425          */
10426         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10427             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10428                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10429                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10430                 return -EINVAL;
10431         }
10432         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10433 }
10434
10435 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10436                                         struct bpf_reg_state *reg,
10437                                         const struct btf_type *ref_t,
10438                                         const char *ref_tname, u32 ref_id,
10439                                         struct bpf_kfunc_call_arg_meta *meta,
10440                                         int argno)
10441 {
10442         const struct btf_type *reg_ref_t;
10443         bool strict_type_match = false;
10444         const struct btf *reg_btf;
10445         const char *reg_ref_tname;
10446         u32 reg_ref_id;
10447
10448         if (base_type(reg->type) == PTR_TO_BTF_ID) {
10449                 reg_btf = reg->btf;
10450                 reg_ref_id = reg->btf_id;
10451         } else {
10452                 reg_btf = btf_vmlinux;
10453                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10454         }
10455
10456         /* Enforce strict type matching for calls to kfuncs that are acquiring
10457          * or releasing a reference, or are no-cast aliases. We do _not_
10458          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10459          * as we want to enable BPF programs to pass types that are bitwise
10460          * equivalent without forcing them to explicitly cast with something
10461          * like bpf_cast_to_kern_ctx().
10462          *
10463          * For example, say we had a type like the following:
10464          *
10465          * struct bpf_cpumask {
10466          *      cpumask_t cpumask;
10467          *      refcount_t usage;
10468          * };
10469          *
10470          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10471          * to a struct cpumask, so it would be safe to pass a struct
10472          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10473          *
10474          * The philosophy here is similar to how we allow scalars of different
10475          * types to be passed to kfuncs as long as the size is the same. The
10476          * only difference here is that we're simply allowing
10477          * btf_struct_ids_match() to walk the struct at the 0th offset, and
10478          * resolve types.
10479          */
10480         if (is_kfunc_acquire(meta) ||
10481             (is_kfunc_release(meta) && reg->ref_obj_id) ||
10482             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10483                 strict_type_match = true;
10484
10485         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10486
10487         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10488         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10489         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10490                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10491                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10492                         btf_type_str(reg_ref_t), reg_ref_tname);
10493                 return -EINVAL;
10494         }
10495         return 0;
10496 }
10497
10498 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10499 {
10500         struct bpf_verifier_state *state = env->cur_state;
10501         struct btf_record *rec = reg_btf_record(reg);
10502
10503         if (!state->active_lock.ptr) {
10504                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10505                 return -EFAULT;
10506         }
10507
10508         if (type_flag(reg->type) & NON_OWN_REF) {
10509                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10510                 return -EFAULT;
10511         }
10512
10513         reg->type |= NON_OWN_REF;
10514         if (rec->refcount_off >= 0)
10515                 reg->type |= MEM_RCU;
10516
10517         return 0;
10518 }
10519
10520 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10521 {
10522         struct bpf_func_state *state, *unused;
10523         struct bpf_reg_state *reg;
10524         int i;
10525
10526         state = cur_func(env);
10527
10528         if (!ref_obj_id) {
10529                 verbose(env, "verifier internal error: ref_obj_id is zero for "
10530                              "owning -> non-owning conversion\n");
10531                 return -EFAULT;
10532         }
10533
10534         for (i = 0; i < state->acquired_refs; i++) {
10535                 if (state->refs[i].id != ref_obj_id)
10536                         continue;
10537
10538                 /* Clear ref_obj_id here so release_reference doesn't clobber
10539                  * the whole reg
10540                  */
10541                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10542                         if (reg->ref_obj_id == ref_obj_id) {
10543                                 reg->ref_obj_id = 0;
10544                                 ref_set_non_owning(env, reg);
10545                         }
10546                 }));
10547                 return 0;
10548         }
10549
10550         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10551         return -EFAULT;
10552 }
10553
10554 /* Implementation details:
10555  *
10556  * Each register points to some region of memory, which we define as an
10557  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10558  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10559  * allocation. The lock and the data it protects are colocated in the same
10560  * memory region.
10561  *
10562  * Hence, everytime a register holds a pointer value pointing to such
10563  * allocation, the verifier preserves a unique reg->id for it.
10564  *
10565  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10566  * bpf_spin_lock is called.
10567  *
10568  * To enable this, lock state in the verifier captures two values:
10569  *      active_lock.ptr = Register's type specific pointer
10570  *      active_lock.id  = A unique ID for each register pointer value
10571  *
10572  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10573  * supported register types.
10574  *
10575  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10576  * allocated objects is the reg->btf pointer.
10577  *
10578  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10579  * can establish the provenance of the map value statically for each distinct
10580  * lookup into such maps. They always contain a single map value hence unique
10581  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10582  *
10583  * So, in case of global variables, they use array maps with max_entries = 1,
10584  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10585  * into the same map value as max_entries is 1, as described above).
10586  *
10587  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10588  * outer map pointer (in verifier context), but each lookup into an inner map
10589  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10590  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10591  * will get different reg->id assigned to each lookup, hence different
10592  * active_lock.id.
10593  *
10594  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10595  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10596  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10597  */
10598 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10599 {
10600         void *ptr;
10601         u32 id;
10602
10603         switch ((int)reg->type) {
10604         case PTR_TO_MAP_VALUE:
10605                 ptr = reg->map_ptr;
10606                 break;
10607         case PTR_TO_BTF_ID | MEM_ALLOC:
10608                 ptr = reg->btf;
10609                 break;
10610         default:
10611                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10612                 return -EFAULT;
10613         }
10614         id = reg->id;
10615
10616         if (!env->cur_state->active_lock.ptr)
10617                 return -EINVAL;
10618         if (env->cur_state->active_lock.ptr != ptr ||
10619             env->cur_state->active_lock.id != id) {
10620                 verbose(env, "held lock and object are not in the same allocation\n");
10621                 return -EINVAL;
10622         }
10623         return 0;
10624 }
10625
10626 static bool is_bpf_list_api_kfunc(u32 btf_id)
10627 {
10628         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10629                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10630                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10631                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10632 }
10633
10634 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10635 {
10636         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10637                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10638                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10639 }
10640
10641 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10642 {
10643         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10644                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10645 }
10646
10647 static bool is_callback_calling_kfunc(u32 btf_id)
10648 {
10649         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10650 }
10651
10652 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10653 {
10654         return is_bpf_rbtree_api_kfunc(btf_id);
10655 }
10656
10657 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10658                                           enum btf_field_type head_field_type,
10659                                           u32 kfunc_btf_id)
10660 {
10661         bool ret;
10662
10663         switch (head_field_type) {
10664         case BPF_LIST_HEAD:
10665                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10666                 break;
10667         case BPF_RB_ROOT:
10668                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10669                 break;
10670         default:
10671                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10672                         btf_field_type_name(head_field_type));
10673                 return false;
10674         }
10675
10676         if (!ret)
10677                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10678                         btf_field_type_name(head_field_type));
10679         return ret;
10680 }
10681
10682 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10683                                           enum btf_field_type node_field_type,
10684                                           u32 kfunc_btf_id)
10685 {
10686         bool ret;
10687
10688         switch (node_field_type) {
10689         case BPF_LIST_NODE:
10690                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10691                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10692                 break;
10693         case BPF_RB_NODE:
10694                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10695                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10696                 break;
10697         default:
10698                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10699                         btf_field_type_name(node_field_type));
10700                 return false;
10701         }
10702
10703         if (!ret)
10704                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10705                         btf_field_type_name(node_field_type));
10706         return ret;
10707 }
10708
10709 static int
10710 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10711                                    struct bpf_reg_state *reg, u32 regno,
10712                                    struct bpf_kfunc_call_arg_meta *meta,
10713                                    enum btf_field_type head_field_type,
10714                                    struct btf_field **head_field)
10715 {
10716         const char *head_type_name;
10717         struct btf_field *field;
10718         struct btf_record *rec;
10719         u32 head_off;
10720
10721         if (meta->btf != btf_vmlinux) {
10722                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10723                 return -EFAULT;
10724         }
10725
10726         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10727                 return -EFAULT;
10728
10729         head_type_name = btf_field_type_name(head_field_type);
10730         if (!tnum_is_const(reg->var_off)) {
10731                 verbose(env,
10732                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10733                         regno, head_type_name);
10734                 return -EINVAL;
10735         }
10736
10737         rec = reg_btf_record(reg);
10738         head_off = reg->off + reg->var_off.value;
10739         field = btf_record_find(rec, head_off, head_field_type);
10740         if (!field) {
10741                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10742                 return -EINVAL;
10743         }
10744
10745         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10746         if (check_reg_allocation_locked(env, reg)) {
10747                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10748                         rec->spin_lock_off, head_type_name);
10749                 return -EINVAL;
10750         }
10751
10752         if (*head_field) {
10753                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10754                 return -EFAULT;
10755         }
10756         *head_field = field;
10757         return 0;
10758 }
10759
10760 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10761                                            struct bpf_reg_state *reg, u32 regno,
10762                                            struct bpf_kfunc_call_arg_meta *meta)
10763 {
10764         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10765                                                           &meta->arg_list_head.field);
10766 }
10767
10768 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10769                                              struct bpf_reg_state *reg, u32 regno,
10770                                              struct bpf_kfunc_call_arg_meta *meta)
10771 {
10772         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10773                                                           &meta->arg_rbtree_root.field);
10774 }
10775
10776 static int
10777 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10778                                    struct bpf_reg_state *reg, u32 regno,
10779                                    struct bpf_kfunc_call_arg_meta *meta,
10780                                    enum btf_field_type head_field_type,
10781                                    enum btf_field_type node_field_type,
10782                                    struct btf_field **node_field)
10783 {
10784         const char *node_type_name;
10785         const struct btf_type *et, *t;
10786         struct btf_field *field;
10787         u32 node_off;
10788
10789         if (meta->btf != btf_vmlinux) {
10790                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10791                 return -EFAULT;
10792         }
10793
10794         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10795                 return -EFAULT;
10796
10797         node_type_name = btf_field_type_name(node_field_type);
10798         if (!tnum_is_const(reg->var_off)) {
10799                 verbose(env,
10800                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10801                         regno, node_type_name);
10802                 return -EINVAL;
10803         }
10804
10805         node_off = reg->off + reg->var_off.value;
10806         field = reg_find_field_offset(reg, node_off, node_field_type);
10807         if (!field || field->offset != node_off) {
10808                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10809                 return -EINVAL;
10810         }
10811
10812         field = *node_field;
10813
10814         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10815         t = btf_type_by_id(reg->btf, reg->btf_id);
10816         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10817                                   field->graph_root.value_btf_id, true)) {
10818                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10819                         "in struct %s, but arg is at offset=%d in struct %s\n",
10820                         btf_field_type_name(head_field_type),
10821                         btf_field_type_name(node_field_type),
10822                         field->graph_root.node_offset,
10823                         btf_name_by_offset(field->graph_root.btf, et->name_off),
10824                         node_off, btf_name_by_offset(reg->btf, t->name_off));
10825                 return -EINVAL;
10826         }
10827         meta->arg_btf = reg->btf;
10828         meta->arg_btf_id = reg->btf_id;
10829
10830         if (node_off != field->graph_root.node_offset) {
10831                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10832                         node_off, btf_field_type_name(node_field_type),
10833                         field->graph_root.node_offset,
10834                         btf_name_by_offset(field->graph_root.btf, et->name_off));
10835                 return -EINVAL;
10836         }
10837
10838         return 0;
10839 }
10840
10841 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10842                                            struct bpf_reg_state *reg, u32 regno,
10843                                            struct bpf_kfunc_call_arg_meta *meta)
10844 {
10845         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10846                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
10847                                                   &meta->arg_list_head.field);
10848 }
10849
10850 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10851                                              struct bpf_reg_state *reg, u32 regno,
10852                                              struct bpf_kfunc_call_arg_meta *meta)
10853 {
10854         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10855                                                   BPF_RB_ROOT, BPF_RB_NODE,
10856                                                   &meta->arg_rbtree_root.field);
10857 }
10858
10859 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10860                             int insn_idx)
10861 {
10862         const char *func_name = meta->func_name, *ref_tname;
10863         const struct btf *btf = meta->btf;
10864         const struct btf_param *args;
10865         struct btf_record *rec;
10866         u32 i, nargs;
10867         int ret;
10868
10869         args = (const struct btf_param *)(meta->func_proto + 1);
10870         nargs = btf_type_vlen(meta->func_proto);
10871         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10872                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10873                         MAX_BPF_FUNC_REG_ARGS);
10874                 return -EINVAL;
10875         }
10876
10877         /* Check that BTF function arguments match actual types that the
10878          * verifier sees.
10879          */
10880         for (i = 0; i < nargs; i++) {
10881                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10882                 const struct btf_type *t, *ref_t, *resolve_ret;
10883                 enum bpf_arg_type arg_type = ARG_DONTCARE;
10884                 u32 regno = i + 1, ref_id, type_size;
10885                 bool is_ret_buf_sz = false;
10886                 int kf_arg_type;
10887
10888                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10889
10890                 if (is_kfunc_arg_ignore(btf, &args[i]))
10891                         continue;
10892
10893                 if (btf_type_is_scalar(t)) {
10894                         if (reg->type != SCALAR_VALUE) {
10895                                 verbose(env, "R%d is not a scalar\n", regno);
10896                                 return -EINVAL;
10897                         }
10898
10899                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10900                                 if (meta->arg_constant.found) {
10901                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10902                                         return -EFAULT;
10903                                 }
10904                                 if (!tnum_is_const(reg->var_off)) {
10905                                         verbose(env, "R%d must be a known constant\n", regno);
10906                                         return -EINVAL;
10907                                 }
10908                                 ret = mark_chain_precision(env, regno);
10909                                 if (ret < 0)
10910                                         return ret;
10911                                 meta->arg_constant.found = true;
10912                                 meta->arg_constant.value = reg->var_off.value;
10913                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10914                                 meta->r0_rdonly = true;
10915                                 is_ret_buf_sz = true;
10916                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10917                                 is_ret_buf_sz = true;
10918                         }
10919
10920                         if (is_ret_buf_sz) {
10921                                 if (meta->r0_size) {
10922                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10923                                         return -EINVAL;
10924                                 }
10925
10926                                 if (!tnum_is_const(reg->var_off)) {
10927                                         verbose(env, "R%d is not a const\n", regno);
10928                                         return -EINVAL;
10929                                 }
10930
10931                                 meta->r0_size = reg->var_off.value;
10932                                 ret = mark_chain_precision(env, regno);
10933                                 if (ret)
10934                                         return ret;
10935                         }
10936                         continue;
10937                 }
10938
10939                 if (!btf_type_is_ptr(t)) {
10940                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10941                         return -EINVAL;
10942                 }
10943
10944                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10945                     (register_is_null(reg) || type_may_be_null(reg->type))) {
10946                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10947                         return -EACCES;
10948                 }
10949
10950                 if (reg->ref_obj_id) {
10951                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
10952                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10953                                         regno, reg->ref_obj_id,
10954                                         meta->ref_obj_id);
10955                                 return -EFAULT;
10956                         }
10957                         meta->ref_obj_id = reg->ref_obj_id;
10958                         if (is_kfunc_release(meta))
10959                                 meta->release_regno = regno;
10960                 }
10961
10962                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10963                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10964
10965                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10966                 if (kf_arg_type < 0)
10967                         return kf_arg_type;
10968
10969                 switch (kf_arg_type) {
10970                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10971                 case KF_ARG_PTR_TO_BTF_ID:
10972                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10973                                 break;
10974
10975                         if (!is_trusted_reg(reg)) {
10976                                 if (!is_kfunc_rcu(meta)) {
10977                                         verbose(env, "R%d must be referenced or trusted\n", regno);
10978                                         return -EINVAL;
10979                                 }
10980                                 if (!is_rcu_reg(reg)) {
10981                                         verbose(env, "R%d must be a rcu pointer\n", regno);
10982                                         return -EINVAL;
10983                                 }
10984                         }
10985
10986                         fallthrough;
10987                 case KF_ARG_PTR_TO_CTX:
10988                         /* Trusted arguments have the same offset checks as release arguments */
10989                         arg_type |= OBJ_RELEASE;
10990                         break;
10991                 case KF_ARG_PTR_TO_DYNPTR:
10992                 case KF_ARG_PTR_TO_ITER:
10993                 case KF_ARG_PTR_TO_LIST_HEAD:
10994                 case KF_ARG_PTR_TO_LIST_NODE:
10995                 case KF_ARG_PTR_TO_RB_ROOT:
10996                 case KF_ARG_PTR_TO_RB_NODE:
10997                 case KF_ARG_PTR_TO_MEM:
10998                 case KF_ARG_PTR_TO_MEM_SIZE:
10999                 case KF_ARG_PTR_TO_CALLBACK:
11000                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11001                         /* Trusted by default */
11002                         break;
11003                 default:
11004                         WARN_ON_ONCE(1);
11005                         return -EFAULT;
11006                 }
11007
11008                 if (is_kfunc_release(meta) && reg->ref_obj_id)
11009                         arg_type |= OBJ_RELEASE;
11010                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11011                 if (ret < 0)
11012                         return ret;
11013
11014                 switch (kf_arg_type) {
11015                 case KF_ARG_PTR_TO_CTX:
11016                         if (reg->type != PTR_TO_CTX) {
11017                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11018                                 return -EINVAL;
11019                         }
11020
11021                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11022                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11023                                 if (ret < 0)
11024                                         return -EINVAL;
11025                                 meta->ret_btf_id  = ret;
11026                         }
11027                         break;
11028                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11029                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11030                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11031                                 return -EINVAL;
11032                         }
11033                         if (!reg->ref_obj_id) {
11034                                 verbose(env, "allocated object must be referenced\n");
11035                                 return -EINVAL;
11036                         }
11037                         if (meta->btf == btf_vmlinux &&
11038                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11039                                 meta->arg_btf = reg->btf;
11040                                 meta->arg_btf_id = reg->btf_id;
11041                         }
11042                         break;
11043                 case KF_ARG_PTR_TO_DYNPTR:
11044                 {
11045                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11046                         int clone_ref_obj_id = 0;
11047
11048                         if (reg->type != PTR_TO_STACK &&
11049                             reg->type != CONST_PTR_TO_DYNPTR) {
11050                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11051                                 return -EINVAL;
11052                         }
11053
11054                         if (reg->type == CONST_PTR_TO_DYNPTR)
11055                                 dynptr_arg_type |= MEM_RDONLY;
11056
11057                         if (is_kfunc_arg_uninit(btf, &args[i]))
11058                                 dynptr_arg_type |= MEM_UNINIT;
11059
11060                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11061                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11062                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11063                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11064                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11065                                    (dynptr_arg_type & MEM_UNINIT)) {
11066                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11067
11068                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11069                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11070                                         return -EFAULT;
11071                                 }
11072
11073                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11074                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11075                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11076                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11077                                         return -EFAULT;
11078                                 }
11079                         }
11080
11081                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11082                         if (ret < 0)
11083                                 return ret;
11084
11085                         if (!(dynptr_arg_type & MEM_UNINIT)) {
11086                                 int id = dynptr_id(env, reg);
11087
11088                                 if (id < 0) {
11089                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11090                                         return id;
11091                                 }
11092                                 meta->initialized_dynptr.id = id;
11093                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11094                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11095                         }
11096
11097                         break;
11098                 }
11099                 case KF_ARG_PTR_TO_ITER:
11100                         ret = process_iter_arg(env, regno, insn_idx, meta);
11101                         if (ret < 0)
11102                                 return ret;
11103                         break;
11104                 case KF_ARG_PTR_TO_LIST_HEAD:
11105                         if (reg->type != PTR_TO_MAP_VALUE &&
11106                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11107                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11108                                 return -EINVAL;
11109                         }
11110                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11111                                 verbose(env, "allocated object must be referenced\n");
11112                                 return -EINVAL;
11113                         }
11114                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11115                         if (ret < 0)
11116                                 return ret;
11117                         break;
11118                 case KF_ARG_PTR_TO_RB_ROOT:
11119                         if (reg->type != PTR_TO_MAP_VALUE &&
11120                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11121                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11122                                 return -EINVAL;
11123                         }
11124                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11125                                 verbose(env, "allocated object must be referenced\n");
11126                                 return -EINVAL;
11127                         }
11128                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11129                         if (ret < 0)
11130                                 return ret;
11131                         break;
11132                 case KF_ARG_PTR_TO_LIST_NODE:
11133                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11134                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11135                                 return -EINVAL;
11136                         }
11137                         if (!reg->ref_obj_id) {
11138                                 verbose(env, "allocated object must be referenced\n");
11139                                 return -EINVAL;
11140                         }
11141                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11142                         if (ret < 0)
11143                                 return ret;
11144                         break;
11145                 case KF_ARG_PTR_TO_RB_NODE:
11146                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11147                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11148                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
11149                                         return -EINVAL;
11150                                 }
11151                                 if (in_rbtree_lock_required_cb(env)) {
11152                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11153                                         return -EINVAL;
11154                                 }
11155                         } else {
11156                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11157                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
11158                                         return -EINVAL;
11159                                 }
11160                                 if (!reg->ref_obj_id) {
11161                                         verbose(env, "allocated object must be referenced\n");
11162                                         return -EINVAL;
11163                                 }
11164                         }
11165
11166                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11167                         if (ret < 0)
11168                                 return ret;
11169                         break;
11170                 case KF_ARG_PTR_TO_BTF_ID:
11171                         /* Only base_type is checked, further checks are done here */
11172                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11173                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11174                             !reg2btf_ids[base_type(reg->type)]) {
11175                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11176                                 verbose(env, "expected %s or socket\n",
11177                                         reg_type_str(env, base_type(reg->type) |
11178                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11179                                 return -EINVAL;
11180                         }
11181                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11182                         if (ret < 0)
11183                                 return ret;
11184                         break;
11185                 case KF_ARG_PTR_TO_MEM:
11186                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11187                         if (IS_ERR(resolve_ret)) {
11188                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11189                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11190                                 return -EINVAL;
11191                         }
11192                         ret = check_mem_reg(env, reg, regno, type_size);
11193                         if (ret < 0)
11194                                 return ret;
11195                         break;
11196                 case KF_ARG_PTR_TO_MEM_SIZE:
11197                 {
11198                         struct bpf_reg_state *buff_reg = &regs[regno];
11199                         const struct btf_param *buff_arg = &args[i];
11200                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11201                         const struct btf_param *size_arg = &args[i + 1];
11202
11203                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11204                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11205                                 if (ret < 0) {
11206                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11207                                         return ret;
11208                                 }
11209                         }
11210
11211                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11212                                 if (meta->arg_constant.found) {
11213                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11214                                         return -EFAULT;
11215                                 }
11216                                 if (!tnum_is_const(size_reg->var_off)) {
11217                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11218                                         return -EINVAL;
11219                                 }
11220                                 meta->arg_constant.found = true;
11221                                 meta->arg_constant.value = size_reg->var_off.value;
11222                         }
11223
11224                         /* Skip next '__sz' or '__szk' argument */
11225                         i++;
11226                         break;
11227                 }
11228                 case KF_ARG_PTR_TO_CALLBACK:
11229                         if (reg->type != PTR_TO_FUNC) {
11230                                 verbose(env, "arg%d expected pointer to func\n", i);
11231                                 return -EINVAL;
11232                         }
11233                         meta->subprogno = reg->subprogno;
11234                         break;
11235                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11236                         if (!type_is_ptr_alloc_obj(reg->type)) {
11237                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11238                                 return -EINVAL;
11239                         }
11240                         if (!type_is_non_owning_ref(reg->type))
11241                                 meta->arg_owning_ref = true;
11242
11243                         rec = reg_btf_record(reg);
11244                         if (!rec) {
11245                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11246                                 return -EFAULT;
11247                         }
11248
11249                         if (rec->refcount_off < 0) {
11250                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11251                                 return -EINVAL;
11252                         }
11253
11254                         meta->arg_btf = reg->btf;
11255                         meta->arg_btf_id = reg->btf_id;
11256                         break;
11257                 }
11258         }
11259
11260         if (is_kfunc_release(meta) && !meta->release_regno) {
11261                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11262                         func_name);
11263                 return -EINVAL;
11264         }
11265
11266         return 0;
11267 }
11268
11269 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11270                             struct bpf_insn *insn,
11271                             struct bpf_kfunc_call_arg_meta *meta,
11272                             const char **kfunc_name)
11273 {
11274         const struct btf_type *func, *func_proto;
11275         u32 func_id, *kfunc_flags;
11276         const char *func_name;
11277         struct btf *desc_btf;
11278
11279         if (kfunc_name)
11280                 *kfunc_name = NULL;
11281
11282         if (!insn->imm)
11283                 return -EINVAL;
11284
11285         desc_btf = find_kfunc_desc_btf(env, insn->off);
11286         if (IS_ERR(desc_btf))
11287                 return PTR_ERR(desc_btf);
11288
11289         func_id = insn->imm;
11290         func = btf_type_by_id(desc_btf, func_id);
11291         func_name = btf_name_by_offset(desc_btf, func->name_off);
11292         if (kfunc_name)
11293                 *kfunc_name = func_name;
11294         func_proto = btf_type_by_id(desc_btf, func->type);
11295
11296         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11297         if (!kfunc_flags) {
11298                 return -EACCES;
11299         }
11300
11301         memset(meta, 0, sizeof(*meta));
11302         meta->btf = desc_btf;
11303         meta->func_id = func_id;
11304         meta->kfunc_flags = *kfunc_flags;
11305         meta->func_proto = func_proto;
11306         meta->func_name = func_name;
11307
11308         return 0;
11309 }
11310
11311 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11312                             int *insn_idx_p)
11313 {
11314         const struct btf_type *t, *ptr_type;
11315         u32 i, nargs, ptr_type_id, release_ref_obj_id;
11316         struct bpf_reg_state *regs = cur_regs(env);
11317         const char *func_name, *ptr_type_name;
11318         bool sleepable, rcu_lock, rcu_unlock;
11319         struct bpf_kfunc_call_arg_meta meta;
11320         struct bpf_insn_aux_data *insn_aux;
11321         int err, insn_idx = *insn_idx_p;
11322         const struct btf_param *args;
11323         const struct btf_type *ret_t;
11324         struct btf *desc_btf;
11325
11326         /* skip for now, but return error when we find this in fixup_kfunc_call */
11327         if (!insn->imm)
11328                 return 0;
11329
11330         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11331         if (err == -EACCES && func_name)
11332                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11333         if (err)
11334                 return err;
11335         desc_btf = meta.btf;
11336         insn_aux = &env->insn_aux_data[insn_idx];
11337
11338         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11339
11340         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11341                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11342                 return -EACCES;
11343         }
11344
11345         sleepable = is_kfunc_sleepable(&meta);
11346         if (sleepable && !env->prog->aux->sleepable) {
11347                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11348                 return -EACCES;
11349         }
11350
11351         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11352         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11353
11354         if (env->cur_state->active_rcu_lock) {
11355                 struct bpf_func_state *state;
11356                 struct bpf_reg_state *reg;
11357
11358                 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11359                         verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11360                         return -EACCES;
11361                 }
11362
11363                 if (rcu_lock) {
11364                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11365                         return -EINVAL;
11366                 } else if (rcu_unlock) {
11367                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11368                                 if (reg->type & MEM_RCU) {
11369                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11370                                         reg->type |= PTR_UNTRUSTED;
11371                                 }
11372                         }));
11373                         env->cur_state->active_rcu_lock = false;
11374                 } else if (sleepable) {
11375                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11376                         return -EACCES;
11377                 }
11378         } else if (rcu_lock) {
11379                 env->cur_state->active_rcu_lock = true;
11380         } else if (rcu_unlock) {
11381                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11382                 return -EINVAL;
11383         }
11384
11385         /* Check the arguments */
11386         err = check_kfunc_args(env, &meta, insn_idx);
11387         if (err < 0)
11388                 return err;
11389         /* In case of release function, we get register number of refcounted
11390          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11391          */
11392         if (meta.release_regno) {
11393                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11394                 if (err) {
11395                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11396                                 func_name, meta.func_id);
11397                         return err;
11398                 }
11399         }
11400
11401         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11402             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11403             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11404                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11405                 insn_aux->insert_off = regs[BPF_REG_2].off;
11406                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11407                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11408                 if (err) {
11409                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11410                                 func_name, meta.func_id);
11411                         return err;
11412                 }
11413
11414                 err = release_reference(env, release_ref_obj_id);
11415                 if (err) {
11416                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11417                                 func_name, meta.func_id);
11418                         return err;
11419                 }
11420         }
11421
11422         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11423                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11424                                         set_rbtree_add_callback_state);
11425                 if (err) {
11426                         verbose(env, "kfunc %s#%d failed callback verification\n",
11427                                 func_name, meta.func_id);
11428                         return err;
11429                 }
11430         }
11431
11432         for (i = 0; i < CALLER_SAVED_REGS; i++)
11433                 mark_reg_not_init(env, regs, caller_saved[i]);
11434
11435         /* Check return type */
11436         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11437
11438         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11439                 /* Only exception is bpf_obj_new_impl */
11440                 if (meta.btf != btf_vmlinux ||
11441                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11442                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11443                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11444                         return -EINVAL;
11445                 }
11446         }
11447
11448         if (btf_type_is_scalar(t)) {
11449                 mark_reg_unknown(env, regs, BPF_REG_0);
11450                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11451         } else if (btf_type_is_ptr(t)) {
11452                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11453
11454                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11455                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11456                                 struct btf *ret_btf;
11457                                 u32 ret_btf_id;
11458
11459                                 if (unlikely(!bpf_global_ma_set))
11460                                         return -ENOMEM;
11461
11462                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11463                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11464                                         return -EINVAL;
11465                                 }
11466
11467                                 ret_btf = env->prog->aux->btf;
11468                                 ret_btf_id = meta.arg_constant.value;
11469
11470                                 /* This may be NULL due to user not supplying a BTF */
11471                                 if (!ret_btf) {
11472                                         verbose(env, "bpf_obj_new requires prog BTF\n");
11473                                         return -EINVAL;
11474                                 }
11475
11476                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11477                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11478                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11479                                         return -EINVAL;
11480                                 }
11481
11482                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11483                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11484                                 regs[BPF_REG_0].btf = ret_btf;
11485                                 regs[BPF_REG_0].btf_id = ret_btf_id;
11486
11487                                 insn_aux->obj_new_size = ret_t->size;
11488                                 insn_aux->kptr_struct_meta =
11489                                         btf_find_struct_meta(ret_btf, ret_btf_id);
11490                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11491                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11492                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11493                                 regs[BPF_REG_0].btf = meta.arg_btf;
11494                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11495
11496                                 insn_aux->kptr_struct_meta =
11497                                         btf_find_struct_meta(meta.arg_btf,
11498                                                              meta.arg_btf_id);
11499                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11500                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11501                                 struct btf_field *field = meta.arg_list_head.field;
11502
11503                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11504                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11505                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11506                                 struct btf_field *field = meta.arg_rbtree_root.field;
11507
11508                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11509                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11510                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11511                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11512                                 regs[BPF_REG_0].btf = desc_btf;
11513                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11514                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11515                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11516                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
11517                                         verbose(env,
11518                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11519                                         return -EINVAL;
11520                                 }
11521
11522                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11523                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11524                                 regs[BPF_REG_0].btf = desc_btf;
11525                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11526                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11527                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11528                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11529
11530                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11531
11532                                 if (!meta.arg_constant.found) {
11533                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11534                                         return -EFAULT;
11535                                 }
11536
11537                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11538
11539                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11540                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11541
11542                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11543                                         regs[BPF_REG_0].type |= MEM_RDONLY;
11544                                 } else {
11545                                         /* this will set env->seen_direct_write to true */
11546                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11547                                                 verbose(env, "the prog does not allow writes to packet data\n");
11548                                                 return -EINVAL;
11549                                         }
11550                                 }
11551
11552                                 if (!meta.initialized_dynptr.id) {
11553                                         verbose(env, "verifier internal error: no dynptr id\n");
11554                                         return -EFAULT;
11555                                 }
11556                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11557
11558                                 /* we don't need to set BPF_REG_0's ref obj id
11559                                  * because packet slices are not refcounted (see
11560                                  * dynptr_type_refcounted)
11561                                  */
11562                         } else {
11563                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
11564                                         meta.func_name);
11565                                 return -EFAULT;
11566                         }
11567                 } else if (!__btf_type_is_struct(ptr_type)) {
11568                         if (!meta.r0_size) {
11569                                 __u32 sz;
11570
11571                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11572                                         meta.r0_size = sz;
11573                                         meta.r0_rdonly = true;
11574                                 }
11575                         }
11576                         if (!meta.r0_size) {
11577                                 ptr_type_name = btf_name_by_offset(desc_btf,
11578                                                                    ptr_type->name_off);
11579                                 verbose(env,
11580                                         "kernel function %s returns pointer type %s %s is not supported\n",
11581                                         func_name,
11582                                         btf_type_str(ptr_type),
11583                                         ptr_type_name);
11584                                 return -EINVAL;
11585                         }
11586
11587                         mark_reg_known_zero(env, regs, BPF_REG_0);
11588                         regs[BPF_REG_0].type = PTR_TO_MEM;
11589                         regs[BPF_REG_0].mem_size = meta.r0_size;
11590
11591                         if (meta.r0_rdonly)
11592                                 regs[BPF_REG_0].type |= MEM_RDONLY;
11593
11594                         /* Ensures we don't access the memory after a release_reference() */
11595                         if (meta.ref_obj_id)
11596                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11597                 } else {
11598                         mark_reg_known_zero(env, regs, BPF_REG_0);
11599                         regs[BPF_REG_0].btf = desc_btf;
11600                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11601                         regs[BPF_REG_0].btf_id = ptr_type_id;
11602                 }
11603
11604                 if (is_kfunc_ret_null(&meta)) {
11605                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11606                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11607                         regs[BPF_REG_0].id = ++env->id_gen;
11608                 }
11609                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11610                 if (is_kfunc_acquire(&meta)) {
11611                         int id = acquire_reference_state(env, insn_idx);
11612
11613                         if (id < 0)
11614                                 return id;
11615                         if (is_kfunc_ret_null(&meta))
11616                                 regs[BPF_REG_0].id = id;
11617                         regs[BPF_REG_0].ref_obj_id = id;
11618                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11619                         ref_set_non_owning(env, &regs[BPF_REG_0]);
11620                 }
11621
11622                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11623                         regs[BPF_REG_0].id = ++env->id_gen;
11624         } else if (btf_type_is_void(t)) {
11625                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11626                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11627                                 insn_aux->kptr_struct_meta =
11628                                         btf_find_struct_meta(meta.arg_btf,
11629                                                              meta.arg_btf_id);
11630                         }
11631                 }
11632         }
11633
11634         nargs = btf_type_vlen(meta.func_proto);
11635         args = (const struct btf_param *)(meta.func_proto + 1);
11636         for (i = 0; i < nargs; i++) {
11637                 u32 regno = i + 1;
11638
11639                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11640                 if (btf_type_is_ptr(t))
11641                         mark_btf_func_reg_size(env, regno, sizeof(void *));
11642                 else
11643                         /* scalar. ensured by btf_check_kfunc_arg_match() */
11644                         mark_btf_func_reg_size(env, regno, t->size);
11645         }
11646
11647         if (is_iter_next_kfunc(&meta)) {
11648                 err = process_iter_next_call(env, insn_idx, &meta);
11649                 if (err)
11650                         return err;
11651         }
11652
11653         return 0;
11654 }
11655
11656 static bool signed_add_overflows(s64 a, s64 b)
11657 {
11658         /* Do the add in u64, where overflow is well-defined */
11659         s64 res = (s64)((u64)a + (u64)b);
11660
11661         if (b < 0)
11662                 return res > a;
11663         return res < a;
11664 }
11665
11666 static bool signed_add32_overflows(s32 a, s32 b)
11667 {
11668         /* Do the add in u32, where overflow is well-defined */
11669         s32 res = (s32)((u32)a + (u32)b);
11670
11671         if (b < 0)
11672                 return res > a;
11673         return res < a;
11674 }
11675
11676 static bool signed_sub_overflows(s64 a, s64 b)
11677 {
11678         /* Do the sub in u64, where overflow is well-defined */
11679         s64 res = (s64)((u64)a - (u64)b);
11680
11681         if (b < 0)
11682                 return res < a;
11683         return res > a;
11684 }
11685
11686 static bool signed_sub32_overflows(s32 a, s32 b)
11687 {
11688         /* Do the sub in u32, where overflow is well-defined */
11689         s32 res = (s32)((u32)a - (u32)b);
11690
11691         if (b < 0)
11692                 return res < a;
11693         return res > a;
11694 }
11695
11696 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11697                                   const struct bpf_reg_state *reg,
11698                                   enum bpf_reg_type type)
11699 {
11700         bool known = tnum_is_const(reg->var_off);
11701         s64 val = reg->var_off.value;
11702         s64 smin = reg->smin_value;
11703
11704         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11705                 verbose(env, "math between %s pointer and %lld is not allowed\n",
11706                         reg_type_str(env, type), val);
11707                 return false;
11708         }
11709
11710         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11711                 verbose(env, "%s pointer offset %d is not allowed\n",
11712                         reg_type_str(env, type), reg->off);
11713                 return false;
11714         }
11715
11716         if (smin == S64_MIN) {
11717                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11718                         reg_type_str(env, type));
11719                 return false;
11720         }
11721
11722         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11723                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11724                         smin, reg_type_str(env, type));
11725                 return false;
11726         }
11727
11728         return true;
11729 }
11730
11731 enum {
11732         REASON_BOUNDS   = -1,
11733         REASON_TYPE     = -2,
11734         REASON_PATHS    = -3,
11735         REASON_LIMIT    = -4,
11736         REASON_STACK    = -5,
11737 };
11738
11739 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11740                               u32 *alu_limit, bool mask_to_left)
11741 {
11742         u32 max = 0, ptr_limit = 0;
11743
11744         switch (ptr_reg->type) {
11745         case PTR_TO_STACK:
11746                 /* Offset 0 is out-of-bounds, but acceptable start for the
11747                  * left direction, see BPF_REG_FP. Also, unknown scalar
11748                  * offset where we would need to deal with min/max bounds is
11749                  * currently prohibited for unprivileged.
11750                  */
11751                 max = MAX_BPF_STACK + mask_to_left;
11752                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11753                 break;
11754         case PTR_TO_MAP_VALUE:
11755                 max = ptr_reg->map_ptr->value_size;
11756                 ptr_limit = (mask_to_left ?
11757                              ptr_reg->smin_value :
11758                              ptr_reg->umax_value) + ptr_reg->off;
11759                 break;
11760         default:
11761                 return REASON_TYPE;
11762         }
11763
11764         if (ptr_limit >= max)
11765                 return REASON_LIMIT;
11766         *alu_limit = ptr_limit;
11767         return 0;
11768 }
11769
11770 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11771                                     const struct bpf_insn *insn)
11772 {
11773         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11774 }
11775
11776 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11777                                        u32 alu_state, u32 alu_limit)
11778 {
11779         /* If we arrived here from different branches with different
11780          * state or limits to sanitize, then this won't work.
11781          */
11782         if (aux->alu_state &&
11783             (aux->alu_state != alu_state ||
11784              aux->alu_limit != alu_limit))
11785                 return REASON_PATHS;
11786
11787         /* Corresponding fixup done in do_misc_fixups(). */
11788         aux->alu_state = alu_state;
11789         aux->alu_limit = alu_limit;
11790         return 0;
11791 }
11792
11793 static int sanitize_val_alu(struct bpf_verifier_env *env,
11794                             struct bpf_insn *insn)
11795 {
11796         struct bpf_insn_aux_data *aux = cur_aux(env);
11797
11798         if (can_skip_alu_sanitation(env, insn))
11799                 return 0;
11800
11801         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11802 }
11803
11804 static bool sanitize_needed(u8 opcode)
11805 {
11806         return opcode == BPF_ADD || opcode == BPF_SUB;
11807 }
11808
11809 struct bpf_sanitize_info {
11810         struct bpf_insn_aux_data aux;
11811         bool mask_to_left;
11812 };
11813
11814 static struct bpf_verifier_state *
11815 sanitize_speculative_path(struct bpf_verifier_env *env,
11816                           const struct bpf_insn *insn,
11817                           u32 next_idx, u32 curr_idx)
11818 {
11819         struct bpf_verifier_state *branch;
11820         struct bpf_reg_state *regs;
11821
11822         branch = push_stack(env, next_idx, curr_idx, true);
11823         if (branch && insn) {
11824                 regs = branch->frame[branch->curframe]->regs;
11825                 if (BPF_SRC(insn->code) == BPF_K) {
11826                         mark_reg_unknown(env, regs, insn->dst_reg);
11827                 } else if (BPF_SRC(insn->code) == BPF_X) {
11828                         mark_reg_unknown(env, regs, insn->dst_reg);
11829                         mark_reg_unknown(env, regs, insn->src_reg);
11830                 }
11831         }
11832         return branch;
11833 }
11834
11835 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11836                             struct bpf_insn *insn,
11837                             const struct bpf_reg_state *ptr_reg,
11838                             const struct bpf_reg_state *off_reg,
11839                             struct bpf_reg_state *dst_reg,
11840                             struct bpf_sanitize_info *info,
11841                             const bool commit_window)
11842 {
11843         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11844         struct bpf_verifier_state *vstate = env->cur_state;
11845         bool off_is_imm = tnum_is_const(off_reg->var_off);
11846         bool off_is_neg = off_reg->smin_value < 0;
11847         bool ptr_is_dst_reg = ptr_reg == dst_reg;
11848         u8 opcode = BPF_OP(insn->code);
11849         u32 alu_state, alu_limit;
11850         struct bpf_reg_state tmp;
11851         bool ret;
11852         int err;
11853
11854         if (can_skip_alu_sanitation(env, insn))
11855                 return 0;
11856
11857         /* We already marked aux for masking from non-speculative
11858          * paths, thus we got here in the first place. We only care
11859          * to explore bad access from here.
11860          */
11861         if (vstate->speculative)
11862                 goto do_sim;
11863
11864         if (!commit_window) {
11865                 if (!tnum_is_const(off_reg->var_off) &&
11866                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11867                         return REASON_BOUNDS;
11868
11869                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11870                                      (opcode == BPF_SUB && !off_is_neg);
11871         }
11872
11873         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11874         if (err < 0)
11875                 return err;
11876
11877         if (commit_window) {
11878                 /* In commit phase we narrow the masking window based on
11879                  * the observed pointer move after the simulated operation.
11880                  */
11881                 alu_state = info->aux.alu_state;
11882                 alu_limit = abs(info->aux.alu_limit - alu_limit);
11883         } else {
11884                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11885                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11886                 alu_state |= ptr_is_dst_reg ?
11887                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11888
11889                 /* Limit pruning on unknown scalars to enable deep search for
11890                  * potential masking differences from other program paths.
11891                  */
11892                 if (!off_is_imm)
11893                         env->explore_alu_limits = true;
11894         }
11895
11896         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11897         if (err < 0)
11898                 return err;
11899 do_sim:
11900         /* If we're in commit phase, we're done here given we already
11901          * pushed the truncated dst_reg into the speculative verification
11902          * stack.
11903          *
11904          * Also, when register is a known constant, we rewrite register-based
11905          * operation to immediate-based, and thus do not need masking (and as
11906          * a consequence, do not need to simulate the zero-truncation either).
11907          */
11908         if (commit_window || off_is_imm)
11909                 return 0;
11910
11911         /* Simulate and find potential out-of-bounds access under
11912          * speculative execution from truncation as a result of
11913          * masking when off was not within expected range. If off
11914          * sits in dst, then we temporarily need to move ptr there
11915          * to simulate dst (== 0) +/-= ptr. Needed, for example,
11916          * for cases where we use K-based arithmetic in one direction
11917          * and truncated reg-based in the other in order to explore
11918          * bad access.
11919          */
11920         if (!ptr_is_dst_reg) {
11921                 tmp = *dst_reg;
11922                 copy_register_state(dst_reg, ptr_reg);
11923         }
11924         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11925                                         env->insn_idx);
11926         if (!ptr_is_dst_reg && ret)
11927                 *dst_reg = tmp;
11928         return !ret ? REASON_STACK : 0;
11929 }
11930
11931 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11932 {
11933         struct bpf_verifier_state *vstate = env->cur_state;
11934
11935         /* If we simulate paths under speculation, we don't update the
11936          * insn as 'seen' such that when we verify unreachable paths in
11937          * the non-speculative domain, sanitize_dead_code() can still
11938          * rewrite/sanitize them.
11939          */
11940         if (!vstate->speculative)
11941                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11942 }
11943
11944 static int sanitize_err(struct bpf_verifier_env *env,
11945                         const struct bpf_insn *insn, int reason,
11946                         const struct bpf_reg_state *off_reg,
11947                         const struct bpf_reg_state *dst_reg)
11948 {
11949         static const char *err = "pointer arithmetic with it prohibited for !root";
11950         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11951         u32 dst = insn->dst_reg, src = insn->src_reg;
11952
11953         switch (reason) {
11954         case REASON_BOUNDS:
11955                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11956                         off_reg == dst_reg ? dst : src, err);
11957                 break;
11958         case REASON_TYPE:
11959                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11960                         off_reg == dst_reg ? src : dst, err);
11961                 break;
11962         case REASON_PATHS:
11963                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11964                         dst, op, err);
11965                 break;
11966         case REASON_LIMIT:
11967                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11968                         dst, op, err);
11969                 break;
11970         case REASON_STACK:
11971                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11972                         dst, err);
11973                 break;
11974         default:
11975                 verbose(env, "verifier internal error: unknown reason (%d)\n",
11976                         reason);
11977                 break;
11978         }
11979
11980         return -EACCES;
11981 }
11982
11983 /* check that stack access falls within stack limits and that 'reg' doesn't
11984  * have a variable offset.
11985  *
11986  * Variable offset is prohibited for unprivileged mode for simplicity since it
11987  * requires corresponding support in Spectre masking for stack ALU.  See also
11988  * retrieve_ptr_limit().
11989  *
11990  *
11991  * 'off' includes 'reg->off'.
11992  */
11993 static int check_stack_access_for_ptr_arithmetic(
11994                                 struct bpf_verifier_env *env,
11995                                 int regno,
11996                                 const struct bpf_reg_state *reg,
11997                                 int off)
11998 {
11999         if (!tnum_is_const(reg->var_off)) {
12000                 char tn_buf[48];
12001
12002                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12003                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12004                         regno, tn_buf, off);
12005                 return -EACCES;
12006         }
12007
12008         if (off >= 0 || off < -MAX_BPF_STACK) {
12009                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12010                         "prohibited for !root; off=%d\n", regno, off);
12011                 return -EACCES;
12012         }
12013
12014         return 0;
12015 }
12016
12017 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12018                                  const struct bpf_insn *insn,
12019                                  const struct bpf_reg_state *dst_reg)
12020 {
12021         u32 dst = insn->dst_reg;
12022
12023         /* For unprivileged we require that resulting offset must be in bounds
12024          * in order to be able to sanitize access later on.
12025          */
12026         if (env->bypass_spec_v1)
12027                 return 0;
12028
12029         switch (dst_reg->type) {
12030         case PTR_TO_STACK:
12031                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12032                                         dst_reg->off + dst_reg->var_off.value))
12033                         return -EACCES;
12034                 break;
12035         case PTR_TO_MAP_VALUE:
12036                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12037                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12038                                 "prohibited for !root\n", dst);
12039                         return -EACCES;
12040                 }
12041                 break;
12042         default:
12043                 break;
12044         }
12045
12046         return 0;
12047 }
12048
12049 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12050  * Caller should also handle BPF_MOV case separately.
12051  * If we return -EACCES, caller may want to try again treating pointer as a
12052  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12053  */
12054 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12055                                    struct bpf_insn *insn,
12056                                    const struct bpf_reg_state *ptr_reg,
12057                                    const struct bpf_reg_state *off_reg)
12058 {
12059         struct bpf_verifier_state *vstate = env->cur_state;
12060         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12061         struct bpf_reg_state *regs = state->regs, *dst_reg;
12062         bool known = tnum_is_const(off_reg->var_off);
12063         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12064             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12065         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12066             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12067         struct bpf_sanitize_info info = {};
12068         u8 opcode = BPF_OP(insn->code);
12069         u32 dst = insn->dst_reg;
12070         int ret;
12071
12072         dst_reg = &regs[dst];
12073
12074         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12075             smin_val > smax_val || umin_val > umax_val) {
12076                 /* Taint dst register if offset had invalid bounds derived from
12077                  * e.g. dead branches.
12078                  */
12079                 __mark_reg_unknown(env, dst_reg);
12080                 return 0;
12081         }
12082
12083         if (BPF_CLASS(insn->code) != BPF_ALU64) {
12084                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12085                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12086                         __mark_reg_unknown(env, dst_reg);
12087                         return 0;
12088                 }
12089
12090                 verbose(env,
12091                         "R%d 32-bit pointer arithmetic prohibited\n",
12092                         dst);
12093                 return -EACCES;
12094         }
12095
12096         if (ptr_reg->type & PTR_MAYBE_NULL) {
12097                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12098                         dst, reg_type_str(env, ptr_reg->type));
12099                 return -EACCES;
12100         }
12101
12102         switch (base_type(ptr_reg->type)) {
12103         case PTR_TO_FLOW_KEYS:
12104                 if (known)
12105                         break;
12106                 fallthrough;
12107         case CONST_PTR_TO_MAP:
12108                 /* smin_val represents the known value */
12109                 if (known && smin_val == 0 && opcode == BPF_ADD)
12110                         break;
12111                 fallthrough;
12112         case PTR_TO_PACKET_END:
12113         case PTR_TO_SOCKET:
12114         case PTR_TO_SOCK_COMMON:
12115         case PTR_TO_TCP_SOCK:
12116         case PTR_TO_XDP_SOCK:
12117                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12118                         dst, reg_type_str(env, ptr_reg->type));
12119                 return -EACCES;
12120         default:
12121                 break;
12122         }
12123
12124         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12125          * The id may be overwritten later if we create a new variable offset.
12126          */
12127         dst_reg->type = ptr_reg->type;
12128         dst_reg->id = ptr_reg->id;
12129
12130         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12131             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12132                 return -EINVAL;
12133
12134         /* pointer types do not carry 32-bit bounds at the moment. */
12135         __mark_reg32_unbounded(dst_reg);
12136
12137         if (sanitize_needed(opcode)) {
12138                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12139                                        &info, false);
12140                 if (ret < 0)
12141                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12142         }
12143
12144         switch (opcode) {
12145         case BPF_ADD:
12146                 /* We can take a fixed offset as long as it doesn't overflow
12147                  * the s32 'off' field
12148                  */
12149                 if (known && (ptr_reg->off + smin_val ==
12150                               (s64)(s32)(ptr_reg->off + smin_val))) {
12151                         /* pointer += K.  Accumulate it into fixed offset */
12152                         dst_reg->smin_value = smin_ptr;
12153                         dst_reg->smax_value = smax_ptr;
12154                         dst_reg->umin_value = umin_ptr;
12155                         dst_reg->umax_value = umax_ptr;
12156                         dst_reg->var_off = ptr_reg->var_off;
12157                         dst_reg->off = ptr_reg->off + smin_val;
12158                         dst_reg->raw = ptr_reg->raw;
12159                         break;
12160                 }
12161                 /* A new variable offset is created.  Note that off_reg->off
12162                  * == 0, since it's a scalar.
12163                  * dst_reg gets the pointer type and since some positive
12164                  * integer value was added to the pointer, give it a new 'id'
12165                  * if it's a PTR_TO_PACKET.
12166                  * this creates a new 'base' pointer, off_reg (variable) gets
12167                  * added into the variable offset, and we copy the fixed offset
12168                  * from ptr_reg.
12169                  */
12170                 if (signed_add_overflows(smin_ptr, smin_val) ||
12171                     signed_add_overflows(smax_ptr, smax_val)) {
12172                         dst_reg->smin_value = S64_MIN;
12173                         dst_reg->smax_value = S64_MAX;
12174                 } else {
12175                         dst_reg->smin_value = smin_ptr + smin_val;
12176                         dst_reg->smax_value = smax_ptr + smax_val;
12177                 }
12178                 if (umin_ptr + umin_val < umin_ptr ||
12179                     umax_ptr + umax_val < umax_ptr) {
12180                         dst_reg->umin_value = 0;
12181                         dst_reg->umax_value = U64_MAX;
12182                 } else {
12183                         dst_reg->umin_value = umin_ptr + umin_val;
12184                         dst_reg->umax_value = umax_ptr + umax_val;
12185                 }
12186                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12187                 dst_reg->off = ptr_reg->off;
12188                 dst_reg->raw = ptr_reg->raw;
12189                 if (reg_is_pkt_pointer(ptr_reg)) {
12190                         dst_reg->id = ++env->id_gen;
12191                         /* something was added to pkt_ptr, set range to zero */
12192                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12193                 }
12194                 break;
12195         case BPF_SUB:
12196                 if (dst_reg == off_reg) {
12197                         /* scalar -= pointer.  Creates an unknown scalar */
12198                         verbose(env, "R%d tried to subtract pointer from scalar\n",
12199                                 dst);
12200                         return -EACCES;
12201                 }
12202                 /* We don't allow subtraction from FP, because (according to
12203                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12204                  * be able to deal with it.
12205                  */
12206                 if (ptr_reg->type == PTR_TO_STACK) {
12207                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12208                                 dst);
12209                         return -EACCES;
12210                 }
12211                 if (known && (ptr_reg->off - smin_val ==
12212                               (s64)(s32)(ptr_reg->off - smin_val))) {
12213                         /* pointer -= K.  Subtract it from fixed offset */
12214                         dst_reg->smin_value = smin_ptr;
12215                         dst_reg->smax_value = smax_ptr;
12216                         dst_reg->umin_value = umin_ptr;
12217                         dst_reg->umax_value = umax_ptr;
12218                         dst_reg->var_off = ptr_reg->var_off;
12219                         dst_reg->id = ptr_reg->id;
12220                         dst_reg->off = ptr_reg->off - smin_val;
12221                         dst_reg->raw = ptr_reg->raw;
12222                         break;
12223                 }
12224                 /* A new variable offset is created.  If the subtrahend is known
12225                  * nonnegative, then any reg->range we had before is still good.
12226                  */
12227                 if (signed_sub_overflows(smin_ptr, smax_val) ||
12228                     signed_sub_overflows(smax_ptr, smin_val)) {
12229                         /* Overflow possible, we know nothing */
12230                         dst_reg->smin_value = S64_MIN;
12231                         dst_reg->smax_value = S64_MAX;
12232                 } else {
12233                         dst_reg->smin_value = smin_ptr - smax_val;
12234                         dst_reg->smax_value = smax_ptr - smin_val;
12235                 }
12236                 if (umin_ptr < umax_val) {
12237                         /* Overflow possible, we know nothing */
12238                         dst_reg->umin_value = 0;
12239                         dst_reg->umax_value = U64_MAX;
12240                 } else {
12241                         /* Cannot overflow (as long as bounds are consistent) */
12242                         dst_reg->umin_value = umin_ptr - umax_val;
12243                         dst_reg->umax_value = umax_ptr - umin_val;
12244                 }
12245                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12246                 dst_reg->off = ptr_reg->off;
12247                 dst_reg->raw = ptr_reg->raw;
12248                 if (reg_is_pkt_pointer(ptr_reg)) {
12249                         dst_reg->id = ++env->id_gen;
12250                         /* something was added to pkt_ptr, set range to zero */
12251                         if (smin_val < 0)
12252                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12253                 }
12254                 break;
12255         case BPF_AND:
12256         case BPF_OR:
12257         case BPF_XOR:
12258                 /* bitwise ops on pointers are troublesome, prohibit. */
12259                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12260                         dst, bpf_alu_string[opcode >> 4]);
12261                 return -EACCES;
12262         default:
12263                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12264                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12265                         dst, bpf_alu_string[opcode >> 4]);
12266                 return -EACCES;
12267         }
12268
12269         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12270                 return -EINVAL;
12271         reg_bounds_sync(dst_reg);
12272         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12273                 return -EACCES;
12274         if (sanitize_needed(opcode)) {
12275                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12276                                        &info, true);
12277                 if (ret < 0)
12278                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12279         }
12280
12281         return 0;
12282 }
12283
12284 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12285                                  struct bpf_reg_state *src_reg)
12286 {
12287         s32 smin_val = src_reg->s32_min_value;
12288         s32 smax_val = src_reg->s32_max_value;
12289         u32 umin_val = src_reg->u32_min_value;
12290         u32 umax_val = src_reg->u32_max_value;
12291
12292         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12293             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12294                 dst_reg->s32_min_value = S32_MIN;
12295                 dst_reg->s32_max_value = S32_MAX;
12296         } else {
12297                 dst_reg->s32_min_value += smin_val;
12298                 dst_reg->s32_max_value += smax_val;
12299         }
12300         if (dst_reg->u32_min_value + umin_val < umin_val ||
12301             dst_reg->u32_max_value + umax_val < umax_val) {
12302                 dst_reg->u32_min_value = 0;
12303                 dst_reg->u32_max_value = U32_MAX;
12304         } else {
12305                 dst_reg->u32_min_value += umin_val;
12306                 dst_reg->u32_max_value += umax_val;
12307         }
12308 }
12309
12310 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12311                                struct bpf_reg_state *src_reg)
12312 {
12313         s64 smin_val = src_reg->smin_value;
12314         s64 smax_val = src_reg->smax_value;
12315         u64 umin_val = src_reg->umin_value;
12316         u64 umax_val = src_reg->umax_value;
12317
12318         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12319             signed_add_overflows(dst_reg->smax_value, smax_val)) {
12320                 dst_reg->smin_value = S64_MIN;
12321                 dst_reg->smax_value = S64_MAX;
12322         } else {
12323                 dst_reg->smin_value += smin_val;
12324                 dst_reg->smax_value += smax_val;
12325         }
12326         if (dst_reg->umin_value + umin_val < umin_val ||
12327             dst_reg->umax_value + umax_val < umax_val) {
12328                 dst_reg->umin_value = 0;
12329                 dst_reg->umax_value = U64_MAX;
12330         } else {
12331                 dst_reg->umin_value += umin_val;
12332                 dst_reg->umax_value += umax_val;
12333         }
12334 }
12335
12336 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12337                                  struct bpf_reg_state *src_reg)
12338 {
12339         s32 smin_val = src_reg->s32_min_value;
12340         s32 smax_val = src_reg->s32_max_value;
12341         u32 umin_val = src_reg->u32_min_value;
12342         u32 umax_val = src_reg->u32_max_value;
12343
12344         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12345             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12346                 /* Overflow possible, we know nothing */
12347                 dst_reg->s32_min_value = S32_MIN;
12348                 dst_reg->s32_max_value = S32_MAX;
12349         } else {
12350                 dst_reg->s32_min_value -= smax_val;
12351                 dst_reg->s32_max_value -= smin_val;
12352         }
12353         if (dst_reg->u32_min_value < umax_val) {
12354                 /* Overflow possible, we know nothing */
12355                 dst_reg->u32_min_value = 0;
12356                 dst_reg->u32_max_value = U32_MAX;
12357         } else {
12358                 /* Cannot overflow (as long as bounds are consistent) */
12359                 dst_reg->u32_min_value -= umax_val;
12360                 dst_reg->u32_max_value -= umin_val;
12361         }
12362 }
12363
12364 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12365                                struct bpf_reg_state *src_reg)
12366 {
12367         s64 smin_val = src_reg->smin_value;
12368         s64 smax_val = src_reg->smax_value;
12369         u64 umin_val = src_reg->umin_value;
12370         u64 umax_val = src_reg->umax_value;
12371
12372         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12373             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12374                 /* Overflow possible, we know nothing */
12375                 dst_reg->smin_value = S64_MIN;
12376                 dst_reg->smax_value = S64_MAX;
12377         } else {
12378                 dst_reg->smin_value -= smax_val;
12379                 dst_reg->smax_value -= smin_val;
12380         }
12381         if (dst_reg->umin_value < umax_val) {
12382                 /* Overflow possible, we know nothing */
12383                 dst_reg->umin_value = 0;
12384                 dst_reg->umax_value = U64_MAX;
12385         } else {
12386                 /* Cannot overflow (as long as bounds are consistent) */
12387                 dst_reg->umin_value -= umax_val;
12388                 dst_reg->umax_value -= umin_val;
12389         }
12390 }
12391
12392 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12393                                  struct bpf_reg_state *src_reg)
12394 {
12395         s32 smin_val = src_reg->s32_min_value;
12396         u32 umin_val = src_reg->u32_min_value;
12397         u32 umax_val = src_reg->u32_max_value;
12398
12399         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12400                 /* Ain't nobody got time to multiply that sign */
12401                 __mark_reg32_unbounded(dst_reg);
12402                 return;
12403         }
12404         /* Both values are positive, so we can work with unsigned and
12405          * copy the result to signed (unless it exceeds S32_MAX).
12406          */
12407         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12408                 /* Potential overflow, we know nothing */
12409                 __mark_reg32_unbounded(dst_reg);
12410                 return;
12411         }
12412         dst_reg->u32_min_value *= umin_val;
12413         dst_reg->u32_max_value *= umax_val;
12414         if (dst_reg->u32_max_value > S32_MAX) {
12415                 /* Overflow possible, we know nothing */
12416                 dst_reg->s32_min_value = S32_MIN;
12417                 dst_reg->s32_max_value = S32_MAX;
12418         } else {
12419                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12420                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12421         }
12422 }
12423
12424 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12425                                struct bpf_reg_state *src_reg)
12426 {
12427         s64 smin_val = src_reg->smin_value;
12428         u64 umin_val = src_reg->umin_value;
12429         u64 umax_val = src_reg->umax_value;
12430
12431         if (smin_val < 0 || dst_reg->smin_value < 0) {
12432                 /* Ain't nobody got time to multiply that sign */
12433                 __mark_reg64_unbounded(dst_reg);
12434                 return;
12435         }
12436         /* Both values are positive, so we can work with unsigned and
12437          * copy the result to signed (unless it exceeds S64_MAX).
12438          */
12439         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12440                 /* Potential overflow, we know nothing */
12441                 __mark_reg64_unbounded(dst_reg);
12442                 return;
12443         }
12444         dst_reg->umin_value *= umin_val;
12445         dst_reg->umax_value *= umax_val;
12446         if (dst_reg->umax_value > S64_MAX) {
12447                 /* Overflow possible, we know nothing */
12448                 dst_reg->smin_value = S64_MIN;
12449                 dst_reg->smax_value = S64_MAX;
12450         } else {
12451                 dst_reg->smin_value = dst_reg->umin_value;
12452                 dst_reg->smax_value = dst_reg->umax_value;
12453         }
12454 }
12455
12456 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12457                                  struct bpf_reg_state *src_reg)
12458 {
12459         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12460         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12461         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12462         s32 smin_val = src_reg->s32_min_value;
12463         u32 umax_val = src_reg->u32_max_value;
12464
12465         if (src_known && dst_known) {
12466                 __mark_reg32_known(dst_reg, var32_off.value);
12467                 return;
12468         }
12469
12470         /* We get our minimum from the var_off, since that's inherently
12471          * bitwise.  Our maximum is the minimum of the operands' maxima.
12472          */
12473         dst_reg->u32_min_value = var32_off.value;
12474         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12475         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12476                 /* Lose signed bounds when ANDing negative numbers,
12477                  * ain't nobody got time for that.
12478                  */
12479                 dst_reg->s32_min_value = S32_MIN;
12480                 dst_reg->s32_max_value = S32_MAX;
12481         } else {
12482                 /* ANDing two positives gives a positive, so safe to
12483                  * cast result into s64.
12484                  */
12485                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12486                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12487         }
12488 }
12489
12490 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12491                                struct bpf_reg_state *src_reg)
12492 {
12493         bool src_known = tnum_is_const(src_reg->var_off);
12494         bool dst_known = tnum_is_const(dst_reg->var_off);
12495         s64 smin_val = src_reg->smin_value;
12496         u64 umax_val = src_reg->umax_value;
12497
12498         if (src_known && dst_known) {
12499                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12500                 return;
12501         }
12502
12503         /* We get our minimum from the var_off, since that's inherently
12504          * bitwise.  Our maximum is the minimum of the operands' maxima.
12505          */
12506         dst_reg->umin_value = dst_reg->var_off.value;
12507         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12508         if (dst_reg->smin_value < 0 || smin_val < 0) {
12509                 /* Lose signed bounds when ANDing negative numbers,
12510                  * ain't nobody got time for that.
12511                  */
12512                 dst_reg->smin_value = S64_MIN;
12513                 dst_reg->smax_value = S64_MAX;
12514         } else {
12515                 /* ANDing two positives gives a positive, so safe to
12516                  * cast result into s64.
12517                  */
12518                 dst_reg->smin_value = dst_reg->umin_value;
12519                 dst_reg->smax_value = dst_reg->umax_value;
12520         }
12521         /* We may learn something more from the var_off */
12522         __update_reg_bounds(dst_reg);
12523 }
12524
12525 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12526                                 struct bpf_reg_state *src_reg)
12527 {
12528         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12529         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12530         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12531         s32 smin_val = src_reg->s32_min_value;
12532         u32 umin_val = src_reg->u32_min_value;
12533
12534         if (src_known && dst_known) {
12535                 __mark_reg32_known(dst_reg, var32_off.value);
12536                 return;
12537         }
12538
12539         /* We get our maximum from the var_off, and our minimum is the
12540          * maximum of the operands' minima
12541          */
12542         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12543         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12544         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12545                 /* Lose signed bounds when ORing negative numbers,
12546                  * ain't nobody got time for that.
12547                  */
12548                 dst_reg->s32_min_value = S32_MIN;
12549                 dst_reg->s32_max_value = S32_MAX;
12550         } else {
12551                 /* ORing two positives gives a positive, so safe to
12552                  * cast result into s64.
12553                  */
12554                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12555                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12556         }
12557 }
12558
12559 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12560                               struct bpf_reg_state *src_reg)
12561 {
12562         bool src_known = tnum_is_const(src_reg->var_off);
12563         bool dst_known = tnum_is_const(dst_reg->var_off);
12564         s64 smin_val = src_reg->smin_value;
12565         u64 umin_val = src_reg->umin_value;
12566
12567         if (src_known && dst_known) {
12568                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12569                 return;
12570         }
12571
12572         /* We get our maximum from the var_off, and our minimum is the
12573          * maximum of the operands' minima
12574          */
12575         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12576         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12577         if (dst_reg->smin_value < 0 || smin_val < 0) {
12578                 /* Lose signed bounds when ORing negative numbers,
12579                  * ain't nobody got time for that.
12580                  */
12581                 dst_reg->smin_value = S64_MIN;
12582                 dst_reg->smax_value = S64_MAX;
12583         } else {
12584                 /* ORing two positives gives a positive, so safe to
12585                  * cast result into s64.
12586                  */
12587                 dst_reg->smin_value = dst_reg->umin_value;
12588                 dst_reg->smax_value = dst_reg->umax_value;
12589         }
12590         /* We may learn something more from the var_off */
12591         __update_reg_bounds(dst_reg);
12592 }
12593
12594 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12595                                  struct bpf_reg_state *src_reg)
12596 {
12597         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12598         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12599         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12600         s32 smin_val = src_reg->s32_min_value;
12601
12602         if (src_known && dst_known) {
12603                 __mark_reg32_known(dst_reg, var32_off.value);
12604                 return;
12605         }
12606
12607         /* We get both minimum and maximum from the var32_off. */
12608         dst_reg->u32_min_value = var32_off.value;
12609         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12610
12611         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12612                 /* XORing two positive sign numbers gives a positive,
12613                  * so safe to cast u32 result into s32.
12614                  */
12615                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12616                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12617         } else {
12618                 dst_reg->s32_min_value = S32_MIN;
12619                 dst_reg->s32_max_value = S32_MAX;
12620         }
12621 }
12622
12623 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12624                                struct bpf_reg_state *src_reg)
12625 {
12626         bool src_known = tnum_is_const(src_reg->var_off);
12627         bool dst_known = tnum_is_const(dst_reg->var_off);
12628         s64 smin_val = src_reg->smin_value;
12629
12630         if (src_known && dst_known) {
12631                 /* dst_reg->var_off.value has been updated earlier */
12632                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12633                 return;
12634         }
12635
12636         /* We get both minimum and maximum from the var_off. */
12637         dst_reg->umin_value = dst_reg->var_off.value;
12638         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12639
12640         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12641                 /* XORing two positive sign numbers gives a positive,
12642                  * so safe to cast u64 result into s64.
12643                  */
12644                 dst_reg->smin_value = dst_reg->umin_value;
12645                 dst_reg->smax_value = dst_reg->umax_value;
12646         } else {
12647                 dst_reg->smin_value = S64_MIN;
12648                 dst_reg->smax_value = S64_MAX;
12649         }
12650
12651         __update_reg_bounds(dst_reg);
12652 }
12653
12654 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12655                                    u64 umin_val, u64 umax_val)
12656 {
12657         /* We lose all sign bit information (except what we can pick
12658          * up from var_off)
12659          */
12660         dst_reg->s32_min_value = S32_MIN;
12661         dst_reg->s32_max_value = S32_MAX;
12662         /* If we might shift our top bit out, then we know nothing */
12663         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12664                 dst_reg->u32_min_value = 0;
12665                 dst_reg->u32_max_value = U32_MAX;
12666         } else {
12667                 dst_reg->u32_min_value <<= umin_val;
12668                 dst_reg->u32_max_value <<= umax_val;
12669         }
12670 }
12671
12672 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12673                                  struct bpf_reg_state *src_reg)
12674 {
12675         u32 umax_val = src_reg->u32_max_value;
12676         u32 umin_val = src_reg->u32_min_value;
12677         /* u32 alu operation will zext upper bits */
12678         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12679
12680         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12681         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12682         /* Not required but being careful mark reg64 bounds as unknown so
12683          * that we are forced to pick them up from tnum and zext later and
12684          * if some path skips this step we are still safe.
12685          */
12686         __mark_reg64_unbounded(dst_reg);
12687         __update_reg32_bounds(dst_reg);
12688 }
12689
12690 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12691                                    u64 umin_val, u64 umax_val)
12692 {
12693         /* Special case <<32 because it is a common compiler pattern to sign
12694          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12695          * positive we know this shift will also be positive so we can track
12696          * bounds correctly. Otherwise we lose all sign bit information except
12697          * what we can pick up from var_off. Perhaps we can generalize this
12698          * later to shifts of any length.
12699          */
12700         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12701                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12702         else
12703                 dst_reg->smax_value = S64_MAX;
12704
12705         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12706                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12707         else
12708                 dst_reg->smin_value = S64_MIN;
12709
12710         /* If we might shift our top bit out, then we know nothing */
12711         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12712                 dst_reg->umin_value = 0;
12713                 dst_reg->umax_value = U64_MAX;
12714         } else {
12715                 dst_reg->umin_value <<= umin_val;
12716                 dst_reg->umax_value <<= umax_val;
12717         }
12718 }
12719
12720 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12721                                struct bpf_reg_state *src_reg)
12722 {
12723         u64 umax_val = src_reg->umax_value;
12724         u64 umin_val = src_reg->umin_value;
12725
12726         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12727         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12728         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12729
12730         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12731         /* We may learn something more from the var_off */
12732         __update_reg_bounds(dst_reg);
12733 }
12734
12735 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12736                                  struct bpf_reg_state *src_reg)
12737 {
12738         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12739         u32 umax_val = src_reg->u32_max_value;
12740         u32 umin_val = src_reg->u32_min_value;
12741
12742         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12743          * be negative, then either:
12744          * 1) src_reg might be zero, so the sign bit of the result is
12745          *    unknown, so we lose our signed bounds
12746          * 2) it's known negative, thus the unsigned bounds capture the
12747          *    signed bounds
12748          * 3) the signed bounds cross zero, so they tell us nothing
12749          *    about the result
12750          * If the value in dst_reg is known nonnegative, then again the
12751          * unsigned bounds capture the signed bounds.
12752          * Thus, in all cases it suffices to blow away our signed bounds
12753          * and rely on inferring new ones from the unsigned bounds and
12754          * var_off of the result.
12755          */
12756         dst_reg->s32_min_value = S32_MIN;
12757         dst_reg->s32_max_value = S32_MAX;
12758
12759         dst_reg->var_off = tnum_rshift(subreg, umin_val);
12760         dst_reg->u32_min_value >>= umax_val;
12761         dst_reg->u32_max_value >>= umin_val;
12762
12763         __mark_reg64_unbounded(dst_reg);
12764         __update_reg32_bounds(dst_reg);
12765 }
12766
12767 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12768                                struct bpf_reg_state *src_reg)
12769 {
12770         u64 umax_val = src_reg->umax_value;
12771         u64 umin_val = src_reg->umin_value;
12772
12773         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12774          * be negative, then either:
12775          * 1) src_reg might be zero, so the sign bit of the result is
12776          *    unknown, so we lose our signed bounds
12777          * 2) it's known negative, thus the unsigned bounds capture the
12778          *    signed bounds
12779          * 3) the signed bounds cross zero, so they tell us nothing
12780          *    about the result
12781          * If the value in dst_reg is known nonnegative, then again the
12782          * unsigned bounds capture the signed bounds.
12783          * Thus, in all cases it suffices to blow away our signed bounds
12784          * and rely on inferring new ones from the unsigned bounds and
12785          * var_off of the result.
12786          */
12787         dst_reg->smin_value = S64_MIN;
12788         dst_reg->smax_value = S64_MAX;
12789         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12790         dst_reg->umin_value >>= umax_val;
12791         dst_reg->umax_value >>= umin_val;
12792
12793         /* Its not easy to operate on alu32 bounds here because it depends
12794          * on bits being shifted in. Take easy way out and mark unbounded
12795          * so we can recalculate later from tnum.
12796          */
12797         __mark_reg32_unbounded(dst_reg);
12798         __update_reg_bounds(dst_reg);
12799 }
12800
12801 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12802                                   struct bpf_reg_state *src_reg)
12803 {
12804         u64 umin_val = src_reg->u32_min_value;
12805
12806         /* Upon reaching here, src_known is true and
12807          * umax_val is equal to umin_val.
12808          */
12809         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12810         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12811
12812         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12813
12814         /* blow away the dst_reg umin_value/umax_value and rely on
12815          * dst_reg var_off to refine the result.
12816          */
12817         dst_reg->u32_min_value = 0;
12818         dst_reg->u32_max_value = U32_MAX;
12819
12820         __mark_reg64_unbounded(dst_reg);
12821         __update_reg32_bounds(dst_reg);
12822 }
12823
12824 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12825                                 struct bpf_reg_state *src_reg)
12826 {
12827         u64 umin_val = src_reg->umin_value;
12828
12829         /* Upon reaching here, src_known is true and umax_val is equal
12830          * to umin_val.
12831          */
12832         dst_reg->smin_value >>= umin_val;
12833         dst_reg->smax_value >>= umin_val;
12834
12835         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12836
12837         /* blow away the dst_reg umin_value/umax_value and rely on
12838          * dst_reg var_off to refine the result.
12839          */
12840         dst_reg->umin_value = 0;
12841         dst_reg->umax_value = U64_MAX;
12842
12843         /* Its not easy to operate on alu32 bounds here because it depends
12844          * on bits being shifted in from upper 32-bits. Take easy way out
12845          * and mark unbounded so we can recalculate later from tnum.
12846          */
12847         __mark_reg32_unbounded(dst_reg);
12848         __update_reg_bounds(dst_reg);
12849 }
12850
12851 /* WARNING: This function does calculations on 64-bit values, but the actual
12852  * execution may occur on 32-bit values. Therefore, things like bitshifts
12853  * need extra checks in the 32-bit case.
12854  */
12855 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12856                                       struct bpf_insn *insn,
12857                                       struct bpf_reg_state *dst_reg,
12858                                       struct bpf_reg_state src_reg)
12859 {
12860         struct bpf_reg_state *regs = cur_regs(env);
12861         u8 opcode = BPF_OP(insn->code);
12862         bool src_known;
12863         s64 smin_val, smax_val;
12864         u64 umin_val, umax_val;
12865         s32 s32_min_val, s32_max_val;
12866         u32 u32_min_val, u32_max_val;
12867         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12868         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12869         int ret;
12870
12871         smin_val = src_reg.smin_value;
12872         smax_val = src_reg.smax_value;
12873         umin_val = src_reg.umin_value;
12874         umax_val = src_reg.umax_value;
12875
12876         s32_min_val = src_reg.s32_min_value;
12877         s32_max_val = src_reg.s32_max_value;
12878         u32_min_val = src_reg.u32_min_value;
12879         u32_max_val = src_reg.u32_max_value;
12880
12881         if (alu32) {
12882                 src_known = tnum_subreg_is_const(src_reg.var_off);
12883                 if ((src_known &&
12884                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12885                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12886                         /* Taint dst register if offset had invalid bounds
12887                          * derived from e.g. dead branches.
12888                          */
12889                         __mark_reg_unknown(env, dst_reg);
12890                         return 0;
12891                 }
12892         } else {
12893                 src_known = tnum_is_const(src_reg.var_off);
12894                 if ((src_known &&
12895                      (smin_val != smax_val || umin_val != umax_val)) ||
12896                     smin_val > smax_val || umin_val > umax_val) {
12897                         /* Taint dst register if offset had invalid bounds
12898                          * derived from e.g. dead branches.
12899                          */
12900                         __mark_reg_unknown(env, dst_reg);
12901                         return 0;
12902                 }
12903         }
12904
12905         if (!src_known &&
12906             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12907                 __mark_reg_unknown(env, dst_reg);
12908                 return 0;
12909         }
12910
12911         if (sanitize_needed(opcode)) {
12912                 ret = sanitize_val_alu(env, insn);
12913                 if (ret < 0)
12914                         return sanitize_err(env, insn, ret, NULL, NULL);
12915         }
12916
12917         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12918          * There are two classes of instructions: The first class we track both
12919          * alu32 and alu64 sign/unsigned bounds independently this provides the
12920          * greatest amount of precision when alu operations are mixed with jmp32
12921          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12922          * and BPF_OR. This is possible because these ops have fairly easy to
12923          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12924          * See alu32 verifier tests for examples. The second class of
12925          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12926          * with regards to tracking sign/unsigned bounds because the bits may
12927          * cross subreg boundaries in the alu64 case. When this happens we mark
12928          * the reg unbounded in the subreg bound space and use the resulting
12929          * tnum to calculate an approximation of the sign/unsigned bounds.
12930          */
12931         switch (opcode) {
12932         case BPF_ADD:
12933                 scalar32_min_max_add(dst_reg, &src_reg);
12934                 scalar_min_max_add(dst_reg, &src_reg);
12935                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12936                 break;
12937         case BPF_SUB:
12938                 scalar32_min_max_sub(dst_reg, &src_reg);
12939                 scalar_min_max_sub(dst_reg, &src_reg);
12940                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12941                 break;
12942         case BPF_MUL:
12943                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12944                 scalar32_min_max_mul(dst_reg, &src_reg);
12945                 scalar_min_max_mul(dst_reg, &src_reg);
12946                 break;
12947         case BPF_AND:
12948                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12949                 scalar32_min_max_and(dst_reg, &src_reg);
12950                 scalar_min_max_and(dst_reg, &src_reg);
12951                 break;
12952         case BPF_OR:
12953                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12954                 scalar32_min_max_or(dst_reg, &src_reg);
12955                 scalar_min_max_or(dst_reg, &src_reg);
12956                 break;
12957         case BPF_XOR:
12958                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12959                 scalar32_min_max_xor(dst_reg, &src_reg);
12960                 scalar_min_max_xor(dst_reg, &src_reg);
12961                 break;
12962         case BPF_LSH:
12963                 if (umax_val >= insn_bitness) {
12964                         /* Shifts greater than 31 or 63 are undefined.
12965                          * This includes shifts by a negative number.
12966                          */
12967                         mark_reg_unknown(env, regs, insn->dst_reg);
12968                         break;
12969                 }
12970                 if (alu32)
12971                         scalar32_min_max_lsh(dst_reg, &src_reg);
12972                 else
12973                         scalar_min_max_lsh(dst_reg, &src_reg);
12974                 break;
12975         case BPF_RSH:
12976                 if (umax_val >= insn_bitness) {
12977                         /* Shifts greater than 31 or 63 are undefined.
12978                          * This includes shifts by a negative number.
12979                          */
12980                         mark_reg_unknown(env, regs, insn->dst_reg);
12981                         break;
12982                 }
12983                 if (alu32)
12984                         scalar32_min_max_rsh(dst_reg, &src_reg);
12985                 else
12986                         scalar_min_max_rsh(dst_reg, &src_reg);
12987                 break;
12988         case BPF_ARSH:
12989                 if (umax_val >= insn_bitness) {
12990                         /* Shifts greater than 31 or 63 are undefined.
12991                          * This includes shifts by a negative number.
12992                          */
12993                         mark_reg_unknown(env, regs, insn->dst_reg);
12994                         break;
12995                 }
12996                 if (alu32)
12997                         scalar32_min_max_arsh(dst_reg, &src_reg);
12998                 else
12999                         scalar_min_max_arsh(dst_reg, &src_reg);
13000                 break;
13001         default:
13002                 mark_reg_unknown(env, regs, insn->dst_reg);
13003                 break;
13004         }
13005
13006         /* ALU32 ops are zero extended into 64bit register */
13007         if (alu32)
13008                 zext_32_to_64(dst_reg);
13009         reg_bounds_sync(dst_reg);
13010         return 0;
13011 }
13012
13013 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13014  * and var_off.
13015  */
13016 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13017                                    struct bpf_insn *insn)
13018 {
13019         struct bpf_verifier_state *vstate = env->cur_state;
13020         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13021         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13022         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13023         u8 opcode = BPF_OP(insn->code);
13024         int err;
13025
13026         dst_reg = &regs[insn->dst_reg];
13027         src_reg = NULL;
13028         if (dst_reg->type != SCALAR_VALUE)
13029                 ptr_reg = dst_reg;
13030         else
13031                 /* Make sure ID is cleared otherwise dst_reg min/max could be
13032                  * incorrectly propagated into other registers by find_equal_scalars()
13033                  */
13034                 dst_reg->id = 0;
13035         if (BPF_SRC(insn->code) == BPF_X) {
13036                 src_reg = &regs[insn->src_reg];
13037                 if (src_reg->type != SCALAR_VALUE) {
13038                         if (dst_reg->type != SCALAR_VALUE) {
13039                                 /* Combining two pointers by any ALU op yields
13040                                  * an arbitrary scalar. Disallow all math except
13041                                  * pointer subtraction
13042                                  */
13043                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13044                                         mark_reg_unknown(env, regs, insn->dst_reg);
13045                                         return 0;
13046                                 }
13047                                 verbose(env, "R%d pointer %s pointer prohibited\n",
13048                                         insn->dst_reg,
13049                                         bpf_alu_string[opcode >> 4]);
13050                                 return -EACCES;
13051                         } else {
13052                                 /* scalar += pointer
13053                                  * This is legal, but we have to reverse our
13054                                  * src/dest handling in computing the range
13055                                  */
13056                                 err = mark_chain_precision(env, insn->dst_reg);
13057                                 if (err)
13058                                         return err;
13059                                 return adjust_ptr_min_max_vals(env, insn,
13060                                                                src_reg, dst_reg);
13061                         }
13062                 } else if (ptr_reg) {
13063                         /* pointer += scalar */
13064                         err = mark_chain_precision(env, insn->src_reg);
13065                         if (err)
13066                                 return err;
13067                         return adjust_ptr_min_max_vals(env, insn,
13068                                                        dst_reg, src_reg);
13069                 } else if (dst_reg->precise) {
13070                         /* if dst_reg is precise, src_reg should be precise as well */
13071                         err = mark_chain_precision(env, insn->src_reg);
13072                         if (err)
13073                                 return err;
13074                 }
13075         } else {
13076                 /* Pretend the src is a reg with a known value, since we only
13077                  * need to be able to read from this state.
13078                  */
13079                 off_reg.type = SCALAR_VALUE;
13080                 __mark_reg_known(&off_reg, insn->imm);
13081                 src_reg = &off_reg;
13082                 if (ptr_reg) /* pointer += K */
13083                         return adjust_ptr_min_max_vals(env, insn,
13084                                                        ptr_reg, src_reg);
13085         }
13086
13087         /* Got here implies adding two SCALAR_VALUEs */
13088         if (WARN_ON_ONCE(ptr_reg)) {
13089                 print_verifier_state(env, state, true);
13090                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13091                 return -EINVAL;
13092         }
13093         if (WARN_ON(!src_reg)) {
13094                 print_verifier_state(env, state, true);
13095                 verbose(env, "verifier internal error: no src_reg\n");
13096                 return -EINVAL;
13097         }
13098         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13099 }
13100
13101 /* check validity of 32-bit and 64-bit arithmetic operations */
13102 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13103 {
13104         struct bpf_reg_state *regs = cur_regs(env);
13105         u8 opcode = BPF_OP(insn->code);
13106         int err;
13107
13108         if (opcode == BPF_END || opcode == BPF_NEG) {
13109                 if (opcode == BPF_NEG) {
13110                         if (BPF_SRC(insn->code) != BPF_K ||
13111                             insn->src_reg != BPF_REG_0 ||
13112                             insn->off != 0 || insn->imm != 0) {
13113                                 verbose(env, "BPF_NEG uses reserved fields\n");
13114                                 return -EINVAL;
13115                         }
13116                 } else {
13117                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13118                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13119                             (BPF_CLASS(insn->code) == BPF_ALU64 &&
13120                              BPF_SRC(insn->code) != BPF_TO_LE)) {
13121                                 verbose(env, "BPF_END uses reserved fields\n");
13122                                 return -EINVAL;
13123                         }
13124                 }
13125
13126                 /* check src operand */
13127                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13128                 if (err)
13129                         return err;
13130
13131                 if (is_pointer_value(env, insn->dst_reg)) {
13132                         verbose(env, "R%d pointer arithmetic prohibited\n",
13133                                 insn->dst_reg);
13134                         return -EACCES;
13135                 }
13136
13137                 /* check dest operand */
13138                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13139                 if (err)
13140                         return err;
13141
13142         } else if (opcode == BPF_MOV) {
13143
13144                 if (BPF_SRC(insn->code) == BPF_X) {
13145                         if (insn->imm != 0) {
13146                                 verbose(env, "BPF_MOV uses reserved fields\n");
13147                                 return -EINVAL;
13148                         }
13149
13150                         if (BPF_CLASS(insn->code) == BPF_ALU) {
13151                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13152                                         verbose(env, "BPF_MOV uses reserved fields\n");
13153                                         return -EINVAL;
13154                                 }
13155                         } else {
13156                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13157                                     insn->off != 32) {
13158                                         verbose(env, "BPF_MOV uses reserved fields\n");
13159                                         return -EINVAL;
13160                                 }
13161                         }
13162
13163                         /* check src operand */
13164                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13165                         if (err)
13166                                 return err;
13167                 } else {
13168                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13169                                 verbose(env, "BPF_MOV uses reserved fields\n");
13170                                 return -EINVAL;
13171                         }
13172                 }
13173
13174                 /* check dest operand, mark as required later */
13175                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13176                 if (err)
13177                         return err;
13178
13179                 if (BPF_SRC(insn->code) == BPF_X) {
13180                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
13181                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13182                         bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13183                                        !tnum_is_const(src_reg->var_off);
13184
13185                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13186                                 if (insn->off == 0) {
13187                                         /* case: R1 = R2
13188                                          * copy register state to dest reg
13189                                          */
13190                                         if (need_id)
13191                                                 /* Assign src and dst registers the same ID
13192                                                  * that will be used by find_equal_scalars()
13193                                                  * to propagate min/max range.
13194                                                  */
13195                                                 src_reg->id = ++env->id_gen;
13196                                         copy_register_state(dst_reg, src_reg);
13197                                         dst_reg->live |= REG_LIVE_WRITTEN;
13198                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13199                                 } else {
13200                                         /* case: R1 = (s8, s16 s32)R2 */
13201                                         if (is_pointer_value(env, insn->src_reg)) {
13202                                                 verbose(env,
13203                                                         "R%d sign-extension part of pointer\n",
13204                                                         insn->src_reg);
13205                                                 return -EACCES;
13206                                         } else if (src_reg->type == SCALAR_VALUE) {
13207                                                 bool no_sext;
13208
13209                                                 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13210                                                 if (no_sext && need_id)
13211                                                         src_reg->id = ++env->id_gen;
13212                                                 copy_register_state(dst_reg, src_reg);
13213                                                 if (!no_sext)
13214                                                         dst_reg->id = 0;
13215                                                 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13216                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13217                                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
13218                                         } else {
13219                                                 mark_reg_unknown(env, regs, insn->dst_reg);
13220                                         }
13221                                 }
13222                         } else {
13223                                 /* R1 = (u32) R2 */
13224                                 if (is_pointer_value(env, insn->src_reg)) {
13225                                         verbose(env,
13226                                                 "R%d partial copy of pointer\n",
13227                                                 insn->src_reg);
13228                                         return -EACCES;
13229                                 } else if (src_reg->type == SCALAR_VALUE) {
13230                                         if (insn->off == 0) {
13231                                                 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13232
13233                                                 if (is_src_reg_u32 && need_id)
13234                                                         src_reg->id = ++env->id_gen;
13235                                                 copy_register_state(dst_reg, src_reg);
13236                                                 /* Make sure ID is cleared if src_reg is not in u32
13237                                                  * range otherwise dst_reg min/max could be incorrectly
13238                                                  * propagated into src_reg by find_equal_scalars()
13239                                                  */
13240                                                 if (!is_src_reg_u32)
13241                                                         dst_reg->id = 0;
13242                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13243                                                 dst_reg->subreg_def = env->insn_idx + 1;
13244                                         } else {
13245                                                 /* case: W1 = (s8, s16)W2 */
13246                                                 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13247
13248                                                 if (no_sext && need_id)
13249                                                         src_reg->id = ++env->id_gen;
13250                                                 copy_register_state(dst_reg, src_reg);
13251                                                 if (!no_sext)
13252                                                         dst_reg->id = 0;
13253                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13254                                                 dst_reg->subreg_def = env->insn_idx + 1;
13255                                                 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13256                                         }
13257                                 } else {
13258                                         mark_reg_unknown(env, regs,
13259                                                          insn->dst_reg);
13260                                 }
13261                                 zext_32_to_64(dst_reg);
13262                                 reg_bounds_sync(dst_reg);
13263                         }
13264                 } else {
13265                         /* case: R = imm
13266                          * remember the value we stored into this reg
13267                          */
13268                         /* clear any state __mark_reg_known doesn't set */
13269                         mark_reg_unknown(env, regs, insn->dst_reg);
13270                         regs[insn->dst_reg].type = SCALAR_VALUE;
13271                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13272                                 __mark_reg_known(regs + insn->dst_reg,
13273                                                  insn->imm);
13274                         } else {
13275                                 __mark_reg_known(regs + insn->dst_reg,
13276                                                  (u32)insn->imm);
13277                         }
13278                 }
13279
13280         } else if (opcode > BPF_END) {
13281                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13282                 return -EINVAL;
13283
13284         } else {        /* all other ALU ops: and, sub, xor, add, ... */
13285
13286                 if (BPF_SRC(insn->code) == BPF_X) {
13287                         if (insn->imm != 0 || insn->off > 1 ||
13288                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13289                                 verbose(env, "BPF_ALU uses reserved fields\n");
13290                                 return -EINVAL;
13291                         }
13292                         /* check src1 operand */
13293                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13294                         if (err)
13295                                 return err;
13296                 } else {
13297                         if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13298                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13299                                 verbose(env, "BPF_ALU uses reserved fields\n");
13300                                 return -EINVAL;
13301                         }
13302                 }
13303
13304                 /* check src2 operand */
13305                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13306                 if (err)
13307                         return err;
13308
13309                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13310                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13311                         verbose(env, "div by zero\n");
13312                         return -EINVAL;
13313                 }
13314
13315                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13316                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13317                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13318
13319                         if (insn->imm < 0 || insn->imm >= size) {
13320                                 verbose(env, "invalid shift %d\n", insn->imm);
13321                                 return -EINVAL;
13322                         }
13323                 }
13324
13325                 /* check dest operand */
13326                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13327                 if (err)
13328                         return err;
13329
13330                 return adjust_reg_min_max_vals(env, insn);
13331         }
13332
13333         return 0;
13334 }
13335
13336 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13337                                    struct bpf_reg_state *dst_reg,
13338                                    enum bpf_reg_type type,
13339                                    bool range_right_open)
13340 {
13341         struct bpf_func_state *state;
13342         struct bpf_reg_state *reg;
13343         int new_range;
13344
13345         if (dst_reg->off < 0 ||
13346             (dst_reg->off == 0 && range_right_open))
13347                 /* This doesn't give us any range */
13348                 return;
13349
13350         if (dst_reg->umax_value > MAX_PACKET_OFF ||
13351             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13352                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
13353                  * than pkt_end, but that's because it's also less than pkt.
13354                  */
13355                 return;
13356
13357         new_range = dst_reg->off;
13358         if (range_right_open)
13359                 new_range++;
13360
13361         /* Examples for register markings:
13362          *
13363          * pkt_data in dst register:
13364          *
13365          *   r2 = r3;
13366          *   r2 += 8;
13367          *   if (r2 > pkt_end) goto <handle exception>
13368          *   <access okay>
13369          *
13370          *   r2 = r3;
13371          *   r2 += 8;
13372          *   if (r2 < pkt_end) goto <access okay>
13373          *   <handle exception>
13374          *
13375          *   Where:
13376          *     r2 == dst_reg, pkt_end == src_reg
13377          *     r2=pkt(id=n,off=8,r=0)
13378          *     r3=pkt(id=n,off=0,r=0)
13379          *
13380          * pkt_data in src register:
13381          *
13382          *   r2 = r3;
13383          *   r2 += 8;
13384          *   if (pkt_end >= r2) goto <access okay>
13385          *   <handle exception>
13386          *
13387          *   r2 = r3;
13388          *   r2 += 8;
13389          *   if (pkt_end <= r2) goto <handle exception>
13390          *   <access okay>
13391          *
13392          *   Where:
13393          *     pkt_end == dst_reg, r2 == src_reg
13394          *     r2=pkt(id=n,off=8,r=0)
13395          *     r3=pkt(id=n,off=0,r=0)
13396          *
13397          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13398          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13399          * and [r3, r3 + 8-1) respectively is safe to access depending on
13400          * the check.
13401          */
13402
13403         /* If our ids match, then we must have the same max_value.  And we
13404          * don't care about the other reg's fixed offset, since if it's too big
13405          * the range won't allow anything.
13406          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13407          */
13408         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13409                 if (reg->type == type && reg->id == dst_reg->id)
13410                         /* keep the maximum range already checked */
13411                         reg->range = max(reg->range, new_range);
13412         }));
13413 }
13414
13415 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13416 {
13417         struct tnum subreg = tnum_subreg(reg->var_off);
13418         s32 sval = (s32)val;
13419
13420         switch (opcode) {
13421         case BPF_JEQ:
13422                 if (tnum_is_const(subreg))
13423                         return !!tnum_equals_const(subreg, val);
13424                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13425                         return 0;
13426                 break;
13427         case BPF_JNE:
13428                 if (tnum_is_const(subreg))
13429                         return !tnum_equals_const(subreg, val);
13430                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13431                         return 1;
13432                 break;
13433         case BPF_JSET:
13434                 if ((~subreg.mask & subreg.value) & val)
13435                         return 1;
13436                 if (!((subreg.mask | subreg.value) & val))
13437                         return 0;
13438                 break;
13439         case BPF_JGT:
13440                 if (reg->u32_min_value > val)
13441                         return 1;
13442                 else if (reg->u32_max_value <= val)
13443                         return 0;
13444                 break;
13445         case BPF_JSGT:
13446                 if (reg->s32_min_value > sval)
13447                         return 1;
13448                 else if (reg->s32_max_value <= sval)
13449                         return 0;
13450                 break;
13451         case BPF_JLT:
13452                 if (reg->u32_max_value < val)
13453                         return 1;
13454                 else if (reg->u32_min_value >= val)
13455                         return 0;
13456                 break;
13457         case BPF_JSLT:
13458                 if (reg->s32_max_value < sval)
13459                         return 1;
13460                 else if (reg->s32_min_value >= sval)
13461                         return 0;
13462                 break;
13463         case BPF_JGE:
13464                 if (reg->u32_min_value >= val)
13465                         return 1;
13466                 else if (reg->u32_max_value < val)
13467                         return 0;
13468                 break;
13469         case BPF_JSGE:
13470                 if (reg->s32_min_value >= sval)
13471                         return 1;
13472                 else if (reg->s32_max_value < sval)
13473                         return 0;
13474                 break;
13475         case BPF_JLE:
13476                 if (reg->u32_max_value <= val)
13477                         return 1;
13478                 else if (reg->u32_min_value > val)
13479                         return 0;
13480                 break;
13481         case BPF_JSLE:
13482                 if (reg->s32_max_value <= sval)
13483                         return 1;
13484                 else if (reg->s32_min_value > sval)
13485                         return 0;
13486                 break;
13487         }
13488
13489         return -1;
13490 }
13491
13492
13493 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13494 {
13495         s64 sval = (s64)val;
13496
13497         switch (opcode) {
13498         case BPF_JEQ:
13499                 if (tnum_is_const(reg->var_off))
13500                         return !!tnum_equals_const(reg->var_off, val);
13501                 else if (val < reg->umin_value || val > reg->umax_value)
13502                         return 0;
13503                 break;
13504         case BPF_JNE:
13505                 if (tnum_is_const(reg->var_off))
13506                         return !tnum_equals_const(reg->var_off, val);
13507                 else if (val < reg->umin_value || val > reg->umax_value)
13508                         return 1;
13509                 break;
13510         case BPF_JSET:
13511                 if ((~reg->var_off.mask & reg->var_off.value) & val)
13512                         return 1;
13513                 if (!((reg->var_off.mask | reg->var_off.value) & val))
13514                         return 0;
13515                 break;
13516         case BPF_JGT:
13517                 if (reg->umin_value > val)
13518                         return 1;
13519                 else if (reg->umax_value <= val)
13520                         return 0;
13521                 break;
13522         case BPF_JSGT:
13523                 if (reg->smin_value > sval)
13524                         return 1;
13525                 else if (reg->smax_value <= sval)
13526                         return 0;
13527                 break;
13528         case BPF_JLT:
13529                 if (reg->umax_value < val)
13530                         return 1;
13531                 else if (reg->umin_value >= val)
13532                         return 0;
13533                 break;
13534         case BPF_JSLT:
13535                 if (reg->smax_value < sval)
13536                         return 1;
13537                 else if (reg->smin_value >= sval)
13538                         return 0;
13539                 break;
13540         case BPF_JGE:
13541                 if (reg->umin_value >= val)
13542                         return 1;
13543                 else if (reg->umax_value < val)
13544                         return 0;
13545                 break;
13546         case BPF_JSGE:
13547                 if (reg->smin_value >= sval)
13548                         return 1;
13549                 else if (reg->smax_value < sval)
13550                         return 0;
13551                 break;
13552         case BPF_JLE:
13553                 if (reg->umax_value <= val)
13554                         return 1;
13555                 else if (reg->umin_value > val)
13556                         return 0;
13557                 break;
13558         case BPF_JSLE:
13559                 if (reg->smax_value <= sval)
13560                         return 1;
13561                 else if (reg->smin_value > sval)
13562                         return 0;
13563                 break;
13564         }
13565
13566         return -1;
13567 }
13568
13569 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13570  * and return:
13571  *  1 - branch will be taken and "goto target" will be executed
13572  *  0 - branch will not be taken and fall-through to next insn
13573  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13574  *      range [0,10]
13575  */
13576 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13577                            bool is_jmp32)
13578 {
13579         if (__is_pointer_value(false, reg)) {
13580                 if (!reg_not_null(reg))
13581                         return -1;
13582
13583                 /* If pointer is valid tests against zero will fail so we can
13584                  * use this to direct branch taken.
13585                  */
13586                 if (val != 0)
13587                         return -1;
13588
13589                 switch (opcode) {
13590                 case BPF_JEQ:
13591                         return 0;
13592                 case BPF_JNE:
13593                         return 1;
13594                 default:
13595                         return -1;
13596                 }
13597         }
13598
13599         if (is_jmp32)
13600                 return is_branch32_taken(reg, val, opcode);
13601         return is_branch64_taken(reg, val, opcode);
13602 }
13603
13604 static int flip_opcode(u32 opcode)
13605 {
13606         /* How can we transform "a <op> b" into "b <op> a"? */
13607         static const u8 opcode_flip[16] = {
13608                 /* these stay the same */
13609                 [BPF_JEQ  >> 4] = BPF_JEQ,
13610                 [BPF_JNE  >> 4] = BPF_JNE,
13611                 [BPF_JSET >> 4] = BPF_JSET,
13612                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13613                 [BPF_JGE  >> 4] = BPF_JLE,
13614                 [BPF_JGT  >> 4] = BPF_JLT,
13615                 [BPF_JLE  >> 4] = BPF_JGE,
13616                 [BPF_JLT  >> 4] = BPF_JGT,
13617                 [BPF_JSGE >> 4] = BPF_JSLE,
13618                 [BPF_JSGT >> 4] = BPF_JSLT,
13619                 [BPF_JSLE >> 4] = BPF_JSGE,
13620                 [BPF_JSLT >> 4] = BPF_JSGT
13621         };
13622         return opcode_flip[opcode >> 4];
13623 }
13624
13625 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13626                                    struct bpf_reg_state *src_reg,
13627                                    u8 opcode)
13628 {
13629         struct bpf_reg_state *pkt;
13630
13631         if (src_reg->type == PTR_TO_PACKET_END) {
13632                 pkt = dst_reg;
13633         } else if (dst_reg->type == PTR_TO_PACKET_END) {
13634                 pkt = src_reg;
13635                 opcode = flip_opcode(opcode);
13636         } else {
13637                 return -1;
13638         }
13639
13640         if (pkt->range >= 0)
13641                 return -1;
13642
13643         switch (opcode) {
13644         case BPF_JLE:
13645                 /* pkt <= pkt_end */
13646                 fallthrough;
13647         case BPF_JGT:
13648                 /* pkt > pkt_end */
13649                 if (pkt->range == BEYOND_PKT_END)
13650                         /* pkt has at last one extra byte beyond pkt_end */
13651                         return opcode == BPF_JGT;
13652                 break;
13653         case BPF_JLT:
13654                 /* pkt < pkt_end */
13655                 fallthrough;
13656         case BPF_JGE:
13657                 /* pkt >= pkt_end */
13658                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13659                         return opcode == BPF_JGE;
13660                 break;
13661         }
13662         return -1;
13663 }
13664
13665 /* Adjusts the register min/max values in the case that the dst_reg is the
13666  * variable register that we are working on, and src_reg is a constant or we're
13667  * simply doing a BPF_K check.
13668  * In JEQ/JNE cases we also adjust the var_off values.
13669  */
13670 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13671                             struct bpf_reg_state *false_reg,
13672                             u64 val, u32 val32,
13673                             u8 opcode, bool is_jmp32)
13674 {
13675         struct tnum false_32off = tnum_subreg(false_reg->var_off);
13676         struct tnum false_64off = false_reg->var_off;
13677         struct tnum true_32off = tnum_subreg(true_reg->var_off);
13678         struct tnum true_64off = true_reg->var_off;
13679         s64 sval = (s64)val;
13680         s32 sval32 = (s32)val32;
13681
13682         /* If the dst_reg is a pointer, we can't learn anything about its
13683          * variable offset from the compare (unless src_reg were a pointer into
13684          * the same object, but we don't bother with that.
13685          * Since false_reg and true_reg have the same type by construction, we
13686          * only need to check one of them for pointerness.
13687          */
13688         if (__is_pointer_value(false, false_reg))
13689                 return;
13690
13691         switch (opcode) {
13692         /* JEQ/JNE comparison doesn't change the register equivalence.
13693          *
13694          * r1 = r2;
13695          * if (r1 == 42) goto label;
13696          * ...
13697          * label: // here both r1 and r2 are known to be 42.
13698          *
13699          * Hence when marking register as known preserve it's ID.
13700          */
13701         case BPF_JEQ:
13702                 if (is_jmp32) {
13703                         __mark_reg32_known(true_reg, val32);
13704                         true_32off = tnum_subreg(true_reg->var_off);
13705                 } else {
13706                         ___mark_reg_known(true_reg, val);
13707                         true_64off = true_reg->var_off;
13708                 }
13709                 break;
13710         case BPF_JNE:
13711                 if (is_jmp32) {
13712                         __mark_reg32_known(false_reg, val32);
13713                         false_32off = tnum_subreg(false_reg->var_off);
13714                 } else {
13715                         ___mark_reg_known(false_reg, val);
13716                         false_64off = false_reg->var_off;
13717                 }
13718                 break;
13719         case BPF_JSET:
13720                 if (is_jmp32) {
13721                         false_32off = tnum_and(false_32off, tnum_const(~val32));
13722                         if (is_power_of_2(val32))
13723                                 true_32off = tnum_or(true_32off,
13724                                                      tnum_const(val32));
13725                 } else {
13726                         false_64off = tnum_and(false_64off, tnum_const(~val));
13727                         if (is_power_of_2(val))
13728                                 true_64off = tnum_or(true_64off,
13729                                                      tnum_const(val));
13730                 }
13731                 break;
13732         case BPF_JGE:
13733         case BPF_JGT:
13734         {
13735                 if (is_jmp32) {
13736                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13737                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13738
13739                         false_reg->u32_max_value = min(false_reg->u32_max_value,
13740                                                        false_umax);
13741                         true_reg->u32_min_value = max(true_reg->u32_min_value,
13742                                                       true_umin);
13743                 } else {
13744                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13745                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13746
13747                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
13748                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
13749                 }
13750                 break;
13751         }
13752         case BPF_JSGE:
13753         case BPF_JSGT:
13754         {
13755                 if (is_jmp32) {
13756                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13757                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13758
13759                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13760                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13761                 } else {
13762                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13763                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13764
13765                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
13766                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
13767                 }
13768                 break;
13769         }
13770         case BPF_JLE:
13771         case BPF_JLT:
13772         {
13773                 if (is_jmp32) {
13774                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13775                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13776
13777                         false_reg->u32_min_value = max(false_reg->u32_min_value,
13778                                                        false_umin);
13779                         true_reg->u32_max_value = min(true_reg->u32_max_value,
13780                                                       true_umax);
13781                 } else {
13782                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13783                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13784
13785                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
13786                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
13787                 }
13788                 break;
13789         }
13790         case BPF_JSLE:
13791         case BPF_JSLT:
13792         {
13793                 if (is_jmp32) {
13794                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13795                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13796
13797                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13798                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13799                 } else {
13800                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13801                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13802
13803                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
13804                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
13805                 }
13806                 break;
13807         }
13808         default:
13809                 return;
13810         }
13811
13812         if (is_jmp32) {
13813                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13814                                              tnum_subreg(false_32off));
13815                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13816                                             tnum_subreg(true_32off));
13817                 __reg_combine_32_into_64(false_reg);
13818                 __reg_combine_32_into_64(true_reg);
13819         } else {
13820                 false_reg->var_off = false_64off;
13821                 true_reg->var_off = true_64off;
13822                 __reg_combine_64_into_32(false_reg);
13823                 __reg_combine_64_into_32(true_reg);
13824         }
13825 }
13826
13827 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13828  * the variable reg.
13829  */
13830 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13831                                 struct bpf_reg_state *false_reg,
13832                                 u64 val, u32 val32,
13833                                 u8 opcode, bool is_jmp32)
13834 {
13835         opcode = flip_opcode(opcode);
13836         /* This uses zero as "not present in table"; luckily the zero opcode,
13837          * BPF_JA, can't get here.
13838          */
13839         if (opcode)
13840                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13841 }
13842
13843 /* Regs are known to be equal, so intersect their min/max/var_off */
13844 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13845                                   struct bpf_reg_state *dst_reg)
13846 {
13847         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13848                                                         dst_reg->umin_value);
13849         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13850                                                         dst_reg->umax_value);
13851         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13852                                                         dst_reg->smin_value);
13853         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13854                                                         dst_reg->smax_value);
13855         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13856                                                              dst_reg->var_off);
13857         reg_bounds_sync(src_reg);
13858         reg_bounds_sync(dst_reg);
13859 }
13860
13861 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13862                                 struct bpf_reg_state *true_dst,
13863                                 struct bpf_reg_state *false_src,
13864                                 struct bpf_reg_state *false_dst,
13865                                 u8 opcode)
13866 {
13867         switch (opcode) {
13868         case BPF_JEQ:
13869                 __reg_combine_min_max(true_src, true_dst);
13870                 break;
13871         case BPF_JNE:
13872                 __reg_combine_min_max(false_src, false_dst);
13873                 break;
13874         }
13875 }
13876
13877 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13878                                  struct bpf_reg_state *reg, u32 id,
13879                                  bool is_null)
13880 {
13881         if (type_may_be_null(reg->type) && reg->id == id &&
13882             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13883                 /* Old offset (both fixed and variable parts) should have been
13884                  * known-zero, because we don't allow pointer arithmetic on
13885                  * pointers that might be NULL. If we see this happening, don't
13886                  * convert the register.
13887                  *
13888                  * But in some cases, some helpers that return local kptrs
13889                  * advance offset for the returned pointer. In those cases, it
13890                  * is fine to expect to see reg->off.
13891                  */
13892                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13893                         return;
13894                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13895                     WARN_ON_ONCE(reg->off))
13896                         return;
13897
13898                 if (is_null) {
13899                         reg->type = SCALAR_VALUE;
13900                         /* We don't need id and ref_obj_id from this point
13901                          * onwards anymore, thus we should better reset it,
13902                          * so that state pruning has chances to take effect.
13903                          */
13904                         reg->id = 0;
13905                         reg->ref_obj_id = 0;
13906
13907                         return;
13908                 }
13909
13910                 mark_ptr_not_null_reg(reg);
13911
13912                 if (!reg_may_point_to_spin_lock(reg)) {
13913                         /* For not-NULL ptr, reg->ref_obj_id will be reset
13914                          * in release_reference().
13915                          *
13916                          * reg->id is still used by spin_lock ptr. Other
13917                          * than spin_lock ptr type, reg->id can be reset.
13918                          */
13919                         reg->id = 0;
13920                 }
13921         }
13922 }
13923
13924 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13925  * be folded together at some point.
13926  */
13927 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13928                                   bool is_null)
13929 {
13930         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13931         struct bpf_reg_state *regs = state->regs, *reg;
13932         u32 ref_obj_id = regs[regno].ref_obj_id;
13933         u32 id = regs[regno].id;
13934
13935         if (ref_obj_id && ref_obj_id == id && is_null)
13936                 /* regs[regno] is in the " == NULL" branch.
13937                  * No one could have freed the reference state before
13938                  * doing the NULL check.
13939                  */
13940                 WARN_ON_ONCE(release_reference_state(state, id));
13941
13942         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13943                 mark_ptr_or_null_reg(state, reg, id, is_null);
13944         }));
13945 }
13946
13947 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13948                                    struct bpf_reg_state *dst_reg,
13949                                    struct bpf_reg_state *src_reg,
13950                                    struct bpf_verifier_state *this_branch,
13951                                    struct bpf_verifier_state *other_branch)
13952 {
13953         if (BPF_SRC(insn->code) != BPF_X)
13954                 return false;
13955
13956         /* Pointers are always 64-bit. */
13957         if (BPF_CLASS(insn->code) == BPF_JMP32)
13958                 return false;
13959
13960         switch (BPF_OP(insn->code)) {
13961         case BPF_JGT:
13962                 if ((dst_reg->type == PTR_TO_PACKET &&
13963                      src_reg->type == PTR_TO_PACKET_END) ||
13964                     (dst_reg->type == PTR_TO_PACKET_META &&
13965                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13966                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13967                         find_good_pkt_pointers(this_branch, dst_reg,
13968                                                dst_reg->type, false);
13969                         mark_pkt_end(other_branch, insn->dst_reg, true);
13970                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13971                             src_reg->type == PTR_TO_PACKET) ||
13972                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13973                             src_reg->type == PTR_TO_PACKET_META)) {
13974                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13975                         find_good_pkt_pointers(other_branch, src_reg,
13976                                                src_reg->type, true);
13977                         mark_pkt_end(this_branch, insn->src_reg, false);
13978                 } else {
13979                         return false;
13980                 }
13981                 break;
13982         case BPF_JLT:
13983                 if ((dst_reg->type == PTR_TO_PACKET &&
13984                      src_reg->type == PTR_TO_PACKET_END) ||
13985                     (dst_reg->type == PTR_TO_PACKET_META &&
13986                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13987                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13988                         find_good_pkt_pointers(other_branch, dst_reg,
13989                                                dst_reg->type, true);
13990                         mark_pkt_end(this_branch, insn->dst_reg, false);
13991                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13992                             src_reg->type == PTR_TO_PACKET) ||
13993                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13994                             src_reg->type == PTR_TO_PACKET_META)) {
13995                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13996                         find_good_pkt_pointers(this_branch, src_reg,
13997                                                src_reg->type, false);
13998                         mark_pkt_end(other_branch, insn->src_reg, true);
13999                 } else {
14000                         return false;
14001                 }
14002                 break;
14003         case BPF_JGE:
14004                 if ((dst_reg->type == PTR_TO_PACKET &&
14005                      src_reg->type == PTR_TO_PACKET_END) ||
14006                     (dst_reg->type == PTR_TO_PACKET_META &&
14007                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14008                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14009                         find_good_pkt_pointers(this_branch, dst_reg,
14010                                                dst_reg->type, true);
14011                         mark_pkt_end(other_branch, insn->dst_reg, false);
14012                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14013                             src_reg->type == PTR_TO_PACKET) ||
14014                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14015                             src_reg->type == PTR_TO_PACKET_META)) {
14016                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14017                         find_good_pkt_pointers(other_branch, src_reg,
14018                                                src_reg->type, false);
14019                         mark_pkt_end(this_branch, insn->src_reg, true);
14020                 } else {
14021                         return false;
14022                 }
14023                 break;
14024         case BPF_JLE:
14025                 if ((dst_reg->type == PTR_TO_PACKET &&
14026                      src_reg->type == PTR_TO_PACKET_END) ||
14027                     (dst_reg->type == PTR_TO_PACKET_META &&
14028                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14029                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14030                         find_good_pkt_pointers(other_branch, dst_reg,
14031                                                dst_reg->type, false);
14032                         mark_pkt_end(this_branch, insn->dst_reg, true);
14033                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14034                             src_reg->type == PTR_TO_PACKET) ||
14035                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14036                             src_reg->type == PTR_TO_PACKET_META)) {
14037                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14038                         find_good_pkt_pointers(this_branch, src_reg,
14039                                                src_reg->type, true);
14040                         mark_pkt_end(other_branch, insn->src_reg, false);
14041                 } else {
14042                         return false;
14043                 }
14044                 break;
14045         default:
14046                 return false;
14047         }
14048
14049         return true;
14050 }
14051
14052 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14053                                struct bpf_reg_state *known_reg)
14054 {
14055         struct bpf_func_state *state;
14056         struct bpf_reg_state *reg;
14057
14058         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14059                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14060                         copy_register_state(reg, known_reg);
14061         }));
14062 }
14063
14064 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14065                              struct bpf_insn *insn, int *insn_idx)
14066 {
14067         struct bpf_verifier_state *this_branch = env->cur_state;
14068         struct bpf_verifier_state *other_branch;
14069         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14070         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14071         struct bpf_reg_state *eq_branch_regs;
14072         u8 opcode = BPF_OP(insn->code);
14073         bool is_jmp32;
14074         int pred = -1;
14075         int err;
14076
14077         /* Only conditional jumps are expected to reach here. */
14078         if (opcode == BPF_JA || opcode > BPF_JSLE) {
14079                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14080                 return -EINVAL;
14081         }
14082
14083         /* check src2 operand */
14084         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14085         if (err)
14086                 return err;
14087
14088         dst_reg = &regs[insn->dst_reg];
14089         if (BPF_SRC(insn->code) == BPF_X) {
14090                 if (insn->imm != 0) {
14091                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14092                         return -EINVAL;
14093                 }
14094
14095                 /* check src1 operand */
14096                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14097                 if (err)
14098                         return err;
14099
14100                 src_reg = &regs[insn->src_reg];
14101                 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14102                     is_pointer_value(env, insn->src_reg)) {
14103                         verbose(env, "R%d pointer comparison prohibited\n",
14104                                 insn->src_reg);
14105                         return -EACCES;
14106                 }
14107         } else {
14108                 if (insn->src_reg != BPF_REG_0) {
14109                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14110                         return -EINVAL;
14111                 }
14112         }
14113
14114         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14115
14116         if (BPF_SRC(insn->code) == BPF_K) {
14117                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14118         } else if (src_reg->type == SCALAR_VALUE &&
14119                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14120                 pred = is_branch_taken(dst_reg,
14121                                        tnum_subreg(src_reg->var_off).value,
14122                                        opcode,
14123                                        is_jmp32);
14124         } else if (src_reg->type == SCALAR_VALUE &&
14125                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14126                 pred = is_branch_taken(dst_reg,
14127                                        src_reg->var_off.value,
14128                                        opcode,
14129                                        is_jmp32);
14130         } else if (dst_reg->type == SCALAR_VALUE &&
14131                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14132                 pred = is_branch_taken(src_reg,
14133                                        tnum_subreg(dst_reg->var_off).value,
14134                                        flip_opcode(opcode),
14135                                        is_jmp32);
14136         } else if (dst_reg->type == SCALAR_VALUE &&
14137                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14138                 pred = is_branch_taken(src_reg,
14139                                        dst_reg->var_off.value,
14140                                        flip_opcode(opcode),
14141                                        is_jmp32);
14142         } else if (reg_is_pkt_pointer_any(dst_reg) &&
14143                    reg_is_pkt_pointer_any(src_reg) &&
14144                    !is_jmp32) {
14145                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14146         }
14147
14148         if (pred >= 0) {
14149                 /* If we get here with a dst_reg pointer type it is because
14150                  * above is_branch_taken() special cased the 0 comparison.
14151                  */
14152                 if (!__is_pointer_value(false, dst_reg))
14153                         err = mark_chain_precision(env, insn->dst_reg);
14154                 if (BPF_SRC(insn->code) == BPF_X && !err &&
14155                     !__is_pointer_value(false, src_reg))
14156                         err = mark_chain_precision(env, insn->src_reg);
14157                 if (err)
14158                         return err;
14159         }
14160
14161         if (pred == 1) {
14162                 /* Only follow the goto, ignore fall-through. If needed, push
14163                  * the fall-through branch for simulation under speculative
14164                  * execution.
14165                  */
14166                 if (!env->bypass_spec_v1 &&
14167                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
14168                                                *insn_idx))
14169                         return -EFAULT;
14170                 if (env->log.level & BPF_LOG_LEVEL)
14171                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14172                 *insn_idx += insn->off;
14173                 return 0;
14174         } else if (pred == 0) {
14175                 /* Only follow the fall-through branch, since that's where the
14176                  * program will go. If needed, push the goto branch for
14177                  * simulation under speculative execution.
14178                  */
14179                 if (!env->bypass_spec_v1 &&
14180                     !sanitize_speculative_path(env, insn,
14181                                                *insn_idx + insn->off + 1,
14182                                                *insn_idx))
14183                         return -EFAULT;
14184                 if (env->log.level & BPF_LOG_LEVEL)
14185                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14186                 return 0;
14187         }
14188
14189         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14190                                   false);
14191         if (!other_branch)
14192                 return -EFAULT;
14193         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14194
14195         /* detect if we are comparing against a constant value so we can adjust
14196          * our min/max values for our dst register.
14197          * this is only legit if both are scalars (or pointers to the same
14198          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14199          * because otherwise the different base pointers mean the offsets aren't
14200          * comparable.
14201          */
14202         if (BPF_SRC(insn->code) == BPF_X) {
14203                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14204
14205                 if (dst_reg->type == SCALAR_VALUE &&
14206                     src_reg->type == SCALAR_VALUE) {
14207                         if (tnum_is_const(src_reg->var_off) ||
14208                             (is_jmp32 &&
14209                              tnum_is_const(tnum_subreg(src_reg->var_off))))
14210                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14211                                                 dst_reg,
14212                                                 src_reg->var_off.value,
14213                                                 tnum_subreg(src_reg->var_off).value,
14214                                                 opcode, is_jmp32);
14215                         else if (tnum_is_const(dst_reg->var_off) ||
14216                                  (is_jmp32 &&
14217                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
14218                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14219                                                     src_reg,
14220                                                     dst_reg->var_off.value,
14221                                                     tnum_subreg(dst_reg->var_off).value,
14222                                                     opcode, is_jmp32);
14223                         else if (!is_jmp32 &&
14224                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
14225                                 /* Comparing for equality, we can combine knowledge */
14226                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14227                                                     &other_branch_regs[insn->dst_reg],
14228                                                     src_reg, dst_reg, opcode);
14229                         if (src_reg->id &&
14230                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14231                                 find_equal_scalars(this_branch, src_reg);
14232                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14233                         }
14234
14235                 }
14236         } else if (dst_reg->type == SCALAR_VALUE) {
14237                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14238                                         dst_reg, insn->imm, (u32)insn->imm,
14239                                         opcode, is_jmp32);
14240         }
14241
14242         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14243             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14244                 find_equal_scalars(this_branch, dst_reg);
14245                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14246         }
14247
14248         /* if one pointer register is compared to another pointer
14249          * register check if PTR_MAYBE_NULL could be lifted.
14250          * E.g. register A - maybe null
14251          *      register B - not null
14252          * for JNE A, B, ... - A is not null in the false branch;
14253          * for JEQ A, B, ... - A is not null in the true branch.
14254          *
14255          * Since PTR_TO_BTF_ID points to a kernel struct that does
14256          * not need to be null checked by the BPF program, i.e.,
14257          * could be null even without PTR_MAYBE_NULL marking, so
14258          * only propagate nullness when neither reg is that type.
14259          */
14260         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14261             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14262             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14263             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14264             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14265                 eq_branch_regs = NULL;
14266                 switch (opcode) {
14267                 case BPF_JEQ:
14268                         eq_branch_regs = other_branch_regs;
14269                         break;
14270                 case BPF_JNE:
14271                         eq_branch_regs = regs;
14272                         break;
14273                 default:
14274                         /* do nothing */
14275                         break;
14276                 }
14277                 if (eq_branch_regs) {
14278                         if (type_may_be_null(src_reg->type))
14279                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14280                         else
14281                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14282                 }
14283         }
14284
14285         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14286          * NOTE: these optimizations below are related with pointer comparison
14287          *       which will never be JMP32.
14288          */
14289         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14290             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14291             type_may_be_null(dst_reg->type)) {
14292                 /* Mark all identical registers in each branch as either
14293                  * safe or unknown depending R == 0 or R != 0 conditional.
14294                  */
14295                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14296                                       opcode == BPF_JNE);
14297                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14298                                       opcode == BPF_JEQ);
14299         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14300                                            this_branch, other_branch) &&
14301                    is_pointer_value(env, insn->dst_reg)) {
14302                 verbose(env, "R%d pointer comparison prohibited\n",
14303                         insn->dst_reg);
14304                 return -EACCES;
14305         }
14306         if (env->log.level & BPF_LOG_LEVEL)
14307                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14308         return 0;
14309 }
14310
14311 /* verify BPF_LD_IMM64 instruction */
14312 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14313 {
14314         struct bpf_insn_aux_data *aux = cur_aux(env);
14315         struct bpf_reg_state *regs = cur_regs(env);
14316         struct bpf_reg_state *dst_reg;
14317         struct bpf_map *map;
14318         int err;
14319
14320         if (BPF_SIZE(insn->code) != BPF_DW) {
14321                 verbose(env, "invalid BPF_LD_IMM insn\n");
14322                 return -EINVAL;
14323         }
14324         if (insn->off != 0) {
14325                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14326                 return -EINVAL;
14327         }
14328
14329         err = check_reg_arg(env, insn->dst_reg, DST_OP);
14330         if (err)
14331                 return err;
14332
14333         dst_reg = &regs[insn->dst_reg];
14334         if (insn->src_reg == 0) {
14335                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14336
14337                 dst_reg->type = SCALAR_VALUE;
14338                 __mark_reg_known(&regs[insn->dst_reg], imm);
14339                 return 0;
14340         }
14341
14342         /* All special src_reg cases are listed below. From this point onwards
14343          * we either succeed and assign a corresponding dst_reg->type after
14344          * zeroing the offset, or fail and reject the program.
14345          */
14346         mark_reg_known_zero(env, regs, insn->dst_reg);
14347
14348         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14349                 dst_reg->type = aux->btf_var.reg_type;
14350                 switch (base_type(dst_reg->type)) {
14351                 case PTR_TO_MEM:
14352                         dst_reg->mem_size = aux->btf_var.mem_size;
14353                         break;
14354                 case PTR_TO_BTF_ID:
14355                         dst_reg->btf = aux->btf_var.btf;
14356                         dst_reg->btf_id = aux->btf_var.btf_id;
14357                         break;
14358                 default:
14359                         verbose(env, "bpf verifier is misconfigured\n");
14360                         return -EFAULT;
14361                 }
14362                 return 0;
14363         }
14364
14365         if (insn->src_reg == BPF_PSEUDO_FUNC) {
14366                 struct bpf_prog_aux *aux = env->prog->aux;
14367                 u32 subprogno = find_subprog(env,
14368                                              env->insn_idx + insn->imm + 1);
14369
14370                 if (!aux->func_info) {
14371                         verbose(env, "missing btf func_info\n");
14372                         return -EINVAL;
14373                 }
14374                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14375                         verbose(env, "callback function not static\n");
14376                         return -EINVAL;
14377                 }
14378
14379                 dst_reg->type = PTR_TO_FUNC;
14380                 dst_reg->subprogno = subprogno;
14381                 return 0;
14382         }
14383
14384         map = env->used_maps[aux->map_index];
14385         dst_reg->map_ptr = map;
14386
14387         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14388             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14389                 dst_reg->type = PTR_TO_MAP_VALUE;
14390                 dst_reg->off = aux->map_off;
14391                 WARN_ON_ONCE(map->max_entries != 1);
14392                 /* We want reg->id to be same (0) as map_value is not distinct */
14393         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14394                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14395                 dst_reg->type = CONST_PTR_TO_MAP;
14396         } else {
14397                 verbose(env, "bpf verifier is misconfigured\n");
14398                 return -EINVAL;
14399         }
14400
14401         return 0;
14402 }
14403
14404 static bool may_access_skb(enum bpf_prog_type type)
14405 {
14406         switch (type) {
14407         case BPF_PROG_TYPE_SOCKET_FILTER:
14408         case BPF_PROG_TYPE_SCHED_CLS:
14409         case BPF_PROG_TYPE_SCHED_ACT:
14410                 return true;
14411         default:
14412                 return false;
14413         }
14414 }
14415
14416 /* verify safety of LD_ABS|LD_IND instructions:
14417  * - they can only appear in the programs where ctx == skb
14418  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14419  *   preserve R6-R9, and store return value into R0
14420  *
14421  * Implicit input:
14422  *   ctx == skb == R6 == CTX
14423  *
14424  * Explicit input:
14425  *   SRC == any register
14426  *   IMM == 32-bit immediate
14427  *
14428  * Output:
14429  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14430  */
14431 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14432 {
14433         struct bpf_reg_state *regs = cur_regs(env);
14434         static const int ctx_reg = BPF_REG_6;
14435         u8 mode = BPF_MODE(insn->code);
14436         int i, err;
14437
14438         if (!may_access_skb(resolve_prog_type(env->prog))) {
14439                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14440                 return -EINVAL;
14441         }
14442
14443         if (!env->ops->gen_ld_abs) {
14444                 verbose(env, "bpf verifier is misconfigured\n");
14445                 return -EINVAL;
14446         }
14447
14448         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14449             BPF_SIZE(insn->code) == BPF_DW ||
14450             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14451                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14452                 return -EINVAL;
14453         }
14454
14455         /* check whether implicit source operand (register R6) is readable */
14456         err = check_reg_arg(env, ctx_reg, SRC_OP);
14457         if (err)
14458                 return err;
14459
14460         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14461          * gen_ld_abs() may terminate the program at runtime, leading to
14462          * reference leak.
14463          */
14464         err = check_reference_leak(env);
14465         if (err) {
14466                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14467                 return err;
14468         }
14469
14470         if (env->cur_state->active_lock.ptr) {
14471                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14472                 return -EINVAL;
14473         }
14474
14475         if (env->cur_state->active_rcu_lock) {
14476                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14477                 return -EINVAL;
14478         }
14479
14480         if (regs[ctx_reg].type != PTR_TO_CTX) {
14481                 verbose(env,
14482                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14483                 return -EINVAL;
14484         }
14485
14486         if (mode == BPF_IND) {
14487                 /* check explicit source operand */
14488                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14489                 if (err)
14490                         return err;
14491         }
14492
14493         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14494         if (err < 0)
14495                 return err;
14496
14497         /* reset caller saved regs to unreadable */
14498         for (i = 0; i < CALLER_SAVED_REGS; i++) {
14499                 mark_reg_not_init(env, regs, caller_saved[i]);
14500                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14501         }
14502
14503         /* mark destination R0 register as readable, since it contains
14504          * the value fetched from the packet.
14505          * Already marked as written above.
14506          */
14507         mark_reg_unknown(env, regs, BPF_REG_0);
14508         /* ld_abs load up to 32-bit skb data. */
14509         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14510         return 0;
14511 }
14512
14513 static int check_return_code(struct bpf_verifier_env *env)
14514 {
14515         struct tnum enforce_attach_type_range = tnum_unknown;
14516         const struct bpf_prog *prog = env->prog;
14517         struct bpf_reg_state *reg;
14518         struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14519         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14520         int err;
14521         struct bpf_func_state *frame = env->cur_state->frame[0];
14522         const bool is_subprog = frame->subprogno;
14523
14524         /* LSM and struct_ops func-ptr's return type could be "void" */
14525         if (!is_subprog) {
14526                 switch (prog_type) {
14527                 case BPF_PROG_TYPE_LSM:
14528                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
14529                                 /* See below, can be 0 or 0-1 depending on hook. */
14530                                 break;
14531                         fallthrough;
14532                 case BPF_PROG_TYPE_STRUCT_OPS:
14533                         if (!prog->aux->attach_func_proto->type)
14534                                 return 0;
14535                         break;
14536                 default:
14537                         break;
14538                 }
14539         }
14540
14541         /* eBPF calling convention is such that R0 is used
14542          * to return the value from eBPF program.
14543          * Make sure that it's readable at this time
14544          * of bpf_exit, which means that program wrote
14545          * something into it earlier
14546          */
14547         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14548         if (err)
14549                 return err;
14550
14551         if (is_pointer_value(env, BPF_REG_0)) {
14552                 verbose(env, "R0 leaks addr as return value\n");
14553                 return -EACCES;
14554         }
14555
14556         reg = cur_regs(env) + BPF_REG_0;
14557
14558         if (frame->in_async_callback_fn) {
14559                 /* enforce return zero from async callbacks like timer */
14560                 if (reg->type != SCALAR_VALUE) {
14561                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14562                                 reg_type_str(env, reg->type));
14563                         return -EINVAL;
14564                 }
14565
14566                 if (!tnum_in(const_0, reg->var_off)) {
14567                         verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14568                         return -EINVAL;
14569                 }
14570                 return 0;
14571         }
14572
14573         if (is_subprog) {
14574                 if (reg->type != SCALAR_VALUE) {
14575                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14576                                 reg_type_str(env, reg->type));
14577                         return -EINVAL;
14578                 }
14579                 return 0;
14580         }
14581
14582         switch (prog_type) {
14583         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14584                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14585                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14586                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14587                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14588                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14589                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14590                         range = tnum_range(1, 1);
14591                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14592                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14593                         range = tnum_range(0, 3);
14594                 break;
14595         case BPF_PROG_TYPE_CGROUP_SKB:
14596                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14597                         range = tnum_range(0, 3);
14598                         enforce_attach_type_range = tnum_range(2, 3);
14599                 }
14600                 break;
14601         case BPF_PROG_TYPE_CGROUP_SOCK:
14602         case BPF_PROG_TYPE_SOCK_OPS:
14603         case BPF_PROG_TYPE_CGROUP_DEVICE:
14604         case BPF_PROG_TYPE_CGROUP_SYSCTL:
14605         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14606                 break;
14607         case BPF_PROG_TYPE_RAW_TRACEPOINT:
14608                 if (!env->prog->aux->attach_btf_id)
14609                         return 0;
14610                 range = tnum_const(0);
14611                 break;
14612         case BPF_PROG_TYPE_TRACING:
14613                 switch (env->prog->expected_attach_type) {
14614                 case BPF_TRACE_FENTRY:
14615                 case BPF_TRACE_FEXIT:
14616                         range = tnum_const(0);
14617                         break;
14618                 case BPF_TRACE_RAW_TP:
14619                 case BPF_MODIFY_RETURN:
14620                         return 0;
14621                 case BPF_TRACE_ITER:
14622                         break;
14623                 default:
14624                         return -ENOTSUPP;
14625                 }
14626                 break;
14627         case BPF_PROG_TYPE_SK_LOOKUP:
14628                 range = tnum_range(SK_DROP, SK_PASS);
14629                 break;
14630
14631         case BPF_PROG_TYPE_LSM:
14632                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14633                         /* Regular BPF_PROG_TYPE_LSM programs can return
14634                          * any value.
14635                          */
14636                         return 0;
14637                 }
14638                 if (!env->prog->aux->attach_func_proto->type) {
14639                         /* Make sure programs that attach to void
14640                          * hooks don't try to modify return value.
14641                          */
14642                         range = tnum_range(1, 1);
14643                 }
14644                 break;
14645
14646         case BPF_PROG_TYPE_NETFILTER:
14647                 range = tnum_range(NF_DROP, NF_ACCEPT);
14648                 break;
14649         case BPF_PROG_TYPE_EXT:
14650                 /* freplace program can return anything as its return value
14651                  * depends on the to-be-replaced kernel func or bpf program.
14652                  */
14653         default:
14654                 return 0;
14655         }
14656
14657         if (reg->type != SCALAR_VALUE) {
14658                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14659                         reg_type_str(env, reg->type));
14660                 return -EINVAL;
14661         }
14662
14663         if (!tnum_in(range, reg->var_off)) {
14664                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14665                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14666                     prog_type == BPF_PROG_TYPE_LSM &&
14667                     !prog->aux->attach_func_proto->type)
14668                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14669                 return -EINVAL;
14670         }
14671
14672         if (!tnum_is_unknown(enforce_attach_type_range) &&
14673             tnum_in(enforce_attach_type_range, reg->var_off))
14674                 env->prog->enforce_expected_attach_type = 1;
14675         return 0;
14676 }
14677
14678 /* non-recursive DFS pseudo code
14679  * 1  procedure DFS-iterative(G,v):
14680  * 2      label v as discovered
14681  * 3      let S be a stack
14682  * 4      S.push(v)
14683  * 5      while S is not empty
14684  * 6            t <- S.peek()
14685  * 7            if t is what we're looking for:
14686  * 8                return t
14687  * 9            for all edges e in G.adjacentEdges(t) do
14688  * 10               if edge e is already labelled
14689  * 11                   continue with the next edge
14690  * 12               w <- G.adjacentVertex(t,e)
14691  * 13               if vertex w is not discovered and not explored
14692  * 14                   label e as tree-edge
14693  * 15                   label w as discovered
14694  * 16                   S.push(w)
14695  * 17                   continue at 5
14696  * 18               else if vertex w is discovered
14697  * 19                   label e as back-edge
14698  * 20               else
14699  * 21                   // vertex w is explored
14700  * 22                   label e as forward- or cross-edge
14701  * 23           label t as explored
14702  * 24           S.pop()
14703  *
14704  * convention:
14705  * 0x10 - discovered
14706  * 0x11 - discovered and fall-through edge labelled
14707  * 0x12 - discovered and fall-through and branch edges labelled
14708  * 0x20 - explored
14709  */
14710
14711 enum {
14712         DISCOVERED = 0x10,
14713         EXPLORED = 0x20,
14714         FALLTHROUGH = 1,
14715         BRANCH = 2,
14716 };
14717
14718 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14719 {
14720         env->insn_aux_data[idx].prune_point = true;
14721 }
14722
14723 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14724 {
14725         return env->insn_aux_data[insn_idx].prune_point;
14726 }
14727
14728 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14729 {
14730         env->insn_aux_data[idx].force_checkpoint = true;
14731 }
14732
14733 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14734 {
14735         return env->insn_aux_data[insn_idx].force_checkpoint;
14736 }
14737
14738
14739 enum {
14740         DONE_EXPLORING = 0,
14741         KEEP_EXPLORING = 1,
14742 };
14743
14744 /* t, w, e - match pseudo-code above:
14745  * t - index of current instruction
14746  * w - next instruction
14747  * e - edge
14748  */
14749 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
14750 {
14751         int *insn_stack = env->cfg.insn_stack;
14752         int *insn_state = env->cfg.insn_state;
14753
14754         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14755                 return DONE_EXPLORING;
14756
14757         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14758                 return DONE_EXPLORING;
14759
14760         if (w < 0 || w >= env->prog->len) {
14761                 verbose_linfo(env, t, "%d: ", t);
14762                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14763                 return -EINVAL;
14764         }
14765
14766         if (e == BRANCH) {
14767                 /* mark branch target for state pruning */
14768                 mark_prune_point(env, w);
14769                 mark_jmp_point(env, w);
14770         }
14771
14772         if (insn_state[w] == 0) {
14773                 /* tree-edge */
14774                 insn_state[t] = DISCOVERED | e;
14775                 insn_state[w] = DISCOVERED;
14776                 if (env->cfg.cur_stack >= env->prog->len)
14777                         return -E2BIG;
14778                 insn_stack[env->cfg.cur_stack++] = w;
14779                 return KEEP_EXPLORING;
14780         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14781                 if (env->bpf_capable)
14782                         return DONE_EXPLORING;
14783                 verbose_linfo(env, t, "%d: ", t);
14784                 verbose_linfo(env, w, "%d: ", w);
14785                 verbose(env, "back-edge from insn %d to %d\n", t, w);
14786                 return -EINVAL;
14787         } else if (insn_state[w] == EXPLORED) {
14788                 /* forward- or cross-edge */
14789                 insn_state[t] = DISCOVERED | e;
14790         } else {
14791                 verbose(env, "insn state internal bug\n");
14792                 return -EFAULT;
14793         }
14794         return DONE_EXPLORING;
14795 }
14796
14797 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14798                                 struct bpf_verifier_env *env,
14799                                 bool visit_callee)
14800 {
14801         int ret, insn_sz;
14802
14803         insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
14804         ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
14805         if (ret)
14806                 return ret;
14807
14808         mark_prune_point(env, t + insn_sz);
14809         /* when we exit from subprog, we need to record non-linear history */
14810         mark_jmp_point(env, t + insn_sz);
14811
14812         if (visit_callee) {
14813                 mark_prune_point(env, t);
14814                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
14815         }
14816         return ret;
14817 }
14818
14819 /* Visits the instruction at index t and returns one of the following:
14820  *  < 0 - an error occurred
14821  *  DONE_EXPLORING - the instruction was fully explored
14822  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14823  */
14824 static int visit_insn(int t, struct bpf_verifier_env *env)
14825 {
14826         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14827         int ret, off, insn_sz;
14828
14829         if (bpf_pseudo_func(insn))
14830                 return visit_func_call_insn(t, insns, env, true);
14831
14832         /* All non-branch instructions have a single fall-through edge. */
14833         if (BPF_CLASS(insn->code) != BPF_JMP &&
14834             BPF_CLASS(insn->code) != BPF_JMP32) {
14835                 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
14836                 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
14837         }
14838
14839         switch (BPF_OP(insn->code)) {
14840         case BPF_EXIT:
14841                 return DONE_EXPLORING;
14842
14843         case BPF_CALL:
14844                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14845                         /* Mark this call insn as a prune point to trigger
14846                          * is_state_visited() check before call itself is
14847                          * processed by __check_func_call(). Otherwise new
14848                          * async state will be pushed for further exploration.
14849                          */
14850                         mark_prune_point(env, t);
14851                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14852                         struct bpf_kfunc_call_arg_meta meta;
14853
14854                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14855                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
14856                                 mark_prune_point(env, t);
14857                                 /* Checking and saving state checkpoints at iter_next() call
14858                                  * is crucial for fast convergence of open-coded iterator loop
14859                                  * logic, so we need to force it. If we don't do that,
14860                                  * is_state_visited() might skip saving a checkpoint, causing
14861                                  * unnecessarily long sequence of not checkpointed
14862                                  * instructions and jumps, leading to exhaustion of jump
14863                                  * history buffer, and potentially other undesired outcomes.
14864                                  * It is expected that with correct open-coded iterators
14865                                  * convergence will happen quickly, so we don't run a risk of
14866                                  * exhausting memory.
14867                                  */
14868                                 mark_force_checkpoint(env, t);
14869                         }
14870                 }
14871                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14872
14873         case BPF_JA:
14874                 if (BPF_SRC(insn->code) != BPF_K)
14875                         return -EINVAL;
14876
14877                 if (BPF_CLASS(insn->code) == BPF_JMP)
14878                         off = insn->off;
14879                 else
14880                         off = insn->imm;
14881
14882                 /* unconditional jump with single edge */
14883                 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
14884                 if (ret)
14885                         return ret;
14886
14887                 mark_prune_point(env, t + off + 1);
14888                 mark_jmp_point(env, t + off + 1);
14889
14890                 return ret;
14891
14892         default:
14893                 /* conditional jump with two edges */
14894                 mark_prune_point(env, t);
14895
14896                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
14897                 if (ret)
14898                         return ret;
14899
14900                 return push_insn(t, t + insn->off + 1, BRANCH, env);
14901         }
14902 }
14903
14904 /* non-recursive depth-first-search to detect loops in BPF program
14905  * loop == back-edge in directed graph
14906  */
14907 static int check_cfg(struct bpf_verifier_env *env)
14908 {
14909         int insn_cnt = env->prog->len;
14910         int *insn_stack, *insn_state;
14911         int ret = 0;
14912         int i;
14913
14914         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14915         if (!insn_state)
14916                 return -ENOMEM;
14917
14918         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14919         if (!insn_stack) {
14920                 kvfree(insn_state);
14921                 return -ENOMEM;
14922         }
14923
14924         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14925         insn_stack[0] = 0; /* 0 is the first instruction */
14926         env->cfg.cur_stack = 1;
14927
14928         while (env->cfg.cur_stack > 0) {
14929                 int t = insn_stack[env->cfg.cur_stack - 1];
14930
14931                 ret = visit_insn(t, env);
14932                 switch (ret) {
14933                 case DONE_EXPLORING:
14934                         insn_state[t] = EXPLORED;
14935                         env->cfg.cur_stack--;
14936                         break;
14937                 case KEEP_EXPLORING:
14938                         break;
14939                 default:
14940                         if (ret > 0) {
14941                                 verbose(env, "visit_insn internal bug\n");
14942                                 ret = -EFAULT;
14943                         }
14944                         goto err_free;
14945                 }
14946         }
14947
14948         if (env->cfg.cur_stack < 0) {
14949                 verbose(env, "pop stack internal bug\n");
14950                 ret = -EFAULT;
14951                 goto err_free;
14952         }
14953
14954         for (i = 0; i < insn_cnt; i++) {
14955                 struct bpf_insn *insn = &env->prog->insnsi[i];
14956
14957                 if (insn_state[i] != EXPLORED) {
14958                         verbose(env, "unreachable insn %d\n", i);
14959                         ret = -EINVAL;
14960                         goto err_free;
14961                 }
14962                 if (bpf_is_ldimm64(insn)) {
14963                         if (insn_state[i + 1] != 0) {
14964                                 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
14965                                 ret = -EINVAL;
14966                                 goto err_free;
14967                         }
14968                         i++; /* skip second half of ldimm64 */
14969                 }
14970         }
14971         ret = 0; /* cfg looks good */
14972
14973 err_free:
14974         kvfree(insn_state);
14975         kvfree(insn_stack);
14976         env->cfg.insn_state = env->cfg.insn_stack = NULL;
14977         return ret;
14978 }
14979
14980 static int check_abnormal_return(struct bpf_verifier_env *env)
14981 {
14982         int i;
14983
14984         for (i = 1; i < env->subprog_cnt; i++) {
14985                 if (env->subprog_info[i].has_ld_abs) {
14986                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14987                         return -EINVAL;
14988                 }
14989                 if (env->subprog_info[i].has_tail_call) {
14990                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14991                         return -EINVAL;
14992                 }
14993         }
14994         return 0;
14995 }
14996
14997 /* The minimum supported BTF func info size */
14998 #define MIN_BPF_FUNCINFO_SIZE   8
14999 #define MAX_FUNCINFO_REC_SIZE   252
15000
15001 static int check_btf_func(struct bpf_verifier_env *env,
15002                           const union bpf_attr *attr,
15003                           bpfptr_t uattr)
15004 {
15005         const struct btf_type *type, *func_proto, *ret_type;
15006         u32 i, nfuncs, urec_size, min_size;
15007         u32 krec_size = sizeof(struct bpf_func_info);
15008         struct bpf_func_info *krecord;
15009         struct bpf_func_info_aux *info_aux = NULL;
15010         struct bpf_prog *prog;
15011         const struct btf *btf;
15012         bpfptr_t urecord;
15013         u32 prev_offset = 0;
15014         bool scalar_return;
15015         int ret = -ENOMEM;
15016
15017         nfuncs = attr->func_info_cnt;
15018         if (!nfuncs) {
15019                 if (check_abnormal_return(env))
15020                         return -EINVAL;
15021                 return 0;
15022         }
15023
15024         if (nfuncs != env->subprog_cnt) {
15025                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15026                 return -EINVAL;
15027         }
15028
15029         urec_size = attr->func_info_rec_size;
15030         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15031             urec_size > MAX_FUNCINFO_REC_SIZE ||
15032             urec_size % sizeof(u32)) {
15033                 verbose(env, "invalid func info rec size %u\n", urec_size);
15034                 return -EINVAL;
15035         }
15036
15037         prog = env->prog;
15038         btf = prog->aux->btf;
15039
15040         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15041         min_size = min_t(u32, krec_size, urec_size);
15042
15043         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15044         if (!krecord)
15045                 return -ENOMEM;
15046         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15047         if (!info_aux)
15048                 goto err_free;
15049
15050         for (i = 0; i < nfuncs; i++) {
15051                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15052                 if (ret) {
15053                         if (ret == -E2BIG) {
15054                                 verbose(env, "nonzero tailing record in func info");
15055                                 /* set the size kernel expects so loader can zero
15056                                  * out the rest of the record.
15057                                  */
15058                                 if (copy_to_bpfptr_offset(uattr,
15059                                                           offsetof(union bpf_attr, func_info_rec_size),
15060                                                           &min_size, sizeof(min_size)))
15061                                         ret = -EFAULT;
15062                         }
15063                         goto err_free;
15064                 }
15065
15066                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15067                         ret = -EFAULT;
15068                         goto err_free;
15069                 }
15070
15071                 /* check insn_off */
15072                 ret = -EINVAL;
15073                 if (i == 0) {
15074                         if (krecord[i].insn_off) {
15075                                 verbose(env,
15076                                         "nonzero insn_off %u for the first func info record",
15077                                         krecord[i].insn_off);
15078                                 goto err_free;
15079                         }
15080                 } else if (krecord[i].insn_off <= prev_offset) {
15081                         verbose(env,
15082                                 "same or smaller insn offset (%u) than previous func info record (%u)",
15083                                 krecord[i].insn_off, prev_offset);
15084                         goto err_free;
15085                 }
15086
15087                 if (env->subprog_info[i].start != krecord[i].insn_off) {
15088                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15089                         goto err_free;
15090                 }
15091
15092                 /* check type_id */
15093                 type = btf_type_by_id(btf, krecord[i].type_id);
15094                 if (!type || !btf_type_is_func(type)) {
15095                         verbose(env, "invalid type id %d in func info",
15096                                 krecord[i].type_id);
15097                         goto err_free;
15098                 }
15099                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15100
15101                 func_proto = btf_type_by_id(btf, type->type);
15102                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15103                         /* btf_func_check() already verified it during BTF load */
15104                         goto err_free;
15105                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15106                 scalar_return =
15107                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15108                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15109                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15110                         goto err_free;
15111                 }
15112                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15113                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15114                         goto err_free;
15115                 }
15116
15117                 prev_offset = krecord[i].insn_off;
15118                 bpfptr_add(&urecord, urec_size);
15119         }
15120
15121         prog->aux->func_info = krecord;
15122         prog->aux->func_info_cnt = nfuncs;
15123         prog->aux->func_info_aux = info_aux;
15124         return 0;
15125
15126 err_free:
15127         kvfree(krecord);
15128         kfree(info_aux);
15129         return ret;
15130 }
15131
15132 static void adjust_btf_func(struct bpf_verifier_env *env)
15133 {
15134         struct bpf_prog_aux *aux = env->prog->aux;
15135         int i;
15136
15137         if (!aux->func_info)
15138                 return;
15139
15140         for (i = 0; i < env->subprog_cnt; i++)
15141                 aux->func_info[i].insn_off = env->subprog_info[i].start;
15142 }
15143
15144 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
15145 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
15146
15147 static int check_btf_line(struct bpf_verifier_env *env,
15148                           const union bpf_attr *attr,
15149                           bpfptr_t uattr)
15150 {
15151         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15152         struct bpf_subprog_info *sub;
15153         struct bpf_line_info *linfo;
15154         struct bpf_prog *prog;
15155         const struct btf *btf;
15156         bpfptr_t ulinfo;
15157         int err;
15158
15159         nr_linfo = attr->line_info_cnt;
15160         if (!nr_linfo)
15161                 return 0;
15162         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15163                 return -EINVAL;
15164
15165         rec_size = attr->line_info_rec_size;
15166         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15167             rec_size > MAX_LINEINFO_REC_SIZE ||
15168             rec_size & (sizeof(u32) - 1))
15169                 return -EINVAL;
15170
15171         /* Need to zero it in case the userspace may
15172          * pass in a smaller bpf_line_info object.
15173          */
15174         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15175                          GFP_KERNEL | __GFP_NOWARN);
15176         if (!linfo)
15177                 return -ENOMEM;
15178
15179         prog = env->prog;
15180         btf = prog->aux->btf;
15181
15182         s = 0;
15183         sub = env->subprog_info;
15184         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15185         expected_size = sizeof(struct bpf_line_info);
15186         ncopy = min_t(u32, expected_size, rec_size);
15187         for (i = 0; i < nr_linfo; i++) {
15188                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15189                 if (err) {
15190                         if (err == -E2BIG) {
15191                                 verbose(env, "nonzero tailing record in line_info");
15192                                 if (copy_to_bpfptr_offset(uattr,
15193                                                           offsetof(union bpf_attr, line_info_rec_size),
15194                                                           &expected_size, sizeof(expected_size)))
15195                                         err = -EFAULT;
15196                         }
15197                         goto err_free;
15198                 }
15199
15200                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15201                         err = -EFAULT;
15202                         goto err_free;
15203                 }
15204
15205                 /*
15206                  * Check insn_off to ensure
15207                  * 1) strictly increasing AND
15208                  * 2) bounded by prog->len
15209                  *
15210                  * The linfo[0].insn_off == 0 check logically falls into
15211                  * the later "missing bpf_line_info for func..." case
15212                  * because the first linfo[0].insn_off must be the
15213                  * first sub also and the first sub must have
15214                  * subprog_info[0].start == 0.
15215                  */
15216                 if ((i && linfo[i].insn_off <= prev_offset) ||
15217                     linfo[i].insn_off >= prog->len) {
15218                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15219                                 i, linfo[i].insn_off, prev_offset,
15220                                 prog->len);
15221                         err = -EINVAL;
15222                         goto err_free;
15223                 }
15224
15225                 if (!prog->insnsi[linfo[i].insn_off].code) {
15226                         verbose(env,
15227                                 "Invalid insn code at line_info[%u].insn_off\n",
15228                                 i);
15229                         err = -EINVAL;
15230                         goto err_free;
15231                 }
15232
15233                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15234                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15235                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15236                         err = -EINVAL;
15237                         goto err_free;
15238                 }
15239
15240                 if (s != env->subprog_cnt) {
15241                         if (linfo[i].insn_off == sub[s].start) {
15242                                 sub[s].linfo_idx = i;
15243                                 s++;
15244                         } else if (sub[s].start < linfo[i].insn_off) {
15245                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
15246                                 err = -EINVAL;
15247                                 goto err_free;
15248                         }
15249                 }
15250
15251                 prev_offset = linfo[i].insn_off;
15252                 bpfptr_add(&ulinfo, rec_size);
15253         }
15254
15255         if (s != env->subprog_cnt) {
15256                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15257                         env->subprog_cnt - s, s);
15258                 err = -EINVAL;
15259                 goto err_free;
15260         }
15261
15262         prog->aux->linfo = linfo;
15263         prog->aux->nr_linfo = nr_linfo;
15264
15265         return 0;
15266
15267 err_free:
15268         kvfree(linfo);
15269         return err;
15270 }
15271
15272 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
15273 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
15274
15275 static int check_core_relo(struct bpf_verifier_env *env,
15276                            const union bpf_attr *attr,
15277                            bpfptr_t uattr)
15278 {
15279         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15280         struct bpf_core_relo core_relo = {};
15281         struct bpf_prog *prog = env->prog;
15282         const struct btf *btf = prog->aux->btf;
15283         struct bpf_core_ctx ctx = {
15284                 .log = &env->log,
15285                 .btf = btf,
15286         };
15287         bpfptr_t u_core_relo;
15288         int err;
15289
15290         nr_core_relo = attr->core_relo_cnt;
15291         if (!nr_core_relo)
15292                 return 0;
15293         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15294                 return -EINVAL;
15295
15296         rec_size = attr->core_relo_rec_size;
15297         if (rec_size < MIN_CORE_RELO_SIZE ||
15298             rec_size > MAX_CORE_RELO_SIZE ||
15299             rec_size % sizeof(u32))
15300                 return -EINVAL;
15301
15302         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15303         expected_size = sizeof(struct bpf_core_relo);
15304         ncopy = min_t(u32, expected_size, rec_size);
15305
15306         /* Unlike func_info and line_info, copy and apply each CO-RE
15307          * relocation record one at a time.
15308          */
15309         for (i = 0; i < nr_core_relo; i++) {
15310                 /* future proofing when sizeof(bpf_core_relo) changes */
15311                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15312                 if (err) {
15313                         if (err == -E2BIG) {
15314                                 verbose(env, "nonzero tailing record in core_relo");
15315                                 if (copy_to_bpfptr_offset(uattr,
15316                                                           offsetof(union bpf_attr, core_relo_rec_size),
15317                                                           &expected_size, sizeof(expected_size)))
15318                                         err = -EFAULT;
15319                         }
15320                         break;
15321                 }
15322
15323                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15324                         err = -EFAULT;
15325                         break;
15326                 }
15327
15328                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15329                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15330                                 i, core_relo.insn_off, prog->len);
15331                         err = -EINVAL;
15332                         break;
15333                 }
15334
15335                 err = bpf_core_apply(&ctx, &core_relo, i,
15336                                      &prog->insnsi[core_relo.insn_off / 8]);
15337                 if (err)
15338                         break;
15339                 bpfptr_add(&u_core_relo, rec_size);
15340         }
15341         return err;
15342 }
15343
15344 static int check_btf_info(struct bpf_verifier_env *env,
15345                           const union bpf_attr *attr,
15346                           bpfptr_t uattr)
15347 {
15348         struct btf *btf;
15349         int err;
15350
15351         if (!attr->func_info_cnt && !attr->line_info_cnt) {
15352                 if (check_abnormal_return(env))
15353                         return -EINVAL;
15354                 return 0;
15355         }
15356
15357         btf = btf_get_by_fd(attr->prog_btf_fd);
15358         if (IS_ERR(btf))
15359                 return PTR_ERR(btf);
15360         if (btf_is_kernel(btf)) {
15361                 btf_put(btf);
15362                 return -EACCES;
15363         }
15364         env->prog->aux->btf = btf;
15365
15366         err = check_btf_func(env, attr, uattr);
15367         if (err)
15368                 return err;
15369
15370         err = check_btf_line(env, attr, uattr);
15371         if (err)
15372                 return err;
15373
15374         err = check_core_relo(env, attr, uattr);
15375         if (err)
15376                 return err;
15377
15378         return 0;
15379 }
15380
15381 /* check %cur's range satisfies %old's */
15382 static bool range_within(struct bpf_reg_state *old,
15383                          struct bpf_reg_state *cur)
15384 {
15385         return old->umin_value <= cur->umin_value &&
15386                old->umax_value >= cur->umax_value &&
15387                old->smin_value <= cur->smin_value &&
15388                old->smax_value >= cur->smax_value &&
15389                old->u32_min_value <= cur->u32_min_value &&
15390                old->u32_max_value >= cur->u32_max_value &&
15391                old->s32_min_value <= cur->s32_min_value &&
15392                old->s32_max_value >= cur->s32_max_value;
15393 }
15394
15395 /* If in the old state two registers had the same id, then they need to have
15396  * the same id in the new state as well.  But that id could be different from
15397  * the old state, so we need to track the mapping from old to new ids.
15398  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15399  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15400  * regs with a different old id could still have new id 9, we don't care about
15401  * that.
15402  * So we look through our idmap to see if this old id has been seen before.  If
15403  * so, we require the new id to match; otherwise, we add the id pair to the map.
15404  */
15405 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15406 {
15407         struct bpf_id_pair *map = idmap->map;
15408         unsigned int i;
15409
15410         /* either both IDs should be set or both should be zero */
15411         if (!!old_id != !!cur_id)
15412                 return false;
15413
15414         if (old_id == 0) /* cur_id == 0 as well */
15415                 return true;
15416
15417         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15418                 if (!map[i].old) {
15419                         /* Reached an empty slot; haven't seen this id before */
15420                         map[i].old = old_id;
15421                         map[i].cur = cur_id;
15422                         return true;
15423                 }
15424                 if (map[i].old == old_id)
15425                         return map[i].cur == cur_id;
15426                 if (map[i].cur == cur_id)
15427                         return false;
15428         }
15429         /* We ran out of idmap slots, which should be impossible */
15430         WARN_ON_ONCE(1);
15431         return false;
15432 }
15433
15434 /* Similar to check_ids(), but allocate a unique temporary ID
15435  * for 'old_id' or 'cur_id' of zero.
15436  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15437  */
15438 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15439 {
15440         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15441         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15442
15443         return check_ids(old_id, cur_id, idmap);
15444 }
15445
15446 static void clean_func_state(struct bpf_verifier_env *env,
15447                              struct bpf_func_state *st)
15448 {
15449         enum bpf_reg_liveness live;
15450         int i, j;
15451
15452         for (i = 0; i < BPF_REG_FP; i++) {
15453                 live = st->regs[i].live;
15454                 /* liveness must not touch this register anymore */
15455                 st->regs[i].live |= REG_LIVE_DONE;
15456                 if (!(live & REG_LIVE_READ))
15457                         /* since the register is unused, clear its state
15458                          * to make further comparison simpler
15459                          */
15460                         __mark_reg_not_init(env, &st->regs[i]);
15461         }
15462
15463         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15464                 live = st->stack[i].spilled_ptr.live;
15465                 /* liveness must not touch this stack slot anymore */
15466                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15467                 if (!(live & REG_LIVE_READ)) {
15468                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15469                         for (j = 0; j < BPF_REG_SIZE; j++)
15470                                 st->stack[i].slot_type[j] = STACK_INVALID;
15471                 }
15472         }
15473 }
15474
15475 static void clean_verifier_state(struct bpf_verifier_env *env,
15476                                  struct bpf_verifier_state *st)
15477 {
15478         int i;
15479
15480         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15481                 /* all regs in this state in all frames were already marked */
15482                 return;
15483
15484         for (i = 0; i <= st->curframe; i++)
15485                 clean_func_state(env, st->frame[i]);
15486 }
15487
15488 /* the parentage chains form a tree.
15489  * the verifier states are added to state lists at given insn and
15490  * pushed into state stack for future exploration.
15491  * when the verifier reaches bpf_exit insn some of the verifer states
15492  * stored in the state lists have their final liveness state already,
15493  * but a lot of states will get revised from liveness point of view when
15494  * the verifier explores other branches.
15495  * Example:
15496  * 1: r0 = 1
15497  * 2: if r1 == 100 goto pc+1
15498  * 3: r0 = 2
15499  * 4: exit
15500  * when the verifier reaches exit insn the register r0 in the state list of
15501  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15502  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15503  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15504  *
15505  * Since the verifier pushes the branch states as it sees them while exploring
15506  * the program the condition of walking the branch instruction for the second
15507  * time means that all states below this branch were already explored and
15508  * their final liveness marks are already propagated.
15509  * Hence when the verifier completes the search of state list in is_state_visited()
15510  * we can call this clean_live_states() function to mark all liveness states
15511  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15512  * will not be used.
15513  * This function also clears the registers and stack for states that !READ
15514  * to simplify state merging.
15515  *
15516  * Important note here that walking the same branch instruction in the callee
15517  * doesn't meant that the states are DONE. The verifier has to compare
15518  * the callsites
15519  */
15520 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15521                               struct bpf_verifier_state *cur)
15522 {
15523         struct bpf_verifier_state_list *sl;
15524         int i;
15525
15526         sl = *explored_state(env, insn);
15527         while (sl) {
15528                 if (sl->state.branches)
15529                         goto next;
15530                 if (sl->state.insn_idx != insn ||
15531                     sl->state.curframe != cur->curframe)
15532                         goto next;
15533                 for (i = 0; i <= cur->curframe; i++)
15534                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15535                                 goto next;
15536                 clean_verifier_state(env, &sl->state);
15537 next:
15538                 sl = sl->next;
15539         }
15540 }
15541
15542 static bool regs_exact(const struct bpf_reg_state *rold,
15543                        const struct bpf_reg_state *rcur,
15544                        struct bpf_idmap *idmap)
15545 {
15546         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15547                check_ids(rold->id, rcur->id, idmap) &&
15548                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15549 }
15550
15551 /* Returns true if (rold safe implies rcur safe) */
15552 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15553                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15554 {
15555         if (!(rold->live & REG_LIVE_READ))
15556                 /* explored state didn't use this */
15557                 return true;
15558         if (rold->type == NOT_INIT)
15559                 /* explored state can't have used this */
15560                 return true;
15561         if (rcur->type == NOT_INIT)
15562                 return false;
15563
15564         /* Enforce that register types have to match exactly, including their
15565          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15566          * rule.
15567          *
15568          * One can make a point that using a pointer register as unbounded
15569          * SCALAR would be technically acceptable, but this could lead to
15570          * pointer leaks because scalars are allowed to leak while pointers
15571          * are not. We could make this safe in special cases if root is
15572          * calling us, but it's probably not worth the hassle.
15573          *
15574          * Also, register types that are *not* MAYBE_NULL could technically be
15575          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15576          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15577          * to the same map).
15578          * However, if the old MAYBE_NULL register then got NULL checked,
15579          * doing so could have affected others with the same id, and we can't
15580          * check for that because we lost the id when we converted to
15581          * a non-MAYBE_NULL variant.
15582          * So, as a general rule we don't allow mixing MAYBE_NULL and
15583          * non-MAYBE_NULL registers as well.
15584          */
15585         if (rold->type != rcur->type)
15586                 return false;
15587
15588         switch (base_type(rold->type)) {
15589         case SCALAR_VALUE:
15590                 if (env->explore_alu_limits) {
15591                         /* explore_alu_limits disables tnum_in() and range_within()
15592                          * logic and requires everything to be strict
15593                          */
15594                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15595                                check_scalar_ids(rold->id, rcur->id, idmap);
15596                 }
15597                 if (!rold->precise)
15598                         return true;
15599                 /* Why check_ids() for scalar registers?
15600                  *
15601                  * Consider the following BPF code:
15602                  *   1: r6 = ... unbound scalar, ID=a ...
15603                  *   2: r7 = ... unbound scalar, ID=b ...
15604                  *   3: if (r6 > r7) goto +1
15605                  *   4: r6 = r7
15606                  *   5: if (r6 > X) goto ...
15607                  *   6: ... memory operation using r7 ...
15608                  *
15609                  * First verification path is [1-6]:
15610                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15611                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15612                  *   r7 <= X, because r6 and r7 share same id.
15613                  * Next verification path is [1-4, 6].
15614                  *
15615                  * Instruction (6) would be reached in two states:
15616                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15617                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15618                  *
15619                  * Use check_ids() to distinguish these states.
15620                  * ---
15621                  * Also verify that new value satisfies old value range knowledge.
15622                  */
15623                 return range_within(rold, rcur) &&
15624                        tnum_in(rold->var_off, rcur->var_off) &&
15625                        check_scalar_ids(rold->id, rcur->id, idmap);
15626         case PTR_TO_MAP_KEY:
15627         case PTR_TO_MAP_VALUE:
15628         case PTR_TO_MEM:
15629         case PTR_TO_BUF:
15630         case PTR_TO_TP_BUFFER:
15631                 /* If the new min/max/var_off satisfy the old ones and
15632                  * everything else matches, we are OK.
15633                  */
15634                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15635                        range_within(rold, rcur) &&
15636                        tnum_in(rold->var_off, rcur->var_off) &&
15637                        check_ids(rold->id, rcur->id, idmap) &&
15638                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15639         case PTR_TO_PACKET_META:
15640         case PTR_TO_PACKET:
15641                 /* We must have at least as much range as the old ptr
15642                  * did, so that any accesses which were safe before are
15643                  * still safe.  This is true even if old range < old off,
15644                  * since someone could have accessed through (ptr - k), or
15645                  * even done ptr -= k in a register, to get a safe access.
15646                  */
15647                 if (rold->range > rcur->range)
15648                         return false;
15649                 /* If the offsets don't match, we can't trust our alignment;
15650                  * nor can we be sure that we won't fall out of range.
15651                  */
15652                 if (rold->off != rcur->off)
15653                         return false;
15654                 /* id relations must be preserved */
15655                 if (!check_ids(rold->id, rcur->id, idmap))
15656                         return false;
15657                 /* new val must satisfy old val knowledge */
15658                 return range_within(rold, rcur) &&
15659                        tnum_in(rold->var_off, rcur->var_off);
15660         case PTR_TO_STACK:
15661                 /* two stack pointers are equal only if they're pointing to
15662                  * the same stack frame, since fp-8 in foo != fp-8 in bar
15663                  */
15664                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15665         default:
15666                 return regs_exact(rold, rcur, idmap);
15667         }
15668 }
15669
15670 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15671                       struct bpf_func_state *cur, struct bpf_idmap *idmap)
15672 {
15673         int i, spi;
15674
15675         /* walk slots of the explored stack and ignore any additional
15676          * slots in the current stack, since explored(safe) state
15677          * didn't use them
15678          */
15679         for (i = 0; i < old->allocated_stack; i++) {
15680                 struct bpf_reg_state *old_reg, *cur_reg;
15681
15682                 spi = i / BPF_REG_SIZE;
15683
15684                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15685                         i += BPF_REG_SIZE - 1;
15686                         /* explored state didn't use this */
15687                         continue;
15688                 }
15689
15690                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15691                         continue;
15692
15693                 if (env->allow_uninit_stack &&
15694                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15695                         continue;
15696
15697                 /* explored stack has more populated slots than current stack
15698                  * and these slots were used
15699                  */
15700                 if (i >= cur->allocated_stack)
15701                         return false;
15702
15703                 /* if old state was safe with misc data in the stack
15704                  * it will be safe with zero-initialized stack.
15705                  * The opposite is not true
15706                  */
15707                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15708                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15709                         continue;
15710                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15711                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15712                         /* Ex: old explored (safe) state has STACK_SPILL in
15713                          * this stack slot, but current has STACK_MISC ->
15714                          * this verifier states are not equivalent,
15715                          * return false to continue verification of this path
15716                          */
15717                         return false;
15718                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15719                         continue;
15720                 /* Both old and cur are having same slot_type */
15721                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15722                 case STACK_SPILL:
15723                         /* when explored and current stack slot are both storing
15724                          * spilled registers, check that stored pointers types
15725                          * are the same as well.
15726                          * Ex: explored safe path could have stored
15727                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15728                          * but current path has stored:
15729                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15730                          * such verifier states are not equivalent.
15731                          * return false to continue verification of this path
15732                          */
15733                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
15734                                      &cur->stack[spi].spilled_ptr, idmap))
15735                                 return false;
15736                         break;
15737                 case STACK_DYNPTR:
15738                         old_reg = &old->stack[spi].spilled_ptr;
15739                         cur_reg = &cur->stack[spi].spilled_ptr;
15740                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15741                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15742                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15743                                 return false;
15744                         break;
15745                 case STACK_ITER:
15746                         old_reg = &old->stack[spi].spilled_ptr;
15747                         cur_reg = &cur->stack[spi].spilled_ptr;
15748                         /* iter.depth is not compared between states as it
15749                          * doesn't matter for correctness and would otherwise
15750                          * prevent convergence; we maintain it only to prevent
15751                          * infinite loop check triggering, see
15752                          * iter_active_depths_differ()
15753                          */
15754                         if (old_reg->iter.btf != cur_reg->iter.btf ||
15755                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15756                             old_reg->iter.state != cur_reg->iter.state ||
15757                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
15758                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15759                                 return false;
15760                         break;
15761                 case STACK_MISC:
15762                 case STACK_ZERO:
15763                 case STACK_INVALID:
15764                         continue;
15765                 /* Ensure that new unhandled slot types return false by default */
15766                 default:
15767                         return false;
15768                 }
15769         }
15770         return true;
15771 }
15772
15773 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15774                     struct bpf_idmap *idmap)
15775 {
15776         int i;
15777
15778         if (old->acquired_refs != cur->acquired_refs)
15779                 return false;
15780
15781         for (i = 0; i < old->acquired_refs; i++) {
15782                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15783                         return false;
15784         }
15785
15786         return true;
15787 }
15788
15789 /* compare two verifier states
15790  *
15791  * all states stored in state_list are known to be valid, since
15792  * verifier reached 'bpf_exit' instruction through them
15793  *
15794  * this function is called when verifier exploring different branches of
15795  * execution popped from the state stack. If it sees an old state that has
15796  * more strict register state and more strict stack state then this execution
15797  * branch doesn't need to be explored further, since verifier already
15798  * concluded that more strict state leads to valid finish.
15799  *
15800  * Therefore two states are equivalent if register state is more conservative
15801  * and explored stack state is more conservative than the current one.
15802  * Example:
15803  *       explored                   current
15804  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15805  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15806  *
15807  * In other words if current stack state (one being explored) has more
15808  * valid slots than old one that already passed validation, it means
15809  * the verifier can stop exploring and conclude that current state is valid too
15810  *
15811  * Similarly with registers. If explored state has register type as invalid
15812  * whereas register type in current state is meaningful, it means that
15813  * the current state will reach 'bpf_exit' instruction safely
15814  */
15815 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15816                               struct bpf_func_state *cur)
15817 {
15818         int i;
15819
15820         for (i = 0; i < MAX_BPF_REG; i++)
15821                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15822                              &env->idmap_scratch))
15823                         return false;
15824
15825         if (!stacksafe(env, old, cur, &env->idmap_scratch))
15826                 return false;
15827
15828         if (!refsafe(old, cur, &env->idmap_scratch))
15829                 return false;
15830
15831         return true;
15832 }
15833
15834 static bool states_equal(struct bpf_verifier_env *env,
15835                          struct bpf_verifier_state *old,
15836                          struct bpf_verifier_state *cur)
15837 {
15838         int i;
15839
15840         if (old->curframe != cur->curframe)
15841                 return false;
15842
15843         env->idmap_scratch.tmp_id_gen = env->id_gen;
15844         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15845
15846         /* Verification state from speculative execution simulation
15847          * must never prune a non-speculative execution one.
15848          */
15849         if (old->speculative && !cur->speculative)
15850                 return false;
15851
15852         if (old->active_lock.ptr != cur->active_lock.ptr)
15853                 return false;
15854
15855         /* Old and cur active_lock's have to be either both present
15856          * or both absent.
15857          */
15858         if (!!old->active_lock.id != !!cur->active_lock.id)
15859                 return false;
15860
15861         if (old->active_lock.id &&
15862             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15863                 return false;
15864
15865         if (old->active_rcu_lock != cur->active_rcu_lock)
15866                 return false;
15867
15868         /* for states to be equal callsites have to be the same
15869          * and all frame states need to be equivalent
15870          */
15871         for (i = 0; i <= old->curframe; i++) {
15872                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15873                         return false;
15874                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15875                         return false;
15876         }
15877         return true;
15878 }
15879
15880 /* Return 0 if no propagation happened. Return negative error code if error
15881  * happened. Otherwise, return the propagated bit.
15882  */
15883 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15884                                   struct bpf_reg_state *reg,
15885                                   struct bpf_reg_state *parent_reg)
15886 {
15887         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15888         u8 flag = reg->live & REG_LIVE_READ;
15889         int err;
15890
15891         /* When comes here, read flags of PARENT_REG or REG could be any of
15892          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15893          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15894          */
15895         if (parent_flag == REG_LIVE_READ64 ||
15896             /* Or if there is no read flag from REG. */
15897             !flag ||
15898             /* Or if the read flag from REG is the same as PARENT_REG. */
15899             parent_flag == flag)
15900                 return 0;
15901
15902         err = mark_reg_read(env, reg, parent_reg, flag);
15903         if (err)
15904                 return err;
15905
15906         return flag;
15907 }
15908
15909 /* A write screens off any subsequent reads; but write marks come from the
15910  * straight-line code between a state and its parent.  When we arrive at an
15911  * equivalent state (jump target or such) we didn't arrive by the straight-line
15912  * code, so read marks in the state must propagate to the parent regardless
15913  * of the state's write marks. That's what 'parent == state->parent' comparison
15914  * in mark_reg_read() is for.
15915  */
15916 static int propagate_liveness(struct bpf_verifier_env *env,
15917                               const struct bpf_verifier_state *vstate,
15918                               struct bpf_verifier_state *vparent)
15919 {
15920         struct bpf_reg_state *state_reg, *parent_reg;
15921         struct bpf_func_state *state, *parent;
15922         int i, frame, err = 0;
15923
15924         if (vparent->curframe != vstate->curframe) {
15925                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15926                      vparent->curframe, vstate->curframe);
15927                 return -EFAULT;
15928         }
15929         /* Propagate read liveness of registers... */
15930         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15931         for (frame = 0; frame <= vstate->curframe; frame++) {
15932                 parent = vparent->frame[frame];
15933                 state = vstate->frame[frame];
15934                 parent_reg = parent->regs;
15935                 state_reg = state->regs;
15936                 /* We don't need to worry about FP liveness, it's read-only */
15937                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15938                         err = propagate_liveness_reg(env, &state_reg[i],
15939                                                      &parent_reg[i]);
15940                         if (err < 0)
15941                                 return err;
15942                         if (err == REG_LIVE_READ64)
15943                                 mark_insn_zext(env, &parent_reg[i]);
15944                 }
15945
15946                 /* Propagate stack slots. */
15947                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15948                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15949                         parent_reg = &parent->stack[i].spilled_ptr;
15950                         state_reg = &state->stack[i].spilled_ptr;
15951                         err = propagate_liveness_reg(env, state_reg,
15952                                                      parent_reg);
15953                         if (err < 0)
15954                                 return err;
15955                 }
15956         }
15957         return 0;
15958 }
15959
15960 /* find precise scalars in the previous equivalent state and
15961  * propagate them into the current state
15962  */
15963 static int propagate_precision(struct bpf_verifier_env *env,
15964                                const struct bpf_verifier_state *old)
15965 {
15966         struct bpf_reg_state *state_reg;
15967         struct bpf_func_state *state;
15968         int i, err = 0, fr;
15969         bool first;
15970
15971         for (fr = old->curframe; fr >= 0; fr--) {
15972                 state = old->frame[fr];
15973                 state_reg = state->regs;
15974                 first = true;
15975                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15976                         if (state_reg->type != SCALAR_VALUE ||
15977                             !state_reg->precise ||
15978                             !(state_reg->live & REG_LIVE_READ))
15979                                 continue;
15980                         if (env->log.level & BPF_LOG_LEVEL2) {
15981                                 if (first)
15982                                         verbose(env, "frame %d: propagating r%d", fr, i);
15983                                 else
15984                                         verbose(env, ",r%d", i);
15985                         }
15986                         bt_set_frame_reg(&env->bt, fr, i);
15987                         first = false;
15988                 }
15989
15990                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15991                         if (!is_spilled_reg(&state->stack[i]))
15992                                 continue;
15993                         state_reg = &state->stack[i].spilled_ptr;
15994                         if (state_reg->type != SCALAR_VALUE ||
15995                             !state_reg->precise ||
15996                             !(state_reg->live & REG_LIVE_READ))
15997                                 continue;
15998                         if (env->log.level & BPF_LOG_LEVEL2) {
15999                                 if (first)
16000                                         verbose(env, "frame %d: propagating fp%d",
16001                                                 fr, (-i - 1) * BPF_REG_SIZE);
16002                                 else
16003                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16004                         }
16005                         bt_set_frame_slot(&env->bt, fr, i);
16006                         first = false;
16007                 }
16008                 if (!first)
16009                         verbose(env, "\n");
16010         }
16011
16012         err = mark_chain_precision_batch(env);
16013         if (err < 0)
16014                 return err;
16015
16016         return 0;
16017 }
16018
16019 static bool states_maybe_looping(struct bpf_verifier_state *old,
16020                                  struct bpf_verifier_state *cur)
16021 {
16022         struct bpf_func_state *fold, *fcur;
16023         int i, fr = cur->curframe;
16024
16025         if (old->curframe != fr)
16026                 return false;
16027
16028         fold = old->frame[fr];
16029         fcur = cur->frame[fr];
16030         for (i = 0; i < MAX_BPF_REG; i++)
16031                 if (memcmp(&fold->regs[i], &fcur->regs[i],
16032                            offsetof(struct bpf_reg_state, parent)))
16033                         return false;
16034         return true;
16035 }
16036
16037 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16038 {
16039         return env->insn_aux_data[insn_idx].is_iter_next;
16040 }
16041
16042 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16043  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16044  * states to match, which otherwise would look like an infinite loop. So while
16045  * iter_next() calls are taken care of, we still need to be careful and
16046  * prevent erroneous and too eager declaration of "ininite loop", when
16047  * iterators are involved.
16048  *
16049  * Here's a situation in pseudo-BPF assembly form:
16050  *
16051  *   0: again:                          ; set up iter_next() call args
16052  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16053  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16054  *   3:   if r0 == 0 goto done
16055  *   4:   ... something useful here ...
16056  *   5:   goto again                    ; another iteration
16057  *   6: done:
16058  *   7:   r1 = &it
16059  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16060  *   9:   exit
16061  *
16062  * This is a typical loop. Let's assume that we have a prune point at 1:,
16063  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16064  * again`, assuming other heuristics don't get in a way).
16065  *
16066  * When we first time come to 1:, let's say we have some state X. We proceed
16067  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16068  * Now we come back to validate that forked ACTIVE state. We proceed through
16069  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16070  * are converging. But the problem is that we don't know that yet, as this
16071  * convergence has to happen at iter_next() call site only. So if nothing is
16072  * done, at 1: verifier will use bounded loop logic and declare infinite
16073  * looping (and would be *technically* correct, if not for iterator's
16074  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16075  * don't want that. So what we do in process_iter_next_call() when we go on
16076  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16077  * a different iteration. So when we suspect an infinite loop, we additionally
16078  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16079  * pretend we are not looping and wait for next iter_next() call.
16080  *
16081  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16082  * loop, because that would actually mean infinite loop, as DRAINED state is
16083  * "sticky", and so we'll keep returning into the same instruction with the
16084  * same state (at least in one of possible code paths).
16085  *
16086  * This approach allows to keep infinite loop heuristic even in the face of
16087  * active iterator. E.g., C snippet below is and will be detected as
16088  * inifintely looping:
16089  *
16090  *   struct bpf_iter_num it;
16091  *   int *p, x;
16092  *
16093  *   bpf_iter_num_new(&it, 0, 10);
16094  *   while ((p = bpf_iter_num_next(&t))) {
16095  *       x = p;
16096  *       while (x--) {} // <<-- infinite loop here
16097  *   }
16098  *
16099  */
16100 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16101 {
16102         struct bpf_reg_state *slot, *cur_slot;
16103         struct bpf_func_state *state;
16104         int i, fr;
16105
16106         for (fr = old->curframe; fr >= 0; fr--) {
16107                 state = old->frame[fr];
16108                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16109                         if (state->stack[i].slot_type[0] != STACK_ITER)
16110                                 continue;
16111
16112                         slot = &state->stack[i].spilled_ptr;
16113                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16114                                 continue;
16115
16116                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16117                         if (cur_slot->iter.depth != slot->iter.depth)
16118                                 return true;
16119                 }
16120         }
16121         return false;
16122 }
16123
16124 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16125 {
16126         struct bpf_verifier_state_list *new_sl;
16127         struct bpf_verifier_state_list *sl, **pprev;
16128         struct bpf_verifier_state *cur = env->cur_state, *new;
16129         int i, j, err, states_cnt = 0;
16130         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16131         bool add_new_state = force_new_state;
16132
16133         /* bpf progs typically have pruning point every 4 instructions
16134          * http://vger.kernel.org/bpfconf2019.html#session-1
16135          * Do not add new state for future pruning if the verifier hasn't seen
16136          * at least 2 jumps and at least 8 instructions.
16137          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16138          * In tests that amounts to up to 50% reduction into total verifier
16139          * memory consumption and 20% verifier time speedup.
16140          */
16141         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16142             env->insn_processed - env->prev_insn_processed >= 8)
16143                 add_new_state = true;
16144
16145         pprev = explored_state(env, insn_idx);
16146         sl = *pprev;
16147
16148         clean_live_states(env, insn_idx, cur);
16149
16150         while (sl) {
16151                 states_cnt++;
16152                 if (sl->state.insn_idx != insn_idx)
16153                         goto next;
16154
16155                 if (sl->state.branches) {
16156                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16157
16158                         if (frame->in_async_callback_fn &&
16159                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16160                                 /* Different async_entry_cnt means that the verifier is
16161                                  * processing another entry into async callback.
16162                                  * Seeing the same state is not an indication of infinite
16163                                  * loop or infinite recursion.
16164                                  * But finding the same state doesn't mean that it's safe
16165                                  * to stop processing the current state. The previous state
16166                                  * hasn't yet reached bpf_exit, since state.branches > 0.
16167                                  * Checking in_async_callback_fn alone is not enough either.
16168                                  * Since the verifier still needs to catch infinite loops
16169                                  * inside async callbacks.
16170                                  */
16171                                 goto skip_inf_loop_check;
16172                         }
16173                         /* BPF open-coded iterators loop detection is special.
16174                          * states_maybe_looping() logic is too simplistic in detecting
16175                          * states that *might* be equivalent, because it doesn't know
16176                          * about ID remapping, so don't even perform it.
16177                          * See process_iter_next_call() and iter_active_depths_differ()
16178                          * for overview of the logic. When current and one of parent
16179                          * states are detected as equivalent, it's a good thing: we prove
16180                          * convergence and can stop simulating further iterations.
16181                          * It's safe to assume that iterator loop will finish, taking into
16182                          * account iter_next() contract of eventually returning
16183                          * sticky NULL result.
16184                          */
16185                         if (is_iter_next_insn(env, insn_idx)) {
16186                                 if (states_equal(env, &sl->state, cur)) {
16187                                         struct bpf_func_state *cur_frame;
16188                                         struct bpf_reg_state *iter_state, *iter_reg;
16189                                         int spi;
16190
16191                                         cur_frame = cur->frame[cur->curframe];
16192                                         /* btf_check_iter_kfuncs() enforces that
16193                                          * iter state pointer is always the first arg
16194                                          */
16195                                         iter_reg = &cur_frame->regs[BPF_REG_1];
16196                                         /* current state is valid due to states_equal(),
16197                                          * so we can assume valid iter and reg state,
16198                                          * no need for extra (re-)validations
16199                                          */
16200                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16201                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16202                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16203                                                 goto hit;
16204                                 }
16205                                 goto skip_inf_loop_check;
16206                         }
16207                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
16208                         if (states_maybe_looping(&sl->state, cur) &&
16209                             states_equal(env, &sl->state, cur) &&
16210                             !iter_active_depths_differ(&sl->state, cur)) {
16211                                 verbose_linfo(env, insn_idx, "; ");
16212                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16213                                 return -EINVAL;
16214                         }
16215                         /* if the verifier is processing a loop, avoid adding new state
16216                          * too often, since different loop iterations have distinct
16217                          * states and may not help future pruning.
16218                          * This threshold shouldn't be too low to make sure that
16219                          * a loop with large bound will be rejected quickly.
16220                          * The most abusive loop will be:
16221                          * r1 += 1
16222                          * if r1 < 1000000 goto pc-2
16223                          * 1M insn_procssed limit / 100 == 10k peak states.
16224                          * This threshold shouldn't be too high either, since states
16225                          * at the end of the loop are likely to be useful in pruning.
16226                          */
16227 skip_inf_loop_check:
16228                         if (!force_new_state &&
16229                             env->jmps_processed - env->prev_jmps_processed < 20 &&
16230                             env->insn_processed - env->prev_insn_processed < 100)
16231                                 add_new_state = false;
16232                         goto miss;
16233                 }
16234                 if (states_equal(env, &sl->state, cur)) {
16235 hit:
16236                         sl->hit_cnt++;
16237                         /* reached equivalent register/stack state,
16238                          * prune the search.
16239                          * Registers read by the continuation are read by us.
16240                          * If we have any write marks in env->cur_state, they
16241                          * will prevent corresponding reads in the continuation
16242                          * from reaching our parent (an explored_state).  Our
16243                          * own state will get the read marks recorded, but
16244                          * they'll be immediately forgotten as we're pruning
16245                          * this state and will pop a new one.
16246                          */
16247                         err = propagate_liveness(env, &sl->state, cur);
16248
16249                         /* if previous state reached the exit with precision and
16250                          * current state is equivalent to it (except precsion marks)
16251                          * the precision needs to be propagated back in
16252                          * the current state.
16253                          */
16254                         err = err ? : push_jmp_history(env, cur);
16255                         err = err ? : propagate_precision(env, &sl->state);
16256                         if (err)
16257                                 return err;
16258                         return 1;
16259                 }
16260 miss:
16261                 /* when new state is not going to be added do not increase miss count.
16262                  * Otherwise several loop iterations will remove the state
16263                  * recorded earlier. The goal of these heuristics is to have
16264                  * states from some iterations of the loop (some in the beginning
16265                  * and some at the end) to help pruning.
16266                  */
16267                 if (add_new_state)
16268                         sl->miss_cnt++;
16269                 /* heuristic to determine whether this state is beneficial
16270                  * to keep checking from state equivalence point of view.
16271                  * Higher numbers increase max_states_per_insn and verification time,
16272                  * but do not meaningfully decrease insn_processed.
16273                  */
16274                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16275                         /* the state is unlikely to be useful. Remove it to
16276                          * speed up verification
16277                          */
16278                         *pprev = sl->next;
16279                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16280                                 u32 br = sl->state.branches;
16281
16282                                 WARN_ONCE(br,
16283                                           "BUG live_done but branches_to_explore %d\n",
16284                                           br);
16285                                 free_verifier_state(&sl->state, false);
16286                                 kfree(sl);
16287                                 env->peak_states--;
16288                         } else {
16289                                 /* cannot free this state, since parentage chain may
16290                                  * walk it later. Add it for free_list instead to
16291                                  * be freed at the end of verification
16292                                  */
16293                                 sl->next = env->free_list;
16294                                 env->free_list = sl;
16295                         }
16296                         sl = *pprev;
16297                         continue;
16298                 }
16299 next:
16300                 pprev = &sl->next;
16301                 sl = *pprev;
16302         }
16303
16304         if (env->max_states_per_insn < states_cnt)
16305                 env->max_states_per_insn = states_cnt;
16306
16307         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16308                 return 0;
16309
16310         if (!add_new_state)
16311                 return 0;
16312
16313         /* There were no equivalent states, remember the current one.
16314          * Technically the current state is not proven to be safe yet,
16315          * but it will either reach outer most bpf_exit (which means it's safe)
16316          * or it will be rejected. When there are no loops the verifier won't be
16317          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16318          * again on the way to bpf_exit.
16319          * When looping the sl->state.branches will be > 0 and this state
16320          * will not be considered for equivalence until branches == 0.
16321          */
16322         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16323         if (!new_sl)
16324                 return -ENOMEM;
16325         env->total_states++;
16326         env->peak_states++;
16327         env->prev_jmps_processed = env->jmps_processed;
16328         env->prev_insn_processed = env->insn_processed;
16329
16330         /* forget precise markings we inherited, see __mark_chain_precision */
16331         if (env->bpf_capable)
16332                 mark_all_scalars_imprecise(env, cur);
16333
16334         /* add new state to the head of linked list */
16335         new = &new_sl->state;
16336         err = copy_verifier_state(new, cur);
16337         if (err) {
16338                 free_verifier_state(new, false);
16339                 kfree(new_sl);
16340                 return err;
16341         }
16342         new->insn_idx = insn_idx;
16343         WARN_ONCE(new->branches != 1,
16344                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16345
16346         cur->parent = new;
16347         cur->first_insn_idx = insn_idx;
16348         clear_jmp_history(cur);
16349         new_sl->next = *explored_state(env, insn_idx);
16350         *explored_state(env, insn_idx) = new_sl;
16351         /* connect new state to parentage chain. Current frame needs all
16352          * registers connected. Only r6 - r9 of the callers are alive (pushed
16353          * to the stack implicitly by JITs) so in callers' frames connect just
16354          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16355          * the state of the call instruction (with WRITTEN set), and r0 comes
16356          * from callee with its full parentage chain, anyway.
16357          */
16358         /* clear write marks in current state: the writes we did are not writes
16359          * our child did, so they don't screen off its reads from us.
16360          * (There are no read marks in current state, because reads always mark
16361          * their parent and current state never has children yet.  Only
16362          * explored_states can get read marks.)
16363          */
16364         for (j = 0; j <= cur->curframe; j++) {
16365                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16366                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16367                 for (i = 0; i < BPF_REG_FP; i++)
16368                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16369         }
16370
16371         /* all stack frames are accessible from callee, clear them all */
16372         for (j = 0; j <= cur->curframe; j++) {
16373                 struct bpf_func_state *frame = cur->frame[j];
16374                 struct bpf_func_state *newframe = new->frame[j];
16375
16376                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16377                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16378                         frame->stack[i].spilled_ptr.parent =
16379                                                 &newframe->stack[i].spilled_ptr;
16380                 }
16381         }
16382         return 0;
16383 }
16384
16385 /* Return true if it's OK to have the same insn return a different type. */
16386 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16387 {
16388         switch (base_type(type)) {
16389         case PTR_TO_CTX:
16390         case PTR_TO_SOCKET:
16391         case PTR_TO_SOCK_COMMON:
16392         case PTR_TO_TCP_SOCK:
16393         case PTR_TO_XDP_SOCK:
16394         case PTR_TO_BTF_ID:
16395                 return false;
16396         default:
16397                 return true;
16398         }
16399 }
16400
16401 /* If an instruction was previously used with particular pointer types, then we
16402  * need to be careful to avoid cases such as the below, where it may be ok
16403  * for one branch accessing the pointer, but not ok for the other branch:
16404  *
16405  * R1 = sock_ptr
16406  * goto X;
16407  * ...
16408  * R1 = some_other_valid_ptr;
16409  * goto X;
16410  * ...
16411  * R2 = *(u32 *)(R1 + 0);
16412  */
16413 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16414 {
16415         return src != prev && (!reg_type_mismatch_ok(src) ||
16416                                !reg_type_mismatch_ok(prev));
16417 }
16418
16419 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16420                              bool allow_trust_missmatch)
16421 {
16422         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16423
16424         if (*prev_type == NOT_INIT) {
16425                 /* Saw a valid insn
16426                  * dst_reg = *(u32 *)(src_reg + off)
16427                  * save type to validate intersecting paths
16428                  */
16429                 *prev_type = type;
16430         } else if (reg_type_mismatch(type, *prev_type)) {
16431                 /* Abuser program is trying to use the same insn
16432                  * dst_reg = *(u32*) (src_reg + off)
16433                  * with different pointer types:
16434                  * src_reg == ctx in one branch and
16435                  * src_reg == stack|map in some other branch.
16436                  * Reject it.
16437                  */
16438                 if (allow_trust_missmatch &&
16439                     base_type(type) == PTR_TO_BTF_ID &&
16440                     base_type(*prev_type) == PTR_TO_BTF_ID) {
16441                         /*
16442                          * Have to support a use case when one path through
16443                          * the program yields TRUSTED pointer while another
16444                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
16445                          * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16446                          */
16447                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16448                 } else {
16449                         verbose(env, "same insn cannot be used with different pointers\n");
16450                         return -EINVAL;
16451                 }
16452         }
16453
16454         return 0;
16455 }
16456
16457 static int do_check(struct bpf_verifier_env *env)
16458 {
16459         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16460         struct bpf_verifier_state *state = env->cur_state;
16461         struct bpf_insn *insns = env->prog->insnsi;
16462         struct bpf_reg_state *regs;
16463         int insn_cnt = env->prog->len;
16464         bool do_print_state = false;
16465         int prev_insn_idx = -1;
16466
16467         for (;;) {
16468                 struct bpf_insn *insn;
16469                 u8 class;
16470                 int err;
16471
16472                 env->prev_insn_idx = prev_insn_idx;
16473                 if (env->insn_idx >= insn_cnt) {
16474                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
16475                                 env->insn_idx, insn_cnt);
16476                         return -EFAULT;
16477                 }
16478
16479                 insn = &insns[env->insn_idx];
16480                 class = BPF_CLASS(insn->code);
16481
16482                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16483                         verbose(env,
16484                                 "BPF program is too large. Processed %d insn\n",
16485                                 env->insn_processed);
16486                         return -E2BIG;
16487                 }
16488
16489                 state->last_insn_idx = env->prev_insn_idx;
16490
16491                 if (is_prune_point(env, env->insn_idx)) {
16492                         err = is_state_visited(env, env->insn_idx);
16493                         if (err < 0)
16494                                 return err;
16495                         if (err == 1) {
16496                                 /* found equivalent state, can prune the search */
16497                                 if (env->log.level & BPF_LOG_LEVEL) {
16498                                         if (do_print_state)
16499                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
16500                                                         env->prev_insn_idx, env->insn_idx,
16501                                                         env->cur_state->speculative ?
16502                                                         " (speculative execution)" : "");
16503                                         else
16504                                                 verbose(env, "%d: safe\n", env->insn_idx);
16505                                 }
16506                                 goto process_bpf_exit;
16507                         }
16508                 }
16509
16510                 if (is_jmp_point(env, env->insn_idx)) {
16511                         err = push_jmp_history(env, state);
16512                         if (err)
16513                                 return err;
16514                 }
16515
16516                 if (signal_pending(current))
16517                         return -EAGAIN;
16518
16519                 if (need_resched())
16520                         cond_resched();
16521
16522                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16523                         verbose(env, "\nfrom %d to %d%s:",
16524                                 env->prev_insn_idx, env->insn_idx,
16525                                 env->cur_state->speculative ?
16526                                 " (speculative execution)" : "");
16527                         print_verifier_state(env, state->frame[state->curframe], true);
16528                         do_print_state = false;
16529                 }
16530
16531                 if (env->log.level & BPF_LOG_LEVEL) {
16532                         const struct bpf_insn_cbs cbs = {
16533                                 .cb_call        = disasm_kfunc_name,
16534                                 .cb_print       = verbose,
16535                                 .private_data   = env,
16536                         };
16537
16538                         if (verifier_state_scratched(env))
16539                                 print_insn_state(env, state->frame[state->curframe]);
16540
16541                         verbose_linfo(env, env->insn_idx, "; ");
16542                         env->prev_log_pos = env->log.end_pos;
16543                         verbose(env, "%d: ", env->insn_idx);
16544                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16545                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16546                         env->prev_log_pos = env->log.end_pos;
16547                 }
16548
16549                 if (bpf_prog_is_offloaded(env->prog->aux)) {
16550                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16551                                                            env->prev_insn_idx);
16552                         if (err)
16553                                 return err;
16554                 }
16555
16556                 regs = cur_regs(env);
16557                 sanitize_mark_insn_seen(env);
16558                 prev_insn_idx = env->insn_idx;
16559
16560                 if (class == BPF_ALU || class == BPF_ALU64) {
16561                         err = check_alu_op(env, insn);
16562                         if (err)
16563                                 return err;
16564
16565                 } else if (class == BPF_LDX) {
16566                         enum bpf_reg_type src_reg_type;
16567
16568                         /* check for reserved fields is already done */
16569
16570                         /* check src operand */
16571                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16572                         if (err)
16573                                 return err;
16574
16575                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16576                         if (err)
16577                                 return err;
16578
16579                         src_reg_type = regs[insn->src_reg].type;
16580
16581                         /* check that memory (src_reg + off) is readable,
16582                          * the state of dst_reg will be updated by this func
16583                          */
16584                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
16585                                                insn->off, BPF_SIZE(insn->code),
16586                                                BPF_READ, insn->dst_reg, false,
16587                                                BPF_MODE(insn->code) == BPF_MEMSX);
16588                         if (err)
16589                                 return err;
16590
16591                         err = save_aux_ptr_type(env, src_reg_type, true);
16592                         if (err)
16593                                 return err;
16594                 } else if (class == BPF_STX) {
16595                         enum bpf_reg_type dst_reg_type;
16596
16597                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16598                                 err = check_atomic(env, env->insn_idx, insn);
16599                                 if (err)
16600                                         return err;
16601                                 env->insn_idx++;
16602                                 continue;
16603                         }
16604
16605                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16606                                 verbose(env, "BPF_STX uses reserved fields\n");
16607                                 return -EINVAL;
16608                         }
16609
16610                         /* check src1 operand */
16611                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16612                         if (err)
16613                                 return err;
16614                         /* check src2 operand */
16615                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16616                         if (err)
16617                                 return err;
16618
16619                         dst_reg_type = regs[insn->dst_reg].type;
16620
16621                         /* check that memory (dst_reg + off) is writeable */
16622                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16623                                                insn->off, BPF_SIZE(insn->code),
16624                                                BPF_WRITE, insn->src_reg, false, false);
16625                         if (err)
16626                                 return err;
16627
16628                         err = save_aux_ptr_type(env, dst_reg_type, false);
16629                         if (err)
16630                                 return err;
16631                 } else if (class == BPF_ST) {
16632                         enum bpf_reg_type dst_reg_type;
16633
16634                         if (BPF_MODE(insn->code) != BPF_MEM ||
16635                             insn->src_reg != BPF_REG_0) {
16636                                 verbose(env, "BPF_ST uses reserved fields\n");
16637                                 return -EINVAL;
16638                         }
16639                         /* check src operand */
16640                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16641                         if (err)
16642                                 return err;
16643
16644                         dst_reg_type = regs[insn->dst_reg].type;
16645
16646                         /* check that memory (dst_reg + off) is writeable */
16647                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16648                                                insn->off, BPF_SIZE(insn->code),
16649                                                BPF_WRITE, -1, false, false);
16650                         if (err)
16651                                 return err;
16652
16653                         err = save_aux_ptr_type(env, dst_reg_type, false);
16654                         if (err)
16655                                 return err;
16656                 } else if (class == BPF_JMP || class == BPF_JMP32) {
16657                         u8 opcode = BPF_OP(insn->code);
16658
16659                         env->jmps_processed++;
16660                         if (opcode == BPF_CALL) {
16661                                 if (BPF_SRC(insn->code) != BPF_K ||
16662                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16663                                      && insn->off != 0) ||
16664                                     (insn->src_reg != BPF_REG_0 &&
16665                                      insn->src_reg != BPF_PSEUDO_CALL &&
16666                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16667                                     insn->dst_reg != BPF_REG_0 ||
16668                                     class == BPF_JMP32) {
16669                                         verbose(env, "BPF_CALL uses reserved fields\n");
16670                                         return -EINVAL;
16671                                 }
16672
16673                                 if (env->cur_state->active_lock.ptr) {
16674                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16675                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
16676                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16677                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16678                                                 verbose(env, "function calls are not allowed while holding a lock\n");
16679                                                 return -EINVAL;
16680                                         }
16681                                 }
16682                                 if (insn->src_reg == BPF_PSEUDO_CALL)
16683                                         err = check_func_call(env, insn, &env->insn_idx);
16684                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16685                                         err = check_kfunc_call(env, insn, &env->insn_idx);
16686                                 else
16687                                         err = check_helper_call(env, insn, &env->insn_idx);
16688                                 if (err)
16689                                         return err;
16690
16691                                 mark_reg_scratched(env, BPF_REG_0);
16692                         } else if (opcode == BPF_JA) {
16693                                 if (BPF_SRC(insn->code) != BPF_K ||
16694                                     insn->src_reg != BPF_REG_0 ||
16695                                     insn->dst_reg != BPF_REG_0 ||
16696                                     (class == BPF_JMP && insn->imm != 0) ||
16697                                     (class == BPF_JMP32 && insn->off != 0)) {
16698                                         verbose(env, "BPF_JA uses reserved fields\n");
16699                                         return -EINVAL;
16700                                 }
16701
16702                                 if (class == BPF_JMP)
16703                                         env->insn_idx += insn->off + 1;
16704                                 else
16705                                         env->insn_idx += insn->imm + 1;
16706                                 continue;
16707
16708                         } else if (opcode == BPF_EXIT) {
16709                                 if (BPF_SRC(insn->code) != BPF_K ||
16710                                     insn->imm != 0 ||
16711                                     insn->src_reg != BPF_REG_0 ||
16712                                     insn->dst_reg != BPF_REG_0 ||
16713                                     class == BPF_JMP32) {
16714                                         verbose(env, "BPF_EXIT uses reserved fields\n");
16715                                         return -EINVAL;
16716                                 }
16717
16718                                 if (env->cur_state->active_lock.ptr &&
16719                                     !in_rbtree_lock_required_cb(env)) {
16720                                         verbose(env, "bpf_spin_unlock is missing\n");
16721                                         return -EINVAL;
16722                                 }
16723
16724                                 if (env->cur_state->active_rcu_lock &&
16725                                     !in_rbtree_lock_required_cb(env)) {
16726                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
16727                                         return -EINVAL;
16728                                 }
16729
16730                                 /* We must do check_reference_leak here before
16731                                  * prepare_func_exit to handle the case when
16732                                  * state->curframe > 0, it may be a callback
16733                                  * function, for which reference_state must
16734                                  * match caller reference state when it exits.
16735                                  */
16736                                 err = check_reference_leak(env);
16737                                 if (err)
16738                                         return err;
16739
16740                                 if (state->curframe) {
16741                                         /* exit from nested function */
16742                                         err = prepare_func_exit(env, &env->insn_idx);
16743                                         if (err)
16744                                                 return err;
16745                                         do_print_state = true;
16746                                         continue;
16747                                 }
16748
16749                                 err = check_return_code(env);
16750                                 if (err)
16751                                         return err;
16752 process_bpf_exit:
16753                                 mark_verifier_state_scratched(env);
16754                                 update_branch_counts(env, env->cur_state);
16755                                 err = pop_stack(env, &prev_insn_idx,
16756                                                 &env->insn_idx, pop_log);
16757                                 if (err < 0) {
16758                                         if (err != -ENOENT)
16759                                                 return err;
16760                                         break;
16761                                 } else {
16762                                         do_print_state = true;
16763                                         continue;
16764                                 }
16765                         } else {
16766                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16767                                 if (err)
16768                                         return err;
16769                         }
16770                 } else if (class == BPF_LD) {
16771                         u8 mode = BPF_MODE(insn->code);
16772
16773                         if (mode == BPF_ABS || mode == BPF_IND) {
16774                                 err = check_ld_abs(env, insn);
16775                                 if (err)
16776                                         return err;
16777
16778                         } else if (mode == BPF_IMM) {
16779                                 err = check_ld_imm(env, insn);
16780                                 if (err)
16781                                         return err;
16782
16783                                 env->insn_idx++;
16784                                 sanitize_mark_insn_seen(env);
16785                         } else {
16786                                 verbose(env, "invalid BPF_LD mode\n");
16787                                 return -EINVAL;
16788                         }
16789                 } else {
16790                         verbose(env, "unknown insn class %d\n", class);
16791                         return -EINVAL;
16792                 }
16793
16794                 env->insn_idx++;
16795         }
16796
16797         return 0;
16798 }
16799
16800 static int find_btf_percpu_datasec(struct btf *btf)
16801 {
16802         const struct btf_type *t;
16803         const char *tname;
16804         int i, n;
16805
16806         /*
16807          * Both vmlinux and module each have their own ".data..percpu"
16808          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16809          * types to look at only module's own BTF types.
16810          */
16811         n = btf_nr_types(btf);
16812         if (btf_is_module(btf))
16813                 i = btf_nr_types(btf_vmlinux);
16814         else
16815                 i = 1;
16816
16817         for(; i < n; i++) {
16818                 t = btf_type_by_id(btf, i);
16819                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16820                         continue;
16821
16822                 tname = btf_name_by_offset(btf, t->name_off);
16823                 if (!strcmp(tname, ".data..percpu"))
16824                         return i;
16825         }
16826
16827         return -ENOENT;
16828 }
16829
16830 /* replace pseudo btf_id with kernel symbol address */
16831 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16832                                struct bpf_insn *insn,
16833                                struct bpf_insn_aux_data *aux)
16834 {
16835         const struct btf_var_secinfo *vsi;
16836         const struct btf_type *datasec;
16837         struct btf_mod_pair *btf_mod;
16838         const struct btf_type *t;
16839         const char *sym_name;
16840         bool percpu = false;
16841         u32 type, id = insn->imm;
16842         struct btf *btf;
16843         s32 datasec_id;
16844         u64 addr;
16845         int i, btf_fd, err;
16846
16847         btf_fd = insn[1].imm;
16848         if (btf_fd) {
16849                 btf = btf_get_by_fd(btf_fd);
16850                 if (IS_ERR(btf)) {
16851                         verbose(env, "invalid module BTF object FD specified.\n");
16852                         return -EINVAL;
16853                 }
16854         } else {
16855                 if (!btf_vmlinux) {
16856                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16857                         return -EINVAL;
16858                 }
16859                 btf = btf_vmlinux;
16860                 btf_get(btf);
16861         }
16862
16863         t = btf_type_by_id(btf, id);
16864         if (!t) {
16865                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16866                 err = -ENOENT;
16867                 goto err_put;
16868         }
16869
16870         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16871                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16872                 err = -EINVAL;
16873                 goto err_put;
16874         }
16875
16876         sym_name = btf_name_by_offset(btf, t->name_off);
16877         addr = kallsyms_lookup_name(sym_name);
16878         if (!addr) {
16879                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16880                         sym_name);
16881                 err = -ENOENT;
16882                 goto err_put;
16883         }
16884         insn[0].imm = (u32)addr;
16885         insn[1].imm = addr >> 32;
16886
16887         if (btf_type_is_func(t)) {
16888                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16889                 aux->btf_var.mem_size = 0;
16890                 goto check_btf;
16891         }
16892
16893         datasec_id = find_btf_percpu_datasec(btf);
16894         if (datasec_id > 0) {
16895                 datasec = btf_type_by_id(btf, datasec_id);
16896                 for_each_vsi(i, datasec, vsi) {
16897                         if (vsi->type == id) {
16898                                 percpu = true;
16899                                 break;
16900                         }
16901                 }
16902         }
16903
16904         type = t->type;
16905         t = btf_type_skip_modifiers(btf, type, NULL);
16906         if (percpu) {
16907                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16908                 aux->btf_var.btf = btf;
16909                 aux->btf_var.btf_id = type;
16910         } else if (!btf_type_is_struct(t)) {
16911                 const struct btf_type *ret;
16912                 const char *tname;
16913                 u32 tsize;
16914
16915                 /* resolve the type size of ksym. */
16916                 ret = btf_resolve_size(btf, t, &tsize);
16917                 if (IS_ERR(ret)) {
16918                         tname = btf_name_by_offset(btf, t->name_off);
16919                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16920                                 tname, PTR_ERR(ret));
16921                         err = -EINVAL;
16922                         goto err_put;
16923                 }
16924                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16925                 aux->btf_var.mem_size = tsize;
16926         } else {
16927                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16928                 aux->btf_var.btf = btf;
16929                 aux->btf_var.btf_id = type;
16930         }
16931 check_btf:
16932         /* check whether we recorded this BTF (and maybe module) already */
16933         for (i = 0; i < env->used_btf_cnt; i++) {
16934                 if (env->used_btfs[i].btf == btf) {
16935                         btf_put(btf);
16936                         return 0;
16937                 }
16938         }
16939
16940         if (env->used_btf_cnt >= MAX_USED_BTFS) {
16941                 err = -E2BIG;
16942                 goto err_put;
16943         }
16944
16945         btf_mod = &env->used_btfs[env->used_btf_cnt];
16946         btf_mod->btf = btf;
16947         btf_mod->module = NULL;
16948
16949         /* if we reference variables from kernel module, bump its refcount */
16950         if (btf_is_module(btf)) {
16951                 btf_mod->module = btf_try_get_module(btf);
16952                 if (!btf_mod->module) {
16953                         err = -ENXIO;
16954                         goto err_put;
16955                 }
16956         }
16957
16958         env->used_btf_cnt++;
16959
16960         return 0;
16961 err_put:
16962         btf_put(btf);
16963         return err;
16964 }
16965
16966 static bool is_tracing_prog_type(enum bpf_prog_type type)
16967 {
16968         switch (type) {
16969         case BPF_PROG_TYPE_KPROBE:
16970         case BPF_PROG_TYPE_TRACEPOINT:
16971         case BPF_PROG_TYPE_PERF_EVENT:
16972         case BPF_PROG_TYPE_RAW_TRACEPOINT:
16973         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16974                 return true;
16975         default:
16976                 return false;
16977         }
16978 }
16979
16980 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16981                                         struct bpf_map *map,
16982                                         struct bpf_prog *prog)
16983
16984 {
16985         enum bpf_prog_type prog_type = resolve_prog_type(prog);
16986
16987         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16988             btf_record_has_field(map->record, BPF_RB_ROOT)) {
16989                 if (is_tracing_prog_type(prog_type)) {
16990                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16991                         return -EINVAL;
16992                 }
16993         }
16994
16995         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16996                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16997                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16998                         return -EINVAL;
16999                 }
17000
17001                 if (is_tracing_prog_type(prog_type)) {
17002                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17003                         return -EINVAL;
17004                 }
17005         }
17006
17007         if (btf_record_has_field(map->record, BPF_TIMER)) {
17008                 if (is_tracing_prog_type(prog_type)) {
17009                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
17010                         return -EINVAL;
17011                 }
17012         }
17013
17014         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17015             !bpf_offload_prog_map_match(prog, map)) {
17016                 verbose(env, "offload device mismatch between prog and map\n");
17017                 return -EINVAL;
17018         }
17019
17020         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17021                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17022                 return -EINVAL;
17023         }
17024
17025         if (prog->aux->sleepable)
17026                 switch (map->map_type) {
17027                 case BPF_MAP_TYPE_HASH:
17028                 case BPF_MAP_TYPE_LRU_HASH:
17029                 case BPF_MAP_TYPE_ARRAY:
17030                 case BPF_MAP_TYPE_PERCPU_HASH:
17031                 case BPF_MAP_TYPE_PERCPU_ARRAY:
17032                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17033                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17034                 case BPF_MAP_TYPE_HASH_OF_MAPS:
17035                 case BPF_MAP_TYPE_RINGBUF:
17036                 case BPF_MAP_TYPE_USER_RINGBUF:
17037                 case BPF_MAP_TYPE_INODE_STORAGE:
17038                 case BPF_MAP_TYPE_SK_STORAGE:
17039                 case BPF_MAP_TYPE_TASK_STORAGE:
17040                 case BPF_MAP_TYPE_CGRP_STORAGE:
17041                         break;
17042                 default:
17043                         verbose(env,
17044                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17045                         return -EINVAL;
17046                 }
17047
17048         return 0;
17049 }
17050
17051 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17052 {
17053         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17054                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17055 }
17056
17057 /* find and rewrite pseudo imm in ld_imm64 instructions:
17058  *
17059  * 1. if it accesses map FD, replace it with actual map pointer.
17060  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17061  *
17062  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17063  */
17064 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17065 {
17066         struct bpf_insn *insn = env->prog->insnsi;
17067         int insn_cnt = env->prog->len;
17068         int i, j, err;
17069
17070         err = bpf_prog_calc_tag(env->prog);
17071         if (err)
17072                 return err;
17073
17074         for (i = 0; i < insn_cnt; i++, insn++) {
17075                 if (BPF_CLASS(insn->code) == BPF_LDX &&
17076                     ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17077                     insn->imm != 0)) {
17078                         verbose(env, "BPF_LDX uses reserved fields\n");
17079                         return -EINVAL;
17080                 }
17081
17082                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17083                         struct bpf_insn_aux_data *aux;
17084                         struct bpf_map *map;
17085                         struct fd f;
17086                         u64 addr;
17087                         u32 fd;
17088
17089                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
17090                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17091                             insn[1].off != 0) {
17092                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
17093                                 return -EINVAL;
17094                         }
17095
17096                         if (insn[0].src_reg == 0)
17097                                 /* valid generic load 64-bit imm */
17098                                 goto next_insn;
17099
17100                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17101                                 aux = &env->insn_aux_data[i];
17102                                 err = check_pseudo_btf_id(env, insn, aux);
17103                                 if (err)
17104                                         return err;
17105                                 goto next_insn;
17106                         }
17107
17108                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17109                                 aux = &env->insn_aux_data[i];
17110                                 aux->ptr_type = PTR_TO_FUNC;
17111                                 goto next_insn;
17112                         }
17113
17114                         /* In final convert_pseudo_ld_imm64() step, this is
17115                          * converted into regular 64-bit imm load insn.
17116                          */
17117                         switch (insn[0].src_reg) {
17118                         case BPF_PSEUDO_MAP_VALUE:
17119                         case BPF_PSEUDO_MAP_IDX_VALUE:
17120                                 break;
17121                         case BPF_PSEUDO_MAP_FD:
17122                         case BPF_PSEUDO_MAP_IDX:
17123                                 if (insn[1].imm == 0)
17124                                         break;
17125                                 fallthrough;
17126                         default:
17127                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17128                                 return -EINVAL;
17129                         }
17130
17131                         switch (insn[0].src_reg) {
17132                         case BPF_PSEUDO_MAP_IDX_VALUE:
17133                         case BPF_PSEUDO_MAP_IDX:
17134                                 if (bpfptr_is_null(env->fd_array)) {
17135                                         verbose(env, "fd_idx without fd_array is invalid\n");
17136                                         return -EPROTO;
17137                                 }
17138                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17139                                                             insn[0].imm * sizeof(fd),
17140                                                             sizeof(fd)))
17141                                         return -EFAULT;
17142                                 break;
17143                         default:
17144                                 fd = insn[0].imm;
17145                                 break;
17146                         }
17147
17148                         f = fdget(fd);
17149                         map = __bpf_map_get(f);
17150                         if (IS_ERR(map)) {
17151                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17152                                         insn[0].imm);
17153                                 return PTR_ERR(map);
17154                         }
17155
17156                         err = check_map_prog_compatibility(env, map, env->prog);
17157                         if (err) {
17158                                 fdput(f);
17159                                 return err;
17160                         }
17161
17162                         aux = &env->insn_aux_data[i];
17163                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17164                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17165                                 addr = (unsigned long)map;
17166                         } else {
17167                                 u32 off = insn[1].imm;
17168
17169                                 if (off >= BPF_MAX_VAR_OFF) {
17170                                         verbose(env, "direct value offset of %u is not allowed\n", off);
17171                                         fdput(f);
17172                                         return -EINVAL;
17173                                 }
17174
17175                                 if (!map->ops->map_direct_value_addr) {
17176                                         verbose(env, "no direct value access support for this map type\n");
17177                                         fdput(f);
17178                                         return -EINVAL;
17179                                 }
17180
17181                                 err = map->ops->map_direct_value_addr(map, &addr, off);
17182                                 if (err) {
17183                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17184                                                 map->value_size, off);
17185                                         fdput(f);
17186                                         return err;
17187                                 }
17188
17189                                 aux->map_off = off;
17190                                 addr += off;
17191                         }
17192
17193                         insn[0].imm = (u32)addr;
17194                         insn[1].imm = addr >> 32;
17195
17196                         /* check whether we recorded this map already */
17197                         for (j = 0; j < env->used_map_cnt; j++) {
17198                                 if (env->used_maps[j] == map) {
17199                                         aux->map_index = j;
17200                                         fdput(f);
17201                                         goto next_insn;
17202                                 }
17203                         }
17204
17205                         if (env->used_map_cnt >= MAX_USED_MAPS) {
17206                                 fdput(f);
17207                                 return -E2BIG;
17208                         }
17209
17210                         /* hold the map. If the program is rejected by verifier,
17211                          * the map will be released by release_maps() or it
17212                          * will be used by the valid program until it's unloaded
17213                          * and all maps are released in free_used_maps()
17214                          */
17215                         bpf_map_inc(map);
17216
17217                         aux->map_index = env->used_map_cnt;
17218                         env->used_maps[env->used_map_cnt++] = map;
17219
17220                         if (bpf_map_is_cgroup_storage(map) &&
17221                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
17222                                 verbose(env, "only one cgroup storage of each type is allowed\n");
17223                                 fdput(f);
17224                                 return -EBUSY;
17225                         }
17226
17227                         fdput(f);
17228 next_insn:
17229                         insn++;
17230                         i++;
17231                         continue;
17232                 }
17233
17234                 /* Basic sanity check before we invest more work here. */
17235                 if (!bpf_opcode_in_insntable(insn->code)) {
17236                         verbose(env, "unknown opcode %02x\n", insn->code);
17237                         return -EINVAL;
17238                 }
17239         }
17240
17241         /* now all pseudo BPF_LD_IMM64 instructions load valid
17242          * 'struct bpf_map *' into a register instead of user map_fd.
17243          * These pointers will be used later by verifier to validate map access.
17244          */
17245         return 0;
17246 }
17247
17248 /* drop refcnt of maps used by the rejected program */
17249 static void release_maps(struct bpf_verifier_env *env)
17250 {
17251         __bpf_free_used_maps(env->prog->aux, env->used_maps,
17252                              env->used_map_cnt);
17253 }
17254
17255 /* drop refcnt of maps used by the rejected program */
17256 static void release_btfs(struct bpf_verifier_env *env)
17257 {
17258         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17259                              env->used_btf_cnt);
17260 }
17261
17262 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17263 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17264 {
17265         struct bpf_insn *insn = env->prog->insnsi;
17266         int insn_cnt = env->prog->len;
17267         int i;
17268
17269         for (i = 0; i < insn_cnt; i++, insn++) {
17270                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17271                         continue;
17272                 if (insn->src_reg == BPF_PSEUDO_FUNC)
17273                         continue;
17274                 insn->src_reg = 0;
17275         }
17276 }
17277
17278 /* single env->prog->insni[off] instruction was replaced with the range
17279  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17280  * [0, off) and [off, end) to new locations, so the patched range stays zero
17281  */
17282 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17283                                  struct bpf_insn_aux_data *new_data,
17284                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
17285 {
17286         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17287         struct bpf_insn *insn = new_prog->insnsi;
17288         u32 old_seen = old_data[off].seen;
17289         u32 prog_len;
17290         int i;
17291
17292         /* aux info at OFF always needs adjustment, no matter fast path
17293          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17294          * original insn at old prog.
17295          */
17296         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17297
17298         if (cnt == 1)
17299                 return;
17300         prog_len = new_prog->len;
17301
17302         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17303         memcpy(new_data + off + cnt - 1, old_data + off,
17304                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17305         for (i = off; i < off + cnt - 1; i++) {
17306                 /* Expand insni[off]'s seen count to the patched range. */
17307                 new_data[i].seen = old_seen;
17308                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17309         }
17310         env->insn_aux_data = new_data;
17311         vfree(old_data);
17312 }
17313
17314 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17315 {
17316         int i;
17317
17318         if (len == 1)
17319                 return;
17320         /* NOTE: fake 'exit' subprog should be updated as well. */
17321         for (i = 0; i <= env->subprog_cnt; i++) {
17322                 if (env->subprog_info[i].start <= off)
17323                         continue;
17324                 env->subprog_info[i].start += len - 1;
17325         }
17326 }
17327
17328 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17329 {
17330         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17331         int i, sz = prog->aux->size_poke_tab;
17332         struct bpf_jit_poke_descriptor *desc;
17333
17334         for (i = 0; i < sz; i++) {
17335                 desc = &tab[i];
17336                 if (desc->insn_idx <= off)
17337                         continue;
17338                 desc->insn_idx += len - 1;
17339         }
17340 }
17341
17342 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17343                                             const struct bpf_insn *patch, u32 len)
17344 {
17345         struct bpf_prog *new_prog;
17346         struct bpf_insn_aux_data *new_data = NULL;
17347
17348         if (len > 1) {
17349                 new_data = vzalloc(array_size(env->prog->len + len - 1,
17350                                               sizeof(struct bpf_insn_aux_data)));
17351                 if (!new_data)
17352                         return NULL;
17353         }
17354
17355         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17356         if (IS_ERR(new_prog)) {
17357                 if (PTR_ERR(new_prog) == -ERANGE)
17358                         verbose(env,
17359                                 "insn %d cannot be patched due to 16-bit range\n",
17360                                 env->insn_aux_data[off].orig_idx);
17361                 vfree(new_data);
17362                 return NULL;
17363         }
17364         adjust_insn_aux_data(env, new_data, new_prog, off, len);
17365         adjust_subprog_starts(env, off, len);
17366         adjust_poke_descs(new_prog, off, len);
17367         return new_prog;
17368 }
17369
17370 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17371                                               u32 off, u32 cnt)
17372 {
17373         int i, j;
17374
17375         /* find first prog starting at or after off (first to remove) */
17376         for (i = 0; i < env->subprog_cnt; i++)
17377                 if (env->subprog_info[i].start >= off)
17378                         break;
17379         /* find first prog starting at or after off + cnt (first to stay) */
17380         for (j = i; j < env->subprog_cnt; j++)
17381                 if (env->subprog_info[j].start >= off + cnt)
17382                         break;
17383         /* if j doesn't start exactly at off + cnt, we are just removing
17384          * the front of previous prog
17385          */
17386         if (env->subprog_info[j].start != off + cnt)
17387                 j--;
17388
17389         if (j > i) {
17390                 struct bpf_prog_aux *aux = env->prog->aux;
17391                 int move;
17392
17393                 /* move fake 'exit' subprog as well */
17394                 move = env->subprog_cnt + 1 - j;
17395
17396                 memmove(env->subprog_info + i,
17397                         env->subprog_info + j,
17398                         sizeof(*env->subprog_info) * move);
17399                 env->subprog_cnt -= j - i;
17400
17401                 /* remove func_info */
17402                 if (aux->func_info) {
17403                         move = aux->func_info_cnt - j;
17404
17405                         memmove(aux->func_info + i,
17406                                 aux->func_info + j,
17407                                 sizeof(*aux->func_info) * move);
17408                         aux->func_info_cnt -= j - i;
17409                         /* func_info->insn_off is set after all code rewrites,
17410                          * in adjust_btf_func() - no need to adjust
17411                          */
17412                 }
17413         } else {
17414                 /* convert i from "first prog to remove" to "first to adjust" */
17415                 if (env->subprog_info[i].start == off)
17416                         i++;
17417         }
17418
17419         /* update fake 'exit' subprog as well */
17420         for (; i <= env->subprog_cnt; i++)
17421                 env->subprog_info[i].start -= cnt;
17422
17423         return 0;
17424 }
17425
17426 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17427                                       u32 cnt)
17428 {
17429         struct bpf_prog *prog = env->prog;
17430         u32 i, l_off, l_cnt, nr_linfo;
17431         struct bpf_line_info *linfo;
17432
17433         nr_linfo = prog->aux->nr_linfo;
17434         if (!nr_linfo)
17435                 return 0;
17436
17437         linfo = prog->aux->linfo;
17438
17439         /* find first line info to remove, count lines to be removed */
17440         for (i = 0; i < nr_linfo; i++)
17441                 if (linfo[i].insn_off >= off)
17442                         break;
17443
17444         l_off = i;
17445         l_cnt = 0;
17446         for (; i < nr_linfo; i++)
17447                 if (linfo[i].insn_off < off + cnt)
17448                         l_cnt++;
17449                 else
17450                         break;
17451
17452         /* First live insn doesn't match first live linfo, it needs to "inherit"
17453          * last removed linfo.  prog is already modified, so prog->len == off
17454          * means no live instructions after (tail of the program was removed).
17455          */
17456         if (prog->len != off && l_cnt &&
17457             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17458                 l_cnt--;
17459                 linfo[--i].insn_off = off + cnt;
17460         }
17461
17462         /* remove the line info which refer to the removed instructions */
17463         if (l_cnt) {
17464                 memmove(linfo + l_off, linfo + i,
17465                         sizeof(*linfo) * (nr_linfo - i));
17466
17467                 prog->aux->nr_linfo -= l_cnt;
17468                 nr_linfo = prog->aux->nr_linfo;
17469         }
17470
17471         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17472         for (i = l_off; i < nr_linfo; i++)
17473                 linfo[i].insn_off -= cnt;
17474
17475         /* fix up all subprogs (incl. 'exit') which start >= off */
17476         for (i = 0; i <= env->subprog_cnt; i++)
17477                 if (env->subprog_info[i].linfo_idx > l_off) {
17478                         /* program may have started in the removed region but
17479                          * may not be fully removed
17480                          */
17481                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17482                                 env->subprog_info[i].linfo_idx -= l_cnt;
17483                         else
17484                                 env->subprog_info[i].linfo_idx = l_off;
17485                 }
17486
17487         return 0;
17488 }
17489
17490 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17491 {
17492         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17493         unsigned int orig_prog_len = env->prog->len;
17494         int err;
17495
17496         if (bpf_prog_is_offloaded(env->prog->aux))
17497                 bpf_prog_offload_remove_insns(env, off, cnt);
17498
17499         err = bpf_remove_insns(env->prog, off, cnt);
17500         if (err)
17501                 return err;
17502
17503         err = adjust_subprog_starts_after_remove(env, off, cnt);
17504         if (err)
17505                 return err;
17506
17507         err = bpf_adj_linfo_after_remove(env, off, cnt);
17508         if (err)
17509                 return err;
17510
17511         memmove(aux_data + off, aux_data + off + cnt,
17512                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17513
17514         return 0;
17515 }
17516
17517 /* The verifier does more data flow analysis than llvm and will not
17518  * explore branches that are dead at run time. Malicious programs can
17519  * have dead code too. Therefore replace all dead at-run-time code
17520  * with 'ja -1'.
17521  *
17522  * Just nops are not optimal, e.g. if they would sit at the end of the
17523  * program and through another bug we would manage to jump there, then
17524  * we'd execute beyond program memory otherwise. Returning exception
17525  * code also wouldn't work since we can have subprogs where the dead
17526  * code could be located.
17527  */
17528 static void sanitize_dead_code(struct bpf_verifier_env *env)
17529 {
17530         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17531         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17532         struct bpf_insn *insn = env->prog->insnsi;
17533         const int insn_cnt = env->prog->len;
17534         int i;
17535
17536         for (i = 0; i < insn_cnt; i++) {
17537                 if (aux_data[i].seen)
17538                         continue;
17539                 memcpy(insn + i, &trap, sizeof(trap));
17540                 aux_data[i].zext_dst = false;
17541         }
17542 }
17543
17544 static bool insn_is_cond_jump(u8 code)
17545 {
17546         u8 op;
17547
17548         op = BPF_OP(code);
17549         if (BPF_CLASS(code) == BPF_JMP32)
17550                 return op != BPF_JA;
17551
17552         if (BPF_CLASS(code) != BPF_JMP)
17553                 return false;
17554
17555         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17556 }
17557
17558 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17559 {
17560         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17561         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17562         struct bpf_insn *insn = env->prog->insnsi;
17563         const int insn_cnt = env->prog->len;
17564         int i;
17565
17566         for (i = 0; i < insn_cnt; i++, insn++) {
17567                 if (!insn_is_cond_jump(insn->code))
17568                         continue;
17569
17570                 if (!aux_data[i + 1].seen)
17571                         ja.off = insn->off;
17572                 else if (!aux_data[i + 1 + insn->off].seen)
17573                         ja.off = 0;
17574                 else
17575                         continue;
17576
17577                 if (bpf_prog_is_offloaded(env->prog->aux))
17578                         bpf_prog_offload_replace_insn(env, i, &ja);
17579
17580                 memcpy(insn, &ja, sizeof(ja));
17581         }
17582 }
17583
17584 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17585 {
17586         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17587         int insn_cnt = env->prog->len;
17588         int i, err;
17589
17590         for (i = 0; i < insn_cnt; i++) {
17591                 int j;
17592
17593                 j = 0;
17594                 while (i + j < insn_cnt && !aux_data[i + j].seen)
17595                         j++;
17596                 if (!j)
17597                         continue;
17598
17599                 err = verifier_remove_insns(env, i, j);
17600                 if (err)
17601                         return err;
17602                 insn_cnt = env->prog->len;
17603         }
17604
17605         return 0;
17606 }
17607
17608 static int opt_remove_nops(struct bpf_verifier_env *env)
17609 {
17610         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17611         struct bpf_insn *insn = env->prog->insnsi;
17612         int insn_cnt = env->prog->len;
17613         int i, err;
17614
17615         for (i = 0; i < insn_cnt; i++) {
17616                 if (memcmp(&insn[i], &ja, sizeof(ja)))
17617                         continue;
17618
17619                 err = verifier_remove_insns(env, i, 1);
17620                 if (err)
17621                         return err;
17622                 insn_cnt--;
17623                 i--;
17624         }
17625
17626         return 0;
17627 }
17628
17629 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17630                                          const union bpf_attr *attr)
17631 {
17632         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17633         struct bpf_insn_aux_data *aux = env->insn_aux_data;
17634         int i, patch_len, delta = 0, len = env->prog->len;
17635         struct bpf_insn *insns = env->prog->insnsi;
17636         struct bpf_prog *new_prog;
17637         bool rnd_hi32;
17638
17639         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17640         zext_patch[1] = BPF_ZEXT_REG(0);
17641         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17642         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17643         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17644         for (i = 0; i < len; i++) {
17645                 int adj_idx = i + delta;
17646                 struct bpf_insn insn;
17647                 int load_reg;
17648
17649                 insn = insns[adj_idx];
17650                 load_reg = insn_def_regno(&insn);
17651                 if (!aux[adj_idx].zext_dst) {
17652                         u8 code, class;
17653                         u32 imm_rnd;
17654
17655                         if (!rnd_hi32)
17656                                 continue;
17657
17658                         code = insn.code;
17659                         class = BPF_CLASS(code);
17660                         if (load_reg == -1)
17661                                 continue;
17662
17663                         /* NOTE: arg "reg" (the fourth one) is only used for
17664                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
17665                          *       here.
17666                          */
17667                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17668                                 if (class == BPF_LD &&
17669                                     BPF_MODE(code) == BPF_IMM)
17670                                         i++;
17671                                 continue;
17672                         }
17673
17674                         /* ctx load could be transformed into wider load. */
17675                         if (class == BPF_LDX &&
17676                             aux[adj_idx].ptr_type == PTR_TO_CTX)
17677                                 continue;
17678
17679                         imm_rnd = get_random_u32();
17680                         rnd_hi32_patch[0] = insn;
17681                         rnd_hi32_patch[1].imm = imm_rnd;
17682                         rnd_hi32_patch[3].dst_reg = load_reg;
17683                         patch = rnd_hi32_patch;
17684                         patch_len = 4;
17685                         goto apply_patch_buffer;
17686                 }
17687
17688                 /* Add in an zero-extend instruction if a) the JIT has requested
17689                  * it or b) it's a CMPXCHG.
17690                  *
17691                  * The latter is because: BPF_CMPXCHG always loads a value into
17692                  * R0, therefore always zero-extends. However some archs'
17693                  * equivalent instruction only does this load when the
17694                  * comparison is successful. This detail of CMPXCHG is
17695                  * orthogonal to the general zero-extension behaviour of the
17696                  * CPU, so it's treated independently of bpf_jit_needs_zext.
17697                  */
17698                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17699                         continue;
17700
17701                 /* Zero-extension is done by the caller. */
17702                 if (bpf_pseudo_kfunc_call(&insn))
17703                         continue;
17704
17705                 if (WARN_ON(load_reg == -1)) {
17706                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17707                         return -EFAULT;
17708                 }
17709
17710                 zext_patch[0] = insn;
17711                 zext_patch[1].dst_reg = load_reg;
17712                 zext_patch[1].src_reg = load_reg;
17713                 patch = zext_patch;
17714                 patch_len = 2;
17715 apply_patch_buffer:
17716                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17717                 if (!new_prog)
17718                         return -ENOMEM;
17719                 env->prog = new_prog;
17720                 insns = new_prog->insnsi;
17721                 aux = env->insn_aux_data;
17722                 delta += patch_len - 1;
17723         }
17724
17725         return 0;
17726 }
17727
17728 /* convert load instructions that access fields of a context type into a
17729  * sequence of instructions that access fields of the underlying structure:
17730  *     struct __sk_buff    -> struct sk_buff
17731  *     struct bpf_sock_ops -> struct sock
17732  */
17733 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17734 {
17735         const struct bpf_verifier_ops *ops = env->ops;
17736         int i, cnt, size, ctx_field_size, delta = 0;
17737         const int insn_cnt = env->prog->len;
17738         struct bpf_insn insn_buf[16], *insn;
17739         u32 target_size, size_default, off;
17740         struct bpf_prog *new_prog;
17741         enum bpf_access_type type;
17742         bool is_narrower_load;
17743
17744         if (ops->gen_prologue || env->seen_direct_write) {
17745                 if (!ops->gen_prologue) {
17746                         verbose(env, "bpf verifier is misconfigured\n");
17747                         return -EINVAL;
17748                 }
17749                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17750                                         env->prog);
17751                 if (cnt >= ARRAY_SIZE(insn_buf)) {
17752                         verbose(env, "bpf verifier is misconfigured\n");
17753                         return -EINVAL;
17754                 } else if (cnt) {
17755                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17756                         if (!new_prog)
17757                                 return -ENOMEM;
17758
17759                         env->prog = new_prog;
17760                         delta += cnt - 1;
17761                 }
17762         }
17763
17764         if (bpf_prog_is_offloaded(env->prog->aux))
17765                 return 0;
17766
17767         insn = env->prog->insnsi + delta;
17768
17769         for (i = 0; i < insn_cnt; i++, insn++) {
17770                 bpf_convert_ctx_access_t convert_ctx_access;
17771                 u8 mode;
17772
17773                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17774                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17775                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17776                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17777                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17778                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17779                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17780                         type = BPF_READ;
17781                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17782                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17783                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17784                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17785                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17786                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17787                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17788                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17789                         type = BPF_WRITE;
17790                 } else {
17791                         continue;
17792                 }
17793
17794                 if (type == BPF_WRITE &&
17795                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
17796                         struct bpf_insn patch[] = {
17797                                 *insn,
17798                                 BPF_ST_NOSPEC(),
17799                         };
17800
17801                         cnt = ARRAY_SIZE(patch);
17802                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17803                         if (!new_prog)
17804                                 return -ENOMEM;
17805
17806                         delta    += cnt - 1;
17807                         env->prog = new_prog;
17808                         insn      = new_prog->insnsi + i + delta;
17809                         continue;
17810                 }
17811
17812                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17813                 case PTR_TO_CTX:
17814                         if (!ops->convert_ctx_access)
17815                                 continue;
17816                         convert_ctx_access = ops->convert_ctx_access;
17817                         break;
17818                 case PTR_TO_SOCKET:
17819                 case PTR_TO_SOCK_COMMON:
17820                         convert_ctx_access = bpf_sock_convert_ctx_access;
17821                         break;
17822                 case PTR_TO_TCP_SOCK:
17823                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17824                         break;
17825                 case PTR_TO_XDP_SOCK:
17826                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17827                         break;
17828                 case PTR_TO_BTF_ID:
17829                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17830                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17831                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17832                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
17833                  * any faults for loads into such types. BPF_WRITE is disallowed
17834                  * for this case.
17835                  */
17836                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17837                         if (type == BPF_READ) {
17838                                 if (BPF_MODE(insn->code) == BPF_MEM)
17839                                         insn->code = BPF_LDX | BPF_PROBE_MEM |
17840                                                      BPF_SIZE((insn)->code);
17841                                 else
17842                                         insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17843                                                      BPF_SIZE((insn)->code);
17844                                 env->prog->aux->num_exentries++;
17845                         }
17846                         continue;
17847                 default:
17848                         continue;
17849                 }
17850
17851                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17852                 size = BPF_LDST_BYTES(insn);
17853                 mode = BPF_MODE(insn->code);
17854
17855                 /* If the read access is a narrower load of the field,
17856                  * convert to a 4/8-byte load, to minimum program type specific
17857                  * convert_ctx_access changes. If conversion is successful,
17858                  * we will apply proper mask to the result.
17859                  */
17860                 is_narrower_load = size < ctx_field_size;
17861                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17862                 off = insn->off;
17863                 if (is_narrower_load) {
17864                         u8 size_code;
17865
17866                         if (type == BPF_WRITE) {
17867                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17868                                 return -EINVAL;
17869                         }
17870
17871                         size_code = BPF_H;
17872                         if (ctx_field_size == 4)
17873                                 size_code = BPF_W;
17874                         else if (ctx_field_size == 8)
17875                                 size_code = BPF_DW;
17876
17877                         insn->off = off & ~(size_default - 1);
17878                         insn->code = BPF_LDX | BPF_MEM | size_code;
17879                 }
17880
17881                 target_size = 0;
17882                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17883                                          &target_size);
17884                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17885                     (ctx_field_size && !target_size)) {
17886                         verbose(env, "bpf verifier is misconfigured\n");
17887                         return -EINVAL;
17888                 }
17889
17890                 if (is_narrower_load && size < target_size) {
17891                         u8 shift = bpf_ctx_narrow_access_offset(
17892                                 off, size, size_default) * 8;
17893                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17894                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17895                                 return -EINVAL;
17896                         }
17897                         if (ctx_field_size <= 4) {
17898                                 if (shift)
17899                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17900                                                                         insn->dst_reg,
17901                                                                         shift);
17902                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17903                                                                 (1 << size * 8) - 1);
17904                         } else {
17905                                 if (shift)
17906                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17907                                                                         insn->dst_reg,
17908                                                                         shift);
17909                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17910                                                                 (1ULL << size * 8) - 1);
17911                         }
17912                 }
17913                 if (mode == BPF_MEMSX)
17914                         insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17915                                                        insn->dst_reg, insn->dst_reg,
17916                                                        size * 8, 0);
17917
17918                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17919                 if (!new_prog)
17920                         return -ENOMEM;
17921
17922                 delta += cnt - 1;
17923
17924                 /* keep walking new program and skip insns we just inserted */
17925                 env->prog = new_prog;
17926                 insn      = new_prog->insnsi + i + delta;
17927         }
17928
17929         return 0;
17930 }
17931
17932 static int jit_subprogs(struct bpf_verifier_env *env)
17933 {
17934         struct bpf_prog *prog = env->prog, **func, *tmp;
17935         int i, j, subprog_start, subprog_end = 0, len, subprog;
17936         struct bpf_map *map_ptr;
17937         struct bpf_insn *insn;
17938         void *old_bpf_func;
17939         int err, num_exentries;
17940
17941         if (env->subprog_cnt <= 1)
17942                 return 0;
17943
17944         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17945                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17946                         continue;
17947
17948                 /* Upon error here we cannot fall back to interpreter but
17949                  * need a hard reject of the program. Thus -EFAULT is
17950                  * propagated in any case.
17951                  */
17952                 subprog = find_subprog(env, i + insn->imm + 1);
17953                 if (subprog < 0) {
17954                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17955                                   i + insn->imm + 1);
17956                         return -EFAULT;
17957                 }
17958                 /* temporarily remember subprog id inside insn instead of
17959                  * aux_data, since next loop will split up all insns into funcs
17960                  */
17961                 insn->off = subprog;
17962                 /* remember original imm in case JIT fails and fallback
17963                  * to interpreter will be needed
17964                  */
17965                 env->insn_aux_data[i].call_imm = insn->imm;
17966                 /* point imm to __bpf_call_base+1 from JITs point of view */
17967                 insn->imm = 1;
17968                 if (bpf_pseudo_func(insn))
17969                         /* jit (e.g. x86_64) may emit fewer instructions
17970                          * if it learns a u32 imm is the same as a u64 imm.
17971                          * Force a non zero here.
17972                          */
17973                         insn[1].imm = 1;
17974         }
17975
17976         err = bpf_prog_alloc_jited_linfo(prog);
17977         if (err)
17978                 goto out_undo_insn;
17979
17980         err = -ENOMEM;
17981         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17982         if (!func)
17983                 goto out_undo_insn;
17984
17985         for (i = 0; i < env->subprog_cnt; i++) {
17986                 subprog_start = subprog_end;
17987                 subprog_end = env->subprog_info[i + 1].start;
17988
17989                 len = subprog_end - subprog_start;
17990                 /* bpf_prog_run() doesn't call subprogs directly,
17991                  * hence main prog stats include the runtime of subprogs.
17992                  * subprogs don't have IDs and not reachable via prog_get_next_id
17993                  * func[i]->stats will never be accessed and stays NULL
17994                  */
17995                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17996                 if (!func[i])
17997                         goto out_free;
17998                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17999                        len * sizeof(struct bpf_insn));
18000                 func[i]->type = prog->type;
18001                 func[i]->len = len;
18002                 if (bpf_prog_calc_tag(func[i]))
18003                         goto out_free;
18004                 func[i]->is_func = 1;
18005                 func[i]->aux->func_idx = i;
18006                 /* Below members will be freed only at prog->aux */
18007                 func[i]->aux->btf = prog->aux->btf;
18008                 func[i]->aux->func_info = prog->aux->func_info;
18009                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18010                 func[i]->aux->poke_tab = prog->aux->poke_tab;
18011                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18012
18013                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18014                         struct bpf_jit_poke_descriptor *poke;
18015
18016                         poke = &prog->aux->poke_tab[j];
18017                         if (poke->insn_idx < subprog_end &&
18018                             poke->insn_idx >= subprog_start)
18019                                 poke->aux = func[i]->aux;
18020                 }
18021
18022                 func[i]->aux->name[0] = 'F';
18023                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18024                 func[i]->jit_requested = 1;
18025                 func[i]->blinding_requested = prog->blinding_requested;
18026                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18027                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18028                 func[i]->aux->linfo = prog->aux->linfo;
18029                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18030                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18031                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18032                 num_exentries = 0;
18033                 insn = func[i]->insnsi;
18034                 for (j = 0; j < func[i]->len; j++, insn++) {
18035                         if (BPF_CLASS(insn->code) == BPF_LDX &&
18036                             (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18037                              BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18038                                 num_exentries++;
18039                 }
18040                 func[i]->aux->num_exentries = num_exentries;
18041                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18042                 func[i] = bpf_int_jit_compile(func[i]);
18043                 if (!func[i]->jited) {
18044                         err = -ENOTSUPP;
18045                         goto out_free;
18046                 }
18047                 cond_resched();
18048         }
18049
18050         /* at this point all bpf functions were successfully JITed
18051          * now populate all bpf_calls with correct addresses and
18052          * run last pass of JIT
18053          */
18054         for (i = 0; i < env->subprog_cnt; i++) {
18055                 insn = func[i]->insnsi;
18056                 for (j = 0; j < func[i]->len; j++, insn++) {
18057                         if (bpf_pseudo_func(insn)) {
18058                                 subprog = insn->off;
18059                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18060                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18061                                 continue;
18062                         }
18063                         if (!bpf_pseudo_call(insn))
18064                                 continue;
18065                         subprog = insn->off;
18066                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18067                 }
18068
18069                 /* we use the aux data to keep a list of the start addresses
18070                  * of the JITed images for each function in the program
18071                  *
18072                  * for some architectures, such as powerpc64, the imm field
18073                  * might not be large enough to hold the offset of the start
18074                  * address of the callee's JITed image from __bpf_call_base
18075                  *
18076                  * in such cases, we can lookup the start address of a callee
18077                  * by using its subprog id, available from the off field of
18078                  * the call instruction, as an index for this list
18079                  */
18080                 func[i]->aux->func = func;
18081                 func[i]->aux->func_cnt = env->subprog_cnt;
18082         }
18083         for (i = 0; i < env->subprog_cnt; i++) {
18084                 old_bpf_func = func[i]->bpf_func;
18085                 tmp = bpf_int_jit_compile(func[i]);
18086                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18087                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18088                         err = -ENOTSUPP;
18089                         goto out_free;
18090                 }
18091                 cond_resched();
18092         }
18093
18094         /* finally lock prog and jit images for all functions and
18095          * populate kallsysm. Begin at the first subprogram, since
18096          * bpf_prog_load will add the kallsyms for the main program.
18097          */
18098         for (i = 1; i < env->subprog_cnt; i++) {
18099                 bpf_prog_lock_ro(func[i]);
18100                 bpf_prog_kallsyms_add(func[i]);
18101         }
18102
18103         /* Last step: make now unused interpreter insns from main
18104          * prog consistent for later dump requests, so they can
18105          * later look the same as if they were interpreted only.
18106          */
18107         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18108                 if (bpf_pseudo_func(insn)) {
18109                         insn[0].imm = env->insn_aux_data[i].call_imm;
18110                         insn[1].imm = insn->off;
18111                         insn->off = 0;
18112                         continue;
18113                 }
18114                 if (!bpf_pseudo_call(insn))
18115                         continue;
18116                 insn->off = env->insn_aux_data[i].call_imm;
18117                 subprog = find_subprog(env, i + insn->off + 1);
18118                 insn->imm = subprog;
18119         }
18120
18121         prog->jited = 1;
18122         prog->bpf_func = func[0]->bpf_func;
18123         prog->jited_len = func[0]->jited_len;
18124         prog->aux->extable = func[0]->aux->extable;
18125         prog->aux->num_exentries = func[0]->aux->num_exentries;
18126         prog->aux->func = func;
18127         prog->aux->func_cnt = env->subprog_cnt;
18128         bpf_prog_jit_attempt_done(prog);
18129         return 0;
18130 out_free:
18131         /* We failed JIT'ing, so at this point we need to unregister poke
18132          * descriptors from subprogs, so that kernel is not attempting to
18133          * patch it anymore as we're freeing the subprog JIT memory.
18134          */
18135         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18136                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18137                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18138         }
18139         /* At this point we're guaranteed that poke descriptors are not
18140          * live anymore. We can just unlink its descriptor table as it's
18141          * released with the main prog.
18142          */
18143         for (i = 0; i < env->subprog_cnt; i++) {
18144                 if (!func[i])
18145                         continue;
18146                 func[i]->aux->poke_tab = NULL;
18147                 bpf_jit_free(func[i]);
18148         }
18149         kfree(func);
18150 out_undo_insn:
18151         /* cleanup main prog to be interpreted */
18152         prog->jit_requested = 0;
18153         prog->blinding_requested = 0;
18154         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18155                 if (!bpf_pseudo_call(insn))
18156                         continue;
18157                 insn->off = 0;
18158                 insn->imm = env->insn_aux_data[i].call_imm;
18159         }
18160         bpf_prog_jit_attempt_done(prog);
18161         return err;
18162 }
18163
18164 static int fixup_call_args(struct bpf_verifier_env *env)
18165 {
18166 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18167         struct bpf_prog *prog = env->prog;
18168         struct bpf_insn *insn = prog->insnsi;
18169         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18170         int i, depth;
18171 #endif
18172         int err = 0;
18173
18174         if (env->prog->jit_requested &&
18175             !bpf_prog_is_offloaded(env->prog->aux)) {
18176                 err = jit_subprogs(env);
18177                 if (err == 0)
18178                         return 0;
18179                 if (err == -EFAULT)
18180                         return err;
18181         }
18182 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18183         if (has_kfunc_call) {
18184                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18185                 return -EINVAL;
18186         }
18187         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18188                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18189                  * have to be rejected, since interpreter doesn't support them yet.
18190                  */
18191                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18192                 return -EINVAL;
18193         }
18194         for (i = 0; i < prog->len; i++, insn++) {
18195                 if (bpf_pseudo_func(insn)) {
18196                         /* When JIT fails the progs with callback calls
18197                          * have to be rejected, since interpreter doesn't support them yet.
18198                          */
18199                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
18200                         return -EINVAL;
18201                 }
18202
18203                 if (!bpf_pseudo_call(insn))
18204                         continue;
18205                 depth = get_callee_stack_depth(env, insn, i);
18206                 if (depth < 0)
18207                         return depth;
18208                 bpf_patch_call_args(insn, depth);
18209         }
18210         err = 0;
18211 #endif
18212         return err;
18213 }
18214
18215 /* replace a generic kfunc with a specialized version if necessary */
18216 static void specialize_kfunc(struct bpf_verifier_env *env,
18217                              u32 func_id, u16 offset, unsigned long *addr)
18218 {
18219         struct bpf_prog *prog = env->prog;
18220         bool seen_direct_write;
18221         void *xdp_kfunc;
18222         bool is_rdonly;
18223
18224         if (bpf_dev_bound_kfunc_id(func_id)) {
18225                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18226                 if (xdp_kfunc) {
18227                         *addr = (unsigned long)xdp_kfunc;
18228                         return;
18229                 }
18230                 /* fallback to default kfunc when not supported by netdev */
18231         }
18232
18233         if (offset)
18234                 return;
18235
18236         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18237                 seen_direct_write = env->seen_direct_write;
18238                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18239
18240                 if (is_rdonly)
18241                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18242
18243                 /* restore env->seen_direct_write to its original value, since
18244                  * may_access_direct_pkt_data mutates it
18245                  */
18246                 env->seen_direct_write = seen_direct_write;
18247         }
18248 }
18249
18250 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18251                                             u16 struct_meta_reg,
18252                                             u16 node_offset_reg,
18253                                             struct bpf_insn *insn,
18254                                             struct bpf_insn *insn_buf,
18255                                             int *cnt)
18256 {
18257         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18258         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18259
18260         insn_buf[0] = addr[0];
18261         insn_buf[1] = addr[1];
18262         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18263         insn_buf[3] = *insn;
18264         *cnt = 4;
18265 }
18266
18267 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18268                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18269 {
18270         const struct bpf_kfunc_desc *desc;
18271
18272         if (!insn->imm) {
18273                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18274                 return -EINVAL;
18275         }
18276
18277         *cnt = 0;
18278
18279         /* insn->imm has the btf func_id. Replace it with an offset relative to
18280          * __bpf_call_base, unless the JIT needs to call functions that are
18281          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18282          */
18283         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18284         if (!desc) {
18285                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18286                         insn->imm);
18287                 return -EFAULT;
18288         }
18289
18290         if (!bpf_jit_supports_far_kfunc_call())
18291                 insn->imm = BPF_CALL_IMM(desc->addr);
18292         if (insn->off)
18293                 return 0;
18294         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18295                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18296                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18297                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18298
18299                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18300                 insn_buf[1] = addr[0];
18301                 insn_buf[2] = addr[1];
18302                 insn_buf[3] = *insn;
18303                 *cnt = 4;
18304         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18305                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18306                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18307                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18308
18309                 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18310                     !kptr_struct_meta) {
18311                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18312                                 insn_idx);
18313                         return -EFAULT;
18314                 }
18315
18316                 insn_buf[0] = addr[0];
18317                 insn_buf[1] = addr[1];
18318                 insn_buf[2] = *insn;
18319                 *cnt = 3;
18320         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18321                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18322                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18323                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18324                 int struct_meta_reg = BPF_REG_3;
18325                 int node_offset_reg = BPF_REG_4;
18326
18327                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18328                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18329                         struct_meta_reg = BPF_REG_4;
18330                         node_offset_reg = BPF_REG_5;
18331                 }
18332
18333                 if (!kptr_struct_meta) {
18334                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18335                                 insn_idx);
18336                         return -EFAULT;
18337                 }
18338
18339                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18340                                                 node_offset_reg, insn, insn_buf, cnt);
18341         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18342                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18343                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18344                 *cnt = 1;
18345         }
18346         return 0;
18347 }
18348
18349 /* Do various post-verification rewrites in a single program pass.
18350  * These rewrites simplify JIT and interpreter implementations.
18351  */
18352 static int do_misc_fixups(struct bpf_verifier_env *env)
18353 {
18354         struct bpf_prog *prog = env->prog;
18355         enum bpf_attach_type eatype = prog->expected_attach_type;
18356         enum bpf_prog_type prog_type = resolve_prog_type(prog);
18357         struct bpf_insn *insn = prog->insnsi;
18358         const struct bpf_func_proto *fn;
18359         const int insn_cnt = prog->len;
18360         const struct bpf_map_ops *ops;
18361         struct bpf_insn_aux_data *aux;
18362         struct bpf_insn insn_buf[16];
18363         struct bpf_prog *new_prog;
18364         struct bpf_map *map_ptr;
18365         int i, ret, cnt, delta = 0;
18366
18367         for (i = 0; i < insn_cnt; i++, insn++) {
18368                 /* Make divide-by-zero exceptions impossible. */
18369                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18370                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18371                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18372                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18373                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18374                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18375                         struct bpf_insn *patchlet;
18376                         struct bpf_insn chk_and_div[] = {
18377                                 /* [R,W]x div 0 -> 0 */
18378                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18379                                              BPF_JNE | BPF_K, insn->src_reg,
18380                                              0, 2, 0),
18381                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18382                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18383                                 *insn,
18384                         };
18385                         struct bpf_insn chk_and_mod[] = {
18386                                 /* [R,W]x mod 0 -> [R,W]x */
18387                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18388                                              BPF_JEQ | BPF_K, insn->src_reg,
18389                                              0, 1 + (is64 ? 0 : 1), 0),
18390                                 *insn,
18391                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18392                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18393                         };
18394
18395                         patchlet = isdiv ? chk_and_div : chk_and_mod;
18396                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18397                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18398
18399                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18400                         if (!new_prog)
18401                                 return -ENOMEM;
18402
18403                         delta    += cnt - 1;
18404                         env->prog = prog = new_prog;
18405                         insn      = new_prog->insnsi + i + delta;
18406                         continue;
18407                 }
18408
18409                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18410                 if (BPF_CLASS(insn->code) == BPF_LD &&
18411                     (BPF_MODE(insn->code) == BPF_ABS ||
18412                      BPF_MODE(insn->code) == BPF_IND)) {
18413                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
18414                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18415                                 verbose(env, "bpf verifier is misconfigured\n");
18416                                 return -EINVAL;
18417                         }
18418
18419                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18420                         if (!new_prog)
18421                                 return -ENOMEM;
18422
18423                         delta    += cnt - 1;
18424                         env->prog = prog = new_prog;
18425                         insn      = new_prog->insnsi + i + delta;
18426                         continue;
18427                 }
18428
18429                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18430                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18431                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18432                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18433                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18434                         struct bpf_insn *patch = &insn_buf[0];
18435                         bool issrc, isneg, isimm;
18436                         u32 off_reg;
18437
18438                         aux = &env->insn_aux_data[i + delta];
18439                         if (!aux->alu_state ||
18440                             aux->alu_state == BPF_ALU_NON_POINTER)
18441                                 continue;
18442
18443                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18444                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18445                                 BPF_ALU_SANITIZE_SRC;
18446                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18447
18448                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
18449                         if (isimm) {
18450                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18451                         } else {
18452                                 if (isneg)
18453                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18454                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18455                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18456                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18457                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18458                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18459                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18460                         }
18461                         if (!issrc)
18462                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18463                         insn->src_reg = BPF_REG_AX;
18464                         if (isneg)
18465                                 insn->code = insn->code == code_add ?
18466                                              code_sub : code_add;
18467                         *patch++ = *insn;
18468                         if (issrc && isneg && !isimm)
18469                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18470                         cnt = patch - insn_buf;
18471
18472                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18473                         if (!new_prog)
18474                                 return -ENOMEM;
18475
18476                         delta    += cnt - 1;
18477                         env->prog = prog = new_prog;
18478                         insn      = new_prog->insnsi + i + delta;
18479                         continue;
18480                 }
18481
18482                 if (insn->code != (BPF_JMP | BPF_CALL))
18483                         continue;
18484                 if (insn->src_reg == BPF_PSEUDO_CALL)
18485                         continue;
18486                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18487                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18488                         if (ret)
18489                                 return ret;
18490                         if (cnt == 0)
18491                                 continue;
18492
18493                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18494                         if (!new_prog)
18495                                 return -ENOMEM;
18496
18497                         delta    += cnt - 1;
18498                         env->prog = prog = new_prog;
18499                         insn      = new_prog->insnsi + i + delta;
18500                         continue;
18501                 }
18502
18503                 if (insn->imm == BPF_FUNC_get_route_realm)
18504                         prog->dst_needed = 1;
18505                 if (insn->imm == BPF_FUNC_get_prandom_u32)
18506                         bpf_user_rnd_init_once();
18507                 if (insn->imm == BPF_FUNC_override_return)
18508                         prog->kprobe_override = 1;
18509                 if (insn->imm == BPF_FUNC_tail_call) {
18510                         /* If we tail call into other programs, we
18511                          * cannot make any assumptions since they can
18512                          * be replaced dynamically during runtime in
18513                          * the program array.
18514                          */
18515                         prog->cb_access = 1;
18516                         if (!allow_tail_call_in_subprogs(env))
18517                                 prog->aux->stack_depth = MAX_BPF_STACK;
18518                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18519
18520                         /* mark bpf_tail_call as different opcode to avoid
18521                          * conditional branch in the interpreter for every normal
18522                          * call and to prevent accidental JITing by JIT compiler
18523                          * that doesn't support bpf_tail_call yet
18524                          */
18525                         insn->imm = 0;
18526                         insn->code = BPF_JMP | BPF_TAIL_CALL;
18527
18528                         aux = &env->insn_aux_data[i + delta];
18529                         if (env->bpf_capable && !prog->blinding_requested &&
18530                             prog->jit_requested &&
18531                             !bpf_map_key_poisoned(aux) &&
18532                             !bpf_map_ptr_poisoned(aux) &&
18533                             !bpf_map_ptr_unpriv(aux)) {
18534                                 struct bpf_jit_poke_descriptor desc = {
18535                                         .reason = BPF_POKE_REASON_TAIL_CALL,
18536                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18537                                         .tail_call.key = bpf_map_key_immediate(aux),
18538                                         .insn_idx = i + delta,
18539                                 };
18540
18541                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18542                                 if (ret < 0) {
18543                                         verbose(env, "adding tail call poke descriptor failed\n");
18544                                         return ret;
18545                                 }
18546
18547                                 insn->imm = ret + 1;
18548                                 continue;
18549                         }
18550
18551                         if (!bpf_map_ptr_unpriv(aux))
18552                                 continue;
18553
18554                         /* instead of changing every JIT dealing with tail_call
18555                          * emit two extra insns:
18556                          * if (index >= max_entries) goto out;
18557                          * index &= array->index_mask;
18558                          * to avoid out-of-bounds cpu speculation
18559                          */
18560                         if (bpf_map_ptr_poisoned(aux)) {
18561                                 verbose(env, "tail_call abusing map_ptr\n");
18562                                 return -EINVAL;
18563                         }
18564
18565                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18566                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18567                                                   map_ptr->max_entries, 2);
18568                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18569                                                     container_of(map_ptr,
18570                                                                  struct bpf_array,
18571                                                                  map)->index_mask);
18572                         insn_buf[2] = *insn;
18573                         cnt = 3;
18574                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18575                         if (!new_prog)
18576                                 return -ENOMEM;
18577
18578                         delta    += cnt - 1;
18579                         env->prog = prog = new_prog;
18580                         insn      = new_prog->insnsi + i + delta;
18581                         continue;
18582                 }
18583
18584                 if (insn->imm == BPF_FUNC_timer_set_callback) {
18585                         /* The verifier will process callback_fn as many times as necessary
18586                          * with different maps and the register states prepared by
18587                          * set_timer_callback_state will be accurate.
18588                          *
18589                          * The following use case is valid:
18590                          *   map1 is shared by prog1, prog2, prog3.
18591                          *   prog1 calls bpf_timer_init for some map1 elements
18592                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
18593                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
18594                          *   prog3 calls bpf_timer_start for some map1 elements.
18595                          *     Those that were not both bpf_timer_init-ed and
18596                          *     bpf_timer_set_callback-ed will return -EINVAL.
18597                          */
18598                         struct bpf_insn ld_addrs[2] = {
18599                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18600                         };
18601
18602                         insn_buf[0] = ld_addrs[0];
18603                         insn_buf[1] = ld_addrs[1];
18604                         insn_buf[2] = *insn;
18605                         cnt = 3;
18606
18607                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18608                         if (!new_prog)
18609                                 return -ENOMEM;
18610
18611                         delta    += cnt - 1;
18612                         env->prog = prog = new_prog;
18613                         insn      = new_prog->insnsi + i + delta;
18614                         goto patch_call_imm;
18615                 }
18616
18617                 if (is_storage_get_function(insn->imm)) {
18618                         if (!env->prog->aux->sleepable ||
18619                             env->insn_aux_data[i + delta].storage_get_func_atomic)
18620                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18621                         else
18622                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18623                         insn_buf[1] = *insn;
18624                         cnt = 2;
18625
18626                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18627                         if (!new_prog)
18628                                 return -ENOMEM;
18629
18630                         delta += cnt - 1;
18631                         env->prog = prog = new_prog;
18632                         insn = new_prog->insnsi + i + delta;
18633                         goto patch_call_imm;
18634                 }
18635
18636                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18637                  * and other inlining handlers are currently limited to 64 bit
18638                  * only.
18639                  */
18640                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18641                     (insn->imm == BPF_FUNC_map_lookup_elem ||
18642                      insn->imm == BPF_FUNC_map_update_elem ||
18643                      insn->imm == BPF_FUNC_map_delete_elem ||
18644                      insn->imm == BPF_FUNC_map_push_elem   ||
18645                      insn->imm == BPF_FUNC_map_pop_elem    ||
18646                      insn->imm == BPF_FUNC_map_peek_elem   ||
18647                      insn->imm == BPF_FUNC_redirect_map    ||
18648                      insn->imm == BPF_FUNC_for_each_map_elem ||
18649                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18650                         aux = &env->insn_aux_data[i + delta];
18651                         if (bpf_map_ptr_poisoned(aux))
18652                                 goto patch_call_imm;
18653
18654                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18655                         ops = map_ptr->ops;
18656                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
18657                             ops->map_gen_lookup) {
18658                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18659                                 if (cnt == -EOPNOTSUPP)
18660                                         goto patch_map_ops_generic;
18661                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18662                                         verbose(env, "bpf verifier is misconfigured\n");
18663                                         return -EINVAL;
18664                                 }
18665
18666                                 new_prog = bpf_patch_insn_data(env, i + delta,
18667                                                                insn_buf, cnt);
18668                                 if (!new_prog)
18669                                         return -ENOMEM;
18670
18671                                 delta    += cnt - 1;
18672                                 env->prog = prog = new_prog;
18673                                 insn      = new_prog->insnsi + i + delta;
18674                                 continue;
18675                         }
18676
18677                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18678                                      (void *(*)(struct bpf_map *map, void *key))NULL));
18679                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18680                                      (long (*)(struct bpf_map *map, void *key))NULL));
18681                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18682                                      (long (*)(struct bpf_map *map, void *key, void *value,
18683                                               u64 flags))NULL));
18684                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18685                                      (long (*)(struct bpf_map *map, void *value,
18686                                               u64 flags))NULL));
18687                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18688                                      (long (*)(struct bpf_map *map, void *value))NULL));
18689                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18690                                      (long (*)(struct bpf_map *map, void *value))NULL));
18691                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
18692                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18693                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18694                                      (long (*)(struct bpf_map *map,
18695                                               bpf_callback_t callback_fn,
18696                                               void *callback_ctx,
18697                                               u64 flags))NULL));
18698                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18699                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18700
18701 patch_map_ops_generic:
18702                         switch (insn->imm) {
18703                         case BPF_FUNC_map_lookup_elem:
18704                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18705                                 continue;
18706                         case BPF_FUNC_map_update_elem:
18707                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18708                                 continue;
18709                         case BPF_FUNC_map_delete_elem:
18710                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18711                                 continue;
18712                         case BPF_FUNC_map_push_elem:
18713                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18714                                 continue;
18715                         case BPF_FUNC_map_pop_elem:
18716                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18717                                 continue;
18718                         case BPF_FUNC_map_peek_elem:
18719                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18720                                 continue;
18721                         case BPF_FUNC_redirect_map:
18722                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18723                                 continue;
18724                         case BPF_FUNC_for_each_map_elem:
18725                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18726                                 continue;
18727                         case BPF_FUNC_map_lookup_percpu_elem:
18728                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18729                                 continue;
18730                         }
18731
18732                         goto patch_call_imm;
18733                 }
18734
18735                 /* Implement bpf_jiffies64 inline. */
18736                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18737                     insn->imm == BPF_FUNC_jiffies64) {
18738                         struct bpf_insn ld_jiffies_addr[2] = {
18739                                 BPF_LD_IMM64(BPF_REG_0,
18740                                              (unsigned long)&jiffies),
18741                         };
18742
18743                         insn_buf[0] = ld_jiffies_addr[0];
18744                         insn_buf[1] = ld_jiffies_addr[1];
18745                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18746                                                   BPF_REG_0, 0);
18747                         cnt = 3;
18748
18749                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18750                                                        cnt);
18751                         if (!new_prog)
18752                                 return -ENOMEM;
18753
18754                         delta    += cnt - 1;
18755                         env->prog = prog = new_prog;
18756                         insn      = new_prog->insnsi + i + delta;
18757                         continue;
18758                 }
18759
18760                 /* Implement bpf_get_func_arg inline. */
18761                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18762                     insn->imm == BPF_FUNC_get_func_arg) {
18763                         /* Load nr_args from ctx - 8 */
18764                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18765                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18766                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18767                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18768                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18769                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18770                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18771                         insn_buf[7] = BPF_JMP_A(1);
18772                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18773                         cnt = 9;
18774
18775                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18776                         if (!new_prog)
18777                                 return -ENOMEM;
18778
18779                         delta    += cnt - 1;
18780                         env->prog = prog = new_prog;
18781                         insn      = new_prog->insnsi + i + delta;
18782                         continue;
18783                 }
18784
18785                 /* Implement bpf_get_func_ret inline. */
18786                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18787                     insn->imm == BPF_FUNC_get_func_ret) {
18788                         if (eatype == BPF_TRACE_FEXIT ||
18789                             eatype == BPF_MODIFY_RETURN) {
18790                                 /* Load nr_args from ctx - 8 */
18791                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18792                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18793                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18794                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18795                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18796                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18797                                 cnt = 6;
18798                         } else {
18799                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18800                                 cnt = 1;
18801                         }
18802
18803                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18804                         if (!new_prog)
18805                                 return -ENOMEM;
18806
18807                         delta    += cnt - 1;
18808                         env->prog = prog = new_prog;
18809                         insn      = new_prog->insnsi + i + delta;
18810                         continue;
18811                 }
18812
18813                 /* Implement get_func_arg_cnt inline. */
18814                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18815                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
18816                         /* Load nr_args from ctx - 8 */
18817                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18818
18819                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18820                         if (!new_prog)
18821                                 return -ENOMEM;
18822
18823                         env->prog = prog = new_prog;
18824                         insn      = new_prog->insnsi + i + delta;
18825                         continue;
18826                 }
18827
18828                 /* Implement bpf_get_func_ip inline. */
18829                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18830                     insn->imm == BPF_FUNC_get_func_ip) {
18831                         /* Load IP address from ctx - 16 */
18832                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18833
18834                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18835                         if (!new_prog)
18836                                 return -ENOMEM;
18837
18838                         env->prog = prog = new_prog;
18839                         insn      = new_prog->insnsi + i + delta;
18840                         continue;
18841                 }
18842
18843 patch_call_imm:
18844                 fn = env->ops->get_func_proto(insn->imm, env->prog);
18845                 /* all functions that have prototype and verifier allowed
18846                  * programs to call them, must be real in-kernel functions
18847                  */
18848                 if (!fn->func) {
18849                         verbose(env,
18850                                 "kernel subsystem misconfigured func %s#%d\n",
18851                                 func_id_name(insn->imm), insn->imm);
18852                         return -EFAULT;
18853                 }
18854                 insn->imm = fn->func - __bpf_call_base;
18855         }
18856
18857         /* Since poke tab is now finalized, publish aux to tracker. */
18858         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18859                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18860                 if (!map_ptr->ops->map_poke_track ||
18861                     !map_ptr->ops->map_poke_untrack ||
18862                     !map_ptr->ops->map_poke_run) {
18863                         verbose(env, "bpf verifier is misconfigured\n");
18864                         return -EINVAL;
18865                 }
18866
18867                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18868                 if (ret < 0) {
18869                         verbose(env, "tracking tail call prog failed\n");
18870                         return ret;
18871                 }
18872         }
18873
18874         sort_kfunc_descs_by_imm_off(env->prog);
18875
18876         return 0;
18877 }
18878
18879 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18880                                         int position,
18881                                         s32 stack_base,
18882                                         u32 callback_subprogno,
18883                                         u32 *cnt)
18884 {
18885         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18886         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18887         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18888         int reg_loop_max = BPF_REG_6;
18889         int reg_loop_cnt = BPF_REG_7;
18890         int reg_loop_ctx = BPF_REG_8;
18891
18892         struct bpf_prog *new_prog;
18893         u32 callback_start;
18894         u32 call_insn_offset;
18895         s32 callback_offset;
18896
18897         /* This represents an inlined version of bpf_iter.c:bpf_loop,
18898          * be careful to modify this code in sync.
18899          */
18900         struct bpf_insn insn_buf[] = {
18901                 /* Return error and jump to the end of the patch if
18902                  * expected number of iterations is too big.
18903                  */
18904                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18905                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18906                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18907                 /* spill R6, R7, R8 to use these as loop vars */
18908                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18909                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18910                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18911                 /* initialize loop vars */
18912                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18913                 BPF_MOV32_IMM(reg_loop_cnt, 0),
18914                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18915                 /* loop header,
18916                  * if reg_loop_cnt >= reg_loop_max skip the loop body
18917                  */
18918                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18919                 /* callback call,
18920                  * correct callback offset would be set after patching
18921                  */
18922                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18923                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18924                 BPF_CALL_REL(0),
18925                 /* increment loop counter */
18926                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18927                 /* jump to loop header if callback returned 0 */
18928                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18929                 /* return value of bpf_loop,
18930                  * set R0 to the number of iterations
18931                  */
18932                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18933                 /* restore original values of R6, R7, R8 */
18934                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18935                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18936                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18937         };
18938
18939         *cnt = ARRAY_SIZE(insn_buf);
18940         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18941         if (!new_prog)
18942                 return new_prog;
18943
18944         /* callback start is known only after patching */
18945         callback_start = env->subprog_info[callback_subprogno].start;
18946         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18947         call_insn_offset = position + 12;
18948         callback_offset = callback_start - call_insn_offset - 1;
18949         new_prog->insnsi[call_insn_offset].imm = callback_offset;
18950
18951         return new_prog;
18952 }
18953
18954 static bool is_bpf_loop_call(struct bpf_insn *insn)
18955 {
18956         return insn->code == (BPF_JMP | BPF_CALL) &&
18957                 insn->src_reg == 0 &&
18958                 insn->imm == BPF_FUNC_loop;
18959 }
18960
18961 /* For all sub-programs in the program (including main) check
18962  * insn_aux_data to see if there are bpf_loop calls that require
18963  * inlining. If such calls are found the calls are replaced with a
18964  * sequence of instructions produced by `inline_bpf_loop` function and
18965  * subprog stack_depth is increased by the size of 3 registers.
18966  * This stack space is used to spill values of the R6, R7, R8.  These
18967  * registers are used to store the loop bound, counter and context
18968  * variables.
18969  */
18970 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18971 {
18972         struct bpf_subprog_info *subprogs = env->subprog_info;
18973         int i, cur_subprog = 0, cnt, delta = 0;
18974         struct bpf_insn *insn = env->prog->insnsi;
18975         int insn_cnt = env->prog->len;
18976         u16 stack_depth = subprogs[cur_subprog].stack_depth;
18977         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18978         u16 stack_depth_extra = 0;
18979
18980         for (i = 0; i < insn_cnt; i++, insn++) {
18981                 struct bpf_loop_inline_state *inline_state =
18982                         &env->insn_aux_data[i + delta].loop_inline_state;
18983
18984                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18985                         struct bpf_prog *new_prog;
18986
18987                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18988                         new_prog = inline_bpf_loop(env,
18989                                                    i + delta,
18990                                                    -(stack_depth + stack_depth_extra),
18991                                                    inline_state->callback_subprogno,
18992                                                    &cnt);
18993                         if (!new_prog)
18994                                 return -ENOMEM;
18995
18996                         delta     += cnt - 1;
18997                         env->prog  = new_prog;
18998                         insn       = new_prog->insnsi + i + delta;
18999                 }
19000
19001                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19002                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
19003                         cur_subprog++;
19004                         stack_depth = subprogs[cur_subprog].stack_depth;
19005                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19006                         stack_depth_extra = 0;
19007                 }
19008         }
19009
19010         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19011
19012         return 0;
19013 }
19014
19015 static void free_states(struct bpf_verifier_env *env)
19016 {
19017         struct bpf_verifier_state_list *sl, *sln;
19018         int i;
19019
19020         sl = env->free_list;
19021         while (sl) {
19022                 sln = sl->next;
19023                 free_verifier_state(&sl->state, false);
19024                 kfree(sl);
19025                 sl = sln;
19026         }
19027         env->free_list = NULL;
19028
19029         if (!env->explored_states)
19030                 return;
19031
19032         for (i = 0; i < state_htab_size(env); i++) {
19033                 sl = env->explored_states[i];
19034
19035                 while (sl) {
19036                         sln = sl->next;
19037                         free_verifier_state(&sl->state, false);
19038                         kfree(sl);
19039                         sl = sln;
19040                 }
19041                 env->explored_states[i] = NULL;
19042         }
19043 }
19044
19045 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19046 {
19047         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19048         struct bpf_verifier_state *state;
19049         struct bpf_reg_state *regs;
19050         int ret, i;
19051
19052         env->prev_linfo = NULL;
19053         env->pass_cnt++;
19054
19055         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19056         if (!state)
19057                 return -ENOMEM;
19058         state->curframe = 0;
19059         state->speculative = false;
19060         state->branches = 1;
19061         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19062         if (!state->frame[0]) {
19063                 kfree(state);
19064                 return -ENOMEM;
19065         }
19066         env->cur_state = state;
19067         init_func_state(env, state->frame[0],
19068                         BPF_MAIN_FUNC /* callsite */,
19069                         0 /* frameno */,
19070                         subprog);
19071         state->first_insn_idx = env->subprog_info[subprog].start;
19072         state->last_insn_idx = -1;
19073
19074         regs = state->frame[state->curframe]->regs;
19075         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19076                 ret = btf_prepare_func_args(env, subprog, regs);
19077                 if (ret)
19078                         goto out;
19079                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19080                         if (regs[i].type == PTR_TO_CTX)
19081                                 mark_reg_known_zero(env, regs, i);
19082                         else if (regs[i].type == SCALAR_VALUE)
19083                                 mark_reg_unknown(env, regs, i);
19084                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
19085                                 const u32 mem_size = regs[i].mem_size;
19086
19087                                 mark_reg_known_zero(env, regs, i);
19088                                 regs[i].mem_size = mem_size;
19089                                 regs[i].id = ++env->id_gen;
19090                         }
19091                 }
19092         } else {
19093                 /* 1st arg to a function */
19094                 regs[BPF_REG_1].type = PTR_TO_CTX;
19095                 mark_reg_known_zero(env, regs, BPF_REG_1);
19096                 ret = btf_check_subprog_arg_match(env, subprog, regs);
19097                 if (ret == -EFAULT)
19098                         /* unlikely verifier bug. abort.
19099                          * ret == 0 and ret < 0 are sadly acceptable for
19100                          * main() function due to backward compatibility.
19101                          * Like socket filter program may be written as:
19102                          * int bpf_prog(struct pt_regs *ctx)
19103                          * and never dereference that ctx in the program.
19104                          * 'struct pt_regs' is a type mismatch for socket
19105                          * filter that should be using 'struct __sk_buff'.
19106                          */
19107                         goto out;
19108         }
19109
19110         ret = do_check(env);
19111 out:
19112         /* check for NULL is necessary, since cur_state can be freed inside
19113          * do_check() under memory pressure.
19114          */
19115         if (env->cur_state) {
19116                 free_verifier_state(env->cur_state, true);
19117                 env->cur_state = NULL;
19118         }
19119         while (!pop_stack(env, NULL, NULL, false));
19120         if (!ret && pop_log)
19121                 bpf_vlog_reset(&env->log, 0);
19122         free_states(env);
19123         return ret;
19124 }
19125
19126 /* Verify all global functions in a BPF program one by one based on their BTF.
19127  * All global functions must pass verification. Otherwise the whole program is rejected.
19128  * Consider:
19129  * int bar(int);
19130  * int foo(int f)
19131  * {
19132  *    return bar(f);
19133  * }
19134  * int bar(int b)
19135  * {
19136  *    ...
19137  * }
19138  * foo() will be verified first for R1=any_scalar_value. During verification it
19139  * will be assumed that bar() already verified successfully and call to bar()
19140  * from foo() will be checked for type match only. Later bar() will be verified
19141  * independently to check that it's safe for R1=any_scalar_value.
19142  */
19143 static int do_check_subprogs(struct bpf_verifier_env *env)
19144 {
19145         struct bpf_prog_aux *aux = env->prog->aux;
19146         int i, ret;
19147
19148         if (!aux->func_info)
19149                 return 0;
19150
19151         for (i = 1; i < env->subprog_cnt; i++) {
19152                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19153                         continue;
19154                 env->insn_idx = env->subprog_info[i].start;
19155                 WARN_ON_ONCE(env->insn_idx == 0);
19156                 ret = do_check_common(env, i);
19157                 if (ret) {
19158                         return ret;
19159                 } else if (env->log.level & BPF_LOG_LEVEL) {
19160                         verbose(env,
19161                                 "Func#%d is safe for any args that match its prototype\n",
19162                                 i);
19163                 }
19164         }
19165         return 0;
19166 }
19167
19168 static int do_check_main(struct bpf_verifier_env *env)
19169 {
19170         int ret;
19171
19172         env->insn_idx = 0;
19173         ret = do_check_common(env, 0);
19174         if (!ret)
19175                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19176         return ret;
19177 }
19178
19179
19180 static void print_verification_stats(struct bpf_verifier_env *env)
19181 {
19182         int i;
19183
19184         if (env->log.level & BPF_LOG_STATS) {
19185                 verbose(env, "verification time %lld usec\n",
19186                         div_u64(env->verification_time, 1000));
19187                 verbose(env, "stack depth ");
19188                 for (i = 0; i < env->subprog_cnt; i++) {
19189                         u32 depth = env->subprog_info[i].stack_depth;
19190
19191                         verbose(env, "%d", depth);
19192                         if (i + 1 < env->subprog_cnt)
19193                                 verbose(env, "+");
19194                 }
19195                 verbose(env, "\n");
19196         }
19197         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19198                 "total_states %d peak_states %d mark_read %d\n",
19199                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19200                 env->max_states_per_insn, env->total_states,
19201                 env->peak_states, env->longest_mark_read_walk);
19202 }
19203
19204 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19205 {
19206         const struct btf_type *t, *func_proto;
19207         const struct bpf_struct_ops *st_ops;
19208         const struct btf_member *member;
19209         struct bpf_prog *prog = env->prog;
19210         u32 btf_id, member_idx;
19211         const char *mname;
19212
19213         if (!prog->gpl_compatible) {
19214                 verbose(env, "struct ops programs must have a GPL compatible license\n");
19215                 return -EINVAL;
19216         }
19217
19218         btf_id = prog->aux->attach_btf_id;
19219         st_ops = bpf_struct_ops_find(btf_id);
19220         if (!st_ops) {
19221                 verbose(env, "attach_btf_id %u is not a supported struct\n",
19222                         btf_id);
19223                 return -ENOTSUPP;
19224         }
19225
19226         t = st_ops->type;
19227         member_idx = prog->expected_attach_type;
19228         if (member_idx >= btf_type_vlen(t)) {
19229                 verbose(env, "attach to invalid member idx %u of struct %s\n",
19230                         member_idx, st_ops->name);
19231                 return -EINVAL;
19232         }
19233
19234         member = &btf_type_member(t)[member_idx];
19235         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19236         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19237                                                NULL);
19238         if (!func_proto) {
19239                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19240                         mname, member_idx, st_ops->name);
19241                 return -EINVAL;
19242         }
19243
19244         if (st_ops->check_member) {
19245                 int err = st_ops->check_member(t, member, prog);
19246
19247                 if (err) {
19248                         verbose(env, "attach to unsupported member %s of struct %s\n",
19249                                 mname, st_ops->name);
19250                         return err;
19251                 }
19252         }
19253
19254         prog->aux->attach_func_proto = func_proto;
19255         prog->aux->attach_func_name = mname;
19256         env->ops = st_ops->verifier_ops;
19257
19258         return 0;
19259 }
19260 #define SECURITY_PREFIX "security_"
19261
19262 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19263 {
19264         if (within_error_injection_list(addr) ||
19265             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19266                 return 0;
19267
19268         return -EINVAL;
19269 }
19270
19271 /* list of non-sleepable functions that are otherwise on
19272  * ALLOW_ERROR_INJECTION list
19273  */
19274 BTF_SET_START(btf_non_sleepable_error_inject)
19275 /* Three functions below can be called from sleepable and non-sleepable context.
19276  * Assume non-sleepable from bpf safety point of view.
19277  */
19278 BTF_ID(func, __filemap_add_folio)
19279 BTF_ID(func, should_fail_alloc_page)
19280 BTF_ID(func, should_failslab)
19281 BTF_SET_END(btf_non_sleepable_error_inject)
19282
19283 static int check_non_sleepable_error_inject(u32 btf_id)
19284 {
19285         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19286 }
19287
19288 int bpf_check_attach_target(struct bpf_verifier_log *log,
19289                             const struct bpf_prog *prog,
19290                             const struct bpf_prog *tgt_prog,
19291                             u32 btf_id,
19292                             struct bpf_attach_target_info *tgt_info)
19293 {
19294         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19295         const char prefix[] = "btf_trace_";
19296         int ret = 0, subprog = -1, i;
19297         const struct btf_type *t;
19298         bool conservative = true;
19299         const char *tname;
19300         struct btf *btf;
19301         long addr = 0;
19302         struct module *mod = NULL;
19303
19304         if (!btf_id) {
19305                 bpf_log(log, "Tracing programs must provide btf_id\n");
19306                 return -EINVAL;
19307         }
19308         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19309         if (!btf) {
19310                 bpf_log(log,
19311                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19312                 return -EINVAL;
19313         }
19314         t = btf_type_by_id(btf, btf_id);
19315         if (!t) {
19316                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19317                 return -EINVAL;
19318         }
19319         tname = btf_name_by_offset(btf, t->name_off);
19320         if (!tname) {
19321                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19322                 return -EINVAL;
19323         }
19324         if (tgt_prog) {
19325                 struct bpf_prog_aux *aux = tgt_prog->aux;
19326
19327                 if (bpf_prog_is_dev_bound(prog->aux) &&
19328                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19329                         bpf_log(log, "Target program bound device mismatch");
19330                         return -EINVAL;
19331                 }
19332
19333                 for (i = 0; i < aux->func_info_cnt; i++)
19334                         if (aux->func_info[i].type_id == btf_id) {
19335                                 subprog = i;
19336                                 break;
19337                         }
19338                 if (subprog == -1) {
19339                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
19340                         return -EINVAL;
19341                 }
19342                 conservative = aux->func_info_aux[subprog].unreliable;
19343                 if (prog_extension) {
19344                         if (conservative) {
19345                                 bpf_log(log,
19346                                         "Cannot replace static functions\n");
19347                                 return -EINVAL;
19348                         }
19349                         if (!prog->jit_requested) {
19350                                 bpf_log(log,
19351                                         "Extension programs should be JITed\n");
19352                                 return -EINVAL;
19353                         }
19354                 }
19355                 if (!tgt_prog->jited) {
19356                         bpf_log(log, "Can attach to only JITed progs\n");
19357                         return -EINVAL;
19358                 }
19359                 if (tgt_prog->type == prog->type) {
19360                         /* Cannot fentry/fexit another fentry/fexit program.
19361                          * Cannot attach program extension to another extension.
19362                          * It's ok to attach fentry/fexit to extension program.
19363                          */
19364                         bpf_log(log, "Cannot recursively attach\n");
19365                         return -EINVAL;
19366                 }
19367                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19368                     prog_extension &&
19369                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19370                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19371                         /* Program extensions can extend all program types
19372                          * except fentry/fexit. The reason is the following.
19373                          * The fentry/fexit programs are used for performance
19374                          * analysis, stats and can be attached to any program
19375                          * type except themselves. When extension program is
19376                          * replacing XDP function it is necessary to allow
19377                          * performance analysis of all functions. Both original
19378                          * XDP program and its program extension. Hence
19379                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19380                          * allowed. If extending of fentry/fexit was allowed it
19381                          * would be possible to create long call chain
19382                          * fentry->extension->fentry->extension beyond
19383                          * reasonable stack size. Hence extending fentry is not
19384                          * allowed.
19385                          */
19386                         bpf_log(log, "Cannot extend fentry/fexit\n");
19387                         return -EINVAL;
19388                 }
19389         } else {
19390                 if (prog_extension) {
19391                         bpf_log(log, "Cannot replace kernel functions\n");
19392                         return -EINVAL;
19393                 }
19394         }
19395
19396         switch (prog->expected_attach_type) {
19397         case BPF_TRACE_RAW_TP:
19398                 if (tgt_prog) {
19399                         bpf_log(log,
19400                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19401                         return -EINVAL;
19402                 }
19403                 if (!btf_type_is_typedef(t)) {
19404                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
19405                                 btf_id);
19406                         return -EINVAL;
19407                 }
19408                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19409                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19410                                 btf_id, tname);
19411                         return -EINVAL;
19412                 }
19413                 tname += sizeof(prefix) - 1;
19414                 t = btf_type_by_id(btf, t->type);
19415                 if (!btf_type_is_ptr(t))
19416                         /* should never happen in valid vmlinux build */
19417                         return -EINVAL;
19418                 t = btf_type_by_id(btf, t->type);
19419                 if (!btf_type_is_func_proto(t))
19420                         /* should never happen in valid vmlinux build */
19421                         return -EINVAL;
19422
19423                 break;
19424         case BPF_TRACE_ITER:
19425                 if (!btf_type_is_func(t)) {
19426                         bpf_log(log, "attach_btf_id %u is not a function\n",
19427                                 btf_id);
19428                         return -EINVAL;
19429                 }
19430                 t = btf_type_by_id(btf, t->type);
19431                 if (!btf_type_is_func_proto(t))
19432                         return -EINVAL;
19433                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19434                 if (ret)
19435                         return ret;
19436                 break;
19437         default:
19438                 if (!prog_extension)
19439                         return -EINVAL;
19440                 fallthrough;
19441         case BPF_MODIFY_RETURN:
19442         case BPF_LSM_MAC:
19443         case BPF_LSM_CGROUP:
19444         case BPF_TRACE_FENTRY:
19445         case BPF_TRACE_FEXIT:
19446                 if (!btf_type_is_func(t)) {
19447                         bpf_log(log, "attach_btf_id %u is not a function\n",
19448                                 btf_id);
19449                         return -EINVAL;
19450                 }
19451                 if (prog_extension &&
19452                     btf_check_type_match(log, prog, btf, t))
19453                         return -EINVAL;
19454                 t = btf_type_by_id(btf, t->type);
19455                 if (!btf_type_is_func_proto(t))
19456                         return -EINVAL;
19457
19458                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19459                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19460                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19461                         return -EINVAL;
19462
19463                 if (tgt_prog && conservative)
19464                         t = NULL;
19465
19466                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19467                 if (ret < 0)
19468                         return ret;
19469
19470                 if (tgt_prog) {
19471                         if (subprog == 0)
19472                                 addr = (long) tgt_prog->bpf_func;
19473                         else
19474                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19475                 } else {
19476                         if (btf_is_module(btf)) {
19477                                 mod = btf_try_get_module(btf);
19478                                 if (mod)
19479                                         addr = find_kallsyms_symbol_value(mod, tname);
19480                                 else
19481                                         addr = 0;
19482                         } else {
19483                                 addr = kallsyms_lookup_name(tname);
19484                         }
19485                         if (!addr) {
19486                                 module_put(mod);
19487                                 bpf_log(log,
19488                                         "The address of function %s cannot be found\n",
19489                                         tname);
19490                                 return -ENOENT;
19491                         }
19492                 }
19493
19494                 if (prog->aux->sleepable) {
19495                         ret = -EINVAL;
19496                         switch (prog->type) {
19497                         case BPF_PROG_TYPE_TRACING:
19498
19499                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19500                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19501                                  */
19502                                 if (!check_non_sleepable_error_inject(btf_id) &&
19503                                     within_error_injection_list(addr))
19504                                         ret = 0;
19505                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19506                                  * in the fmodret id set with the KF_SLEEPABLE flag.
19507                                  */
19508                                 else {
19509                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19510                                                                                 prog);
19511
19512                                         if (flags && (*flags & KF_SLEEPABLE))
19513                                                 ret = 0;
19514                                 }
19515                                 break;
19516                         case BPF_PROG_TYPE_LSM:
19517                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19518                                  * Only some of them are sleepable.
19519                                  */
19520                                 if (bpf_lsm_is_sleepable_hook(btf_id))
19521                                         ret = 0;
19522                                 break;
19523                         default:
19524                                 break;
19525                         }
19526                         if (ret) {
19527                                 module_put(mod);
19528                                 bpf_log(log, "%s is not sleepable\n", tname);
19529                                 return ret;
19530                         }
19531                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19532                         if (tgt_prog) {
19533                                 module_put(mod);
19534                                 bpf_log(log, "can't modify return codes of BPF programs\n");
19535                                 return -EINVAL;
19536                         }
19537                         ret = -EINVAL;
19538                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19539                             !check_attach_modify_return(addr, tname))
19540                                 ret = 0;
19541                         if (ret) {
19542                                 module_put(mod);
19543                                 bpf_log(log, "%s() is not modifiable\n", tname);
19544                                 return ret;
19545                         }
19546                 }
19547
19548                 break;
19549         }
19550         tgt_info->tgt_addr = addr;
19551         tgt_info->tgt_name = tname;
19552         tgt_info->tgt_type = t;
19553         tgt_info->tgt_mod = mod;
19554         return 0;
19555 }
19556
19557 BTF_SET_START(btf_id_deny)
19558 BTF_ID_UNUSED
19559 #ifdef CONFIG_SMP
19560 BTF_ID(func, migrate_disable)
19561 BTF_ID(func, migrate_enable)
19562 #endif
19563 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19564 BTF_ID(func, rcu_read_unlock_strict)
19565 #endif
19566 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19567 BTF_ID(func, preempt_count_add)
19568 BTF_ID(func, preempt_count_sub)
19569 #endif
19570 #ifdef CONFIG_PREEMPT_RCU
19571 BTF_ID(func, __rcu_read_lock)
19572 BTF_ID(func, __rcu_read_unlock)
19573 #endif
19574 BTF_SET_END(btf_id_deny)
19575
19576 static bool can_be_sleepable(struct bpf_prog *prog)
19577 {
19578         if (prog->type == BPF_PROG_TYPE_TRACING) {
19579                 switch (prog->expected_attach_type) {
19580                 case BPF_TRACE_FENTRY:
19581                 case BPF_TRACE_FEXIT:
19582                 case BPF_MODIFY_RETURN:
19583                 case BPF_TRACE_ITER:
19584                         return true;
19585                 default:
19586                         return false;
19587                 }
19588         }
19589         return prog->type == BPF_PROG_TYPE_LSM ||
19590                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19591                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19592 }
19593
19594 static int check_attach_btf_id(struct bpf_verifier_env *env)
19595 {
19596         struct bpf_prog *prog = env->prog;
19597         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19598         struct bpf_attach_target_info tgt_info = {};
19599         u32 btf_id = prog->aux->attach_btf_id;
19600         struct bpf_trampoline *tr;
19601         int ret;
19602         u64 key;
19603
19604         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19605                 if (prog->aux->sleepable)
19606                         /* attach_btf_id checked to be zero already */
19607                         return 0;
19608                 verbose(env, "Syscall programs can only be sleepable\n");
19609                 return -EINVAL;
19610         }
19611
19612         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19613                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19614                 return -EINVAL;
19615         }
19616
19617         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19618                 return check_struct_ops_btf_id(env);
19619
19620         if (prog->type != BPF_PROG_TYPE_TRACING &&
19621             prog->type != BPF_PROG_TYPE_LSM &&
19622             prog->type != BPF_PROG_TYPE_EXT)
19623                 return 0;
19624
19625         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19626         if (ret)
19627                 return ret;
19628
19629         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19630                 /* to make freplace equivalent to their targets, they need to
19631                  * inherit env->ops and expected_attach_type for the rest of the
19632                  * verification
19633                  */
19634                 env->ops = bpf_verifier_ops[tgt_prog->type];
19635                 prog->expected_attach_type = tgt_prog->expected_attach_type;
19636         }
19637
19638         /* store info about the attachment target that will be used later */
19639         prog->aux->attach_func_proto = tgt_info.tgt_type;
19640         prog->aux->attach_func_name = tgt_info.tgt_name;
19641         prog->aux->mod = tgt_info.tgt_mod;
19642
19643         if (tgt_prog) {
19644                 prog->aux->saved_dst_prog_type = tgt_prog->type;
19645                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19646         }
19647
19648         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19649                 prog->aux->attach_btf_trace = true;
19650                 return 0;
19651         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19652                 if (!bpf_iter_prog_supported(prog))
19653                         return -EINVAL;
19654                 return 0;
19655         }
19656
19657         if (prog->type == BPF_PROG_TYPE_LSM) {
19658                 ret = bpf_lsm_verify_prog(&env->log, prog);
19659                 if (ret < 0)
19660                         return ret;
19661         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19662                    btf_id_set_contains(&btf_id_deny, btf_id)) {
19663                 return -EINVAL;
19664         }
19665
19666         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19667         tr = bpf_trampoline_get(key, &tgt_info);
19668         if (!tr)
19669                 return -ENOMEM;
19670
19671         if (tgt_prog && tgt_prog->aux->tail_call_reachable)
19672                 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
19673
19674         prog->aux->dst_trampoline = tr;
19675         return 0;
19676 }
19677
19678 struct btf *bpf_get_btf_vmlinux(void)
19679 {
19680         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19681                 mutex_lock(&bpf_verifier_lock);
19682                 if (!btf_vmlinux)
19683                         btf_vmlinux = btf_parse_vmlinux();
19684                 mutex_unlock(&bpf_verifier_lock);
19685         }
19686         return btf_vmlinux;
19687 }
19688
19689 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19690 {
19691         u64 start_time = ktime_get_ns();
19692         struct bpf_verifier_env *env;
19693         int i, len, ret = -EINVAL, err;
19694         u32 log_true_size;
19695         bool is_priv;
19696
19697         /* no program is valid */
19698         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19699                 return -EINVAL;
19700
19701         /* 'struct bpf_verifier_env' can be global, but since it's not small,
19702          * allocate/free it every time bpf_check() is called
19703          */
19704         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19705         if (!env)
19706                 return -ENOMEM;
19707
19708         env->bt.env = env;
19709
19710         len = (*prog)->len;
19711         env->insn_aux_data =
19712                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19713         ret = -ENOMEM;
19714         if (!env->insn_aux_data)
19715                 goto err_free_env;
19716         for (i = 0; i < len; i++)
19717                 env->insn_aux_data[i].orig_idx = i;
19718         env->prog = *prog;
19719         env->ops = bpf_verifier_ops[env->prog->type];
19720         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19721         is_priv = bpf_capable();
19722
19723         bpf_get_btf_vmlinux();
19724
19725         /* grab the mutex to protect few globals used by verifier */
19726         if (!is_priv)
19727                 mutex_lock(&bpf_verifier_lock);
19728
19729         /* user could have requested verbose verifier output
19730          * and supplied buffer to store the verification trace
19731          */
19732         ret = bpf_vlog_init(&env->log, attr->log_level,
19733                             (char __user *) (unsigned long) attr->log_buf,
19734                             attr->log_size);
19735         if (ret)
19736                 goto err_unlock;
19737
19738         mark_verifier_state_clean(env);
19739
19740         if (IS_ERR(btf_vmlinux)) {
19741                 /* Either gcc or pahole or kernel are broken. */
19742                 verbose(env, "in-kernel BTF is malformed\n");
19743                 ret = PTR_ERR(btf_vmlinux);
19744                 goto skip_full_check;
19745         }
19746
19747         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19748         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19749                 env->strict_alignment = true;
19750         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19751                 env->strict_alignment = false;
19752
19753         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19754         env->allow_uninit_stack = bpf_allow_uninit_stack();
19755         env->bypass_spec_v1 = bpf_bypass_spec_v1();
19756         env->bypass_spec_v4 = bpf_bypass_spec_v4();
19757         env->bpf_capable = bpf_capable();
19758
19759         if (is_priv)
19760                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19761
19762         env->explored_states = kvcalloc(state_htab_size(env),
19763                                        sizeof(struct bpf_verifier_state_list *),
19764                                        GFP_USER);
19765         ret = -ENOMEM;
19766         if (!env->explored_states)
19767                 goto skip_full_check;
19768
19769         ret = add_subprog_and_kfunc(env);
19770         if (ret < 0)
19771                 goto skip_full_check;
19772
19773         ret = check_subprogs(env);
19774         if (ret < 0)
19775                 goto skip_full_check;
19776
19777         ret = check_btf_info(env, attr, uattr);
19778         if (ret < 0)
19779                 goto skip_full_check;
19780
19781         ret = check_attach_btf_id(env);
19782         if (ret)
19783                 goto skip_full_check;
19784
19785         ret = resolve_pseudo_ldimm64(env);
19786         if (ret < 0)
19787                 goto skip_full_check;
19788
19789         if (bpf_prog_is_offloaded(env->prog->aux)) {
19790                 ret = bpf_prog_offload_verifier_prep(env->prog);
19791                 if (ret)
19792                         goto skip_full_check;
19793         }
19794
19795         ret = check_cfg(env);
19796         if (ret < 0)
19797                 goto skip_full_check;
19798
19799         ret = do_check_subprogs(env);
19800         ret = ret ?: do_check_main(env);
19801
19802         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19803                 ret = bpf_prog_offload_finalize(env);
19804
19805 skip_full_check:
19806         kvfree(env->explored_states);
19807
19808         if (ret == 0)
19809                 ret = check_max_stack_depth(env);
19810
19811         /* instruction rewrites happen after this point */
19812         if (ret == 0)
19813                 ret = optimize_bpf_loop(env);
19814
19815         if (is_priv) {
19816                 if (ret == 0)
19817                         opt_hard_wire_dead_code_branches(env);
19818                 if (ret == 0)
19819                         ret = opt_remove_dead_code(env);
19820                 if (ret == 0)
19821                         ret = opt_remove_nops(env);
19822         } else {
19823                 if (ret == 0)
19824                         sanitize_dead_code(env);
19825         }
19826
19827         if (ret == 0)
19828                 /* program is valid, convert *(u32*)(ctx + off) accesses */
19829                 ret = convert_ctx_accesses(env);
19830
19831         if (ret == 0)
19832                 ret = do_misc_fixups(env);
19833
19834         /* do 32-bit optimization after insn patching has done so those patched
19835          * insns could be handled correctly.
19836          */
19837         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19838                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19839                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19840                                                                      : false;
19841         }
19842
19843         if (ret == 0)
19844                 ret = fixup_call_args(env);
19845
19846         env->verification_time = ktime_get_ns() - start_time;
19847         print_verification_stats(env);
19848         env->prog->aux->verified_insns = env->insn_processed;
19849
19850         /* preserve original error even if log finalization is successful */
19851         err = bpf_vlog_finalize(&env->log, &log_true_size);
19852         if (err)
19853                 ret = err;
19854
19855         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19856             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19857                                   &log_true_size, sizeof(log_true_size))) {
19858                 ret = -EFAULT;
19859                 goto err_release_maps;
19860         }
19861
19862         if (ret)
19863                 goto err_release_maps;
19864
19865         if (env->used_map_cnt) {
19866                 /* if program passed verifier, update used_maps in bpf_prog_info */
19867                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19868                                                           sizeof(env->used_maps[0]),
19869                                                           GFP_KERNEL);
19870
19871                 if (!env->prog->aux->used_maps) {
19872                         ret = -ENOMEM;
19873                         goto err_release_maps;
19874                 }
19875
19876                 memcpy(env->prog->aux->used_maps, env->used_maps,
19877                        sizeof(env->used_maps[0]) * env->used_map_cnt);
19878                 env->prog->aux->used_map_cnt = env->used_map_cnt;
19879         }
19880         if (env->used_btf_cnt) {
19881                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19882                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19883                                                           sizeof(env->used_btfs[0]),
19884                                                           GFP_KERNEL);
19885                 if (!env->prog->aux->used_btfs) {
19886                         ret = -ENOMEM;
19887                         goto err_release_maps;
19888                 }
19889
19890                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19891                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19892                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19893         }
19894         if (env->used_map_cnt || env->used_btf_cnt) {
19895                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19896                  * bpf_ld_imm64 instructions
19897                  */
19898                 convert_pseudo_ld_imm64(env);
19899         }
19900
19901         adjust_btf_func(env);
19902
19903 err_release_maps:
19904         if (!env->prog->aux->used_maps)
19905                 /* if we didn't copy map pointers into bpf_prog_info, release
19906                  * them now. Otherwise free_used_maps() will release them.
19907                  */
19908                 release_maps(env);
19909         if (!env->prog->aux->used_btfs)
19910                 release_btfs(env);
19911
19912         /* extension progs temporarily inherit the attach_type of their targets
19913            for verification purposes, so set it back to zero before returning
19914          */
19915         if (env->prog->type == BPF_PROG_TYPE_EXT)
19916                 env->prog->expected_attach_type = 0;
19917
19918         *prog = env->prog;
19919 err_unlock:
19920         if (!is_priv)
19921                 mutex_unlock(&bpf_verifier_lock);
19922         vfree(env->insn_aux_data);
19923 err_free_env:
19924         kfree(env);
19925         return ret;
19926 }