bpf: fix control-flow graph checking in privileged mode
[platform/kernel/linux-rpi.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 static int grow_stack_state(struct bpf_func_state *state, int size)
1636 {
1637         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1638
1639         if (old_n >= n)
1640                 return 0;
1641
1642         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1643         if (!state->stack)
1644                 return -ENOMEM;
1645
1646         state->allocated_stack = size;
1647         return 0;
1648 }
1649
1650 /* Acquire a pointer id from the env and update the state->refs to include
1651  * this new pointer reference.
1652  * On success, returns a valid pointer id to associate with the register
1653  * On failure, returns a negative errno.
1654  */
1655 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1656 {
1657         struct bpf_func_state *state = cur_func(env);
1658         int new_ofs = state->acquired_refs;
1659         int id, err;
1660
1661         err = resize_reference_state(state, state->acquired_refs + 1);
1662         if (err)
1663                 return err;
1664         id = ++env->id_gen;
1665         state->refs[new_ofs].id = id;
1666         state->refs[new_ofs].insn_idx = insn_idx;
1667         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1668
1669         return id;
1670 }
1671
1672 /* release function corresponding to acquire_reference_state(). Idempotent. */
1673 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1674 {
1675         int i, last_idx;
1676
1677         last_idx = state->acquired_refs - 1;
1678         for (i = 0; i < state->acquired_refs; i++) {
1679                 if (state->refs[i].id == ptr_id) {
1680                         /* Cannot release caller references in callbacks */
1681                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1682                                 return -EINVAL;
1683                         if (last_idx && i != last_idx)
1684                                 memcpy(&state->refs[i], &state->refs[last_idx],
1685                                        sizeof(*state->refs));
1686                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1687                         state->acquired_refs--;
1688                         return 0;
1689                 }
1690         }
1691         return -EINVAL;
1692 }
1693
1694 static void free_func_state(struct bpf_func_state *state)
1695 {
1696         if (!state)
1697                 return;
1698         kfree(state->refs);
1699         kfree(state->stack);
1700         kfree(state);
1701 }
1702
1703 static void clear_jmp_history(struct bpf_verifier_state *state)
1704 {
1705         kfree(state->jmp_history);
1706         state->jmp_history = NULL;
1707         state->jmp_history_cnt = 0;
1708 }
1709
1710 static void free_verifier_state(struct bpf_verifier_state *state,
1711                                 bool free_self)
1712 {
1713         int i;
1714
1715         for (i = 0; i <= state->curframe; i++) {
1716                 free_func_state(state->frame[i]);
1717                 state->frame[i] = NULL;
1718         }
1719         clear_jmp_history(state);
1720         if (free_self)
1721                 kfree(state);
1722 }
1723
1724 /* copy verifier state from src to dst growing dst stack space
1725  * when necessary to accommodate larger src stack
1726  */
1727 static int copy_func_state(struct bpf_func_state *dst,
1728                            const struct bpf_func_state *src)
1729 {
1730         int err;
1731
1732         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1733         err = copy_reference_state(dst, src);
1734         if (err)
1735                 return err;
1736         return copy_stack_state(dst, src);
1737 }
1738
1739 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1740                                const struct bpf_verifier_state *src)
1741 {
1742         struct bpf_func_state *dst;
1743         int i, err;
1744
1745         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1746                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1747                                             GFP_USER);
1748         if (!dst_state->jmp_history)
1749                 return -ENOMEM;
1750         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1751
1752         /* if dst has more stack frames then src frame, free them */
1753         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1754                 free_func_state(dst_state->frame[i]);
1755                 dst_state->frame[i] = NULL;
1756         }
1757         dst_state->speculative = src->speculative;
1758         dst_state->active_rcu_lock = src->active_rcu_lock;
1759         dst_state->curframe = src->curframe;
1760         dst_state->active_lock.ptr = src->active_lock.ptr;
1761         dst_state->active_lock.id = src->active_lock.id;
1762         dst_state->branches = src->branches;
1763         dst_state->parent = src->parent;
1764         dst_state->first_insn_idx = src->first_insn_idx;
1765         dst_state->last_insn_idx = src->last_insn_idx;
1766         for (i = 0; i <= src->curframe; i++) {
1767                 dst = dst_state->frame[i];
1768                 if (!dst) {
1769                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1770                         if (!dst)
1771                                 return -ENOMEM;
1772                         dst_state->frame[i] = dst;
1773                 }
1774                 err = copy_func_state(dst, src->frame[i]);
1775                 if (err)
1776                         return err;
1777         }
1778         return 0;
1779 }
1780
1781 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1782 {
1783         while (st) {
1784                 u32 br = --st->branches;
1785
1786                 /* WARN_ON(br > 1) technically makes sense here,
1787                  * but see comment in push_stack(), hence:
1788                  */
1789                 WARN_ONCE((int)br < 0,
1790                           "BUG update_branch_counts:branches_to_explore=%d\n",
1791                           br);
1792                 if (br)
1793                         break;
1794                 st = st->parent;
1795         }
1796 }
1797
1798 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1799                      int *insn_idx, bool pop_log)
1800 {
1801         struct bpf_verifier_state *cur = env->cur_state;
1802         struct bpf_verifier_stack_elem *elem, *head = env->head;
1803         int err;
1804
1805         if (env->head == NULL)
1806                 return -ENOENT;
1807
1808         if (cur) {
1809                 err = copy_verifier_state(cur, &head->st);
1810                 if (err)
1811                         return err;
1812         }
1813         if (pop_log)
1814                 bpf_vlog_reset(&env->log, head->log_pos);
1815         if (insn_idx)
1816                 *insn_idx = head->insn_idx;
1817         if (prev_insn_idx)
1818                 *prev_insn_idx = head->prev_insn_idx;
1819         elem = head->next;
1820         free_verifier_state(&head->st, false);
1821         kfree(head);
1822         env->head = elem;
1823         env->stack_size--;
1824         return 0;
1825 }
1826
1827 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1828                                              int insn_idx, int prev_insn_idx,
1829                                              bool speculative)
1830 {
1831         struct bpf_verifier_state *cur = env->cur_state;
1832         struct bpf_verifier_stack_elem *elem;
1833         int err;
1834
1835         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1836         if (!elem)
1837                 goto err;
1838
1839         elem->insn_idx = insn_idx;
1840         elem->prev_insn_idx = prev_insn_idx;
1841         elem->next = env->head;
1842         elem->log_pos = env->log.end_pos;
1843         env->head = elem;
1844         env->stack_size++;
1845         err = copy_verifier_state(&elem->st, cur);
1846         if (err)
1847                 goto err;
1848         elem->st.speculative |= speculative;
1849         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1850                 verbose(env, "The sequence of %d jumps is too complex.\n",
1851                         env->stack_size);
1852                 goto err;
1853         }
1854         if (elem->st.parent) {
1855                 ++elem->st.parent->branches;
1856                 /* WARN_ON(branches > 2) technically makes sense here,
1857                  * but
1858                  * 1. speculative states will bump 'branches' for non-branch
1859                  * instructions
1860                  * 2. is_state_visited() heuristics may decide not to create
1861                  * a new state for a sequence of branches and all such current
1862                  * and cloned states will be pointing to a single parent state
1863                  * which might have large 'branches' count.
1864                  */
1865         }
1866         return &elem->st;
1867 err:
1868         free_verifier_state(env->cur_state, true);
1869         env->cur_state = NULL;
1870         /* pop all elements and return */
1871         while (!pop_stack(env, NULL, NULL, false));
1872         return NULL;
1873 }
1874
1875 #define CALLER_SAVED_REGS 6
1876 static const int caller_saved[CALLER_SAVED_REGS] = {
1877         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1878 };
1879
1880 /* This helper doesn't clear reg->id */
1881 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1882 {
1883         reg->var_off = tnum_const(imm);
1884         reg->smin_value = (s64)imm;
1885         reg->smax_value = (s64)imm;
1886         reg->umin_value = imm;
1887         reg->umax_value = imm;
1888
1889         reg->s32_min_value = (s32)imm;
1890         reg->s32_max_value = (s32)imm;
1891         reg->u32_min_value = (u32)imm;
1892         reg->u32_max_value = (u32)imm;
1893 }
1894
1895 /* Mark the unknown part of a register (variable offset or scalar value) as
1896  * known to have the value @imm.
1897  */
1898 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1899 {
1900         /* Clear off and union(map_ptr, range) */
1901         memset(((u8 *)reg) + sizeof(reg->type), 0,
1902                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1903         reg->id = 0;
1904         reg->ref_obj_id = 0;
1905         ___mark_reg_known(reg, imm);
1906 }
1907
1908 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1909 {
1910         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1911         reg->s32_min_value = (s32)imm;
1912         reg->s32_max_value = (s32)imm;
1913         reg->u32_min_value = (u32)imm;
1914         reg->u32_max_value = (u32)imm;
1915 }
1916
1917 /* Mark the 'variable offset' part of a register as zero.  This should be
1918  * used only on registers holding a pointer type.
1919  */
1920 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1921 {
1922         __mark_reg_known(reg, 0);
1923 }
1924
1925 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1926 {
1927         __mark_reg_known(reg, 0);
1928         reg->type = SCALAR_VALUE;
1929 }
1930
1931 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1932                                 struct bpf_reg_state *regs, u32 regno)
1933 {
1934         if (WARN_ON(regno >= MAX_BPF_REG)) {
1935                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1936                 /* Something bad happened, let's kill all regs */
1937                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1938                         __mark_reg_not_init(env, regs + regno);
1939                 return;
1940         }
1941         __mark_reg_known_zero(regs + regno);
1942 }
1943
1944 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1945                               bool first_slot, int dynptr_id)
1946 {
1947         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1948          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1949          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1950          */
1951         __mark_reg_known_zero(reg);
1952         reg->type = CONST_PTR_TO_DYNPTR;
1953         /* Give each dynptr a unique id to uniquely associate slices to it. */
1954         reg->id = dynptr_id;
1955         reg->dynptr.type = type;
1956         reg->dynptr.first_slot = first_slot;
1957 }
1958
1959 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1960 {
1961         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1962                 const struct bpf_map *map = reg->map_ptr;
1963
1964                 if (map->inner_map_meta) {
1965                         reg->type = CONST_PTR_TO_MAP;
1966                         reg->map_ptr = map->inner_map_meta;
1967                         /* transfer reg's id which is unique for every map_lookup_elem
1968                          * as UID of the inner map.
1969                          */
1970                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1971                                 reg->map_uid = reg->id;
1972                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1973                         reg->type = PTR_TO_XDP_SOCK;
1974                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1975                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1976                         reg->type = PTR_TO_SOCKET;
1977                 } else {
1978                         reg->type = PTR_TO_MAP_VALUE;
1979                 }
1980                 return;
1981         }
1982
1983         reg->type &= ~PTR_MAYBE_NULL;
1984 }
1985
1986 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1987                                 struct btf_field_graph_root *ds_head)
1988 {
1989         __mark_reg_known_zero(&regs[regno]);
1990         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1991         regs[regno].btf = ds_head->btf;
1992         regs[regno].btf_id = ds_head->value_btf_id;
1993         regs[regno].off = ds_head->node_offset;
1994 }
1995
1996 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1997 {
1998         return type_is_pkt_pointer(reg->type);
1999 }
2000
2001 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2002 {
2003         return reg_is_pkt_pointer(reg) ||
2004                reg->type == PTR_TO_PACKET_END;
2005 }
2006
2007 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2008 {
2009         return base_type(reg->type) == PTR_TO_MEM &&
2010                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2011 }
2012
2013 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2014 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2015                                     enum bpf_reg_type which)
2016 {
2017         /* The register can already have a range from prior markings.
2018          * This is fine as long as it hasn't been advanced from its
2019          * origin.
2020          */
2021         return reg->type == which &&
2022                reg->id == 0 &&
2023                reg->off == 0 &&
2024                tnum_equals_const(reg->var_off, 0);
2025 }
2026
2027 /* Reset the min/max bounds of a register */
2028 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2029 {
2030         reg->smin_value = S64_MIN;
2031         reg->smax_value = S64_MAX;
2032         reg->umin_value = 0;
2033         reg->umax_value = U64_MAX;
2034
2035         reg->s32_min_value = S32_MIN;
2036         reg->s32_max_value = S32_MAX;
2037         reg->u32_min_value = 0;
2038         reg->u32_max_value = U32_MAX;
2039 }
2040
2041 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2042 {
2043         reg->smin_value = S64_MIN;
2044         reg->smax_value = S64_MAX;
2045         reg->umin_value = 0;
2046         reg->umax_value = U64_MAX;
2047 }
2048
2049 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2050 {
2051         reg->s32_min_value = S32_MIN;
2052         reg->s32_max_value = S32_MAX;
2053         reg->u32_min_value = 0;
2054         reg->u32_max_value = U32_MAX;
2055 }
2056
2057 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2058 {
2059         struct tnum var32_off = tnum_subreg(reg->var_off);
2060
2061         /* min signed is max(sign bit) | min(other bits) */
2062         reg->s32_min_value = max_t(s32, reg->s32_min_value,
2063                         var32_off.value | (var32_off.mask & S32_MIN));
2064         /* max signed is min(sign bit) | max(other bits) */
2065         reg->s32_max_value = min_t(s32, reg->s32_max_value,
2066                         var32_off.value | (var32_off.mask & S32_MAX));
2067         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2068         reg->u32_max_value = min(reg->u32_max_value,
2069                                  (u32)(var32_off.value | var32_off.mask));
2070 }
2071
2072 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2073 {
2074         /* min signed is max(sign bit) | min(other bits) */
2075         reg->smin_value = max_t(s64, reg->smin_value,
2076                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2077         /* max signed is min(sign bit) | max(other bits) */
2078         reg->smax_value = min_t(s64, reg->smax_value,
2079                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2080         reg->umin_value = max(reg->umin_value, reg->var_off.value);
2081         reg->umax_value = min(reg->umax_value,
2082                               reg->var_off.value | reg->var_off.mask);
2083 }
2084
2085 static void __update_reg_bounds(struct bpf_reg_state *reg)
2086 {
2087         __update_reg32_bounds(reg);
2088         __update_reg64_bounds(reg);
2089 }
2090
2091 /* Uses signed min/max values to inform unsigned, and vice-versa */
2092 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2093 {
2094         /* Learn sign from signed bounds.
2095          * If we cannot cross the sign boundary, then signed and unsigned bounds
2096          * are the same, so combine.  This works even in the negative case, e.g.
2097          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2098          */
2099         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2100                 reg->s32_min_value = reg->u32_min_value =
2101                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2102                 reg->s32_max_value = reg->u32_max_value =
2103                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2104                 return;
2105         }
2106         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2107          * boundary, so we must be careful.
2108          */
2109         if ((s32)reg->u32_max_value >= 0) {
2110                 /* Positive.  We can't learn anything from the smin, but smax
2111                  * is positive, hence safe.
2112                  */
2113                 reg->s32_min_value = reg->u32_min_value;
2114                 reg->s32_max_value = reg->u32_max_value =
2115                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2116         } else if ((s32)reg->u32_min_value < 0) {
2117                 /* Negative.  We can't learn anything from the smax, but smin
2118                  * is negative, hence safe.
2119                  */
2120                 reg->s32_min_value = reg->u32_min_value =
2121                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2122                 reg->s32_max_value = reg->u32_max_value;
2123         }
2124 }
2125
2126 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2127 {
2128         /* Learn sign from signed bounds.
2129          * If we cannot cross the sign boundary, then signed and unsigned bounds
2130          * are the same, so combine.  This works even in the negative case, e.g.
2131          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2132          */
2133         if (reg->smin_value >= 0 || reg->smax_value < 0) {
2134                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2135                                                           reg->umin_value);
2136                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2137                                                           reg->umax_value);
2138                 return;
2139         }
2140         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2141          * boundary, so we must be careful.
2142          */
2143         if ((s64)reg->umax_value >= 0) {
2144                 /* Positive.  We can't learn anything from the smin, but smax
2145                  * is positive, hence safe.
2146                  */
2147                 reg->smin_value = reg->umin_value;
2148                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2149                                                           reg->umax_value);
2150         } else if ((s64)reg->umin_value < 0) {
2151                 /* Negative.  We can't learn anything from the smax, but smin
2152                  * is negative, hence safe.
2153                  */
2154                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2155                                                           reg->umin_value);
2156                 reg->smax_value = reg->umax_value;
2157         }
2158 }
2159
2160 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2161 {
2162         __reg32_deduce_bounds(reg);
2163         __reg64_deduce_bounds(reg);
2164 }
2165
2166 /* Attempts to improve var_off based on unsigned min/max information */
2167 static void __reg_bound_offset(struct bpf_reg_state *reg)
2168 {
2169         struct tnum var64_off = tnum_intersect(reg->var_off,
2170                                                tnum_range(reg->umin_value,
2171                                                           reg->umax_value));
2172         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2173                                                tnum_range(reg->u32_min_value,
2174                                                           reg->u32_max_value));
2175
2176         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2177 }
2178
2179 static void reg_bounds_sync(struct bpf_reg_state *reg)
2180 {
2181         /* We might have learned new bounds from the var_off. */
2182         __update_reg_bounds(reg);
2183         /* We might have learned something about the sign bit. */
2184         __reg_deduce_bounds(reg);
2185         /* We might have learned some bits from the bounds. */
2186         __reg_bound_offset(reg);
2187         /* Intersecting with the old var_off might have improved our bounds
2188          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2189          * then new var_off is (0; 0x7f...fc) which improves our umax.
2190          */
2191         __update_reg_bounds(reg);
2192 }
2193
2194 static bool __reg32_bound_s64(s32 a)
2195 {
2196         return a >= 0 && a <= S32_MAX;
2197 }
2198
2199 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2200 {
2201         reg->umin_value = reg->u32_min_value;
2202         reg->umax_value = reg->u32_max_value;
2203
2204         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2205          * be positive otherwise set to worse case bounds and refine later
2206          * from tnum.
2207          */
2208         if (__reg32_bound_s64(reg->s32_min_value) &&
2209             __reg32_bound_s64(reg->s32_max_value)) {
2210                 reg->smin_value = reg->s32_min_value;
2211                 reg->smax_value = reg->s32_max_value;
2212         } else {
2213                 reg->smin_value = 0;
2214                 reg->smax_value = U32_MAX;
2215         }
2216 }
2217
2218 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2219 {
2220         /* special case when 64-bit register has upper 32-bit register
2221          * zeroed. Typically happens after zext or <<32, >>32 sequence
2222          * allowing us to use 32-bit bounds directly,
2223          */
2224         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2225                 __reg_assign_32_into_64(reg);
2226         } else {
2227                 /* Otherwise the best we can do is push lower 32bit known and
2228                  * unknown bits into register (var_off set from jmp logic)
2229                  * then learn as much as possible from the 64-bit tnum
2230                  * known and unknown bits. The previous smin/smax bounds are
2231                  * invalid here because of jmp32 compare so mark them unknown
2232                  * so they do not impact tnum bounds calculation.
2233                  */
2234                 __mark_reg64_unbounded(reg);
2235         }
2236         reg_bounds_sync(reg);
2237 }
2238
2239 static bool __reg64_bound_s32(s64 a)
2240 {
2241         return a >= S32_MIN && a <= S32_MAX;
2242 }
2243
2244 static bool __reg64_bound_u32(u64 a)
2245 {
2246         return a >= U32_MIN && a <= U32_MAX;
2247 }
2248
2249 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2250 {
2251         __mark_reg32_unbounded(reg);
2252         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2253                 reg->s32_min_value = (s32)reg->smin_value;
2254                 reg->s32_max_value = (s32)reg->smax_value;
2255         }
2256         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2257                 reg->u32_min_value = (u32)reg->umin_value;
2258                 reg->u32_max_value = (u32)reg->umax_value;
2259         }
2260         reg_bounds_sync(reg);
2261 }
2262
2263 /* Mark a register as having a completely unknown (scalar) value. */
2264 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2265                                struct bpf_reg_state *reg)
2266 {
2267         /*
2268          * Clear type, off, and union(map_ptr, range) and
2269          * padding between 'type' and union
2270          */
2271         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2272         reg->type = SCALAR_VALUE;
2273         reg->id = 0;
2274         reg->ref_obj_id = 0;
2275         reg->var_off = tnum_unknown;
2276         reg->frameno = 0;
2277         reg->precise = !env->bpf_capable;
2278         __mark_reg_unbounded(reg);
2279 }
2280
2281 static void mark_reg_unknown(struct bpf_verifier_env *env,
2282                              struct bpf_reg_state *regs, u32 regno)
2283 {
2284         if (WARN_ON(regno >= MAX_BPF_REG)) {
2285                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2286                 /* Something bad happened, let's kill all regs except FP */
2287                 for (regno = 0; regno < BPF_REG_FP; regno++)
2288                         __mark_reg_not_init(env, regs + regno);
2289                 return;
2290         }
2291         __mark_reg_unknown(env, regs + regno);
2292 }
2293
2294 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2295                                 struct bpf_reg_state *reg)
2296 {
2297         __mark_reg_unknown(env, reg);
2298         reg->type = NOT_INIT;
2299 }
2300
2301 static void mark_reg_not_init(struct bpf_verifier_env *env,
2302                               struct bpf_reg_state *regs, u32 regno)
2303 {
2304         if (WARN_ON(regno >= MAX_BPF_REG)) {
2305                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2306                 /* Something bad happened, let's kill all regs except FP */
2307                 for (regno = 0; regno < BPF_REG_FP; regno++)
2308                         __mark_reg_not_init(env, regs + regno);
2309                 return;
2310         }
2311         __mark_reg_not_init(env, regs + regno);
2312 }
2313
2314 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2315                             struct bpf_reg_state *regs, u32 regno,
2316                             enum bpf_reg_type reg_type,
2317                             struct btf *btf, u32 btf_id,
2318                             enum bpf_type_flag flag)
2319 {
2320         if (reg_type == SCALAR_VALUE) {
2321                 mark_reg_unknown(env, regs, regno);
2322                 return;
2323         }
2324         mark_reg_known_zero(env, regs, regno);
2325         regs[regno].type = PTR_TO_BTF_ID | flag;
2326         regs[regno].btf = btf;
2327         regs[regno].btf_id = btf_id;
2328 }
2329
2330 #define DEF_NOT_SUBREG  (0)
2331 static void init_reg_state(struct bpf_verifier_env *env,
2332                            struct bpf_func_state *state)
2333 {
2334         struct bpf_reg_state *regs = state->regs;
2335         int i;
2336
2337         for (i = 0; i < MAX_BPF_REG; i++) {
2338                 mark_reg_not_init(env, regs, i);
2339                 regs[i].live = REG_LIVE_NONE;
2340                 regs[i].parent = NULL;
2341                 regs[i].subreg_def = DEF_NOT_SUBREG;
2342         }
2343
2344         /* frame pointer */
2345         regs[BPF_REG_FP].type = PTR_TO_STACK;
2346         mark_reg_known_zero(env, regs, BPF_REG_FP);
2347         regs[BPF_REG_FP].frameno = state->frameno;
2348 }
2349
2350 #define BPF_MAIN_FUNC (-1)
2351 static void init_func_state(struct bpf_verifier_env *env,
2352                             struct bpf_func_state *state,
2353                             int callsite, int frameno, int subprogno)
2354 {
2355         state->callsite = callsite;
2356         state->frameno = frameno;
2357         state->subprogno = subprogno;
2358         state->callback_ret_range = tnum_range(0, 0);
2359         init_reg_state(env, state);
2360         mark_verifier_state_scratched(env);
2361 }
2362
2363 /* Similar to push_stack(), but for async callbacks */
2364 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2365                                                 int insn_idx, int prev_insn_idx,
2366                                                 int subprog)
2367 {
2368         struct bpf_verifier_stack_elem *elem;
2369         struct bpf_func_state *frame;
2370
2371         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2372         if (!elem)
2373                 goto err;
2374
2375         elem->insn_idx = insn_idx;
2376         elem->prev_insn_idx = prev_insn_idx;
2377         elem->next = env->head;
2378         elem->log_pos = env->log.end_pos;
2379         env->head = elem;
2380         env->stack_size++;
2381         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2382                 verbose(env,
2383                         "The sequence of %d jumps is too complex for async cb.\n",
2384                         env->stack_size);
2385                 goto err;
2386         }
2387         /* Unlike push_stack() do not copy_verifier_state().
2388          * The caller state doesn't matter.
2389          * This is async callback. It starts in a fresh stack.
2390          * Initialize it similar to do_check_common().
2391          */
2392         elem->st.branches = 1;
2393         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2394         if (!frame)
2395                 goto err;
2396         init_func_state(env, frame,
2397                         BPF_MAIN_FUNC /* callsite */,
2398                         0 /* frameno within this callchain */,
2399                         subprog /* subprog number within this prog */);
2400         elem->st.frame[0] = frame;
2401         return &elem->st;
2402 err:
2403         free_verifier_state(env->cur_state, true);
2404         env->cur_state = NULL;
2405         /* pop all elements and return */
2406         while (!pop_stack(env, NULL, NULL, false));
2407         return NULL;
2408 }
2409
2410
2411 enum reg_arg_type {
2412         SRC_OP,         /* register is used as source operand */
2413         DST_OP,         /* register is used as destination operand */
2414         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2415 };
2416
2417 static int cmp_subprogs(const void *a, const void *b)
2418 {
2419         return ((struct bpf_subprog_info *)a)->start -
2420                ((struct bpf_subprog_info *)b)->start;
2421 }
2422
2423 static int find_subprog(struct bpf_verifier_env *env, int off)
2424 {
2425         struct bpf_subprog_info *p;
2426
2427         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2428                     sizeof(env->subprog_info[0]), cmp_subprogs);
2429         if (!p)
2430                 return -ENOENT;
2431         return p - env->subprog_info;
2432
2433 }
2434
2435 static int add_subprog(struct bpf_verifier_env *env, int off)
2436 {
2437         int insn_cnt = env->prog->len;
2438         int ret;
2439
2440         if (off >= insn_cnt || off < 0) {
2441                 verbose(env, "call to invalid destination\n");
2442                 return -EINVAL;
2443         }
2444         ret = find_subprog(env, off);
2445         if (ret >= 0)
2446                 return ret;
2447         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2448                 verbose(env, "too many subprograms\n");
2449                 return -E2BIG;
2450         }
2451         /* determine subprog starts. The end is one before the next starts */
2452         env->subprog_info[env->subprog_cnt++].start = off;
2453         sort(env->subprog_info, env->subprog_cnt,
2454              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2455         return env->subprog_cnt - 1;
2456 }
2457
2458 #define MAX_KFUNC_DESCS 256
2459 #define MAX_KFUNC_BTFS  256
2460
2461 struct bpf_kfunc_desc {
2462         struct btf_func_model func_model;
2463         u32 func_id;
2464         s32 imm;
2465         u16 offset;
2466         unsigned long addr;
2467 };
2468
2469 struct bpf_kfunc_btf {
2470         struct btf *btf;
2471         struct module *module;
2472         u16 offset;
2473 };
2474
2475 struct bpf_kfunc_desc_tab {
2476         /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2477          * verification. JITs do lookups by bpf_insn, where func_id may not be
2478          * available, therefore at the end of verification do_misc_fixups()
2479          * sorts this by imm and offset.
2480          */
2481         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2482         u32 nr_descs;
2483 };
2484
2485 struct bpf_kfunc_btf_tab {
2486         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2487         u32 nr_descs;
2488 };
2489
2490 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2491 {
2492         const struct bpf_kfunc_desc *d0 = a;
2493         const struct bpf_kfunc_desc *d1 = b;
2494
2495         /* func_id is not greater than BTF_MAX_TYPE */
2496         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2497 }
2498
2499 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2500 {
2501         const struct bpf_kfunc_btf *d0 = a;
2502         const struct bpf_kfunc_btf *d1 = b;
2503
2504         return d0->offset - d1->offset;
2505 }
2506
2507 static const struct bpf_kfunc_desc *
2508 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2509 {
2510         struct bpf_kfunc_desc desc = {
2511                 .func_id = func_id,
2512                 .offset = offset,
2513         };
2514         struct bpf_kfunc_desc_tab *tab;
2515
2516         tab = prog->aux->kfunc_tab;
2517         return bsearch(&desc, tab->descs, tab->nr_descs,
2518                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2519 }
2520
2521 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2522                        u16 btf_fd_idx, u8 **func_addr)
2523 {
2524         const struct bpf_kfunc_desc *desc;
2525
2526         desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2527         if (!desc)
2528                 return -EFAULT;
2529
2530         *func_addr = (u8 *)desc->addr;
2531         return 0;
2532 }
2533
2534 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2535                                          s16 offset)
2536 {
2537         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2538         struct bpf_kfunc_btf_tab *tab;
2539         struct bpf_kfunc_btf *b;
2540         struct module *mod;
2541         struct btf *btf;
2542         int btf_fd;
2543
2544         tab = env->prog->aux->kfunc_btf_tab;
2545         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2546                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2547         if (!b) {
2548                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2549                         verbose(env, "too many different module BTFs\n");
2550                         return ERR_PTR(-E2BIG);
2551                 }
2552
2553                 if (bpfptr_is_null(env->fd_array)) {
2554                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2555                         return ERR_PTR(-EPROTO);
2556                 }
2557
2558                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2559                                             offset * sizeof(btf_fd),
2560                                             sizeof(btf_fd)))
2561                         return ERR_PTR(-EFAULT);
2562
2563                 btf = btf_get_by_fd(btf_fd);
2564                 if (IS_ERR(btf)) {
2565                         verbose(env, "invalid module BTF fd specified\n");
2566                         return btf;
2567                 }
2568
2569                 if (!btf_is_module(btf)) {
2570                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2571                         btf_put(btf);
2572                         return ERR_PTR(-EINVAL);
2573                 }
2574
2575                 mod = btf_try_get_module(btf);
2576                 if (!mod) {
2577                         btf_put(btf);
2578                         return ERR_PTR(-ENXIO);
2579                 }
2580
2581                 b = &tab->descs[tab->nr_descs++];
2582                 b->btf = btf;
2583                 b->module = mod;
2584                 b->offset = offset;
2585
2586                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2587                      kfunc_btf_cmp_by_off, NULL);
2588         }
2589         return b->btf;
2590 }
2591
2592 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2593 {
2594         if (!tab)
2595                 return;
2596
2597         while (tab->nr_descs--) {
2598                 module_put(tab->descs[tab->nr_descs].module);
2599                 btf_put(tab->descs[tab->nr_descs].btf);
2600         }
2601         kfree(tab);
2602 }
2603
2604 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2605 {
2606         if (offset) {
2607                 if (offset < 0) {
2608                         /* In the future, this can be allowed to increase limit
2609                          * of fd index into fd_array, interpreted as u16.
2610                          */
2611                         verbose(env, "negative offset disallowed for kernel module function call\n");
2612                         return ERR_PTR(-EINVAL);
2613                 }
2614
2615                 return __find_kfunc_desc_btf(env, offset);
2616         }
2617         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2618 }
2619
2620 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2621 {
2622         const struct btf_type *func, *func_proto;
2623         struct bpf_kfunc_btf_tab *btf_tab;
2624         struct bpf_kfunc_desc_tab *tab;
2625         struct bpf_prog_aux *prog_aux;
2626         struct bpf_kfunc_desc *desc;
2627         const char *func_name;
2628         struct btf *desc_btf;
2629         unsigned long call_imm;
2630         unsigned long addr;
2631         int err;
2632
2633         prog_aux = env->prog->aux;
2634         tab = prog_aux->kfunc_tab;
2635         btf_tab = prog_aux->kfunc_btf_tab;
2636         if (!tab) {
2637                 if (!btf_vmlinux) {
2638                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2639                         return -ENOTSUPP;
2640                 }
2641
2642                 if (!env->prog->jit_requested) {
2643                         verbose(env, "JIT is required for calling kernel function\n");
2644                         return -ENOTSUPP;
2645                 }
2646
2647                 if (!bpf_jit_supports_kfunc_call()) {
2648                         verbose(env, "JIT does not support calling kernel function\n");
2649                         return -ENOTSUPP;
2650                 }
2651
2652                 if (!env->prog->gpl_compatible) {
2653                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2654                         return -EINVAL;
2655                 }
2656
2657                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2658                 if (!tab)
2659                         return -ENOMEM;
2660                 prog_aux->kfunc_tab = tab;
2661         }
2662
2663         /* func_id == 0 is always invalid, but instead of returning an error, be
2664          * conservative and wait until the code elimination pass before returning
2665          * error, so that invalid calls that get pruned out can be in BPF programs
2666          * loaded from userspace.  It is also required that offset be untouched
2667          * for such calls.
2668          */
2669         if (!func_id && !offset)
2670                 return 0;
2671
2672         if (!btf_tab && offset) {
2673                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2674                 if (!btf_tab)
2675                         return -ENOMEM;
2676                 prog_aux->kfunc_btf_tab = btf_tab;
2677         }
2678
2679         desc_btf = find_kfunc_desc_btf(env, offset);
2680         if (IS_ERR(desc_btf)) {
2681                 verbose(env, "failed to find BTF for kernel function\n");
2682                 return PTR_ERR(desc_btf);
2683         }
2684
2685         if (find_kfunc_desc(env->prog, func_id, offset))
2686                 return 0;
2687
2688         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2689                 verbose(env, "too many different kernel function calls\n");
2690                 return -E2BIG;
2691         }
2692
2693         func = btf_type_by_id(desc_btf, func_id);
2694         if (!func || !btf_type_is_func(func)) {
2695                 verbose(env, "kernel btf_id %u is not a function\n",
2696                         func_id);
2697                 return -EINVAL;
2698         }
2699         func_proto = btf_type_by_id(desc_btf, func->type);
2700         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2701                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2702                         func_id);
2703                 return -EINVAL;
2704         }
2705
2706         func_name = btf_name_by_offset(desc_btf, func->name_off);
2707         addr = kallsyms_lookup_name(func_name);
2708         if (!addr) {
2709                 verbose(env, "cannot find address for kernel function %s\n",
2710                         func_name);
2711                 return -EINVAL;
2712         }
2713         specialize_kfunc(env, func_id, offset, &addr);
2714
2715         if (bpf_jit_supports_far_kfunc_call()) {
2716                 call_imm = func_id;
2717         } else {
2718                 call_imm = BPF_CALL_IMM(addr);
2719                 /* Check whether the relative offset overflows desc->imm */
2720                 if ((unsigned long)(s32)call_imm != call_imm) {
2721                         verbose(env, "address of kernel function %s is out of range\n",
2722                                 func_name);
2723                         return -EINVAL;
2724                 }
2725         }
2726
2727         if (bpf_dev_bound_kfunc_id(func_id)) {
2728                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2729                 if (err)
2730                         return err;
2731         }
2732
2733         desc = &tab->descs[tab->nr_descs++];
2734         desc->func_id = func_id;
2735         desc->imm = call_imm;
2736         desc->offset = offset;
2737         desc->addr = addr;
2738         err = btf_distill_func_proto(&env->log, desc_btf,
2739                                      func_proto, func_name,
2740                                      &desc->func_model);
2741         if (!err)
2742                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2743                      kfunc_desc_cmp_by_id_off, NULL);
2744         return err;
2745 }
2746
2747 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2748 {
2749         const struct bpf_kfunc_desc *d0 = a;
2750         const struct bpf_kfunc_desc *d1 = b;
2751
2752         if (d0->imm != d1->imm)
2753                 return d0->imm < d1->imm ? -1 : 1;
2754         if (d0->offset != d1->offset)
2755                 return d0->offset < d1->offset ? -1 : 1;
2756         return 0;
2757 }
2758
2759 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2760 {
2761         struct bpf_kfunc_desc_tab *tab;
2762
2763         tab = prog->aux->kfunc_tab;
2764         if (!tab)
2765                 return;
2766
2767         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2768              kfunc_desc_cmp_by_imm_off, NULL);
2769 }
2770
2771 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2772 {
2773         return !!prog->aux->kfunc_tab;
2774 }
2775
2776 const struct btf_func_model *
2777 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2778                          const struct bpf_insn *insn)
2779 {
2780         const struct bpf_kfunc_desc desc = {
2781                 .imm = insn->imm,
2782                 .offset = insn->off,
2783         };
2784         const struct bpf_kfunc_desc *res;
2785         struct bpf_kfunc_desc_tab *tab;
2786
2787         tab = prog->aux->kfunc_tab;
2788         res = bsearch(&desc, tab->descs, tab->nr_descs,
2789                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2790
2791         return res ? &res->func_model : NULL;
2792 }
2793
2794 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2795 {
2796         struct bpf_subprog_info *subprog = env->subprog_info;
2797         struct bpf_insn *insn = env->prog->insnsi;
2798         int i, ret, insn_cnt = env->prog->len;
2799
2800         /* Add entry function. */
2801         ret = add_subprog(env, 0);
2802         if (ret)
2803                 return ret;
2804
2805         for (i = 0; i < insn_cnt; i++, insn++) {
2806                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2807                     !bpf_pseudo_kfunc_call(insn))
2808                         continue;
2809
2810                 if (!env->bpf_capable) {
2811                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2812                         return -EPERM;
2813                 }
2814
2815                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2816                         ret = add_subprog(env, i + insn->imm + 1);
2817                 else
2818                         ret = add_kfunc_call(env, insn->imm, insn->off);
2819
2820                 if (ret < 0)
2821                         return ret;
2822         }
2823
2824         /* Add a fake 'exit' subprog which could simplify subprog iteration
2825          * logic. 'subprog_cnt' should not be increased.
2826          */
2827         subprog[env->subprog_cnt].start = insn_cnt;
2828
2829         if (env->log.level & BPF_LOG_LEVEL2)
2830                 for (i = 0; i < env->subprog_cnt; i++)
2831                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2832
2833         return 0;
2834 }
2835
2836 static int check_subprogs(struct bpf_verifier_env *env)
2837 {
2838         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2839         struct bpf_subprog_info *subprog = env->subprog_info;
2840         struct bpf_insn *insn = env->prog->insnsi;
2841         int insn_cnt = env->prog->len;
2842
2843         /* now check that all jumps are within the same subprog */
2844         subprog_start = subprog[cur_subprog].start;
2845         subprog_end = subprog[cur_subprog + 1].start;
2846         for (i = 0; i < insn_cnt; i++) {
2847                 u8 code = insn[i].code;
2848
2849                 if (code == (BPF_JMP | BPF_CALL) &&
2850                     insn[i].src_reg == 0 &&
2851                     insn[i].imm == BPF_FUNC_tail_call)
2852                         subprog[cur_subprog].has_tail_call = true;
2853                 if (BPF_CLASS(code) == BPF_LD &&
2854                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2855                         subprog[cur_subprog].has_ld_abs = true;
2856                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2857                         goto next;
2858                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2859                         goto next;
2860                 if (code == (BPF_JMP32 | BPF_JA))
2861                         off = i + insn[i].imm + 1;
2862                 else
2863                         off = i + insn[i].off + 1;
2864                 if (off < subprog_start || off >= subprog_end) {
2865                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2866                         return -EINVAL;
2867                 }
2868 next:
2869                 if (i == subprog_end - 1) {
2870                         /* to avoid fall-through from one subprog into another
2871                          * the last insn of the subprog should be either exit
2872                          * or unconditional jump back
2873                          */
2874                         if (code != (BPF_JMP | BPF_EXIT) &&
2875                             code != (BPF_JMP32 | BPF_JA) &&
2876                             code != (BPF_JMP | BPF_JA)) {
2877                                 verbose(env, "last insn is not an exit or jmp\n");
2878                                 return -EINVAL;
2879                         }
2880                         subprog_start = subprog_end;
2881                         cur_subprog++;
2882                         if (cur_subprog < env->subprog_cnt)
2883                                 subprog_end = subprog[cur_subprog + 1].start;
2884                 }
2885         }
2886         return 0;
2887 }
2888
2889 /* Parentage chain of this register (or stack slot) should take care of all
2890  * issues like callee-saved registers, stack slot allocation time, etc.
2891  */
2892 static int mark_reg_read(struct bpf_verifier_env *env,
2893                          const struct bpf_reg_state *state,
2894                          struct bpf_reg_state *parent, u8 flag)
2895 {
2896         bool writes = parent == state->parent; /* Observe write marks */
2897         int cnt = 0;
2898
2899         while (parent) {
2900                 /* if read wasn't screened by an earlier write ... */
2901                 if (writes && state->live & REG_LIVE_WRITTEN)
2902                         break;
2903                 if (parent->live & REG_LIVE_DONE) {
2904                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2905                                 reg_type_str(env, parent->type),
2906                                 parent->var_off.value, parent->off);
2907                         return -EFAULT;
2908                 }
2909                 /* The first condition is more likely to be true than the
2910                  * second, checked it first.
2911                  */
2912                 if ((parent->live & REG_LIVE_READ) == flag ||
2913                     parent->live & REG_LIVE_READ64)
2914                         /* The parentage chain never changes and
2915                          * this parent was already marked as LIVE_READ.
2916                          * There is no need to keep walking the chain again and
2917                          * keep re-marking all parents as LIVE_READ.
2918                          * This case happens when the same register is read
2919                          * multiple times without writes into it in-between.
2920                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2921                          * then no need to set the weak REG_LIVE_READ32.
2922                          */
2923                         break;
2924                 /* ... then we depend on parent's value */
2925                 parent->live |= flag;
2926                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2927                 if (flag == REG_LIVE_READ64)
2928                         parent->live &= ~REG_LIVE_READ32;
2929                 state = parent;
2930                 parent = state->parent;
2931                 writes = true;
2932                 cnt++;
2933         }
2934
2935         if (env->longest_mark_read_walk < cnt)
2936                 env->longest_mark_read_walk = cnt;
2937         return 0;
2938 }
2939
2940 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2941 {
2942         struct bpf_func_state *state = func(env, reg);
2943         int spi, ret;
2944
2945         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2946          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2947          * check_kfunc_call.
2948          */
2949         if (reg->type == CONST_PTR_TO_DYNPTR)
2950                 return 0;
2951         spi = dynptr_get_spi(env, reg);
2952         if (spi < 0)
2953                 return spi;
2954         /* Caller ensures dynptr is valid and initialized, which means spi is in
2955          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2956          * read.
2957          */
2958         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2959                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2960         if (ret)
2961                 return ret;
2962         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2963                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2964 }
2965
2966 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2967                           int spi, int nr_slots)
2968 {
2969         struct bpf_func_state *state = func(env, reg);
2970         int err, i;
2971
2972         for (i = 0; i < nr_slots; i++) {
2973                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2974
2975                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2976                 if (err)
2977                         return err;
2978
2979                 mark_stack_slot_scratched(env, spi - i);
2980         }
2981
2982         return 0;
2983 }
2984
2985 /* This function is supposed to be used by the following 32-bit optimization
2986  * code only. It returns TRUE if the source or destination register operates
2987  * on 64-bit, otherwise return FALSE.
2988  */
2989 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2990                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2991 {
2992         u8 code, class, op;
2993
2994         code = insn->code;
2995         class = BPF_CLASS(code);
2996         op = BPF_OP(code);
2997         if (class == BPF_JMP) {
2998                 /* BPF_EXIT for "main" will reach here. Return TRUE
2999                  * conservatively.
3000                  */
3001                 if (op == BPF_EXIT)
3002                         return true;
3003                 if (op == BPF_CALL) {
3004                         /* BPF to BPF call will reach here because of marking
3005                          * caller saved clobber with DST_OP_NO_MARK for which we
3006                          * don't care the register def because they are anyway
3007                          * marked as NOT_INIT already.
3008                          */
3009                         if (insn->src_reg == BPF_PSEUDO_CALL)
3010                                 return false;
3011                         /* Helper call will reach here because of arg type
3012                          * check, conservatively return TRUE.
3013                          */
3014                         if (t == SRC_OP)
3015                                 return true;
3016
3017                         return false;
3018                 }
3019         }
3020
3021         if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3022                 return false;
3023
3024         if (class == BPF_ALU64 || class == BPF_JMP ||
3025             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3026                 return true;
3027
3028         if (class == BPF_ALU || class == BPF_JMP32)
3029                 return false;
3030
3031         if (class == BPF_LDX) {
3032                 if (t != SRC_OP)
3033                         return BPF_SIZE(code) == BPF_DW;
3034                 /* LDX source must be ptr. */
3035                 return true;
3036         }
3037
3038         if (class == BPF_STX) {
3039                 /* BPF_STX (including atomic variants) has multiple source
3040                  * operands, one of which is a ptr. Check whether the caller is
3041                  * asking about it.
3042                  */
3043                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3044                         return true;
3045                 return BPF_SIZE(code) == BPF_DW;
3046         }
3047
3048         if (class == BPF_LD) {
3049                 u8 mode = BPF_MODE(code);
3050
3051                 /* LD_IMM64 */
3052                 if (mode == BPF_IMM)
3053                         return true;
3054
3055                 /* Both LD_IND and LD_ABS return 32-bit data. */
3056                 if (t != SRC_OP)
3057                         return  false;
3058
3059                 /* Implicit ctx ptr. */
3060                 if (regno == BPF_REG_6)
3061                         return true;
3062
3063                 /* Explicit source could be any width. */
3064                 return true;
3065         }
3066
3067         if (class == BPF_ST)
3068                 /* The only source register for BPF_ST is a ptr. */
3069                 return true;
3070
3071         /* Conservatively return true at default. */
3072         return true;
3073 }
3074
3075 /* Return the regno defined by the insn, or -1. */
3076 static int insn_def_regno(const struct bpf_insn *insn)
3077 {
3078         switch (BPF_CLASS(insn->code)) {
3079         case BPF_JMP:
3080         case BPF_JMP32:
3081         case BPF_ST:
3082                 return -1;
3083         case BPF_STX:
3084                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3085                     (insn->imm & BPF_FETCH)) {
3086                         if (insn->imm == BPF_CMPXCHG)
3087                                 return BPF_REG_0;
3088                         else
3089                                 return insn->src_reg;
3090                 } else {
3091                         return -1;
3092                 }
3093         default:
3094                 return insn->dst_reg;
3095         }
3096 }
3097
3098 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3099 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3100 {
3101         int dst_reg = insn_def_regno(insn);
3102
3103         if (dst_reg == -1)
3104                 return false;
3105
3106         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3107 }
3108
3109 static void mark_insn_zext(struct bpf_verifier_env *env,
3110                            struct bpf_reg_state *reg)
3111 {
3112         s32 def_idx = reg->subreg_def;
3113
3114         if (def_idx == DEF_NOT_SUBREG)
3115                 return;
3116
3117         env->insn_aux_data[def_idx - 1].zext_dst = true;
3118         /* The dst will be zero extended, so won't be sub-register anymore. */
3119         reg->subreg_def = DEF_NOT_SUBREG;
3120 }
3121
3122 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3123                          enum reg_arg_type t)
3124 {
3125         struct bpf_verifier_state *vstate = env->cur_state;
3126         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3127         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3128         struct bpf_reg_state *reg, *regs = state->regs;
3129         bool rw64;
3130
3131         if (regno >= MAX_BPF_REG) {
3132                 verbose(env, "R%d is invalid\n", regno);
3133                 return -EINVAL;
3134         }
3135
3136         mark_reg_scratched(env, regno);
3137
3138         reg = &regs[regno];
3139         rw64 = is_reg64(env, insn, regno, reg, t);
3140         if (t == SRC_OP) {
3141                 /* check whether register used as source operand can be read */
3142                 if (reg->type == NOT_INIT) {
3143                         verbose(env, "R%d !read_ok\n", regno);
3144                         return -EACCES;
3145                 }
3146                 /* We don't need to worry about FP liveness because it's read-only */
3147                 if (regno == BPF_REG_FP)
3148                         return 0;
3149
3150                 if (rw64)
3151                         mark_insn_zext(env, reg);
3152
3153                 return mark_reg_read(env, reg, reg->parent,
3154                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3155         } else {
3156                 /* check whether register used as dest operand can be written to */
3157                 if (regno == BPF_REG_FP) {
3158                         verbose(env, "frame pointer is read only\n");
3159                         return -EACCES;
3160                 }
3161                 reg->live |= REG_LIVE_WRITTEN;
3162                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3163                 if (t == DST_OP)
3164                         mark_reg_unknown(env, regs, regno);
3165         }
3166         return 0;
3167 }
3168
3169 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3170 {
3171         env->insn_aux_data[idx].jmp_point = true;
3172 }
3173
3174 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3175 {
3176         return env->insn_aux_data[insn_idx].jmp_point;
3177 }
3178
3179 /* for any branch, call, exit record the history of jmps in the given state */
3180 static int push_jmp_history(struct bpf_verifier_env *env,
3181                             struct bpf_verifier_state *cur)
3182 {
3183         u32 cnt = cur->jmp_history_cnt;
3184         struct bpf_idx_pair *p;
3185         size_t alloc_size;
3186
3187         if (!is_jmp_point(env, env->insn_idx))
3188                 return 0;
3189
3190         cnt++;
3191         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3192         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3193         if (!p)
3194                 return -ENOMEM;
3195         p[cnt - 1].idx = env->insn_idx;
3196         p[cnt - 1].prev_idx = env->prev_insn_idx;
3197         cur->jmp_history = p;
3198         cur->jmp_history_cnt = cnt;
3199         return 0;
3200 }
3201
3202 /* Backtrack one insn at a time. If idx is not at the top of recorded
3203  * history then previous instruction came from straight line execution.
3204  * Return -ENOENT if we exhausted all instructions within given state.
3205  *
3206  * It's legal to have a bit of a looping with the same starting and ending
3207  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3208  * instruction index is the same as state's first_idx doesn't mean we are
3209  * done. If there is still some jump history left, we should keep going. We
3210  * need to take into account that we might have a jump history between given
3211  * state's parent and itself, due to checkpointing. In this case, we'll have
3212  * history entry recording a jump from last instruction of parent state and
3213  * first instruction of given state.
3214  */
3215 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3216                              u32 *history)
3217 {
3218         u32 cnt = *history;
3219
3220         if (i == st->first_insn_idx) {
3221                 if (cnt == 0)
3222                         return -ENOENT;
3223                 if (cnt == 1 && st->jmp_history[0].idx == i)
3224                         return -ENOENT;
3225         }
3226
3227         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3228                 i = st->jmp_history[cnt - 1].prev_idx;
3229                 (*history)--;
3230         } else {
3231                 i--;
3232         }
3233         return i;
3234 }
3235
3236 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3237 {
3238         const struct btf_type *func;
3239         struct btf *desc_btf;
3240
3241         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3242                 return NULL;
3243
3244         desc_btf = find_kfunc_desc_btf(data, insn->off);
3245         if (IS_ERR(desc_btf))
3246                 return "<error>";
3247
3248         func = btf_type_by_id(desc_btf, insn->imm);
3249         return btf_name_by_offset(desc_btf, func->name_off);
3250 }
3251
3252 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3253 {
3254         bt->frame = frame;
3255 }
3256
3257 static inline void bt_reset(struct backtrack_state *bt)
3258 {
3259         struct bpf_verifier_env *env = bt->env;
3260
3261         memset(bt, 0, sizeof(*bt));
3262         bt->env = env;
3263 }
3264
3265 static inline u32 bt_empty(struct backtrack_state *bt)
3266 {
3267         u64 mask = 0;
3268         int i;
3269
3270         for (i = 0; i <= bt->frame; i++)
3271                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3272
3273         return mask == 0;
3274 }
3275
3276 static inline int bt_subprog_enter(struct backtrack_state *bt)
3277 {
3278         if (bt->frame == MAX_CALL_FRAMES - 1) {
3279                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3280                 WARN_ONCE(1, "verifier backtracking bug");
3281                 return -EFAULT;
3282         }
3283         bt->frame++;
3284         return 0;
3285 }
3286
3287 static inline int bt_subprog_exit(struct backtrack_state *bt)
3288 {
3289         if (bt->frame == 0) {
3290                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3291                 WARN_ONCE(1, "verifier backtracking bug");
3292                 return -EFAULT;
3293         }
3294         bt->frame--;
3295         return 0;
3296 }
3297
3298 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3299 {
3300         bt->reg_masks[frame] |= 1 << reg;
3301 }
3302
3303 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3304 {
3305         bt->reg_masks[frame] &= ~(1 << reg);
3306 }
3307
3308 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3309 {
3310         bt_set_frame_reg(bt, bt->frame, reg);
3311 }
3312
3313 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3314 {
3315         bt_clear_frame_reg(bt, bt->frame, reg);
3316 }
3317
3318 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3319 {
3320         bt->stack_masks[frame] |= 1ull << slot;
3321 }
3322
3323 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3324 {
3325         bt->stack_masks[frame] &= ~(1ull << slot);
3326 }
3327
3328 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3329 {
3330         bt_set_frame_slot(bt, bt->frame, slot);
3331 }
3332
3333 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3334 {
3335         bt_clear_frame_slot(bt, bt->frame, slot);
3336 }
3337
3338 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3339 {
3340         return bt->reg_masks[frame];
3341 }
3342
3343 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3344 {
3345         return bt->reg_masks[bt->frame];
3346 }
3347
3348 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3349 {
3350         return bt->stack_masks[frame];
3351 }
3352
3353 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3354 {
3355         return bt->stack_masks[bt->frame];
3356 }
3357
3358 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3359 {
3360         return bt->reg_masks[bt->frame] & (1 << reg);
3361 }
3362
3363 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3364 {
3365         return bt->stack_masks[bt->frame] & (1ull << slot);
3366 }
3367
3368 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3369 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3370 {
3371         DECLARE_BITMAP(mask, 64);
3372         bool first = true;
3373         int i, n;
3374
3375         buf[0] = '\0';
3376
3377         bitmap_from_u64(mask, reg_mask);
3378         for_each_set_bit(i, mask, 32) {
3379                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3380                 first = false;
3381                 buf += n;
3382                 buf_sz -= n;
3383                 if (buf_sz < 0)
3384                         break;
3385         }
3386 }
3387 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3388 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3389 {
3390         DECLARE_BITMAP(mask, 64);
3391         bool first = true;
3392         int i, n;
3393
3394         buf[0] = '\0';
3395
3396         bitmap_from_u64(mask, stack_mask);
3397         for_each_set_bit(i, mask, 64) {
3398                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3399                 first = false;
3400                 buf += n;
3401                 buf_sz -= n;
3402                 if (buf_sz < 0)
3403                         break;
3404         }
3405 }
3406
3407 /* For given verifier state backtrack_insn() is called from the last insn to
3408  * the first insn. Its purpose is to compute a bitmask of registers and
3409  * stack slots that needs precision in the parent verifier state.
3410  *
3411  * @idx is an index of the instruction we are currently processing;
3412  * @subseq_idx is an index of the subsequent instruction that:
3413  *   - *would be* executed next, if jump history is viewed in forward order;
3414  *   - *was* processed previously during backtracking.
3415  */
3416 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3417                           struct backtrack_state *bt)
3418 {
3419         const struct bpf_insn_cbs cbs = {
3420                 .cb_call        = disasm_kfunc_name,
3421                 .cb_print       = verbose,
3422                 .private_data   = env,
3423         };
3424         struct bpf_insn *insn = env->prog->insnsi + idx;
3425         u8 class = BPF_CLASS(insn->code);
3426         u8 opcode = BPF_OP(insn->code);
3427         u8 mode = BPF_MODE(insn->code);
3428         u32 dreg = insn->dst_reg;
3429         u32 sreg = insn->src_reg;
3430         u32 spi, i;
3431
3432         if (insn->code == 0)
3433                 return 0;
3434         if (env->log.level & BPF_LOG_LEVEL2) {
3435                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3436                 verbose(env, "mark_precise: frame%d: regs=%s ",
3437                         bt->frame, env->tmp_str_buf);
3438                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3439                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3440                 verbose(env, "%d: ", idx);
3441                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3442         }
3443
3444         if (class == BPF_ALU || class == BPF_ALU64) {
3445                 if (!bt_is_reg_set(bt, dreg))
3446                         return 0;
3447                 if (opcode == BPF_MOV) {
3448                         if (BPF_SRC(insn->code) == BPF_X) {
3449                                 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3450                                  * dreg needs precision after this insn
3451                                  * sreg needs precision before this insn
3452                                  */
3453                                 bt_clear_reg(bt, dreg);
3454                                 bt_set_reg(bt, sreg);
3455                         } else {
3456                                 /* dreg = K
3457                                  * dreg needs precision after this insn.
3458                                  * Corresponding register is already marked
3459                                  * as precise=true in this verifier state.
3460                                  * No further markings in parent are necessary
3461                                  */
3462                                 bt_clear_reg(bt, dreg);
3463                         }
3464                 } else {
3465                         if (BPF_SRC(insn->code) == BPF_X) {
3466                                 /* dreg += sreg
3467                                  * both dreg and sreg need precision
3468                                  * before this insn
3469                                  */
3470                                 bt_set_reg(bt, sreg);
3471                         } /* else dreg += K
3472                            * dreg still needs precision before this insn
3473                            */
3474                 }
3475         } else if (class == BPF_LDX) {
3476                 if (!bt_is_reg_set(bt, dreg))
3477                         return 0;
3478                 bt_clear_reg(bt, dreg);
3479
3480                 /* scalars can only be spilled into stack w/o losing precision.
3481                  * Load from any other memory can be zero extended.
3482                  * The desire to keep that precision is already indicated
3483                  * by 'precise' mark in corresponding register of this state.
3484                  * No further tracking necessary.
3485                  */
3486                 if (insn->src_reg != BPF_REG_FP)
3487                         return 0;
3488
3489                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3490                  * that [fp - off] slot contains scalar that needs to be
3491                  * tracked with precision
3492                  */
3493                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3494                 if (spi >= 64) {
3495                         verbose(env, "BUG spi %d\n", spi);
3496                         WARN_ONCE(1, "verifier backtracking bug");
3497                         return -EFAULT;
3498                 }
3499                 bt_set_slot(bt, spi);
3500         } else if (class == BPF_STX || class == BPF_ST) {
3501                 if (bt_is_reg_set(bt, dreg))
3502                         /* stx & st shouldn't be using _scalar_ dst_reg
3503                          * to access memory. It means backtracking
3504                          * encountered a case of pointer subtraction.
3505                          */
3506                         return -ENOTSUPP;
3507                 /* scalars can only be spilled into stack */
3508                 if (insn->dst_reg != BPF_REG_FP)
3509                         return 0;
3510                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3511                 if (spi >= 64) {
3512                         verbose(env, "BUG spi %d\n", spi);
3513                         WARN_ONCE(1, "verifier backtracking bug");
3514                         return -EFAULT;
3515                 }
3516                 if (!bt_is_slot_set(bt, spi))
3517                         return 0;
3518                 bt_clear_slot(bt, spi);
3519                 if (class == BPF_STX)
3520                         bt_set_reg(bt, sreg);
3521         } else if (class == BPF_JMP || class == BPF_JMP32) {
3522                 if (bpf_pseudo_call(insn)) {
3523                         int subprog_insn_idx, subprog;
3524
3525                         subprog_insn_idx = idx + insn->imm + 1;
3526                         subprog = find_subprog(env, subprog_insn_idx);
3527                         if (subprog < 0)
3528                                 return -EFAULT;
3529
3530                         if (subprog_is_global(env, subprog)) {
3531                                 /* check that jump history doesn't have any
3532                                  * extra instructions from subprog; the next
3533                                  * instruction after call to global subprog
3534                                  * should be literally next instruction in
3535                                  * caller program
3536                                  */
3537                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3538                                 /* r1-r5 are invalidated after subprog call,
3539                                  * so for global func call it shouldn't be set
3540                                  * anymore
3541                                  */
3542                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3543                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3544                                         WARN_ONCE(1, "verifier backtracking bug");
3545                                         return -EFAULT;
3546                                 }
3547                                 /* global subprog always sets R0 */
3548                                 bt_clear_reg(bt, BPF_REG_0);
3549                                 return 0;
3550                         } else {
3551                                 /* static subprog call instruction, which
3552                                  * means that we are exiting current subprog,
3553                                  * so only r1-r5 could be still requested as
3554                                  * precise, r0 and r6-r10 or any stack slot in
3555                                  * the current frame should be zero by now
3556                                  */
3557                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3558                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3559                                         WARN_ONCE(1, "verifier backtracking bug");
3560                                         return -EFAULT;
3561                                 }
3562                                 /* we don't track register spills perfectly,
3563                                  * so fallback to force-precise instead of failing */
3564                                 if (bt_stack_mask(bt) != 0)
3565                                         return -ENOTSUPP;
3566                                 /* propagate r1-r5 to the caller */
3567                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3568                                         if (bt_is_reg_set(bt, i)) {
3569                                                 bt_clear_reg(bt, i);
3570                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3571                                         }
3572                                 }
3573                                 if (bt_subprog_exit(bt))
3574                                         return -EFAULT;
3575                                 return 0;
3576                         }
3577                 } else if ((bpf_helper_call(insn) &&
3578                             is_callback_calling_function(insn->imm) &&
3579                             !is_async_callback_calling_function(insn->imm)) ||
3580                            (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3581                         /* callback-calling helper or kfunc call, which means
3582                          * we are exiting from subprog, but unlike the subprog
3583                          * call handling above, we shouldn't propagate
3584                          * precision of r1-r5 (if any requested), as they are
3585                          * not actually arguments passed directly to callback
3586                          * subprogs
3587                          */
3588                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3589                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3590                                 WARN_ONCE(1, "verifier backtracking bug");
3591                                 return -EFAULT;
3592                         }
3593                         if (bt_stack_mask(bt) != 0)
3594                                 return -ENOTSUPP;
3595                         /* clear r1-r5 in callback subprog's mask */
3596                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3597                                 bt_clear_reg(bt, i);
3598                         if (bt_subprog_exit(bt))
3599                                 return -EFAULT;
3600                         return 0;
3601                 } else if (opcode == BPF_CALL) {
3602                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3603                          * catch this error later. Make backtracking conservative
3604                          * with ENOTSUPP.
3605                          */
3606                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3607                                 return -ENOTSUPP;
3608                         /* regular helper call sets R0 */
3609                         bt_clear_reg(bt, BPF_REG_0);
3610                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3611                                 /* if backtracing was looking for registers R1-R5
3612                                  * they should have been found already.
3613                                  */
3614                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3615                                 WARN_ONCE(1, "verifier backtracking bug");
3616                                 return -EFAULT;
3617                         }
3618                 } else if (opcode == BPF_EXIT) {
3619                         bool r0_precise;
3620
3621                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3622                                 /* if backtracing was looking for registers R1-R5
3623                                  * they should have been found already.
3624                                  */
3625                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3626                                 WARN_ONCE(1, "verifier backtracking bug");
3627                                 return -EFAULT;
3628                         }
3629
3630                         /* BPF_EXIT in subprog or callback always returns
3631                          * right after the call instruction, so by checking
3632                          * whether the instruction at subseq_idx-1 is subprog
3633                          * call or not we can distinguish actual exit from
3634                          * *subprog* from exit from *callback*. In the former
3635                          * case, we need to propagate r0 precision, if
3636                          * necessary. In the former we never do that.
3637                          */
3638                         r0_precise = subseq_idx - 1 >= 0 &&
3639                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3640                                      bt_is_reg_set(bt, BPF_REG_0);
3641
3642                         bt_clear_reg(bt, BPF_REG_0);
3643                         if (bt_subprog_enter(bt))
3644                                 return -EFAULT;
3645
3646                         if (r0_precise)
3647                                 bt_set_reg(bt, BPF_REG_0);
3648                         /* r6-r9 and stack slots will stay set in caller frame
3649                          * bitmasks until we return back from callee(s)
3650                          */
3651                         return 0;
3652                 } else if (BPF_SRC(insn->code) == BPF_X) {
3653                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3654                                 return 0;
3655                         /* dreg <cond> sreg
3656                          * Both dreg and sreg need precision before
3657                          * this insn. If only sreg was marked precise
3658                          * before it would be equally necessary to
3659                          * propagate it to dreg.
3660                          */
3661                         bt_set_reg(bt, dreg);
3662                         bt_set_reg(bt, sreg);
3663                          /* else dreg <cond> K
3664                           * Only dreg still needs precision before
3665                           * this insn, so for the K-based conditional
3666                           * there is nothing new to be marked.
3667                           */
3668                 }
3669         } else if (class == BPF_LD) {
3670                 if (!bt_is_reg_set(bt, dreg))
3671                         return 0;
3672                 bt_clear_reg(bt, dreg);
3673                 /* It's ld_imm64 or ld_abs or ld_ind.
3674                  * For ld_imm64 no further tracking of precision
3675                  * into parent is necessary
3676                  */
3677                 if (mode == BPF_IND || mode == BPF_ABS)
3678                         /* to be analyzed */
3679                         return -ENOTSUPP;
3680         }
3681         return 0;
3682 }
3683
3684 /* the scalar precision tracking algorithm:
3685  * . at the start all registers have precise=false.
3686  * . scalar ranges are tracked as normal through alu and jmp insns.
3687  * . once precise value of the scalar register is used in:
3688  *   .  ptr + scalar alu
3689  *   . if (scalar cond K|scalar)
3690  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3691  *   backtrack through the verifier states and mark all registers and
3692  *   stack slots with spilled constants that these scalar regisers
3693  *   should be precise.
3694  * . during state pruning two registers (or spilled stack slots)
3695  *   are equivalent if both are not precise.
3696  *
3697  * Note the verifier cannot simply walk register parentage chain,
3698  * since many different registers and stack slots could have been
3699  * used to compute single precise scalar.
3700  *
3701  * The approach of starting with precise=true for all registers and then
3702  * backtrack to mark a register as not precise when the verifier detects
3703  * that program doesn't care about specific value (e.g., when helper
3704  * takes register as ARG_ANYTHING parameter) is not safe.
3705  *
3706  * It's ok to walk single parentage chain of the verifier states.
3707  * It's possible that this backtracking will go all the way till 1st insn.
3708  * All other branches will be explored for needing precision later.
3709  *
3710  * The backtracking needs to deal with cases like:
3711  *   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)
3712  * r9 -= r8
3713  * r5 = r9
3714  * if r5 > 0x79f goto pc+7
3715  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3716  * r5 += 1
3717  * ...
3718  * call bpf_perf_event_output#25
3719  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3720  *
3721  * and this case:
3722  * r6 = 1
3723  * call foo // uses callee's r6 inside to compute r0
3724  * r0 += r6
3725  * if r0 == 0 goto
3726  *
3727  * to track above reg_mask/stack_mask needs to be independent for each frame.
3728  *
3729  * Also if parent's curframe > frame where backtracking started,
3730  * the verifier need to mark registers in both frames, otherwise callees
3731  * may incorrectly prune callers. This is similar to
3732  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3733  *
3734  * For now backtracking falls back into conservative marking.
3735  */
3736 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3737                                      struct bpf_verifier_state *st)
3738 {
3739         struct bpf_func_state *func;
3740         struct bpf_reg_state *reg;
3741         int i, j;
3742
3743         if (env->log.level & BPF_LOG_LEVEL2) {
3744                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3745                         st->curframe);
3746         }
3747
3748         /* big hammer: mark all scalars precise in this path.
3749          * pop_stack may still get !precise scalars.
3750          * We also skip current state and go straight to first parent state,
3751          * because precision markings in current non-checkpointed state are
3752          * not needed. See why in the comment in __mark_chain_precision below.
3753          */
3754         for (st = st->parent; st; st = st->parent) {
3755                 for (i = 0; i <= st->curframe; i++) {
3756                         func = st->frame[i];
3757                         for (j = 0; j < BPF_REG_FP; j++) {
3758                                 reg = &func->regs[j];
3759                                 if (reg->type != SCALAR_VALUE || reg->precise)
3760                                         continue;
3761                                 reg->precise = true;
3762                                 if (env->log.level & BPF_LOG_LEVEL2) {
3763                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3764                                                 i, j);
3765                                 }
3766                         }
3767                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3768                                 if (!is_spilled_reg(&func->stack[j]))
3769                                         continue;
3770                                 reg = &func->stack[j].spilled_ptr;
3771                                 if (reg->type != SCALAR_VALUE || reg->precise)
3772                                         continue;
3773                                 reg->precise = true;
3774                                 if (env->log.level & BPF_LOG_LEVEL2) {
3775                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3776                                                 i, -(j + 1) * 8);
3777                                 }
3778                         }
3779                 }
3780         }
3781 }
3782
3783 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3784 {
3785         struct bpf_func_state *func;
3786         struct bpf_reg_state *reg;
3787         int i, j;
3788
3789         for (i = 0; i <= st->curframe; i++) {
3790                 func = st->frame[i];
3791                 for (j = 0; j < BPF_REG_FP; j++) {
3792                         reg = &func->regs[j];
3793                         if (reg->type != SCALAR_VALUE)
3794                                 continue;
3795                         reg->precise = false;
3796                 }
3797                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3798                         if (!is_spilled_reg(&func->stack[j]))
3799                                 continue;
3800                         reg = &func->stack[j].spilled_ptr;
3801                         if (reg->type != SCALAR_VALUE)
3802                                 continue;
3803                         reg->precise = false;
3804                 }
3805         }
3806 }
3807
3808 static bool idset_contains(struct bpf_idset *s, u32 id)
3809 {
3810         u32 i;
3811
3812         for (i = 0; i < s->count; ++i)
3813                 if (s->ids[i] == id)
3814                         return true;
3815
3816         return false;
3817 }
3818
3819 static int idset_push(struct bpf_idset *s, u32 id)
3820 {
3821         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3822                 return -EFAULT;
3823         s->ids[s->count++] = id;
3824         return 0;
3825 }
3826
3827 static void idset_reset(struct bpf_idset *s)
3828 {
3829         s->count = 0;
3830 }
3831
3832 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3833  * Mark all registers with these IDs as precise.
3834  */
3835 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3836 {
3837         struct bpf_idset *precise_ids = &env->idset_scratch;
3838         struct backtrack_state *bt = &env->bt;
3839         struct bpf_func_state *func;
3840         struct bpf_reg_state *reg;
3841         DECLARE_BITMAP(mask, 64);
3842         int i, fr;
3843
3844         idset_reset(precise_ids);
3845
3846         for (fr = bt->frame; fr >= 0; fr--) {
3847                 func = st->frame[fr];
3848
3849                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3850                 for_each_set_bit(i, mask, 32) {
3851                         reg = &func->regs[i];
3852                         if (!reg->id || reg->type != SCALAR_VALUE)
3853                                 continue;
3854                         if (idset_push(precise_ids, reg->id))
3855                                 return -EFAULT;
3856                 }
3857
3858                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3859                 for_each_set_bit(i, mask, 64) {
3860                         if (i >= func->allocated_stack / BPF_REG_SIZE)
3861                                 break;
3862                         if (!is_spilled_scalar_reg(&func->stack[i]))
3863                                 continue;
3864                         reg = &func->stack[i].spilled_ptr;
3865                         if (!reg->id)
3866                                 continue;
3867                         if (idset_push(precise_ids, reg->id))
3868                                 return -EFAULT;
3869                 }
3870         }
3871
3872         for (fr = 0; fr <= st->curframe; ++fr) {
3873                 func = st->frame[fr];
3874
3875                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3876                         reg = &func->regs[i];
3877                         if (!reg->id)
3878                                 continue;
3879                         if (!idset_contains(precise_ids, reg->id))
3880                                 continue;
3881                         bt_set_frame_reg(bt, fr, i);
3882                 }
3883                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3884                         if (!is_spilled_scalar_reg(&func->stack[i]))
3885                                 continue;
3886                         reg = &func->stack[i].spilled_ptr;
3887                         if (!reg->id)
3888                                 continue;
3889                         if (!idset_contains(precise_ids, reg->id))
3890                                 continue;
3891                         bt_set_frame_slot(bt, fr, i);
3892                 }
3893         }
3894
3895         return 0;
3896 }
3897
3898 /*
3899  * __mark_chain_precision() backtracks BPF program instruction sequence and
3900  * chain of verifier states making sure that register *regno* (if regno >= 0)
3901  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3902  * SCALARS, as well as any other registers and slots that contribute to
3903  * a tracked state of given registers/stack slots, depending on specific BPF
3904  * assembly instructions (see backtrack_insns() for exact instruction handling
3905  * logic). This backtracking relies on recorded jmp_history and is able to
3906  * traverse entire chain of parent states. This process ends only when all the
3907  * necessary registers/slots and their transitive dependencies are marked as
3908  * precise.
3909  *
3910  * One important and subtle aspect is that precise marks *do not matter* in
3911  * the currently verified state (current state). It is important to understand
3912  * why this is the case.
3913  *
3914  * First, note that current state is the state that is not yet "checkpointed",
3915  * i.e., it is not yet put into env->explored_states, and it has no children
3916  * states as well. It's ephemeral, and can end up either a) being discarded if
3917  * compatible explored state is found at some point or BPF_EXIT instruction is
3918  * reached or b) checkpointed and put into env->explored_states, branching out
3919  * into one or more children states.
3920  *
3921  * In the former case, precise markings in current state are completely
3922  * ignored by state comparison code (see regsafe() for details). Only
3923  * checkpointed ("old") state precise markings are important, and if old
3924  * state's register/slot is precise, regsafe() assumes current state's
3925  * register/slot as precise and checks value ranges exactly and precisely. If
3926  * states turn out to be compatible, current state's necessary precise
3927  * markings and any required parent states' precise markings are enforced
3928  * after the fact with propagate_precision() logic, after the fact. But it's
3929  * important to realize that in this case, even after marking current state
3930  * registers/slots as precise, we immediately discard current state. So what
3931  * actually matters is any of the precise markings propagated into current
3932  * state's parent states, which are always checkpointed (due to b) case above).
3933  * As such, for scenario a) it doesn't matter if current state has precise
3934  * markings set or not.
3935  *
3936  * Now, for the scenario b), checkpointing and forking into child(ren)
3937  * state(s). Note that before current state gets to checkpointing step, any
3938  * processed instruction always assumes precise SCALAR register/slot
3939  * knowledge: if precise value or range is useful to prune jump branch, BPF
3940  * verifier takes this opportunity enthusiastically. Similarly, when
3941  * register's value is used to calculate offset or memory address, exact
3942  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3943  * what we mentioned above about state comparison ignoring precise markings
3944  * during state comparison, BPF verifier ignores and also assumes precise
3945  * markings *at will* during instruction verification process. But as verifier
3946  * assumes precision, it also propagates any precision dependencies across
3947  * parent states, which are not yet finalized, so can be further restricted
3948  * based on new knowledge gained from restrictions enforced by their children
3949  * states. This is so that once those parent states are finalized, i.e., when
3950  * they have no more active children state, state comparison logic in
3951  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3952  * required for correctness.
3953  *
3954  * To build a bit more intuition, note also that once a state is checkpointed,
3955  * the path we took to get to that state is not important. This is crucial
3956  * property for state pruning. When state is checkpointed and finalized at
3957  * some instruction index, it can be correctly and safely used to "short
3958  * circuit" any *compatible* state that reaches exactly the same instruction
3959  * index. I.e., if we jumped to that instruction from a completely different
3960  * code path than original finalized state was derived from, it doesn't
3961  * matter, current state can be discarded because from that instruction
3962  * forward having a compatible state will ensure we will safely reach the
3963  * exit. States describe preconditions for further exploration, but completely
3964  * forget the history of how we got here.
3965  *
3966  * This also means that even if we needed precise SCALAR range to get to
3967  * finalized state, but from that point forward *that same* SCALAR register is
3968  * never used in a precise context (i.e., it's precise value is not needed for
3969  * correctness), it's correct and safe to mark such register as "imprecise"
3970  * (i.e., precise marking set to false). This is what we rely on when we do
3971  * not set precise marking in current state. If no child state requires
3972  * precision for any given SCALAR register, it's safe to dictate that it can
3973  * be imprecise. If any child state does require this register to be precise,
3974  * we'll mark it precise later retroactively during precise markings
3975  * propagation from child state to parent states.
3976  *
3977  * Skipping precise marking setting in current state is a mild version of
3978  * relying on the above observation. But we can utilize this property even
3979  * more aggressively by proactively forgetting any precise marking in the
3980  * current state (which we inherited from the parent state), right before we
3981  * checkpoint it and branch off into new child state. This is done by
3982  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3983  * finalized states which help in short circuiting more future states.
3984  */
3985 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3986 {
3987         struct backtrack_state *bt = &env->bt;
3988         struct bpf_verifier_state *st = env->cur_state;
3989         int first_idx = st->first_insn_idx;
3990         int last_idx = env->insn_idx;
3991         int subseq_idx = -1;
3992         struct bpf_func_state *func;
3993         struct bpf_reg_state *reg;
3994         bool skip_first = true;
3995         int i, fr, err;
3996
3997         if (!env->bpf_capable)
3998                 return 0;
3999
4000         /* set frame number from which we are starting to backtrack */
4001         bt_init(bt, env->cur_state->curframe);
4002
4003         /* Do sanity checks against current state of register and/or stack
4004          * slot, but don't set precise flag in current state, as precision
4005          * tracking in the current state is unnecessary.
4006          */
4007         func = st->frame[bt->frame];
4008         if (regno >= 0) {
4009                 reg = &func->regs[regno];
4010                 if (reg->type != SCALAR_VALUE) {
4011                         WARN_ONCE(1, "backtracing misuse");
4012                         return -EFAULT;
4013                 }
4014                 bt_set_reg(bt, regno);
4015         }
4016
4017         if (bt_empty(bt))
4018                 return 0;
4019
4020         for (;;) {
4021                 DECLARE_BITMAP(mask, 64);
4022                 u32 history = st->jmp_history_cnt;
4023
4024                 if (env->log.level & BPF_LOG_LEVEL2) {
4025                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4026                                 bt->frame, last_idx, first_idx, subseq_idx);
4027                 }
4028
4029                 /* If some register with scalar ID is marked as precise,
4030                  * make sure that all registers sharing this ID are also precise.
4031                  * This is needed to estimate effect of find_equal_scalars().
4032                  * Do this at the last instruction of each state,
4033                  * bpf_reg_state::id fields are valid for these instructions.
4034                  *
4035                  * Allows to track precision in situation like below:
4036                  *
4037                  *     r2 = unknown value
4038                  *     ...
4039                  *   --- state #0 ---
4040                  *     ...
4041                  *     r1 = r2                 // r1 and r2 now share the same ID
4042                  *     ...
4043                  *   --- state #1 {r1.id = A, r2.id = A} ---
4044                  *     ...
4045                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4046                  *     ...
4047                  *   --- state #2 {r1.id = A, r2.id = A} ---
4048                  *     r3 = r10
4049                  *     r3 += r1                // need to mark both r1 and r2
4050                  */
4051                 if (mark_precise_scalar_ids(env, st))
4052                         return -EFAULT;
4053
4054                 if (last_idx < 0) {
4055                         /* we are at the entry into subprog, which
4056                          * is expected for global funcs, but only if
4057                          * requested precise registers are R1-R5
4058                          * (which are global func's input arguments)
4059                          */
4060                         if (st->curframe == 0 &&
4061                             st->frame[0]->subprogno > 0 &&
4062                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4063                             bt_stack_mask(bt) == 0 &&
4064                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4065                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4066                                 for_each_set_bit(i, mask, 32) {
4067                                         reg = &st->frame[0]->regs[i];
4068                                         bt_clear_reg(bt, i);
4069                                         if (reg->type == SCALAR_VALUE)
4070                                                 reg->precise = true;
4071                                 }
4072                                 return 0;
4073                         }
4074
4075                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4076                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4077                         WARN_ONCE(1, "verifier backtracking bug");
4078                         return -EFAULT;
4079                 }
4080
4081                 for (i = last_idx;;) {
4082                         if (skip_first) {
4083                                 err = 0;
4084                                 skip_first = false;
4085                         } else {
4086                                 err = backtrack_insn(env, i, subseq_idx, bt);
4087                         }
4088                         if (err == -ENOTSUPP) {
4089                                 mark_all_scalars_precise(env, env->cur_state);
4090                                 bt_reset(bt);
4091                                 return 0;
4092                         } else if (err) {
4093                                 return err;
4094                         }
4095                         if (bt_empty(bt))
4096                                 /* Found assignment(s) into tracked register in this state.
4097                                  * Since this state is already marked, just return.
4098                                  * Nothing to be tracked further in the parent state.
4099                                  */
4100                                 return 0;
4101                         subseq_idx = i;
4102                         i = get_prev_insn_idx(st, i, &history);
4103                         if (i == -ENOENT)
4104                                 break;
4105                         if (i >= env->prog->len) {
4106                                 /* This can happen if backtracking reached insn 0
4107                                  * and there are still reg_mask or stack_mask
4108                                  * to backtrack.
4109                                  * It means the backtracking missed the spot where
4110                                  * particular register was initialized with a constant.
4111                                  */
4112                                 verbose(env, "BUG backtracking idx %d\n", i);
4113                                 WARN_ONCE(1, "verifier backtracking bug");
4114                                 return -EFAULT;
4115                         }
4116                 }
4117                 st = st->parent;
4118                 if (!st)
4119                         break;
4120
4121                 for (fr = bt->frame; fr >= 0; fr--) {
4122                         func = st->frame[fr];
4123                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4124                         for_each_set_bit(i, mask, 32) {
4125                                 reg = &func->regs[i];
4126                                 if (reg->type != SCALAR_VALUE) {
4127                                         bt_clear_frame_reg(bt, fr, i);
4128                                         continue;
4129                                 }
4130                                 if (reg->precise)
4131                                         bt_clear_frame_reg(bt, fr, i);
4132                                 else
4133                                         reg->precise = true;
4134                         }
4135
4136                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4137                         for_each_set_bit(i, mask, 64) {
4138                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4139                                         /* the sequence of instructions:
4140                                          * 2: (bf) r3 = r10
4141                                          * 3: (7b) *(u64 *)(r3 -8) = r0
4142                                          * 4: (79) r4 = *(u64 *)(r10 -8)
4143                                          * doesn't contain jmps. It's backtracked
4144                                          * as a single block.
4145                                          * During backtracking insn 3 is not recognized as
4146                                          * stack access, so at the end of backtracking
4147                                          * stack slot fp-8 is still marked in stack_mask.
4148                                          * However the parent state may not have accessed
4149                                          * fp-8 and it's "unallocated" stack space.
4150                                          * In such case fallback to conservative.
4151                                          */
4152                                         mark_all_scalars_precise(env, env->cur_state);
4153                                         bt_reset(bt);
4154                                         return 0;
4155                                 }
4156
4157                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4158                                         bt_clear_frame_slot(bt, fr, i);
4159                                         continue;
4160                                 }
4161                                 reg = &func->stack[i].spilled_ptr;
4162                                 if (reg->precise)
4163                                         bt_clear_frame_slot(bt, fr, i);
4164                                 else
4165                                         reg->precise = true;
4166                         }
4167                         if (env->log.level & BPF_LOG_LEVEL2) {
4168                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4169                                              bt_frame_reg_mask(bt, fr));
4170                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4171                                         fr, env->tmp_str_buf);
4172                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4173                                                bt_frame_stack_mask(bt, fr));
4174                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4175                                 print_verifier_state(env, func, true);
4176                         }
4177                 }
4178
4179                 if (bt_empty(bt))
4180                         return 0;
4181
4182                 subseq_idx = first_idx;
4183                 last_idx = st->last_insn_idx;
4184                 first_idx = st->first_insn_idx;
4185         }
4186
4187         /* if we still have requested precise regs or slots, we missed
4188          * something (e.g., stack access through non-r10 register), so
4189          * fallback to marking all precise
4190          */
4191         if (!bt_empty(bt)) {
4192                 mark_all_scalars_precise(env, env->cur_state);
4193                 bt_reset(bt);
4194         }
4195
4196         return 0;
4197 }
4198
4199 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4200 {
4201         return __mark_chain_precision(env, regno);
4202 }
4203
4204 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4205  * desired reg and stack masks across all relevant frames
4206  */
4207 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4208 {
4209         return __mark_chain_precision(env, -1);
4210 }
4211
4212 static bool is_spillable_regtype(enum bpf_reg_type type)
4213 {
4214         switch (base_type(type)) {
4215         case PTR_TO_MAP_VALUE:
4216         case PTR_TO_STACK:
4217         case PTR_TO_CTX:
4218         case PTR_TO_PACKET:
4219         case PTR_TO_PACKET_META:
4220         case PTR_TO_PACKET_END:
4221         case PTR_TO_FLOW_KEYS:
4222         case CONST_PTR_TO_MAP:
4223         case PTR_TO_SOCKET:
4224         case PTR_TO_SOCK_COMMON:
4225         case PTR_TO_TCP_SOCK:
4226         case PTR_TO_XDP_SOCK:
4227         case PTR_TO_BTF_ID:
4228         case PTR_TO_BUF:
4229         case PTR_TO_MEM:
4230         case PTR_TO_FUNC:
4231         case PTR_TO_MAP_KEY:
4232                 return true;
4233         default:
4234                 return false;
4235         }
4236 }
4237
4238 /* Does this register contain a constant zero? */
4239 static bool register_is_null(struct bpf_reg_state *reg)
4240 {
4241         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4242 }
4243
4244 static bool register_is_const(struct bpf_reg_state *reg)
4245 {
4246         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4247 }
4248
4249 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4250 {
4251         return tnum_is_unknown(reg->var_off) &&
4252                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4253                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4254                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4255                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4256 }
4257
4258 static bool register_is_bounded(struct bpf_reg_state *reg)
4259 {
4260         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4261 }
4262
4263 static bool __is_pointer_value(bool allow_ptr_leaks,
4264                                const struct bpf_reg_state *reg)
4265 {
4266         if (allow_ptr_leaks)
4267                 return false;
4268
4269         return reg->type != SCALAR_VALUE;
4270 }
4271
4272 /* Copy src state preserving dst->parent and dst->live fields */
4273 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4274 {
4275         struct bpf_reg_state *parent = dst->parent;
4276         enum bpf_reg_liveness live = dst->live;
4277
4278         *dst = *src;
4279         dst->parent = parent;
4280         dst->live = live;
4281 }
4282
4283 static void save_register_state(struct bpf_func_state *state,
4284                                 int spi, struct bpf_reg_state *reg,
4285                                 int size)
4286 {
4287         int i;
4288
4289         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4290         if (size == BPF_REG_SIZE)
4291                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4292
4293         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4294                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4295
4296         /* size < 8 bytes spill */
4297         for (; i; i--)
4298                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4299 }
4300
4301 static bool is_bpf_st_mem(struct bpf_insn *insn)
4302 {
4303         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4304 }
4305
4306 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4307  * stack boundary and alignment are checked in check_mem_access()
4308  */
4309 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4310                                        /* stack frame we're writing to */
4311                                        struct bpf_func_state *state,
4312                                        int off, int size, int value_regno,
4313                                        int insn_idx)
4314 {
4315         struct bpf_func_state *cur; /* state of the current function */
4316         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4317         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4318         struct bpf_reg_state *reg = NULL;
4319         u32 dst_reg = insn->dst_reg;
4320
4321         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4322         if (err)
4323                 return err;
4324         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4325          * so it's aligned access and [off, off + size) are within stack limits
4326          */
4327         if (!env->allow_ptr_leaks &&
4328             state->stack[spi].slot_type[0] == STACK_SPILL &&
4329             size != BPF_REG_SIZE) {
4330                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4331                 return -EACCES;
4332         }
4333
4334         cur = env->cur_state->frame[env->cur_state->curframe];
4335         if (value_regno >= 0)
4336                 reg = &cur->regs[value_regno];
4337         if (!env->bypass_spec_v4) {
4338                 bool sanitize = reg && is_spillable_regtype(reg->type);
4339
4340                 for (i = 0; i < size; i++) {
4341                         u8 type = state->stack[spi].slot_type[i];
4342
4343                         if (type != STACK_MISC && type != STACK_ZERO) {
4344                                 sanitize = true;
4345                                 break;
4346                         }
4347                 }
4348
4349                 if (sanitize)
4350                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4351         }
4352
4353         err = destroy_if_dynptr_stack_slot(env, state, spi);
4354         if (err)
4355                 return err;
4356
4357         mark_stack_slot_scratched(env, spi);
4358         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4359             !register_is_null(reg) && env->bpf_capable) {
4360                 if (dst_reg != BPF_REG_FP) {
4361                         /* The backtracking logic can only recognize explicit
4362                          * stack slot address like [fp - 8]. Other spill of
4363                          * scalar via different register has to be conservative.
4364                          * Backtrack from here and mark all registers as precise
4365                          * that contributed into 'reg' being a constant.
4366                          */
4367                         err = mark_chain_precision(env, value_regno);
4368                         if (err)
4369                                 return err;
4370                 }
4371                 save_register_state(state, spi, reg, size);
4372                 /* Break the relation on a narrowing spill. */
4373                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4374                         state->stack[spi].spilled_ptr.id = 0;
4375         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4376                    insn->imm != 0 && env->bpf_capable) {
4377                 struct bpf_reg_state fake_reg = {};
4378
4379                 __mark_reg_known(&fake_reg, (u32)insn->imm);
4380                 fake_reg.type = SCALAR_VALUE;
4381                 save_register_state(state, spi, &fake_reg, size);
4382         } else if (reg && is_spillable_regtype(reg->type)) {
4383                 /* register containing pointer is being spilled into stack */
4384                 if (size != BPF_REG_SIZE) {
4385                         verbose_linfo(env, insn_idx, "; ");
4386                         verbose(env, "invalid size of register spill\n");
4387                         return -EACCES;
4388                 }
4389                 if (state != cur && reg->type == PTR_TO_STACK) {
4390                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4391                         return -EINVAL;
4392                 }
4393                 save_register_state(state, spi, reg, size);
4394         } else {
4395                 u8 type = STACK_MISC;
4396
4397                 /* regular write of data into stack destroys any spilled ptr */
4398                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4399                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4400                 if (is_stack_slot_special(&state->stack[spi]))
4401                         for (i = 0; i < BPF_REG_SIZE; i++)
4402                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4403
4404                 /* only mark the slot as written if all 8 bytes were written
4405                  * otherwise read propagation may incorrectly stop too soon
4406                  * when stack slots are partially written.
4407                  * This heuristic means that read propagation will be
4408                  * conservative, since it will add reg_live_read marks
4409                  * to stack slots all the way to first state when programs
4410                  * writes+reads less than 8 bytes
4411                  */
4412                 if (size == BPF_REG_SIZE)
4413                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4414
4415                 /* when we zero initialize stack slots mark them as such */
4416                 if ((reg && register_is_null(reg)) ||
4417                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4418                         /* backtracking doesn't work for STACK_ZERO yet. */
4419                         err = mark_chain_precision(env, value_regno);
4420                         if (err)
4421                                 return err;
4422                         type = STACK_ZERO;
4423                 }
4424
4425                 /* Mark slots affected by this stack write. */
4426                 for (i = 0; i < size; i++)
4427                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4428                                 type;
4429         }
4430         return 0;
4431 }
4432
4433 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4434  * known to contain a variable offset.
4435  * This function checks whether the write is permitted and conservatively
4436  * tracks the effects of the write, considering that each stack slot in the
4437  * dynamic range is potentially written to.
4438  *
4439  * 'off' includes 'regno->off'.
4440  * 'value_regno' can be -1, meaning that an unknown value is being written to
4441  * the stack.
4442  *
4443  * Spilled pointers in range are not marked as written because we don't know
4444  * what's going to be actually written. This means that read propagation for
4445  * future reads cannot be terminated by this write.
4446  *
4447  * For privileged programs, uninitialized stack slots are considered
4448  * initialized by this write (even though we don't know exactly what offsets
4449  * are going to be written to). The idea is that we don't want the verifier to
4450  * reject future reads that access slots written to through variable offsets.
4451  */
4452 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4453                                      /* func where register points to */
4454                                      struct bpf_func_state *state,
4455                                      int ptr_regno, int off, int size,
4456                                      int value_regno, int insn_idx)
4457 {
4458         struct bpf_func_state *cur; /* state of the current function */
4459         int min_off, max_off;
4460         int i, err;
4461         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4462         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4463         bool writing_zero = false;
4464         /* set if the fact that we're writing a zero is used to let any
4465          * stack slots remain STACK_ZERO
4466          */
4467         bool zero_used = false;
4468
4469         cur = env->cur_state->frame[env->cur_state->curframe];
4470         ptr_reg = &cur->regs[ptr_regno];
4471         min_off = ptr_reg->smin_value + off;
4472         max_off = ptr_reg->smax_value + off + size;
4473         if (value_regno >= 0)
4474                 value_reg = &cur->regs[value_regno];
4475         if ((value_reg && register_is_null(value_reg)) ||
4476             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4477                 writing_zero = true;
4478
4479         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4480         if (err)
4481                 return err;
4482
4483         for (i = min_off; i < max_off; i++) {
4484                 int spi;
4485
4486                 spi = __get_spi(i);
4487                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4488                 if (err)
4489                         return err;
4490         }
4491
4492         /* Variable offset writes destroy any spilled pointers in range. */
4493         for (i = min_off; i < max_off; i++) {
4494                 u8 new_type, *stype;
4495                 int slot, spi;
4496
4497                 slot = -i - 1;
4498                 spi = slot / BPF_REG_SIZE;
4499                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4500                 mark_stack_slot_scratched(env, spi);
4501
4502                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4503                         /* Reject the write if range we may write to has not
4504                          * been initialized beforehand. If we didn't reject
4505                          * here, the ptr status would be erased below (even
4506                          * though not all slots are actually overwritten),
4507                          * possibly opening the door to leaks.
4508                          *
4509                          * We do however catch STACK_INVALID case below, and
4510                          * only allow reading possibly uninitialized memory
4511                          * later for CAP_PERFMON, as the write may not happen to
4512                          * that slot.
4513                          */
4514                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4515                                 insn_idx, i);
4516                         return -EINVAL;
4517                 }
4518
4519                 /* Erase all spilled pointers. */
4520                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4521
4522                 /* Update the slot type. */
4523                 new_type = STACK_MISC;
4524                 if (writing_zero && *stype == STACK_ZERO) {
4525                         new_type = STACK_ZERO;
4526                         zero_used = true;
4527                 }
4528                 /* If the slot is STACK_INVALID, we check whether it's OK to
4529                  * pretend that it will be initialized by this write. The slot
4530                  * might not actually be written to, and so if we mark it as
4531                  * initialized future reads might leak uninitialized memory.
4532                  * For privileged programs, we will accept such reads to slots
4533                  * that may or may not be written because, if we're reject
4534                  * them, the error would be too confusing.
4535                  */
4536                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4537                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4538                                         insn_idx, i);
4539                         return -EINVAL;
4540                 }
4541                 *stype = new_type;
4542         }
4543         if (zero_used) {
4544                 /* backtracking doesn't work for STACK_ZERO yet. */
4545                 err = mark_chain_precision(env, value_regno);
4546                 if (err)
4547                         return err;
4548         }
4549         return 0;
4550 }
4551
4552 /* When register 'dst_regno' is assigned some values from stack[min_off,
4553  * max_off), we set the register's type according to the types of the
4554  * respective stack slots. If all the stack values are known to be zeros, then
4555  * so is the destination reg. Otherwise, the register is considered to be
4556  * SCALAR. This function does not deal with register filling; the caller must
4557  * ensure that all spilled registers in the stack range have been marked as
4558  * read.
4559  */
4560 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4561                                 /* func where src register points to */
4562                                 struct bpf_func_state *ptr_state,
4563                                 int min_off, int max_off, int dst_regno)
4564 {
4565         struct bpf_verifier_state *vstate = env->cur_state;
4566         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4567         int i, slot, spi;
4568         u8 *stype;
4569         int zeros = 0;
4570
4571         for (i = min_off; i < max_off; i++) {
4572                 slot = -i - 1;
4573                 spi = slot / BPF_REG_SIZE;
4574                 mark_stack_slot_scratched(env, spi);
4575                 stype = ptr_state->stack[spi].slot_type;
4576                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4577                         break;
4578                 zeros++;
4579         }
4580         if (zeros == max_off - min_off) {
4581                 /* any access_size read into register is zero extended,
4582                  * so the whole register == const_zero
4583                  */
4584                 __mark_reg_const_zero(&state->regs[dst_regno]);
4585                 /* backtracking doesn't support STACK_ZERO yet,
4586                  * so mark it precise here, so that later
4587                  * backtracking can stop here.
4588                  * Backtracking may not need this if this register
4589                  * doesn't participate in pointer adjustment.
4590                  * Forward propagation of precise flag is not
4591                  * necessary either. This mark is only to stop
4592                  * backtracking. Any register that contributed
4593                  * to const 0 was marked precise before spill.
4594                  */
4595                 state->regs[dst_regno].precise = true;
4596         } else {
4597                 /* have read misc data from the stack */
4598                 mark_reg_unknown(env, state->regs, dst_regno);
4599         }
4600         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4601 }
4602
4603 /* Read the stack at 'off' and put the results into the register indicated by
4604  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4605  * spilled reg.
4606  *
4607  * 'dst_regno' can be -1, meaning that the read value is not going to a
4608  * register.
4609  *
4610  * The access is assumed to be within the current stack bounds.
4611  */
4612 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4613                                       /* func where src register points to */
4614                                       struct bpf_func_state *reg_state,
4615                                       int off, int size, int dst_regno)
4616 {
4617         struct bpf_verifier_state *vstate = env->cur_state;
4618         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4619         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4620         struct bpf_reg_state *reg;
4621         u8 *stype, type;
4622
4623         stype = reg_state->stack[spi].slot_type;
4624         reg = &reg_state->stack[spi].spilled_ptr;
4625
4626         mark_stack_slot_scratched(env, spi);
4627
4628         if (is_spilled_reg(&reg_state->stack[spi])) {
4629                 u8 spill_size = 1;
4630
4631                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4632                         spill_size++;
4633
4634                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4635                         if (reg->type != SCALAR_VALUE) {
4636                                 verbose_linfo(env, env->insn_idx, "; ");
4637                                 verbose(env, "invalid size of register fill\n");
4638                                 return -EACCES;
4639                         }
4640
4641                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4642                         if (dst_regno < 0)
4643                                 return 0;
4644
4645                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4646                                 /* The earlier check_reg_arg() has decided the
4647                                  * subreg_def for this insn.  Save it first.
4648                                  */
4649                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4650
4651                                 copy_register_state(&state->regs[dst_regno], reg);
4652                                 state->regs[dst_regno].subreg_def = subreg_def;
4653                         } else {
4654                                 for (i = 0; i < size; i++) {
4655                                         type = stype[(slot - i) % BPF_REG_SIZE];
4656                                         if (type == STACK_SPILL)
4657                                                 continue;
4658                                         if (type == STACK_MISC)
4659                                                 continue;
4660                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4661                                                 continue;
4662                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4663                                                 off, i, size);
4664                                         return -EACCES;
4665                                 }
4666                                 mark_reg_unknown(env, state->regs, dst_regno);
4667                         }
4668                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4669                         return 0;
4670                 }
4671
4672                 if (dst_regno >= 0) {
4673                         /* restore register state from stack */
4674                         copy_register_state(&state->regs[dst_regno], reg);
4675                         /* mark reg as written since spilled pointer state likely
4676                          * has its liveness marks cleared by is_state_visited()
4677                          * which resets stack/reg liveness for state transitions
4678                          */
4679                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4680                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4681                         /* If dst_regno==-1, the caller is asking us whether
4682                          * it is acceptable to use this value as a SCALAR_VALUE
4683                          * (e.g. for XADD).
4684                          * We must not allow unprivileged callers to do that
4685                          * with spilled pointers.
4686                          */
4687                         verbose(env, "leaking pointer from stack off %d\n",
4688                                 off);
4689                         return -EACCES;
4690                 }
4691                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4692         } else {
4693                 for (i = 0; i < size; i++) {
4694                         type = stype[(slot - i) % BPF_REG_SIZE];
4695                         if (type == STACK_MISC)
4696                                 continue;
4697                         if (type == STACK_ZERO)
4698                                 continue;
4699                         if (type == STACK_INVALID && env->allow_uninit_stack)
4700                                 continue;
4701                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4702                                 off, i, size);
4703                         return -EACCES;
4704                 }
4705                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4706                 if (dst_regno >= 0)
4707                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4708         }
4709         return 0;
4710 }
4711
4712 enum bpf_access_src {
4713         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4714         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4715 };
4716
4717 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4718                                          int regno, int off, int access_size,
4719                                          bool zero_size_allowed,
4720                                          enum bpf_access_src type,
4721                                          struct bpf_call_arg_meta *meta);
4722
4723 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4724 {
4725         return cur_regs(env) + regno;
4726 }
4727
4728 /* Read the stack at 'ptr_regno + off' and put the result into the register
4729  * 'dst_regno'.
4730  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4731  * but not its variable offset.
4732  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4733  *
4734  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4735  * filling registers (i.e. reads of spilled register cannot be detected when
4736  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4737  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4738  * offset; for a fixed offset check_stack_read_fixed_off should be used
4739  * instead.
4740  */
4741 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4742                                     int ptr_regno, int off, int size, int dst_regno)
4743 {
4744         /* The state of the source register. */
4745         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4746         struct bpf_func_state *ptr_state = func(env, reg);
4747         int err;
4748         int min_off, max_off;
4749
4750         /* Note that we pass a NULL meta, so raw access will not be permitted.
4751          */
4752         err = check_stack_range_initialized(env, ptr_regno, off, size,
4753                                             false, ACCESS_DIRECT, NULL);
4754         if (err)
4755                 return err;
4756
4757         min_off = reg->smin_value + off;
4758         max_off = reg->smax_value + off;
4759         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4760         return 0;
4761 }
4762
4763 /* check_stack_read dispatches to check_stack_read_fixed_off or
4764  * check_stack_read_var_off.
4765  *
4766  * The caller must ensure that the offset falls within the allocated stack
4767  * bounds.
4768  *
4769  * 'dst_regno' is a register which will receive the value from the stack. It
4770  * can be -1, meaning that the read value is not going to a register.
4771  */
4772 static int check_stack_read(struct bpf_verifier_env *env,
4773                             int ptr_regno, int off, int size,
4774                             int dst_regno)
4775 {
4776         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4777         struct bpf_func_state *state = func(env, reg);
4778         int err;
4779         /* Some accesses are only permitted with a static offset. */
4780         bool var_off = !tnum_is_const(reg->var_off);
4781
4782         /* The offset is required to be static when reads don't go to a
4783          * register, in order to not leak pointers (see
4784          * check_stack_read_fixed_off).
4785          */
4786         if (dst_regno < 0 && var_off) {
4787                 char tn_buf[48];
4788
4789                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4790                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4791                         tn_buf, off, size);
4792                 return -EACCES;
4793         }
4794         /* Variable offset is prohibited for unprivileged mode for simplicity
4795          * since it requires corresponding support in Spectre masking for stack
4796          * ALU. See also retrieve_ptr_limit(). The check in
4797          * check_stack_access_for_ptr_arithmetic() called by
4798          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4799          * with variable offsets, therefore no check is required here. Further,
4800          * just checking it here would be insufficient as speculative stack
4801          * writes could still lead to unsafe speculative behaviour.
4802          */
4803         if (!var_off) {
4804                 off += reg->var_off.value;
4805                 err = check_stack_read_fixed_off(env, state, off, size,
4806                                                  dst_regno);
4807         } else {
4808                 /* Variable offset stack reads need more conservative handling
4809                  * than fixed offset ones. Note that dst_regno >= 0 on this
4810                  * branch.
4811                  */
4812                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4813                                                dst_regno);
4814         }
4815         return err;
4816 }
4817
4818
4819 /* check_stack_write dispatches to check_stack_write_fixed_off or
4820  * check_stack_write_var_off.
4821  *
4822  * 'ptr_regno' is the register used as a pointer into the stack.
4823  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4824  * 'value_regno' is the register whose value we're writing to the stack. It can
4825  * be -1, meaning that we're not writing from a register.
4826  *
4827  * The caller must ensure that the offset falls within the maximum stack size.
4828  */
4829 static int check_stack_write(struct bpf_verifier_env *env,
4830                              int ptr_regno, int off, int size,
4831                              int value_regno, int insn_idx)
4832 {
4833         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4834         struct bpf_func_state *state = func(env, reg);
4835         int err;
4836
4837         if (tnum_is_const(reg->var_off)) {
4838                 off += reg->var_off.value;
4839                 err = check_stack_write_fixed_off(env, state, off, size,
4840                                                   value_regno, insn_idx);
4841         } else {
4842                 /* Variable offset stack reads need more conservative handling
4843                  * than fixed offset ones.
4844                  */
4845                 err = check_stack_write_var_off(env, state,
4846                                                 ptr_regno, off, size,
4847                                                 value_regno, insn_idx);
4848         }
4849         return err;
4850 }
4851
4852 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4853                                  int off, int size, enum bpf_access_type type)
4854 {
4855         struct bpf_reg_state *regs = cur_regs(env);
4856         struct bpf_map *map = regs[regno].map_ptr;
4857         u32 cap = bpf_map_flags_to_cap(map);
4858
4859         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4860                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4861                         map->value_size, off, size);
4862                 return -EACCES;
4863         }
4864
4865         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4866                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4867                         map->value_size, off, size);
4868                 return -EACCES;
4869         }
4870
4871         return 0;
4872 }
4873
4874 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4875 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4876                               int off, int size, u32 mem_size,
4877                               bool zero_size_allowed)
4878 {
4879         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4880         struct bpf_reg_state *reg;
4881
4882         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4883                 return 0;
4884
4885         reg = &cur_regs(env)[regno];
4886         switch (reg->type) {
4887         case PTR_TO_MAP_KEY:
4888                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4889                         mem_size, off, size);
4890                 break;
4891         case PTR_TO_MAP_VALUE:
4892                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4893                         mem_size, off, size);
4894                 break;
4895         case PTR_TO_PACKET:
4896         case PTR_TO_PACKET_META:
4897         case PTR_TO_PACKET_END:
4898                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4899                         off, size, regno, reg->id, off, mem_size);
4900                 break;
4901         case PTR_TO_MEM:
4902         default:
4903                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4904                         mem_size, off, size);
4905         }
4906
4907         return -EACCES;
4908 }
4909
4910 /* check read/write into a memory region with possible variable offset */
4911 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4912                                    int off, int size, u32 mem_size,
4913                                    bool zero_size_allowed)
4914 {
4915         struct bpf_verifier_state *vstate = env->cur_state;
4916         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4917         struct bpf_reg_state *reg = &state->regs[regno];
4918         int err;
4919
4920         /* We may have adjusted the register pointing to memory region, so we
4921          * need to try adding each of min_value and max_value to off
4922          * to make sure our theoretical access will be safe.
4923          *
4924          * The minimum value is only important with signed
4925          * comparisons where we can't assume the floor of a
4926          * value is 0.  If we are using signed variables for our
4927          * index'es we need to make sure that whatever we use
4928          * will have a set floor within our range.
4929          */
4930         if (reg->smin_value < 0 &&
4931             (reg->smin_value == S64_MIN ||
4932              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4933               reg->smin_value + off < 0)) {
4934                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4935                         regno);
4936                 return -EACCES;
4937         }
4938         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4939                                  mem_size, zero_size_allowed);
4940         if (err) {
4941                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4942                         regno);
4943                 return err;
4944         }
4945
4946         /* If we haven't set a max value then we need to bail since we can't be
4947          * sure we won't do bad things.
4948          * If reg->umax_value + off could overflow, treat that as unbounded too.
4949          */
4950         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4951                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4952                         regno);
4953                 return -EACCES;
4954         }
4955         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4956                                  mem_size, zero_size_allowed);
4957         if (err) {
4958                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4959                         regno);
4960                 return err;
4961         }
4962
4963         return 0;
4964 }
4965
4966 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4967                                const struct bpf_reg_state *reg, int regno,
4968                                bool fixed_off_ok)
4969 {
4970         /* Access to this pointer-typed register or passing it to a helper
4971          * is only allowed in its original, unmodified form.
4972          */
4973
4974         if (reg->off < 0) {
4975                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4976                         reg_type_str(env, reg->type), regno, reg->off);
4977                 return -EACCES;
4978         }
4979
4980         if (!fixed_off_ok && reg->off) {
4981                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4982                         reg_type_str(env, reg->type), regno, reg->off);
4983                 return -EACCES;
4984         }
4985
4986         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4987                 char tn_buf[48];
4988
4989                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4990                 verbose(env, "variable %s access var_off=%s disallowed\n",
4991                         reg_type_str(env, reg->type), tn_buf);
4992                 return -EACCES;
4993         }
4994
4995         return 0;
4996 }
4997
4998 int check_ptr_off_reg(struct bpf_verifier_env *env,
4999                       const struct bpf_reg_state *reg, int regno)
5000 {
5001         return __check_ptr_off_reg(env, reg, regno, false);
5002 }
5003
5004 static int map_kptr_match_type(struct bpf_verifier_env *env,
5005                                struct btf_field *kptr_field,
5006                                struct bpf_reg_state *reg, u32 regno)
5007 {
5008         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5009         int perm_flags;
5010         const char *reg_name = "";
5011
5012         if (btf_is_kernel(reg->btf)) {
5013                 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5014
5015                 /* Only unreferenced case accepts untrusted pointers */
5016                 if (kptr_field->type == BPF_KPTR_UNREF)
5017                         perm_flags |= PTR_UNTRUSTED;
5018         } else {
5019                 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5020         }
5021
5022         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5023                 goto bad_type;
5024
5025         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5026         reg_name = btf_type_name(reg->btf, reg->btf_id);
5027
5028         /* For ref_ptr case, release function check should ensure we get one
5029          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5030          * normal store of unreferenced kptr, we must ensure var_off is zero.
5031          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5032          * reg->off and reg->ref_obj_id are not needed here.
5033          */
5034         if (__check_ptr_off_reg(env, reg, regno, true))
5035                 return -EACCES;
5036
5037         /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5038          * we also need to take into account the reg->off.
5039          *
5040          * We want to support cases like:
5041          *
5042          * struct foo {
5043          *         struct bar br;
5044          *         struct baz bz;
5045          * };
5046          *
5047          * struct foo *v;
5048          * v = func();        // PTR_TO_BTF_ID
5049          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5050          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5051          *                    // first member type of struct after comparison fails
5052          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5053          *                    // to match type
5054          *
5055          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5056          * is zero. We must also ensure that btf_struct_ids_match does not walk
5057          * the struct to match type against first member of struct, i.e. reject
5058          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5059          * strict mode to true for type match.
5060          */
5061         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5062                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5063                                   kptr_field->type == BPF_KPTR_REF))
5064                 goto bad_type;
5065         return 0;
5066 bad_type:
5067         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5068                 reg_type_str(env, reg->type), reg_name);
5069         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5070         if (kptr_field->type == BPF_KPTR_UNREF)
5071                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5072                         targ_name);
5073         else
5074                 verbose(env, "\n");
5075         return -EINVAL;
5076 }
5077
5078 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5079  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5080  */
5081 static bool in_rcu_cs(struct bpf_verifier_env *env)
5082 {
5083         return env->cur_state->active_rcu_lock ||
5084                env->cur_state->active_lock.ptr ||
5085                !env->prog->aux->sleepable;
5086 }
5087
5088 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5089 BTF_SET_START(rcu_protected_types)
5090 BTF_ID(struct, prog_test_ref_kfunc)
5091 BTF_ID(struct, cgroup)
5092 BTF_ID(struct, bpf_cpumask)
5093 BTF_ID(struct, task_struct)
5094 BTF_SET_END(rcu_protected_types)
5095
5096 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5097 {
5098         if (!btf_is_kernel(btf))
5099                 return false;
5100         return btf_id_set_contains(&rcu_protected_types, btf_id);
5101 }
5102
5103 static bool rcu_safe_kptr(const struct btf_field *field)
5104 {
5105         const struct btf_field_kptr *kptr = &field->kptr;
5106
5107         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5108 }
5109
5110 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5111                                  int value_regno, int insn_idx,
5112                                  struct btf_field *kptr_field)
5113 {
5114         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5115         int class = BPF_CLASS(insn->code);
5116         struct bpf_reg_state *val_reg;
5117
5118         /* Things we already checked for in check_map_access and caller:
5119          *  - Reject cases where variable offset may touch kptr
5120          *  - size of access (must be BPF_DW)
5121          *  - tnum_is_const(reg->var_off)
5122          *  - kptr_field->offset == off + reg->var_off.value
5123          */
5124         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5125         if (BPF_MODE(insn->code) != BPF_MEM) {
5126                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5127                 return -EACCES;
5128         }
5129
5130         /* We only allow loading referenced kptr, since it will be marked as
5131          * untrusted, similar to unreferenced kptr.
5132          */
5133         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5134                 verbose(env, "store to referenced kptr disallowed\n");
5135                 return -EACCES;
5136         }
5137
5138         if (class == BPF_LDX) {
5139                 val_reg = reg_state(env, value_regno);
5140                 /* We can simply mark the value_regno receiving the pointer
5141                  * value from map as PTR_TO_BTF_ID, with the correct type.
5142                  */
5143                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5144                                 kptr_field->kptr.btf_id,
5145                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5146                                 PTR_MAYBE_NULL | MEM_RCU :
5147                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5148                 /* For mark_ptr_or_null_reg */
5149                 val_reg->id = ++env->id_gen;
5150         } else if (class == BPF_STX) {
5151                 val_reg = reg_state(env, value_regno);
5152                 if (!register_is_null(val_reg) &&
5153                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5154                         return -EACCES;
5155         } else if (class == BPF_ST) {
5156                 if (insn->imm) {
5157                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5158                                 kptr_field->offset);
5159                         return -EACCES;
5160                 }
5161         } else {
5162                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5163                 return -EACCES;
5164         }
5165         return 0;
5166 }
5167
5168 /* check read/write into a map element with possible variable offset */
5169 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5170                             int off, int size, bool zero_size_allowed,
5171                             enum bpf_access_src src)
5172 {
5173         struct bpf_verifier_state *vstate = env->cur_state;
5174         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5175         struct bpf_reg_state *reg = &state->regs[regno];
5176         struct bpf_map *map = reg->map_ptr;
5177         struct btf_record *rec;
5178         int err, i;
5179
5180         err = check_mem_region_access(env, regno, off, size, map->value_size,
5181                                       zero_size_allowed);
5182         if (err)
5183                 return err;
5184
5185         if (IS_ERR_OR_NULL(map->record))
5186                 return 0;
5187         rec = map->record;
5188         for (i = 0; i < rec->cnt; i++) {
5189                 struct btf_field *field = &rec->fields[i];
5190                 u32 p = field->offset;
5191
5192                 /* If any part of a field  can be touched by load/store, reject
5193                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5194                  * it is sufficient to check x1 < y2 && y1 < x2.
5195                  */
5196                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5197                     p < reg->umax_value + off + size) {
5198                         switch (field->type) {
5199                         case BPF_KPTR_UNREF:
5200                         case BPF_KPTR_REF:
5201                                 if (src != ACCESS_DIRECT) {
5202                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5203                                         return -EACCES;
5204                                 }
5205                                 if (!tnum_is_const(reg->var_off)) {
5206                                         verbose(env, "kptr access cannot have variable offset\n");
5207                                         return -EACCES;
5208                                 }
5209                                 if (p != off + reg->var_off.value) {
5210                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5211                                                 p, off + reg->var_off.value);
5212                                         return -EACCES;
5213                                 }
5214                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5215                                         verbose(env, "kptr access size must be BPF_DW\n");
5216                                         return -EACCES;
5217                                 }
5218                                 break;
5219                         default:
5220                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5221                                         btf_field_type_name(field->type));
5222                                 return -EACCES;
5223                         }
5224                 }
5225         }
5226         return 0;
5227 }
5228
5229 #define MAX_PACKET_OFF 0xffff
5230
5231 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5232                                        const struct bpf_call_arg_meta *meta,
5233                                        enum bpf_access_type t)
5234 {
5235         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5236
5237         switch (prog_type) {
5238         /* Program types only with direct read access go here! */
5239         case BPF_PROG_TYPE_LWT_IN:
5240         case BPF_PROG_TYPE_LWT_OUT:
5241         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5242         case BPF_PROG_TYPE_SK_REUSEPORT:
5243         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5244         case BPF_PROG_TYPE_CGROUP_SKB:
5245                 if (t == BPF_WRITE)
5246                         return false;
5247                 fallthrough;
5248
5249         /* Program types with direct read + write access go here! */
5250         case BPF_PROG_TYPE_SCHED_CLS:
5251         case BPF_PROG_TYPE_SCHED_ACT:
5252         case BPF_PROG_TYPE_XDP:
5253         case BPF_PROG_TYPE_LWT_XMIT:
5254         case BPF_PROG_TYPE_SK_SKB:
5255         case BPF_PROG_TYPE_SK_MSG:
5256                 if (meta)
5257                         return meta->pkt_access;
5258
5259                 env->seen_direct_write = true;
5260                 return true;
5261
5262         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5263                 if (t == BPF_WRITE)
5264                         env->seen_direct_write = true;
5265
5266                 return true;
5267
5268         default:
5269                 return false;
5270         }
5271 }
5272
5273 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5274                                int size, bool zero_size_allowed)
5275 {
5276         struct bpf_reg_state *regs = cur_regs(env);
5277         struct bpf_reg_state *reg = &regs[regno];
5278         int err;
5279
5280         /* We may have added a variable offset to the packet pointer; but any
5281          * reg->range we have comes after that.  We are only checking the fixed
5282          * offset.
5283          */
5284
5285         /* We don't allow negative numbers, because we aren't tracking enough
5286          * detail to prove they're safe.
5287          */
5288         if (reg->smin_value < 0) {
5289                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5290                         regno);
5291                 return -EACCES;
5292         }
5293
5294         err = reg->range < 0 ? -EINVAL :
5295               __check_mem_access(env, regno, off, size, reg->range,
5296                                  zero_size_allowed);
5297         if (err) {
5298                 verbose(env, "R%d offset is outside of the packet\n", regno);
5299                 return err;
5300         }
5301
5302         /* __check_mem_access has made sure "off + size - 1" is within u16.
5303          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5304          * otherwise find_good_pkt_pointers would have refused to set range info
5305          * that __check_mem_access would have rejected this pkt access.
5306          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5307          */
5308         env->prog->aux->max_pkt_offset =
5309                 max_t(u32, env->prog->aux->max_pkt_offset,
5310                       off + reg->umax_value + size - 1);
5311
5312         return err;
5313 }
5314
5315 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5316 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5317                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5318                             struct btf **btf, u32 *btf_id)
5319 {
5320         struct bpf_insn_access_aux info = {
5321                 .reg_type = *reg_type,
5322                 .log = &env->log,
5323         };
5324
5325         if (env->ops->is_valid_access &&
5326             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5327                 /* A non zero info.ctx_field_size indicates that this field is a
5328                  * candidate for later verifier transformation to load the whole
5329                  * field and then apply a mask when accessed with a narrower
5330                  * access than actual ctx access size. A zero info.ctx_field_size
5331                  * will only allow for whole field access and rejects any other
5332                  * type of narrower access.
5333                  */
5334                 *reg_type = info.reg_type;
5335
5336                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5337                         *btf = info.btf;
5338                         *btf_id = info.btf_id;
5339                 } else {
5340                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5341                 }
5342                 /* remember the offset of last byte accessed in ctx */
5343                 if (env->prog->aux->max_ctx_offset < off + size)
5344                         env->prog->aux->max_ctx_offset = off + size;
5345                 return 0;
5346         }
5347
5348         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5349         return -EACCES;
5350 }
5351
5352 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5353                                   int size)
5354 {
5355         if (size < 0 || off < 0 ||
5356             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5357                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5358                         off, size);
5359                 return -EACCES;
5360         }
5361         return 0;
5362 }
5363
5364 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5365                              u32 regno, int off, int size,
5366                              enum bpf_access_type t)
5367 {
5368         struct bpf_reg_state *regs = cur_regs(env);
5369         struct bpf_reg_state *reg = &regs[regno];
5370         struct bpf_insn_access_aux info = {};
5371         bool valid;
5372
5373         if (reg->smin_value < 0) {
5374                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5375                         regno);
5376                 return -EACCES;
5377         }
5378
5379         switch (reg->type) {
5380         case PTR_TO_SOCK_COMMON:
5381                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5382                 break;
5383         case PTR_TO_SOCKET:
5384                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5385                 break;
5386         case PTR_TO_TCP_SOCK:
5387                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5388                 break;
5389         case PTR_TO_XDP_SOCK:
5390                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5391                 break;
5392         default:
5393                 valid = false;
5394         }
5395
5396
5397         if (valid) {
5398                 env->insn_aux_data[insn_idx].ctx_field_size =
5399                         info.ctx_field_size;
5400                 return 0;
5401         }
5402
5403         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5404                 regno, reg_type_str(env, reg->type), off, size);
5405
5406         return -EACCES;
5407 }
5408
5409 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5410 {
5411         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5412 }
5413
5414 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5415 {
5416         const struct bpf_reg_state *reg = reg_state(env, regno);
5417
5418         return reg->type == PTR_TO_CTX;
5419 }
5420
5421 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5422 {
5423         const struct bpf_reg_state *reg = reg_state(env, regno);
5424
5425         return type_is_sk_pointer(reg->type);
5426 }
5427
5428 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5429 {
5430         const struct bpf_reg_state *reg = reg_state(env, regno);
5431
5432         return type_is_pkt_pointer(reg->type);
5433 }
5434
5435 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5436 {
5437         const struct bpf_reg_state *reg = reg_state(env, regno);
5438
5439         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5440         return reg->type == PTR_TO_FLOW_KEYS;
5441 }
5442
5443 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5444 #ifdef CONFIG_NET
5445         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5446         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5447         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5448 #endif
5449         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5450 };
5451
5452 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5453 {
5454         /* A referenced register is always trusted. */
5455         if (reg->ref_obj_id)
5456                 return true;
5457
5458         /* Types listed in the reg2btf_ids are always trusted */
5459         if (reg2btf_ids[base_type(reg->type)])
5460                 return true;
5461
5462         /* If a register is not referenced, it is trusted if it has the
5463          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5464          * other type modifiers may be safe, but we elect to take an opt-in
5465          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5466          * not.
5467          *
5468          * Eventually, we should make PTR_TRUSTED the single source of truth
5469          * for whether a register is trusted.
5470          */
5471         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5472                !bpf_type_has_unsafe_modifiers(reg->type);
5473 }
5474
5475 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5476 {
5477         return reg->type & MEM_RCU;
5478 }
5479
5480 static void clear_trusted_flags(enum bpf_type_flag *flag)
5481 {
5482         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5483 }
5484
5485 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5486                                    const struct bpf_reg_state *reg,
5487                                    int off, int size, bool strict)
5488 {
5489         struct tnum reg_off;
5490         int ip_align;
5491
5492         /* Byte size accesses are always allowed. */
5493         if (!strict || size == 1)
5494                 return 0;
5495
5496         /* For platforms that do not have a Kconfig enabling
5497          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5498          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5499          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5500          * to this code only in strict mode where we want to emulate
5501          * the NET_IP_ALIGN==2 checking.  Therefore use an
5502          * unconditional IP align value of '2'.
5503          */
5504         ip_align = 2;
5505
5506         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5507         if (!tnum_is_aligned(reg_off, size)) {
5508                 char tn_buf[48];
5509
5510                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5511                 verbose(env,
5512                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5513                         ip_align, tn_buf, reg->off, off, size);
5514                 return -EACCES;
5515         }
5516
5517         return 0;
5518 }
5519
5520 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5521                                        const struct bpf_reg_state *reg,
5522                                        const char *pointer_desc,
5523                                        int off, int size, bool strict)
5524 {
5525         struct tnum reg_off;
5526
5527         /* Byte size accesses are always allowed. */
5528         if (!strict || size == 1)
5529                 return 0;
5530
5531         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5532         if (!tnum_is_aligned(reg_off, size)) {
5533                 char tn_buf[48];
5534
5535                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5536                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5537                         pointer_desc, tn_buf, reg->off, off, size);
5538                 return -EACCES;
5539         }
5540
5541         return 0;
5542 }
5543
5544 static int check_ptr_alignment(struct bpf_verifier_env *env,
5545                                const struct bpf_reg_state *reg, int off,
5546                                int size, bool strict_alignment_once)
5547 {
5548         bool strict = env->strict_alignment || strict_alignment_once;
5549         const char *pointer_desc = "";
5550
5551         switch (reg->type) {
5552         case PTR_TO_PACKET:
5553         case PTR_TO_PACKET_META:
5554                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5555                  * right in front, treat it the very same way.
5556                  */
5557                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5558         case PTR_TO_FLOW_KEYS:
5559                 pointer_desc = "flow keys ";
5560                 break;
5561         case PTR_TO_MAP_KEY:
5562                 pointer_desc = "key ";
5563                 break;
5564         case PTR_TO_MAP_VALUE:
5565                 pointer_desc = "value ";
5566                 break;
5567         case PTR_TO_CTX:
5568                 pointer_desc = "context ";
5569                 break;
5570         case PTR_TO_STACK:
5571                 pointer_desc = "stack ";
5572                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5573                  * and check_stack_read_fixed_off() relies on stack accesses being
5574                  * aligned.
5575                  */
5576                 strict = true;
5577                 break;
5578         case PTR_TO_SOCKET:
5579                 pointer_desc = "sock ";
5580                 break;
5581         case PTR_TO_SOCK_COMMON:
5582                 pointer_desc = "sock_common ";
5583                 break;
5584         case PTR_TO_TCP_SOCK:
5585                 pointer_desc = "tcp_sock ";
5586                 break;
5587         case PTR_TO_XDP_SOCK:
5588                 pointer_desc = "xdp_sock ";
5589                 break;
5590         default:
5591                 break;
5592         }
5593         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5594                                            strict);
5595 }
5596
5597 static int update_stack_depth(struct bpf_verifier_env *env,
5598                               const struct bpf_func_state *func,
5599                               int off)
5600 {
5601         u16 stack = env->subprog_info[func->subprogno].stack_depth;
5602
5603         if (stack >= -off)
5604                 return 0;
5605
5606         /* update known max for given subprogram */
5607         env->subprog_info[func->subprogno].stack_depth = -off;
5608         return 0;
5609 }
5610
5611 /* starting from main bpf function walk all instructions of the function
5612  * and recursively walk all callees that given function can call.
5613  * Ignore jump and exit insns.
5614  * Since recursion is prevented by check_cfg() this algorithm
5615  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5616  */
5617 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5618 {
5619         struct bpf_subprog_info *subprog = env->subprog_info;
5620         struct bpf_insn *insn = env->prog->insnsi;
5621         int depth = 0, frame = 0, i, subprog_end;
5622         bool tail_call_reachable = false;
5623         int ret_insn[MAX_CALL_FRAMES];
5624         int ret_prog[MAX_CALL_FRAMES];
5625         int j;
5626
5627         i = subprog[idx].start;
5628 process_func:
5629         /* protect against potential stack overflow that might happen when
5630          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5631          * depth for such case down to 256 so that the worst case scenario
5632          * would result in 8k stack size (32 which is tailcall limit * 256 =
5633          * 8k).
5634          *
5635          * To get the idea what might happen, see an example:
5636          * func1 -> sub rsp, 128
5637          *  subfunc1 -> sub rsp, 256
5638          *  tailcall1 -> add rsp, 256
5639          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5640          *   subfunc2 -> sub rsp, 64
5641          *   subfunc22 -> sub rsp, 128
5642          *   tailcall2 -> add rsp, 128
5643          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5644          *
5645          * tailcall will unwind the current stack frame but it will not get rid
5646          * of caller's stack as shown on the example above.
5647          */
5648         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5649                 verbose(env,
5650                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5651                         depth);
5652                 return -EACCES;
5653         }
5654         /* round up to 32-bytes, since this is granularity
5655          * of interpreter stack size
5656          */
5657         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5658         if (depth > MAX_BPF_STACK) {
5659                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5660                         frame + 1, depth);
5661                 return -EACCES;
5662         }
5663 continue_func:
5664         subprog_end = subprog[idx + 1].start;
5665         for (; i < subprog_end; i++) {
5666                 int next_insn, sidx;
5667
5668                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5669                         continue;
5670                 /* remember insn and function to return to */
5671                 ret_insn[frame] = i + 1;
5672                 ret_prog[frame] = idx;
5673
5674                 /* find the callee */
5675                 next_insn = i + insn[i].imm + 1;
5676                 sidx = find_subprog(env, next_insn);
5677                 if (sidx < 0) {
5678                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5679                                   next_insn);
5680                         return -EFAULT;
5681                 }
5682                 if (subprog[sidx].is_async_cb) {
5683                         if (subprog[sidx].has_tail_call) {
5684                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5685                                 return -EFAULT;
5686                         }
5687                         /* async callbacks don't increase bpf prog stack size unless called directly */
5688                         if (!bpf_pseudo_call(insn + i))
5689                                 continue;
5690                 }
5691                 i = next_insn;
5692                 idx = sidx;
5693
5694                 if (subprog[idx].has_tail_call)
5695                         tail_call_reachable = true;
5696
5697                 frame++;
5698                 if (frame >= MAX_CALL_FRAMES) {
5699                         verbose(env, "the call stack of %d frames is too deep !\n",
5700                                 frame);
5701                         return -E2BIG;
5702                 }
5703                 goto process_func;
5704         }
5705         /* if tail call got detected across bpf2bpf calls then mark each of the
5706          * currently present subprog frames as tail call reachable subprogs;
5707          * this info will be utilized by JIT so that we will be preserving the
5708          * tail call counter throughout bpf2bpf calls combined with tailcalls
5709          */
5710         if (tail_call_reachable)
5711                 for (j = 0; j < frame; j++)
5712                         subprog[ret_prog[j]].tail_call_reachable = true;
5713         if (subprog[0].tail_call_reachable)
5714                 env->prog->aux->tail_call_reachable = true;
5715
5716         /* end of for() loop means the last insn of the 'subprog'
5717          * was reached. Doesn't matter whether it was JA or EXIT
5718          */
5719         if (frame == 0)
5720                 return 0;
5721         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5722         frame--;
5723         i = ret_insn[frame];
5724         idx = ret_prog[frame];
5725         goto continue_func;
5726 }
5727
5728 static int check_max_stack_depth(struct bpf_verifier_env *env)
5729 {
5730         struct bpf_subprog_info *si = env->subprog_info;
5731         int ret;
5732
5733         for (int i = 0; i < env->subprog_cnt; i++) {
5734                 if (!i || si[i].is_async_cb) {
5735                         ret = check_max_stack_depth_subprog(env, i);
5736                         if (ret < 0)
5737                                 return ret;
5738                 }
5739                 continue;
5740         }
5741         return 0;
5742 }
5743
5744 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5745 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5746                                   const struct bpf_insn *insn, int idx)
5747 {
5748         int start = idx + insn->imm + 1, subprog;
5749
5750         subprog = find_subprog(env, start);
5751         if (subprog < 0) {
5752                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5753                           start);
5754                 return -EFAULT;
5755         }
5756         return env->subprog_info[subprog].stack_depth;
5757 }
5758 #endif
5759
5760 static int __check_buffer_access(struct bpf_verifier_env *env,
5761                                  const char *buf_info,
5762                                  const struct bpf_reg_state *reg,
5763                                  int regno, int off, int size)
5764 {
5765         if (off < 0) {
5766                 verbose(env,
5767                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5768                         regno, buf_info, off, size);
5769                 return -EACCES;
5770         }
5771         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5772                 char tn_buf[48];
5773
5774                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5775                 verbose(env,
5776                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5777                         regno, off, tn_buf);
5778                 return -EACCES;
5779         }
5780
5781         return 0;
5782 }
5783
5784 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5785                                   const struct bpf_reg_state *reg,
5786                                   int regno, int off, int size)
5787 {
5788         int err;
5789
5790         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5791         if (err)
5792                 return err;
5793
5794         if (off + size > env->prog->aux->max_tp_access)
5795                 env->prog->aux->max_tp_access = off + size;
5796
5797         return 0;
5798 }
5799
5800 static int check_buffer_access(struct bpf_verifier_env *env,
5801                                const struct bpf_reg_state *reg,
5802                                int regno, int off, int size,
5803                                bool zero_size_allowed,
5804                                u32 *max_access)
5805 {
5806         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5807         int err;
5808
5809         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5810         if (err)
5811                 return err;
5812
5813         if (off + size > *max_access)
5814                 *max_access = off + size;
5815
5816         return 0;
5817 }
5818
5819 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5820 static void zext_32_to_64(struct bpf_reg_state *reg)
5821 {
5822         reg->var_off = tnum_subreg(reg->var_off);
5823         __reg_assign_32_into_64(reg);
5824 }
5825
5826 /* truncate register to smaller size (in bytes)
5827  * must be called with size < BPF_REG_SIZE
5828  */
5829 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5830 {
5831         u64 mask;
5832
5833         /* clear high bits in bit representation */
5834         reg->var_off = tnum_cast(reg->var_off, size);
5835
5836         /* fix arithmetic bounds */
5837         mask = ((u64)1 << (size * 8)) - 1;
5838         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5839                 reg->umin_value &= mask;
5840                 reg->umax_value &= mask;
5841         } else {
5842                 reg->umin_value = 0;
5843                 reg->umax_value = mask;
5844         }
5845         reg->smin_value = reg->umin_value;
5846         reg->smax_value = reg->umax_value;
5847
5848         /* If size is smaller than 32bit register the 32bit register
5849          * values are also truncated so we push 64-bit bounds into
5850          * 32-bit bounds. Above were truncated < 32-bits already.
5851          */
5852         if (size >= 4)
5853                 return;
5854         __reg_combine_64_into_32(reg);
5855 }
5856
5857 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5858 {
5859         if (size == 1) {
5860                 reg->smin_value = reg->s32_min_value = S8_MIN;
5861                 reg->smax_value = reg->s32_max_value = S8_MAX;
5862         } else if (size == 2) {
5863                 reg->smin_value = reg->s32_min_value = S16_MIN;
5864                 reg->smax_value = reg->s32_max_value = S16_MAX;
5865         } else {
5866                 /* size == 4 */
5867                 reg->smin_value = reg->s32_min_value = S32_MIN;
5868                 reg->smax_value = reg->s32_max_value = S32_MAX;
5869         }
5870         reg->umin_value = reg->u32_min_value = 0;
5871         reg->umax_value = U64_MAX;
5872         reg->u32_max_value = U32_MAX;
5873         reg->var_off = tnum_unknown;
5874 }
5875
5876 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5877 {
5878         s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5879         u64 top_smax_value, top_smin_value;
5880         u64 num_bits = size * 8;
5881
5882         if (tnum_is_const(reg->var_off)) {
5883                 u64_cval = reg->var_off.value;
5884                 if (size == 1)
5885                         reg->var_off = tnum_const((s8)u64_cval);
5886                 else if (size == 2)
5887                         reg->var_off = tnum_const((s16)u64_cval);
5888                 else
5889                         /* size == 4 */
5890                         reg->var_off = tnum_const((s32)u64_cval);
5891
5892                 u64_cval = reg->var_off.value;
5893                 reg->smax_value = reg->smin_value = u64_cval;
5894                 reg->umax_value = reg->umin_value = u64_cval;
5895                 reg->s32_max_value = reg->s32_min_value = u64_cval;
5896                 reg->u32_max_value = reg->u32_min_value = u64_cval;
5897                 return;
5898         }
5899
5900         top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5901         top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5902
5903         if (top_smax_value != top_smin_value)
5904                 goto out;
5905
5906         /* find the s64_min and s64_min after sign extension */
5907         if (size == 1) {
5908                 init_s64_max = (s8)reg->smax_value;
5909                 init_s64_min = (s8)reg->smin_value;
5910         } else if (size == 2) {
5911                 init_s64_max = (s16)reg->smax_value;
5912                 init_s64_min = (s16)reg->smin_value;
5913         } else {
5914                 init_s64_max = (s32)reg->smax_value;
5915                 init_s64_min = (s32)reg->smin_value;
5916         }
5917
5918         s64_max = max(init_s64_max, init_s64_min);
5919         s64_min = min(init_s64_max, init_s64_min);
5920
5921         /* both of s64_max/s64_min positive or negative */
5922         if ((s64_max >= 0) == (s64_min >= 0)) {
5923                 reg->smin_value = reg->s32_min_value = s64_min;
5924                 reg->smax_value = reg->s32_max_value = s64_max;
5925                 reg->umin_value = reg->u32_min_value = s64_min;
5926                 reg->umax_value = reg->u32_max_value = s64_max;
5927                 reg->var_off = tnum_range(s64_min, s64_max);
5928                 return;
5929         }
5930
5931 out:
5932         set_sext64_default_val(reg, size);
5933 }
5934
5935 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5936 {
5937         if (size == 1) {
5938                 reg->s32_min_value = S8_MIN;
5939                 reg->s32_max_value = S8_MAX;
5940         } else {
5941                 /* size == 2 */
5942                 reg->s32_min_value = S16_MIN;
5943                 reg->s32_max_value = S16_MAX;
5944         }
5945         reg->u32_min_value = 0;
5946         reg->u32_max_value = U32_MAX;
5947 }
5948
5949 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5950 {
5951         s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5952         u32 top_smax_value, top_smin_value;
5953         u32 num_bits = size * 8;
5954
5955         if (tnum_is_const(reg->var_off)) {
5956                 u32_val = reg->var_off.value;
5957                 if (size == 1)
5958                         reg->var_off = tnum_const((s8)u32_val);
5959                 else
5960                         reg->var_off = tnum_const((s16)u32_val);
5961
5962                 u32_val = reg->var_off.value;
5963                 reg->s32_min_value = reg->s32_max_value = u32_val;
5964                 reg->u32_min_value = reg->u32_max_value = u32_val;
5965                 return;
5966         }
5967
5968         top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5969         top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5970
5971         if (top_smax_value != top_smin_value)
5972                 goto out;
5973
5974         /* find the s32_min and s32_min after sign extension */
5975         if (size == 1) {
5976                 init_s32_max = (s8)reg->s32_max_value;
5977                 init_s32_min = (s8)reg->s32_min_value;
5978         } else {
5979                 /* size == 2 */
5980                 init_s32_max = (s16)reg->s32_max_value;
5981                 init_s32_min = (s16)reg->s32_min_value;
5982         }
5983         s32_max = max(init_s32_max, init_s32_min);
5984         s32_min = min(init_s32_max, init_s32_min);
5985
5986         if ((s32_min >= 0) == (s32_max >= 0)) {
5987                 reg->s32_min_value = s32_min;
5988                 reg->s32_max_value = s32_max;
5989                 reg->u32_min_value = (u32)s32_min;
5990                 reg->u32_max_value = (u32)s32_max;
5991                 return;
5992         }
5993
5994 out:
5995         set_sext32_default_val(reg, size);
5996 }
5997
5998 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5999 {
6000         /* A map is considered read-only if the following condition are true:
6001          *
6002          * 1) BPF program side cannot change any of the map content. The
6003          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6004          *    and was set at map creation time.
6005          * 2) The map value(s) have been initialized from user space by a
6006          *    loader and then "frozen", such that no new map update/delete
6007          *    operations from syscall side are possible for the rest of
6008          *    the map's lifetime from that point onwards.
6009          * 3) Any parallel/pending map update/delete operations from syscall
6010          *    side have been completed. Only after that point, it's safe to
6011          *    assume that map value(s) are immutable.
6012          */
6013         return (map->map_flags & BPF_F_RDONLY_PROG) &&
6014                READ_ONCE(map->frozen) &&
6015                !bpf_map_write_active(map);
6016 }
6017
6018 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6019                                bool is_ldsx)
6020 {
6021         void *ptr;
6022         u64 addr;
6023         int err;
6024
6025         err = map->ops->map_direct_value_addr(map, &addr, off);
6026         if (err)
6027                 return err;
6028         ptr = (void *)(long)addr + off;
6029
6030         switch (size) {
6031         case sizeof(u8):
6032                 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6033                 break;
6034         case sizeof(u16):
6035                 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6036                 break;
6037         case sizeof(u32):
6038                 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6039                 break;
6040         case sizeof(u64):
6041                 *val = *(u64 *)ptr;
6042                 break;
6043         default:
6044                 return -EINVAL;
6045         }
6046         return 0;
6047 }
6048
6049 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6050 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6051 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6052
6053 /*
6054  * Allow list few fields as RCU trusted or full trusted.
6055  * This logic doesn't allow mix tagging and will be removed once GCC supports
6056  * btf_type_tag.
6057  */
6058
6059 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6060 BTF_TYPE_SAFE_RCU(struct task_struct) {
6061         const cpumask_t *cpus_ptr;
6062         struct css_set __rcu *cgroups;
6063         struct task_struct __rcu *real_parent;
6064         struct task_struct *group_leader;
6065 };
6066
6067 BTF_TYPE_SAFE_RCU(struct cgroup) {
6068         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6069         struct kernfs_node *kn;
6070 };
6071
6072 BTF_TYPE_SAFE_RCU(struct css_set) {
6073         struct cgroup *dfl_cgrp;
6074 };
6075
6076 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6077 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6078         struct file __rcu *exe_file;
6079 };
6080
6081 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6082  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6083  */
6084 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6085         struct sock *sk;
6086 };
6087
6088 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6089         struct sock *sk;
6090 };
6091
6092 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6093 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6094         struct seq_file *seq;
6095 };
6096
6097 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6098         struct bpf_iter_meta *meta;
6099         struct task_struct *task;
6100 };
6101
6102 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6103         struct file *file;
6104 };
6105
6106 BTF_TYPE_SAFE_TRUSTED(struct file) {
6107         struct inode *f_inode;
6108 };
6109
6110 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6111         /* no negative dentry-s in places where bpf can see it */
6112         struct inode *d_inode;
6113 };
6114
6115 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6116         struct sock *sk;
6117 };
6118
6119 static bool type_is_rcu(struct bpf_verifier_env *env,
6120                         struct bpf_reg_state *reg,
6121                         const char *field_name, u32 btf_id)
6122 {
6123         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6124         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6125         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6126
6127         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6128 }
6129
6130 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6131                                 struct bpf_reg_state *reg,
6132                                 const char *field_name, u32 btf_id)
6133 {
6134         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6135         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6136         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6137
6138         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6139 }
6140
6141 static bool type_is_trusted(struct bpf_verifier_env *env,
6142                             struct bpf_reg_state *reg,
6143                             const char *field_name, u32 btf_id)
6144 {
6145         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6146         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6147         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6148         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6149         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6150         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6151
6152         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6153 }
6154
6155 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6156                                    struct bpf_reg_state *regs,
6157                                    int regno, int off, int size,
6158                                    enum bpf_access_type atype,
6159                                    int value_regno)
6160 {
6161         struct bpf_reg_state *reg = regs + regno;
6162         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6163         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6164         const char *field_name = NULL;
6165         enum bpf_type_flag flag = 0;
6166         u32 btf_id = 0;
6167         int ret;
6168
6169         if (!env->allow_ptr_leaks) {
6170                 verbose(env,
6171                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6172                         tname);
6173                 return -EPERM;
6174         }
6175         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6176                 verbose(env,
6177                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6178                         tname);
6179                 return -EINVAL;
6180         }
6181         if (off < 0) {
6182                 verbose(env,
6183                         "R%d is ptr_%s invalid negative access: off=%d\n",
6184                         regno, tname, off);
6185                 return -EACCES;
6186         }
6187         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6188                 char tn_buf[48];
6189
6190                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6191                 verbose(env,
6192                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6193                         regno, tname, off, tn_buf);
6194                 return -EACCES;
6195         }
6196
6197         if (reg->type & MEM_USER) {
6198                 verbose(env,
6199                         "R%d is ptr_%s access user memory: off=%d\n",
6200                         regno, tname, off);
6201                 return -EACCES;
6202         }
6203
6204         if (reg->type & MEM_PERCPU) {
6205                 verbose(env,
6206                         "R%d is ptr_%s access percpu memory: off=%d\n",
6207                         regno, tname, off);
6208                 return -EACCES;
6209         }
6210
6211         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6212                 if (!btf_is_kernel(reg->btf)) {
6213                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6214                         return -EFAULT;
6215                 }
6216                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6217         } else {
6218                 /* Writes are permitted with default btf_struct_access for
6219                  * program allocated objects (which always have ref_obj_id > 0),
6220                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6221                  */
6222                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6223                         verbose(env, "only read is supported\n");
6224                         return -EACCES;
6225                 }
6226
6227                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6228                     !reg->ref_obj_id) {
6229                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6230                         return -EFAULT;
6231                 }
6232
6233                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6234         }
6235
6236         if (ret < 0)
6237                 return ret;
6238
6239         if (ret != PTR_TO_BTF_ID) {
6240                 /* just mark; */
6241
6242         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6243                 /* If this is an untrusted pointer, all pointers formed by walking it
6244                  * also inherit the untrusted flag.
6245                  */
6246                 flag = PTR_UNTRUSTED;
6247
6248         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6249                 /* By default any pointer obtained from walking a trusted pointer is no
6250                  * longer trusted, unless the field being accessed has explicitly been
6251                  * marked as inheriting its parent's state of trust (either full or RCU).
6252                  * For example:
6253                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6254                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6255                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6256                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6257                  *
6258                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6259                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6260                  */
6261                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6262                         flag |= PTR_TRUSTED;
6263                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6264                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6265                                 /* ignore __rcu tag and mark it MEM_RCU */
6266                                 flag |= MEM_RCU;
6267                         } else if (flag & MEM_RCU ||
6268                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6269                                 /* __rcu tagged pointers can be NULL */
6270                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6271
6272                                 /* We always trust them */
6273                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6274                                     flag & PTR_UNTRUSTED)
6275                                         flag &= ~PTR_UNTRUSTED;
6276                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6277                                 /* keep as-is */
6278                         } else {
6279                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6280                                 clear_trusted_flags(&flag);
6281                         }
6282                 } else {
6283                         /*
6284                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6285                          * aggressively mark as untrusted otherwise such
6286                          * pointers will be plain PTR_TO_BTF_ID without flags
6287                          * and will be allowed to be passed into helpers for
6288                          * compat reasons.
6289                          */
6290                         flag = PTR_UNTRUSTED;
6291                 }
6292         } else {
6293                 /* Old compat. Deprecated */
6294                 clear_trusted_flags(&flag);
6295         }
6296
6297         if (atype == BPF_READ && value_regno >= 0)
6298                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6299
6300         return 0;
6301 }
6302
6303 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6304                                    struct bpf_reg_state *regs,
6305                                    int regno, int off, int size,
6306                                    enum bpf_access_type atype,
6307                                    int value_regno)
6308 {
6309         struct bpf_reg_state *reg = regs + regno;
6310         struct bpf_map *map = reg->map_ptr;
6311         struct bpf_reg_state map_reg;
6312         enum bpf_type_flag flag = 0;
6313         const struct btf_type *t;
6314         const char *tname;
6315         u32 btf_id;
6316         int ret;
6317
6318         if (!btf_vmlinux) {
6319                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6320                 return -ENOTSUPP;
6321         }
6322
6323         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6324                 verbose(env, "map_ptr access not supported for map type %d\n",
6325                         map->map_type);
6326                 return -ENOTSUPP;
6327         }
6328
6329         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6330         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6331
6332         if (!env->allow_ptr_leaks) {
6333                 verbose(env,
6334                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6335                         tname);
6336                 return -EPERM;
6337         }
6338
6339         if (off < 0) {
6340                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6341                         regno, tname, off);
6342                 return -EACCES;
6343         }
6344
6345         if (atype != BPF_READ) {
6346                 verbose(env, "only read from %s is supported\n", tname);
6347                 return -EACCES;
6348         }
6349
6350         /* Simulate access to a PTR_TO_BTF_ID */
6351         memset(&map_reg, 0, sizeof(map_reg));
6352         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6353         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6354         if (ret < 0)
6355                 return ret;
6356
6357         if (value_regno >= 0)
6358                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6359
6360         return 0;
6361 }
6362
6363 /* Check that the stack access at the given offset is within bounds. The
6364  * maximum valid offset is -1.
6365  *
6366  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6367  * -state->allocated_stack for reads.
6368  */
6369 static int check_stack_slot_within_bounds(int off,
6370                                           struct bpf_func_state *state,
6371                                           enum bpf_access_type t)
6372 {
6373         int min_valid_off;
6374
6375         if (t == BPF_WRITE)
6376                 min_valid_off = -MAX_BPF_STACK;
6377         else
6378                 min_valid_off = -state->allocated_stack;
6379
6380         if (off < min_valid_off || off > -1)
6381                 return -EACCES;
6382         return 0;
6383 }
6384
6385 /* Check that the stack access at 'regno + off' falls within the maximum stack
6386  * bounds.
6387  *
6388  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6389  */
6390 static int check_stack_access_within_bounds(
6391                 struct bpf_verifier_env *env,
6392                 int regno, int off, int access_size,
6393                 enum bpf_access_src src, enum bpf_access_type type)
6394 {
6395         struct bpf_reg_state *regs = cur_regs(env);
6396         struct bpf_reg_state *reg = regs + regno;
6397         struct bpf_func_state *state = func(env, reg);
6398         int min_off, max_off;
6399         int err;
6400         char *err_extra;
6401
6402         if (src == ACCESS_HELPER)
6403                 /* We don't know if helpers are reading or writing (or both). */
6404                 err_extra = " indirect access to";
6405         else if (type == BPF_READ)
6406                 err_extra = " read from";
6407         else
6408                 err_extra = " write to";
6409
6410         if (tnum_is_const(reg->var_off)) {
6411                 min_off = reg->var_off.value + off;
6412                 if (access_size > 0)
6413                         max_off = min_off + access_size - 1;
6414                 else
6415                         max_off = min_off;
6416         } else {
6417                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6418                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6419                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6420                                 err_extra, regno);
6421                         return -EACCES;
6422                 }
6423                 min_off = reg->smin_value + off;
6424                 if (access_size > 0)
6425                         max_off = reg->smax_value + off + access_size - 1;
6426                 else
6427                         max_off = min_off;
6428         }
6429
6430         err = check_stack_slot_within_bounds(min_off, state, type);
6431         if (!err)
6432                 err = check_stack_slot_within_bounds(max_off, state, type);
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         }
6446         return err;
6447 }
6448
6449 /* check whether memory at (regno + off) is accessible for t = (read | write)
6450  * if t==write, value_regno is a register which value is stored into memory
6451  * if t==read, value_regno is a register which will receive the value from memory
6452  * if t==write && value_regno==-1, some unknown value is stored into memory
6453  * if t==read && value_regno==-1, don't care what we read from memory
6454  */
6455 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6456                             int off, int bpf_size, enum bpf_access_type t,
6457                             int value_regno, bool strict_alignment_once, bool is_ldsx)
6458 {
6459         struct bpf_reg_state *regs = cur_regs(env);
6460         struct bpf_reg_state *reg = regs + regno;
6461         struct bpf_func_state *state;
6462         int size, err = 0;
6463
6464         size = bpf_size_to_bytes(bpf_size);
6465         if (size < 0)
6466                 return size;
6467
6468         /* alignment checks will add in reg->off themselves */
6469         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6470         if (err)
6471                 return err;
6472
6473         /* for access checks, reg->off is just part of off */
6474         off += reg->off;
6475
6476         if (reg->type == PTR_TO_MAP_KEY) {
6477                 if (t == BPF_WRITE) {
6478                         verbose(env, "write to change key R%d not allowed\n", regno);
6479                         return -EACCES;
6480                 }
6481
6482                 err = check_mem_region_access(env, regno, off, size,
6483                                               reg->map_ptr->key_size, false);
6484                 if (err)
6485                         return err;
6486                 if (value_regno >= 0)
6487                         mark_reg_unknown(env, regs, value_regno);
6488         } else if (reg->type == PTR_TO_MAP_VALUE) {
6489                 struct btf_field *kptr_field = NULL;
6490
6491                 if (t == BPF_WRITE && value_regno >= 0 &&
6492                     is_pointer_value(env, value_regno)) {
6493                         verbose(env, "R%d leaks addr into map\n", value_regno);
6494                         return -EACCES;
6495                 }
6496                 err = check_map_access_type(env, regno, off, size, t);
6497                 if (err)
6498                         return err;
6499                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6500                 if (err)
6501                         return err;
6502                 if (tnum_is_const(reg->var_off))
6503                         kptr_field = btf_record_find(reg->map_ptr->record,
6504                                                      off + reg->var_off.value, BPF_KPTR);
6505                 if (kptr_field) {
6506                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6507                 } else if (t == BPF_READ && value_regno >= 0) {
6508                         struct bpf_map *map = reg->map_ptr;
6509
6510                         /* if map is read-only, track its contents as scalars */
6511                         if (tnum_is_const(reg->var_off) &&
6512                             bpf_map_is_rdonly(map) &&
6513                             map->ops->map_direct_value_addr) {
6514                                 int map_off = off + reg->var_off.value;
6515                                 u64 val = 0;
6516
6517                                 err = bpf_map_direct_read(map, map_off, size,
6518                                                           &val, is_ldsx);
6519                                 if (err)
6520                                         return err;
6521
6522                                 regs[value_regno].type = SCALAR_VALUE;
6523                                 __mark_reg_known(&regs[value_regno], val);
6524                         } else {
6525                                 mark_reg_unknown(env, regs, value_regno);
6526                         }
6527                 }
6528         } else if (base_type(reg->type) == PTR_TO_MEM) {
6529                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6530
6531                 if (type_may_be_null(reg->type)) {
6532                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6533                                 reg_type_str(env, reg->type));
6534                         return -EACCES;
6535                 }
6536
6537                 if (t == BPF_WRITE && rdonly_mem) {
6538                         verbose(env, "R%d cannot write into %s\n",
6539                                 regno, reg_type_str(env, reg->type));
6540                         return -EACCES;
6541                 }
6542
6543                 if (t == BPF_WRITE && value_regno >= 0 &&
6544                     is_pointer_value(env, value_regno)) {
6545                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6546                         return -EACCES;
6547                 }
6548
6549                 err = check_mem_region_access(env, regno, off, size,
6550                                               reg->mem_size, false);
6551                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6552                         mark_reg_unknown(env, regs, value_regno);
6553         } else if (reg->type == PTR_TO_CTX) {
6554                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6555                 struct btf *btf = NULL;
6556                 u32 btf_id = 0;
6557
6558                 if (t == BPF_WRITE && value_regno >= 0 &&
6559                     is_pointer_value(env, value_regno)) {
6560                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6561                         return -EACCES;
6562                 }
6563
6564                 err = check_ptr_off_reg(env, reg, regno);
6565                 if (err < 0)
6566                         return err;
6567
6568                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6569                                        &btf_id);
6570                 if (err)
6571                         verbose_linfo(env, insn_idx, "; ");
6572                 if (!err && t == BPF_READ && value_regno >= 0) {
6573                         /* ctx access returns either a scalar, or a
6574                          * PTR_TO_PACKET[_META,_END]. In the latter
6575                          * case, we know the offset is zero.
6576                          */
6577                         if (reg_type == SCALAR_VALUE) {
6578                                 mark_reg_unknown(env, regs, value_regno);
6579                         } else {
6580                                 mark_reg_known_zero(env, regs,
6581                                                     value_regno);
6582                                 if (type_may_be_null(reg_type))
6583                                         regs[value_regno].id = ++env->id_gen;
6584                                 /* A load of ctx field could have different
6585                                  * actual load size with the one encoded in the
6586                                  * insn. When the dst is PTR, it is for sure not
6587                                  * a sub-register.
6588                                  */
6589                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6590                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6591                                         regs[value_regno].btf = btf;
6592                                         regs[value_regno].btf_id = btf_id;
6593                                 }
6594                         }
6595                         regs[value_regno].type = reg_type;
6596                 }
6597
6598         } else if (reg->type == PTR_TO_STACK) {
6599                 /* Basic bounds checks. */
6600                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6601                 if (err)
6602                         return err;
6603
6604                 state = func(env, reg);
6605                 err = update_stack_depth(env, state, off);
6606                 if (err)
6607                         return err;
6608
6609                 if (t == BPF_READ)
6610                         err = check_stack_read(env, regno, off, size,
6611                                                value_regno);
6612                 else
6613                         err = check_stack_write(env, regno, off, size,
6614                                                 value_regno, insn_idx);
6615         } else if (reg_is_pkt_pointer(reg)) {
6616                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6617                         verbose(env, "cannot write into packet\n");
6618                         return -EACCES;
6619                 }
6620                 if (t == BPF_WRITE && value_regno >= 0 &&
6621                     is_pointer_value(env, value_regno)) {
6622                         verbose(env, "R%d leaks addr into packet\n",
6623                                 value_regno);
6624                         return -EACCES;
6625                 }
6626                 err = check_packet_access(env, regno, off, size, false);
6627                 if (!err && t == BPF_READ && value_regno >= 0)
6628                         mark_reg_unknown(env, regs, value_regno);
6629         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6630                 if (t == BPF_WRITE && value_regno >= 0 &&
6631                     is_pointer_value(env, value_regno)) {
6632                         verbose(env, "R%d leaks addr into flow keys\n",
6633                                 value_regno);
6634                         return -EACCES;
6635                 }
6636
6637                 err = check_flow_keys_access(env, off, size);
6638                 if (!err && t == BPF_READ && value_regno >= 0)
6639                         mark_reg_unknown(env, regs, value_regno);
6640         } else if (type_is_sk_pointer(reg->type)) {
6641                 if (t == BPF_WRITE) {
6642                         verbose(env, "R%d cannot write into %s\n",
6643                                 regno, reg_type_str(env, reg->type));
6644                         return -EACCES;
6645                 }
6646                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6647                 if (!err && value_regno >= 0)
6648                         mark_reg_unknown(env, regs, value_regno);
6649         } else if (reg->type == PTR_TO_TP_BUFFER) {
6650                 err = check_tp_buffer_access(env, reg, regno, off, size);
6651                 if (!err && t == BPF_READ && value_regno >= 0)
6652                         mark_reg_unknown(env, regs, value_regno);
6653         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6654                    !type_may_be_null(reg->type)) {
6655                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6656                                               value_regno);
6657         } else if (reg->type == CONST_PTR_TO_MAP) {
6658                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6659                                               value_regno);
6660         } else if (base_type(reg->type) == PTR_TO_BUF) {
6661                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6662                 u32 *max_access;
6663
6664                 if (rdonly_mem) {
6665                         if (t == BPF_WRITE) {
6666                                 verbose(env, "R%d cannot write into %s\n",
6667                                         regno, reg_type_str(env, reg->type));
6668                                 return -EACCES;
6669                         }
6670                         max_access = &env->prog->aux->max_rdonly_access;
6671                 } else {
6672                         max_access = &env->prog->aux->max_rdwr_access;
6673                 }
6674
6675                 err = check_buffer_access(env, reg, regno, off, size, false,
6676                                           max_access);
6677
6678                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6679                         mark_reg_unknown(env, regs, value_regno);
6680         } else {
6681                 verbose(env, "R%d invalid mem access '%s'\n", regno,
6682                         reg_type_str(env, reg->type));
6683                 return -EACCES;
6684         }
6685
6686         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6687             regs[value_regno].type == SCALAR_VALUE) {
6688                 if (!is_ldsx)
6689                         /* b/h/w load zero-extends, mark upper bits as known 0 */
6690                         coerce_reg_to_size(&regs[value_regno], size);
6691                 else
6692                         coerce_reg_to_size_sx(&regs[value_regno], size);
6693         }
6694         return err;
6695 }
6696
6697 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6698 {
6699         int load_reg;
6700         int err;
6701
6702         switch (insn->imm) {
6703         case BPF_ADD:
6704         case BPF_ADD | BPF_FETCH:
6705         case BPF_AND:
6706         case BPF_AND | BPF_FETCH:
6707         case BPF_OR:
6708         case BPF_OR | BPF_FETCH:
6709         case BPF_XOR:
6710         case BPF_XOR | BPF_FETCH:
6711         case BPF_XCHG:
6712         case BPF_CMPXCHG:
6713                 break;
6714         default:
6715                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6716                 return -EINVAL;
6717         }
6718
6719         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6720                 verbose(env, "invalid atomic operand size\n");
6721                 return -EINVAL;
6722         }
6723
6724         /* check src1 operand */
6725         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6726         if (err)
6727                 return err;
6728
6729         /* check src2 operand */
6730         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6731         if (err)
6732                 return err;
6733
6734         if (insn->imm == BPF_CMPXCHG) {
6735                 /* Check comparison of R0 with memory location */
6736                 const u32 aux_reg = BPF_REG_0;
6737
6738                 err = check_reg_arg(env, aux_reg, SRC_OP);
6739                 if (err)
6740                         return err;
6741
6742                 if (is_pointer_value(env, aux_reg)) {
6743                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6744                         return -EACCES;
6745                 }
6746         }
6747
6748         if (is_pointer_value(env, insn->src_reg)) {
6749                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6750                 return -EACCES;
6751         }
6752
6753         if (is_ctx_reg(env, insn->dst_reg) ||
6754             is_pkt_reg(env, insn->dst_reg) ||
6755             is_flow_key_reg(env, insn->dst_reg) ||
6756             is_sk_reg(env, insn->dst_reg)) {
6757                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6758                         insn->dst_reg,
6759                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6760                 return -EACCES;
6761         }
6762
6763         if (insn->imm & BPF_FETCH) {
6764                 if (insn->imm == BPF_CMPXCHG)
6765                         load_reg = BPF_REG_0;
6766                 else
6767                         load_reg = insn->src_reg;
6768
6769                 /* check and record load of old value */
6770                 err = check_reg_arg(env, load_reg, DST_OP);
6771                 if (err)
6772                         return err;
6773         } else {
6774                 /* This instruction accesses a memory location but doesn't
6775                  * actually load it into a register.
6776                  */
6777                 load_reg = -1;
6778         }
6779
6780         /* Check whether we can read the memory, with second call for fetch
6781          * case to simulate the register fill.
6782          */
6783         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6784                                BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6785         if (!err && load_reg >= 0)
6786                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6787                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
6788                                        true, false);
6789         if (err)
6790                 return err;
6791
6792         /* Check whether we can write into the same memory. */
6793         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6794                                BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6795         if (err)
6796                 return err;
6797
6798         return 0;
6799 }
6800
6801 /* When register 'regno' is used to read the stack (either directly or through
6802  * a helper function) make sure that it's within stack boundary and, depending
6803  * on the access type, that all elements of the stack are initialized.
6804  *
6805  * 'off' includes 'regno->off', but not its dynamic part (if any).
6806  *
6807  * All registers that have been spilled on the stack in the slots within the
6808  * read offsets are marked as read.
6809  */
6810 static int check_stack_range_initialized(
6811                 struct bpf_verifier_env *env, int regno, int off,
6812                 int access_size, bool zero_size_allowed,
6813                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6814 {
6815         struct bpf_reg_state *reg = reg_state(env, regno);
6816         struct bpf_func_state *state = func(env, reg);
6817         int err, min_off, max_off, i, j, slot, spi;
6818         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6819         enum bpf_access_type bounds_check_type;
6820         /* Some accesses can write anything into the stack, others are
6821          * read-only.
6822          */
6823         bool clobber = false;
6824
6825         if (access_size == 0 && !zero_size_allowed) {
6826                 verbose(env, "invalid zero-sized read\n");
6827                 return -EACCES;
6828         }
6829
6830         if (type == ACCESS_HELPER) {
6831                 /* The bounds checks for writes are more permissive than for
6832                  * reads. However, if raw_mode is not set, we'll do extra
6833                  * checks below.
6834                  */
6835                 bounds_check_type = BPF_WRITE;
6836                 clobber = true;
6837         } else {
6838                 bounds_check_type = BPF_READ;
6839         }
6840         err = check_stack_access_within_bounds(env, regno, off, access_size,
6841                                                type, bounds_check_type);
6842         if (err)
6843                 return err;
6844
6845
6846         if (tnum_is_const(reg->var_off)) {
6847                 min_off = max_off = reg->var_off.value + off;
6848         } else {
6849                 /* Variable offset is prohibited for unprivileged mode for
6850                  * simplicity since it requires corresponding support in
6851                  * Spectre masking for stack ALU.
6852                  * See also retrieve_ptr_limit().
6853                  */
6854                 if (!env->bypass_spec_v1) {
6855                         char tn_buf[48];
6856
6857                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6858                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6859                                 regno, err_extra, tn_buf);
6860                         return -EACCES;
6861                 }
6862                 /* Only initialized buffer on stack is allowed to be accessed
6863                  * with variable offset. With uninitialized buffer it's hard to
6864                  * guarantee that whole memory is marked as initialized on
6865                  * helper return since specific bounds are unknown what may
6866                  * cause uninitialized stack leaking.
6867                  */
6868                 if (meta && meta->raw_mode)
6869                         meta = NULL;
6870
6871                 min_off = reg->smin_value + off;
6872                 max_off = reg->smax_value + off;
6873         }
6874
6875         if (meta && meta->raw_mode) {
6876                 /* Ensure we won't be overwriting dynptrs when simulating byte
6877                  * by byte access in check_helper_call using meta.access_size.
6878                  * This would be a problem if we have a helper in the future
6879                  * which takes:
6880                  *
6881                  *      helper(uninit_mem, len, dynptr)
6882                  *
6883                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6884                  * may end up writing to dynptr itself when touching memory from
6885                  * arg 1. This can be relaxed on a case by case basis for known
6886                  * safe cases, but reject due to the possibilitiy of aliasing by
6887                  * default.
6888                  */
6889                 for (i = min_off; i < max_off + access_size; i++) {
6890                         int stack_off = -i - 1;
6891
6892                         spi = __get_spi(i);
6893                         /* raw_mode may write past allocated_stack */
6894                         if (state->allocated_stack <= stack_off)
6895                                 continue;
6896                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6897                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6898                                 return -EACCES;
6899                         }
6900                 }
6901                 meta->access_size = access_size;
6902                 meta->regno = regno;
6903                 return 0;
6904         }
6905
6906         for (i = min_off; i < max_off + access_size; i++) {
6907                 u8 *stype;
6908
6909                 slot = -i - 1;
6910                 spi = slot / BPF_REG_SIZE;
6911                 if (state->allocated_stack <= slot)
6912                         goto err;
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 err:
6937                 if (tnum_is_const(reg->var_off)) {
6938                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6939                                 err_extra, regno, min_off, i - min_off, access_size);
6940                 } else {
6941                         char tn_buf[48];
6942
6943                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6944                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6945                                 err_extra, regno, tn_buf, i - min_off, access_size);
6946                 }
6947                 return -EACCES;
6948 mark:
6949                 /* reading any byte out of 8-byte 'spill_slot' will cause
6950                  * the whole slot to be marked as 'read'
6951                  */
6952                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6953                               state->stack[spi].spilled_ptr.parent,
6954                               REG_LIVE_READ64);
6955                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6956                  * be sure that whether stack slot is written to or not. Hence,
6957                  * we must still conservatively propagate reads upwards even if
6958                  * helper may write to the entire memory range.
6959                  */
6960         }
6961         return update_stack_depth(env, state, min_off);
6962 }
6963
6964 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6965                                    int access_size, bool zero_size_allowed,
6966                                    struct bpf_call_arg_meta *meta)
6967 {
6968         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6969         u32 *max_access;
6970
6971         switch (base_type(reg->type)) {
6972         case PTR_TO_PACKET:
6973         case PTR_TO_PACKET_META:
6974                 return check_packet_access(env, regno, reg->off, access_size,
6975                                            zero_size_allowed);
6976         case PTR_TO_MAP_KEY:
6977                 if (meta && meta->raw_mode) {
6978                         verbose(env, "R%d cannot write into %s\n", regno,
6979                                 reg_type_str(env, reg->type));
6980                         return -EACCES;
6981                 }
6982                 return check_mem_region_access(env, regno, reg->off, access_size,
6983                                                reg->map_ptr->key_size, false);
6984         case PTR_TO_MAP_VALUE:
6985                 if (check_map_access_type(env, regno, reg->off, access_size,
6986                                           meta && meta->raw_mode ? BPF_WRITE :
6987                                           BPF_READ))
6988                         return -EACCES;
6989                 return check_map_access(env, regno, reg->off, access_size,
6990                                         zero_size_allowed, ACCESS_HELPER);
6991         case PTR_TO_MEM:
6992                 if (type_is_rdonly_mem(reg->type)) {
6993                         if (meta && meta->raw_mode) {
6994                                 verbose(env, "R%d cannot write into %s\n", regno,
6995                                         reg_type_str(env, reg->type));
6996                                 return -EACCES;
6997                         }
6998                 }
6999                 return check_mem_region_access(env, regno, reg->off,
7000                                                access_size, reg->mem_size,
7001                                                zero_size_allowed);
7002         case PTR_TO_BUF:
7003                 if (type_is_rdonly_mem(reg->type)) {
7004                         if (meta && meta->raw_mode) {
7005                                 verbose(env, "R%d cannot write into %s\n", regno,
7006                                         reg_type_str(env, reg->type));
7007                                 return -EACCES;
7008                         }
7009
7010                         max_access = &env->prog->aux->max_rdonly_access;
7011                 } else {
7012                         max_access = &env->prog->aux->max_rdwr_access;
7013                 }
7014                 return check_buffer_access(env, reg, regno, reg->off,
7015                                            access_size, zero_size_allowed,
7016                                            max_access);
7017         case PTR_TO_STACK:
7018                 return check_stack_range_initialized(
7019                                 env,
7020                                 regno, reg->off, access_size,
7021                                 zero_size_allowed, ACCESS_HELPER, meta);
7022         case PTR_TO_BTF_ID:
7023                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7024                                                access_size, BPF_READ, -1);
7025         case PTR_TO_CTX:
7026                 /* in case the function doesn't know how to access the context,
7027                  * (because we are in a program of type SYSCALL for example), we
7028                  * can not statically check its size.
7029                  * Dynamically check it now.
7030                  */
7031                 if (!env->ops->convert_ctx_access) {
7032                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7033                         int offset = access_size - 1;
7034
7035                         /* Allow zero-byte read from PTR_TO_CTX */
7036                         if (access_size == 0)
7037                                 return zero_size_allowed ? 0 : -EACCES;
7038
7039                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7040                                                 atype, -1, false, false);
7041                 }
7042
7043                 fallthrough;
7044         default: /* scalar_value or invalid ptr */
7045                 /* Allow zero-byte read from NULL, regardless of pointer type */
7046                 if (zero_size_allowed && access_size == 0 &&
7047                     register_is_null(reg))
7048                         return 0;
7049
7050                 verbose(env, "R%d type=%s ", regno,
7051                         reg_type_str(env, reg->type));
7052                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7053                 return -EACCES;
7054         }
7055 }
7056
7057 static int check_mem_size_reg(struct bpf_verifier_env *env,
7058                               struct bpf_reg_state *reg, u32 regno,
7059                               bool zero_size_allowed,
7060                               struct bpf_call_arg_meta *meta)
7061 {
7062         int err;
7063
7064         /* This is used to refine r0 return value bounds for helpers
7065          * that enforce this value as an upper bound on return values.
7066          * See do_refine_retval_range() for helpers that can refine
7067          * the return value. C type of helper is u32 so we pull register
7068          * bound from umax_value however, if negative verifier errors
7069          * out. Only upper bounds can be learned because retval is an
7070          * int type and negative retvals are allowed.
7071          */
7072         meta->msize_max_value = reg->umax_value;
7073
7074         /* The register is SCALAR_VALUE; the access check
7075          * happens using its boundaries.
7076          */
7077         if (!tnum_is_const(reg->var_off))
7078                 /* For unprivileged variable accesses, disable raw
7079                  * mode so that the program is required to
7080                  * initialize all the memory that the helper could
7081                  * just partially fill up.
7082                  */
7083                 meta = NULL;
7084
7085         if (reg->smin_value < 0) {
7086                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7087                         regno);
7088                 return -EACCES;
7089         }
7090
7091         if (reg->umin_value == 0) {
7092                 err = check_helper_mem_access(env, regno - 1, 0,
7093                                               zero_size_allowed,
7094                                               meta);
7095                 if (err)
7096                         return err;
7097         }
7098
7099         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7100                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7101                         regno);
7102                 return -EACCES;
7103         }
7104         err = check_helper_mem_access(env, regno - 1,
7105                                       reg->umax_value,
7106                                       zero_size_allowed, meta);
7107         if (!err)
7108                 err = mark_chain_precision(env, regno);
7109         return err;
7110 }
7111
7112 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7113                    u32 regno, u32 mem_size)
7114 {
7115         bool may_be_null = type_may_be_null(reg->type);
7116         struct bpf_reg_state saved_reg;
7117         struct bpf_call_arg_meta meta;
7118         int err;
7119
7120         if (register_is_null(reg))
7121                 return 0;
7122
7123         memset(&meta, 0, sizeof(meta));
7124         /* Assuming that the register contains a value check if the memory
7125          * access is safe. Temporarily save and restore the register's state as
7126          * the conversion shouldn't be visible to a caller.
7127          */
7128         if (may_be_null) {
7129                 saved_reg = *reg;
7130                 mark_ptr_not_null_reg(reg);
7131         }
7132
7133         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7134         /* Check access for BPF_WRITE */
7135         meta.raw_mode = true;
7136         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7137
7138         if (may_be_null)
7139                 *reg = saved_reg;
7140
7141         return err;
7142 }
7143
7144 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7145                                     u32 regno)
7146 {
7147         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7148         bool may_be_null = type_may_be_null(mem_reg->type);
7149         struct bpf_reg_state saved_reg;
7150         struct bpf_call_arg_meta meta;
7151         int err;
7152
7153         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7154
7155         memset(&meta, 0, sizeof(meta));
7156
7157         if (may_be_null) {
7158                 saved_reg = *mem_reg;
7159                 mark_ptr_not_null_reg(mem_reg);
7160         }
7161
7162         err = check_mem_size_reg(env, reg, regno, true, &meta);
7163         /* Check access for BPF_WRITE */
7164         meta.raw_mode = true;
7165         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7166
7167         if (may_be_null)
7168                 *mem_reg = saved_reg;
7169         return err;
7170 }
7171
7172 /* Implementation details:
7173  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7174  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7175  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7176  * Two separate bpf_obj_new will also have different reg->id.
7177  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7178  * clears reg->id after value_or_null->value transition, since the verifier only
7179  * cares about the range of access to valid map value pointer and doesn't care
7180  * about actual address of the map element.
7181  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7182  * reg->id > 0 after value_or_null->value transition. By doing so
7183  * two bpf_map_lookups will be considered two different pointers that
7184  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7185  * returned from bpf_obj_new.
7186  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7187  * dead-locks.
7188  * Since only one bpf_spin_lock is allowed the checks are simpler than
7189  * reg_is_refcounted() logic. The verifier needs to remember only
7190  * one spin_lock instead of array of acquired_refs.
7191  * cur_state->active_lock remembers which map value element or allocated
7192  * object got locked and clears it after bpf_spin_unlock.
7193  */
7194 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7195                              bool is_lock)
7196 {
7197         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7198         struct bpf_verifier_state *cur = env->cur_state;
7199         bool is_const = tnum_is_const(reg->var_off);
7200         u64 val = reg->var_off.value;
7201         struct bpf_map *map = NULL;
7202         struct btf *btf = NULL;
7203         struct btf_record *rec;
7204
7205         if (!is_const) {
7206                 verbose(env,
7207                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7208                         regno);
7209                 return -EINVAL;
7210         }
7211         if (reg->type == PTR_TO_MAP_VALUE) {
7212                 map = reg->map_ptr;
7213                 if (!map->btf) {
7214                         verbose(env,
7215                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7216                                 map->name);
7217                         return -EINVAL;
7218                 }
7219         } else {
7220                 btf = reg->btf;
7221         }
7222
7223         rec = reg_btf_record(reg);
7224         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7225                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7226                         map ? map->name : "kptr");
7227                 return -EINVAL;
7228         }
7229         if (rec->spin_lock_off != val + reg->off) {
7230                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7231                         val + reg->off, rec->spin_lock_off);
7232                 return -EINVAL;
7233         }
7234         if (is_lock) {
7235                 if (cur->active_lock.ptr) {
7236                         verbose(env,
7237                                 "Locking two bpf_spin_locks are not allowed\n");
7238                         return -EINVAL;
7239                 }
7240                 if (map)
7241                         cur->active_lock.ptr = map;
7242                 else
7243                         cur->active_lock.ptr = btf;
7244                 cur->active_lock.id = reg->id;
7245         } else {
7246                 void *ptr;
7247
7248                 if (map)
7249                         ptr = map;
7250                 else
7251                         ptr = btf;
7252
7253                 if (!cur->active_lock.ptr) {
7254                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7255                         return -EINVAL;
7256                 }
7257                 if (cur->active_lock.ptr != ptr ||
7258                     cur->active_lock.id != reg->id) {
7259                         verbose(env, "bpf_spin_unlock of different lock\n");
7260                         return -EINVAL;
7261                 }
7262
7263                 invalidate_non_owning_refs(env);
7264
7265                 cur->active_lock.ptr = NULL;
7266                 cur->active_lock.id = 0;
7267         }
7268         return 0;
7269 }
7270
7271 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7272                               struct bpf_call_arg_meta *meta)
7273 {
7274         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7275         bool is_const = tnum_is_const(reg->var_off);
7276         struct bpf_map *map = reg->map_ptr;
7277         u64 val = reg->var_off.value;
7278
7279         if (!is_const) {
7280                 verbose(env,
7281                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7282                         regno);
7283                 return -EINVAL;
7284         }
7285         if (!map->btf) {
7286                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7287                         map->name);
7288                 return -EINVAL;
7289         }
7290         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7291                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7292                 return -EINVAL;
7293         }
7294         if (map->record->timer_off != val + reg->off) {
7295                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7296                         val + reg->off, map->record->timer_off);
7297                 return -EINVAL;
7298         }
7299         if (meta->map_ptr) {
7300                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7301                 return -EFAULT;
7302         }
7303         meta->map_uid = reg->map_uid;
7304         meta->map_ptr = map;
7305         return 0;
7306 }
7307
7308 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7309                              struct bpf_call_arg_meta *meta)
7310 {
7311         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7312         struct bpf_map *map_ptr = reg->map_ptr;
7313         struct btf_field *kptr_field;
7314         u32 kptr_off;
7315
7316         if (!tnum_is_const(reg->var_off)) {
7317                 verbose(env,
7318                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7319                         regno);
7320                 return -EINVAL;
7321         }
7322         if (!map_ptr->btf) {
7323                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7324                         map_ptr->name);
7325                 return -EINVAL;
7326         }
7327         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7328                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7329                 return -EINVAL;
7330         }
7331
7332         meta->map_ptr = map_ptr;
7333         kptr_off = reg->off + reg->var_off.value;
7334         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7335         if (!kptr_field) {
7336                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7337                 return -EACCES;
7338         }
7339         if (kptr_field->type != BPF_KPTR_REF) {
7340                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7341                 return -EACCES;
7342         }
7343         meta->kptr_field = kptr_field;
7344         return 0;
7345 }
7346
7347 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7348  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7349  *
7350  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7351  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7352  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7353  *
7354  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7355  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7356  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7357  * mutate the view of the dynptr and also possibly destroy it. In the latter
7358  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7359  * memory that dynptr points to.
7360  *
7361  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7362  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7363  * readonly dynptr view yet, hence only the first case is tracked and checked.
7364  *
7365  * This is consistent with how C applies the const modifier to a struct object,
7366  * where the pointer itself inside bpf_dynptr becomes const but not what it
7367  * points to.
7368  *
7369  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7370  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7371  */
7372 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7373                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7374 {
7375         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7376         int err;
7377
7378         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7379          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7380          */
7381         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7382                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7383                 return -EFAULT;
7384         }
7385
7386         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7387          *               constructing a mutable bpf_dynptr object.
7388          *
7389          *               Currently, this is only possible with PTR_TO_STACK
7390          *               pointing to a region of at least 16 bytes which doesn't
7391          *               contain an existing bpf_dynptr.
7392          *
7393          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7394          *               mutated or destroyed. However, the memory it points to
7395          *               may be mutated.
7396          *
7397          *  None       - Points to a initialized dynptr that can be mutated and
7398          *               destroyed, including mutation of the memory it points
7399          *               to.
7400          */
7401         if (arg_type & MEM_UNINIT) {
7402                 int i;
7403
7404                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7405                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7406                         return -EINVAL;
7407                 }
7408
7409                 /* we write BPF_DW bits (8 bytes) at a time */
7410                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7411                         err = check_mem_access(env, insn_idx, regno,
7412                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7413                         if (err)
7414                                 return err;
7415                 }
7416
7417                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7418         } else /* MEM_RDONLY and None case from above */ {
7419                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7420                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7421                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7422                         return -EINVAL;
7423                 }
7424
7425                 if (!is_dynptr_reg_valid_init(env, reg)) {
7426                         verbose(env,
7427                                 "Expected an initialized dynptr as arg #%d\n",
7428                                 regno);
7429                         return -EINVAL;
7430                 }
7431
7432                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7433                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7434                         verbose(env,
7435                                 "Expected a dynptr of type %s as arg #%d\n",
7436                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7437                         return -EINVAL;
7438                 }
7439
7440                 err = mark_dynptr_read(env, reg);
7441         }
7442         return err;
7443 }
7444
7445 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7446 {
7447         struct bpf_func_state *state = func(env, reg);
7448
7449         return state->stack[spi].spilled_ptr.ref_obj_id;
7450 }
7451
7452 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7453 {
7454         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7455 }
7456
7457 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7458 {
7459         return meta->kfunc_flags & KF_ITER_NEW;
7460 }
7461
7462 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7463 {
7464         return meta->kfunc_flags & KF_ITER_NEXT;
7465 }
7466
7467 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7468 {
7469         return meta->kfunc_flags & KF_ITER_DESTROY;
7470 }
7471
7472 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7473 {
7474         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7475          * kfunc is iter state pointer
7476          */
7477         return arg == 0 && is_iter_kfunc(meta);
7478 }
7479
7480 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7481                             struct bpf_kfunc_call_arg_meta *meta)
7482 {
7483         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7484         const struct btf_type *t;
7485         const struct btf_param *arg;
7486         int spi, err, i, nr_slots;
7487         u32 btf_id;
7488
7489         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7490         arg = &btf_params(meta->func_proto)[0];
7491         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7492         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7493         nr_slots = t->size / BPF_REG_SIZE;
7494
7495         if (is_iter_new_kfunc(meta)) {
7496                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7497                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7498                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7499                                 iter_type_str(meta->btf, btf_id), regno);
7500                         return -EINVAL;
7501                 }
7502
7503                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7504                         err = check_mem_access(env, insn_idx, regno,
7505                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7506                         if (err)
7507                                 return err;
7508                 }
7509
7510                 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7511                 if (err)
7512                         return err;
7513         } else {
7514                 /* iter_next() or iter_destroy() expect initialized iter state*/
7515                 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7516                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7517                                 iter_type_str(meta->btf, btf_id), regno);
7518                         return -EINVAL;
7519                 }
7520
7521                 spi = iter_get_spi(env, reg, nr_slots);
7522                 if (spi < 0)
7523                         return spi;
7524
7525                 err = mark_iter_read(env, reg, spi, nr_slots);
7526                 if (err)
7527                         return err;
7528
7529                 /* remember meta->iter info for process_iter_next_call() */
7530                 meta->iter.spi = spi;
7531                 meta->iter.frameno = reg->frameno;
7532                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7533
7534                 if (is_iter_destroy_kfunc(meta)) {
7535                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7536                         if (err)
7537                                 return err;
7538                 }
7539         }
7540
7541         return 0;
7542 }
7543
7544 /* process_iter_next_call() is called when verifier gets to iterator's next
7545  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7546  * to it as just "iter_next()" in comments below.
7547  *
7548  * BPF verifier relies on a crucial contract for any iter_next()
7549  * implementation: it should *eventually* return NULL, and once that happens
7550  * it should keep returning NULL. That is, once iterator exhausts elements to
7551  * iterate, it should never reset or spuriously return new elements.
7552  *
7553  * With the assumption of such contract, process_iter_next_call() simulates
7554  * a fork in the verifier state to validate loop logic correctness and safety
7555  * without having to simulate infinite amount of iterations.
7556  *
7557  * In current state, we first assume that iter_next() returned NULL and
7558  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7559  * conditions we should not form an infinite loop and should eventually reach
7560  * exit.
7561  *
7562  * Besides that, we also fork current state and enqueue it for later
7563  * verification. In a forked state we keep iterator state as ACTIVE
7564  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7565  * also bump iteration depth to prevent erroneous infinite loop detection
7566  * later on (see iter_active_depths_differ() comment for details). In this
7567  * state we assume that we'll eventually loop back to another iter_next()
7568  * calls (it could be in exactly same location or in some other instruction,
7569  * it doesn't matter, we don't make any unnecessary assumptions about this,
7570  * everything revolves around iterator state in a stack slot, not which
7571  * instruction is calling iter_next()). When that happens, we either will come
7572  * to iter_next() with equivalent state and can conclude that next iteration
7573  * will proceed in exactly the same way as we just verified, so it's safe to
7574  * assume that loop converges. If not, we'll go on another iteration
7575  * simulation with a different input state, until all possible starting states
7576  * are validated or we reach maximum number of instructions limit.
7577  *
7578  * This way, we will either exhaustively discover all possible input states
7579  * that iterator loop can start with and eventually will converge, or we'll
7580  * effectively regress into bounded loop simulation logic and either reach
7581  * maximum number of instructions if loop is not provably convergent, or there
7582  * is some statically known limit on number of iterations (e.g., if there is
7583  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7584  *
7585  * One very subtle but very important aspect is that we *always* simulate NULL
7586  * condition first (as the current state) before we simulate non-NULL case.
7587  * This has to do with intricacies of scalar precision tracking. By simulating
7588  * "exit condition" of iter_next() returning NULL first, we make sure all the
7589  * relevant precision marks *that will be set **after** we exit iterator loop*
7590  * are propagated backwards to common parent state of NULL and non-NULL
7591  * branches. Thanks to that, state equivalence checks done later in forked
7592  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7593  * precision marks are finalized and won't change. Because simulating another
7594  * ACTIVE iterator iteration won't change them (because given same input
7595  * states we'll end up with exactly same output states which we are currently
7596  * comparing; and verification after the loop already propagated back what
7597  * needs to be **additionally** tracked as precise). It's subtle, grok
7598  * precision tracking for more intuitive understanding.
7599  */
7600 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7601                                   struct bpf_kfunc_call_arg_meta *meta)
7602 {
7603         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7604         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7605         struct bpf_reg_state *cur_iter, *queued_iter;
7606         int iter_frameno = meta->iter.frameno;
7607         int iter_spi = meta->iter.spi;
7608
7609         BTF_TYPE_EMIT(struct bpf_iter);
7610
7611         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7612
7613         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7614             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7615                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7616                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7617                 return -EFAULT;
7618         }
7619
7620         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7621                 /* branch out active iter state */
7622                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7623                 if (!queued_st)
7624                         return -ENOMEM;
7625
7626                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7627                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7628                 queued_iter->iter.depth++;
7629
7630                 queued_fr = queued_st->frame[queued_st->curframe];
7631                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7632         }
7633
7634         /* switch to DRAINED state, but keep the depth unchanged */
7635         /* mark current iter state as drained and assume returned NULL */
7636         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7637         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7638
7639         return 0;
7640 }
7641
7642 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7643 {
7644         return type == ARG_CONST_SIZE ||
7645                type == ARG_CONST_SIZE_OR_ZERO;
7646 }
7647
7648 static bool arg_type_is_release(enum bpf_arg_type type)
7649 {
7650         return type & OBJ_RELEASE;
7651 }
7652
7653 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7654 {
7655         return base_type(type) == ARG_PTR_TO_DYNPTR;
7656 }
7657
7658 static int int_ptr_type_to_size(enum bpf_arg_type type)
7659 {
7660         if (type == ARG_PTR_TO_INT)
7661                 return sizeof(u32);
7662         else if (type == ARG_PTR_TO_LONG)
7663                 return sizeof(u64);
7664
7665         return -EINVAL;
7666 }
7667
7668 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7669                                  const struct bpf_call_arg_meta *meta,
7670                                  enum bpf_arg_type *arg_type)
7671 {
7672         if (!meta->map_ptr) {
7673                 /* kernel subsystem misconfigured verifier */
7674                 verbose(env, "invalid map_ptr to access map->type\n");
7675                 return -EACCES;
7676         }
7677
7678         switch (meta->map_ptr->map_type) {
7679         case BPF_MAP_TYPE_SOCKMAP:
7680         case BPF_MAP_TYPE_SOCKHASH:
7681                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7682                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7683                 } else {
7684                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
7685                         return -EINVAL;
7686                 }
7687                 break;
7688         case BPF_MAP_TYPE_BLOOM_FILTER:
7689                 if (meta->func_id == BPF_FUNC_map_peek_elem)
7690                         *arg_type = ARG_PTR_TO_MAP_VALUE;
7691                 break;
7692         default:
7693                 break;
7694         }
7695         return 0;
7696 }
7697
7698 struct bpf_reg_types {
7699         const enum bpf_reg_type types[10];
7700         u32 *btf_id;
7701 };
7702
7703 static const struct bpf_reg_types sock_types = {
7704         .types = {
7705                 PTR_TO_SOCK_COMMON,
7706                 PTR_TO_SOCKET,
7707                 PTR_TO_TCP_SOCK,
7708                 PTR_TO_XDP_SOCK,
7709         },
7710 };
7711
7712 #ifdef CONFIG_NET
7713 static const struct bpf_reg_types btf_id_sock_common_types = {
7714         .types = {
7715                 PTR_TO_SOCK_COMMON,
7716                 PTR_TO_SOCKET,
7717                 PTR_TO_TCP_SOCK,
7718                 PTR_TO_XDP_SOCK,
7719                 PTR_TO_BTF_ID,
7720                 PTR_TO_BTF_ID | PTR_TRUSTED,
7721         },
7722         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7723 };
7724 #endif
7725
7726 static const struct bpf_reg_types mem_types = {
7727         .types = {
7728                 PTR_TO_STACK,
7729                 PTR_TO_PACKET,
7730                 PTR_TO_PACKET_META,
7731                 PTR_TO_MAP_KEY,
7732                 PTR_TO_MAP_VALUE,
7733                 PTR_TO_MEM,
7734                 PTR_TO_MEM | MEM_RINGBUF,
7735                 PTR_TO_BUF,
7736                 PTR_TO_BTF_ID | PTR_TRUSTED,
7737         },
7738 };
7739
7740 static const struct bpf_reg_types int_ptr_types = {
7741         .types = {
7742                 PTR_TO_STACK,
7743                 PTR_TO_PACKET,
7744                 PTR_TO_PACKET_META,
7745                 PTR_TO_MAP_KEY,
7746                 PTR_TO_MAP_VALUE,
7747         },
7748 };
7749
7750 static const struct bpf_reg_types spin_lock_types = {
7751         .types = {
7752                 PTR_TO_MAP_VALUE,
7753                 PTR_TO_BTF_ID | MEM_ALLOC,
7754         }
7755 };
7756
7757 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7758 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7759 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7760 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7761 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7762 static const struct bpf_reg_types btf_ptr_types = {
7763         .types = {
7764                 PTR_TO_BTF_ID,
7765                 PTR_TO_BTF_ID | PTR_TRUSTED,
7766                 PTR_TO_BTF_ID | MEM_RCU,
7767         },
7768 };
7769 static const struct bpf_reg_types percpu_btf_ptr_types = {
7770         .types = {
7771                 PTR_TO_BTF_ID | MEM_PERCPU,
7772                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7773         }
7774 };
7775 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7776 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7777 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7778 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7779 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7780 static const struct bpf_reg_types dynptr_types = {
7781         .types = {
7782                 PTR_TO_STACK,
7783                 CONST_PTR_TO_DYNPTR,
7784         }
7785 };
7786
7787 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7788         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
7789         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
7790         [ARG_CONST_SIZE]                = &scalar_types,
7791         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
7792         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
7793         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
7794         [ARG_PTR_TO_CTX]                = &context_types,
7795         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
7796 #ifdef CONFIG_NET
7797         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7798 #endif
7799         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
7800         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
7801         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
7802         [ARG_PTR_TO_MEM]                = &mem_types,
7803         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
7804         [ARG_PTR_TO_INT]                = &int_ptr_types,
7805         [ARG_PTR_TO_LONG]               = &int_ptr_types,
7806         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
7807         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
7808         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
7809         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
7810         [ARG_PTR_TO_TIMER]              = &timer_types,
7811         [ARG_PTR_TO_KPTR]               = &kptr_types,
7812         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
7813 };
7814
7815 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7816                           enum bpf_arg_type arg_type,
7817                           const u32 *arg_btf_id,
7818                           struct bpf_call_arg_meta *meta)
7819 {
7820         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7821         enum bpf_reg_type expected, type = reg->type;
7822         const struct bpf_reg_types *compatible;
7823         int i, j;
7824
7825         compatible = compatible_reg_types[base_type(arg_type)];
7826         if (!compatible) {
7827                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7828                 return -EFAULT;
7829         }
7830
7831         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7832          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7833          *
7834          * Same for MAYBE_NULL:
7835          *
7836          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7837          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7838          *
7839          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7840          *
7841          * Therefore we fold these flags depending on the arg_type before comparison.
7842          */
7843         if (arg_type & MEM_RDONLY)
7844                 type &= ~MEM_RDONLY;
7845         if (arg_type & PTR_MAYBE_NULL)
7846                 type &= ~PTR_MAYBE_NULL;
7847         if (base_type(arg_type) == ARG_PTR_TO_MEM)
7848                 type &= ~DYNPTR_TYPE_FLAG_MASK;
7849
7850         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7851                 type &= ~MEM_ALLOC;
7852
7853         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7854                 expected = compatible->types[i];
7855                 if (expected == NOT_INIT)
7856                         break;
7857
7858                 if (type == expected)
7859                         goto found;
7860         }
7861
7862         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7863         for (j = 0; j + 1 < i; j++)
7864                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7865         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7866         return -EACCES;
7867
7868 found:
7869         if (base_type(reg->type) != PTR_TO_BTF_ID)
7870                 return 0;
7871
7872         if (compatible == &mem_types) {
7873                 if (!(arg_type & MEM_RDONLY)) {
7874                         verbose(env,
7875                                 "%s() may write into memory pointed by R%d type=%s\n",
7876                                 func_id_name(meta->func_id),
7877                                 regno, reg_type_str(env, reg->type));
7878                         return -EACCES;
7879                 }
7880                 return 0;
7881         }
7882
7883         switch ((int)reg->type) {
7884         case PTR_TO_BTF_ID:
7885         case PTR_TO_BTF_ID | PTR_TRUSTED:
7886         case PTR_TO_BTF_ID | MEM_RCU:
7887         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7888         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7889         {
7890                 /* For bpf_sk_release, it needs to match against first member
7891                  * 'struct sock_common', hence make an exception for it. This
7892                  * allows bpf_sk_release to work for multiple socket types.
7893                  */
7894                 bool strict_type_match = arg_type_is_release(arg_type) &&
7895                                          meta->func_id != BPF_FUNC_sk_release;
7896
7897                 if (type_may_be_null(reg->type) &&
7898                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7899                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7900                         return -EACCES;
7901                 }
7902
7903                 if (!arg_btf_id) {
7904                         if (!compatible->btf_id) {
7905                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7906                                 return -EFAULT;
7907                         }
7908                         arg_btf_id = compatible->btf_id;
7909                 }
7910
7911                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7912                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7913                                 return -EACCES;
7914                 } else {
7915                         if (arg_btf_id == BPF_PTR_POISON) {
7916                                 verbose(env, "verifier internal error:");
7917                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7918                                         regno);
7919                                 return -EACCES;
7920                         }
7921
7922                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7923                                                   btf_vmlinux, *arg_btf_id,
7924                                                   strict_type_match)) {
7925                                 verbose(env, "R%d is of type %s but %s is expected\n",
7926                                         regno, btf_type_name(reg->btf, reg->btf_id),
7927                                         btf_type_name(btf_vmlinux, *arg_btf_id));
7928                                 return -EACCES;
7929                         }
7930                 }
7931                 break;
7932         }
7933         case PTR_TO_BTF_ID | MEM_ALLOC:
7934                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7935                     meta->func_id != BPF_FUNC_kptr_xchg) {
7936                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7937                         return -EFAULT;
7938                 }
7939                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7940                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7941                                 return -EACCES;
7942                 }
7943                 break;
7944         case PTR_TO_BTF_ID | MEM_PERCPU:
7945         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7946                 /* Handled by helper specific checks */
7947                 break;
7948         default:
7949                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7950                 return -EFAULT;
7951         }
7952         return 0;
7953 }
7954
7955 static struct btf_field *
7956 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7957 {
7958         struct btf_field *field;
7959         struct btf_record *rec;
7960
7961         rec = reg_btf_record(reg);
7962         if (!rec)
7963                 return NULL;
7964
7965         field = btf_record_find(rec, off, fields);
7966         if (!field)
7967                 return NULL;
7968
7969         return field;
7970 }
7971
7972 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7973                            const struct bpf_reg_state *reg, int regno,
7974                            enum bpf_arg_type arg_type)
7975 {
7976         u32 type = reg->type;
7977
7978         /* When referenced register is passed to release function, its fixed
7979          * offset must be 0.
7980          *
7981          * We will check arg_type_is_release reg has ref_obj_id when storing
7982          * meta->release_regno.
7983          */
7984         if (arg_type_is_release(arg_type)) {
7985                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7986                  * may not directly point to the object being released, but to
7987                  * dynptr pointing to such object, which might be at some offset
7988                  * on the stack. In that case, we simply to fallback to the
7989                  * default handling.
7990                  */
7991                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7992                         return 0;
7993
7994                 /* Doing check_ptr_off_reg check for the offset will catch this
7995                  * because fixed_off_ok is false, but checking here allows us
7996                  * to give the user a better error message.
7997                  */
7998                 if (reg->off) {
7999                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8000                                 regno);
8001                         return -EINVAL;
8002                 }
8003                 return __check_ptr_off_reg(env, reg, regno, false);
8004         }
8005
8006         switch (type) {
8007         /* Pointer types where both fixed and variable offset is explicitly allowed: */
8008         case PTR_TO_STACK:
8009         case PTR_TO_PACKET:
8010         case PTR_TO_PACKET_META:
8011         case PTR_TO_MAP_KEY:
8012         case PTR_TO_MAP_VALUE:
8013         case PTR_TO_MEM:
8014         case PTR_TO_MEM | MEM_RDONLY:
8015         case PTR_TO_MEM | MEM_RINGBUF:
8016         case PTR_TO_BUF:
8017         case PTR_TO_BUF | MEM_RDONLY:
8018         case SCALAR_VALUE:
8019                 return 0;
8020         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8021          * fixed offset.
8022          */
8023         case PTR_TO_BTF_ID:
8024         case PTR_TO_BTF_ID | MEM_ALLOC:
8025         case PTR_TO_BTF_ID | PTR_TRUSTED:
8026         case PTR_TO_BTF_ID | MEM_RCU:
8027         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8028         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8029                 /* When referenced PTR_TO_BTF_ID is passed to release function,
8030                  * its fixed offset must be 0. In the other cases, fixed offset
8031                  * can be non-zero. This was already checked above. So pass
8032                  * fixed_off_ok as true to allow fixed offset for all other
8033                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8034                  * still need to do checks instead of returning.
8035                  */
8036                 return __check_ptr_off_reg(env, reg, regno, true);
8037         default:
8038                 return __check_ptr_off_reg(env, reg, regno, false);
8039         }
8040 }
8041
8042 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8043                                                 const struct bpf_func_proto *fn,
8044                                                 struct bpf_reg_state *regs)
8045 {
8046         struct bpf_reg_state *state = NULL;
8047         int i;
8048
8049         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8050                 if (arg_type_is_dynptr(fn->arg_type[i])) {
8051                         if (state) {
8052                                 verbose(env, "verifier internal error: multiple dynptr args\n");
8053                                 return NULL;
8054                         }
8055                         state = &regs[BPF_REG_1 + i];
8056                 }
8057
8058         if (!state)
8059                 verbose(env, "verifier internal error: no dynptr arg found\n");
8060
8061         return state;
8062 }
8063
8064 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8065 {
8066         struct bpf_func_state *state = func(env, reg);
8067         int spi;
8068
8069         if (reg->type == CONST_PTR_TO_DYNPTR)
8070                 return reg->id;
8071         spi = dynptr_get_spi(env, reg);
8072         if (spi < 0)
8073                 return spi;
8074         return state->stack[spi].spilled_ptr.id;
8075 }
8076
8077 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8078 {
8079         struct bpf_func_state *state = func(env, reg);
8080         int spi;
8081
8082         if (reg->type == CONST_PTR_TO_DYNPTR)
8083                 return reg->ref_obj_id;
8084         spi = dynptr_get_spi(env, reg);
8085         if (spi < 0)
8086                 return spi;
8087         return state->stack[spi].spilled_ptr.ref_obj_id;
8088 }
8089
8090 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8091                                             struct bpf_reg_state *reg)
8092 {
8093         struct bpf_func_state *state = func(env, reg);
8094         int spi;
8095
8096         if (reg->type == CONST_PTR_TO_DYNPTR)
8097                 return reg->dynptr.type;
8098
8099         spi = __get_spi(reg->off);
8100         if (spi < 0) {
8101                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8102                 return BPF_DYNPTR_TYPE_INVALID;
8103         }
8104
8105         return state->stack[spi].spilled_ptr.dynptr.type;
8106 }
8107
8108 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8109                           struct bpf_call_arg_meta *meta,
8110                           const struct bpf_func_proto *fn,
8111                           int insn_idx)
8112 {
8113         u32 regno = BPF_REG_1 + arg;
8114         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8115         enum bpf_arg_type arg_type = fn->arg_type[arg];
8116         enum bpf_reg_type type = reg->type;
8117         u32 *arg_btf_id = NULL;
8118         int err = 0;
8119
8120         if (arg_type == ARG_DONTCARE)
8121                 return 0;
8122
8123         err = check_reg_arg(env, regno, SRC_OP);
8124         if (err)
8125                 return err;
8126
8127         if (arg_type == ARG_ANYTHING) {
8128                 if (is_pointer_value(env, regno)) {
8129                         verbose(env, "R%d leaks addr into helper function\n",
8130                                 regno);
8131                         return -EACCES;
8132                 }
8133                 return 0;
8134         }
8135
8136         if (type_is_pkt_pointer(type) &&
8137             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8138                 verbose(env, "helper access to the packet is not allowed\n");
8139                 return -EACCES;
8140         }
8141
8142         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8143                 err = resolve_map_arg_type(env, meta, &arg_type);
8144                 if (err)
8145                         return err;
8146         }
8147
8148         if (register_is_null(reg) && type_may_be_null(arg_type))
8149                 /* A NULL register has a SCALAR_VALUE type, so skip
8150                  * type checking.
8151                  */
8152                 goto skip_type_check;
8153
8154         /* arg_btf_id and arg_size are in a union. */
8155         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8156             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8157                 arg_btf_id = fn->arg_btf_id[arg];
8158
8159         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8160         if (err)
8161                 return err;
8162
8163         err = check_func_arg_reg_off(env, reg, regno, arg_type);
8164         if (err)
8165                 return err;
8166
8167 skip_type_check:
8168         if (arg_type_is_release(arg_type)) {
8169                 if (arg_type_is_dynptr(arg_type)) {
8170                         struct bpf_func_state *state = func(env, reg);
8171                         int spi;
8172
8173                         /* Only dynptr created on stack can be released, thus
8174                          * the get_spi and stack state checks for spilled_ptr
8175                          * should only be done before process_dynptr_func for
8176                          * PTR_TO_STACK.
8177                          */
8178                         if (reg->type == PTR_TO_STACK) {
8179                                 spi = dynptr_get_spi(env, reg);
8180                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8181                                         verbose(env, "arg %d is an unacquired reference\n", regno);
8182                                         return -EINVAL;
8183                                 }
8184                         } else {
8185                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8186                                 return -EINVAL;
8187                         }
8188                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8189                         verbose(env, "R%d must be referenced when passed to release function\n",
8190                                 regno);
8191                         return -EINVAL;
8192                 }
8193                 if (meta->release_regno) {
8194                         verbose(env, "verifier internal error: more than one release argument\n");
8195                         return -EFAULT;
8196                 }
8197                 meta->release_regno = regno;
8198         }
8199
8200         if (reg->ref_obj_id) {
8201                 if (meta->ref_obj_id) {
8202                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8203                                 regno, reg->ref_obj_id,
8204                                 meta->ref_obj_id);
8205                         return -EFAULT;
8206                 }
8207                 meta->ref_obj_id = reg->ref_obj_id;
8208         }
8209
8210         switch (base_type(arg_type)) {
8211         case ARG_CONST_MAP_PTR:
8212                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8213                 if (meta->map_ptr) {
8214                         /* Use map_uid (which is unique id of inner map) to reject:
8215                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8216                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8217                          * if (inner_map1 && inner_map2) {
8218                          *     timer = bpf_map_lookup_elem(inner_map1);
8219                          *     if (timer)
8220                          *         // mismatch would have been allowed
8221                          *         bpf_timer_init(timer, inner_map2);
8222                          * }
8223                          *
8224                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8225                          */
8226                         if (meta->map_ptr != reg->map_ptr ||
8227                             meta->map_uid != reg->map_uid) {
8228                                 verbose(env,
8229                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8230                                         meta->map_uid, reg->map_uid);
8231                                 return -EINVAL;
8232                         }
8233                 }
8234                 meta->map_ptr = reg->map_ptr;
8235                 meta->map_uid = reg->map_uid;
8236                 break;
8237         case ARG_PTR_TO_MAP_KEY:
8238                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8239                  * check that [key, key + map->key_size) are within
8240                  * stack limits and initialized
8241                  */
8242                 if (!meta->map_ptr) {
8243                         /* in function declaration map_ptr must come before
8244                          * map_key, so that it's verified and known before
8245                          * we have to check map_key here. Otherwise it means
8246                          * that kernel subsystem misconfigured verifier
8247                          */
8248                         verbose(env, "invalid map_ptr to access map->key\n");
8249                         return -EACCES;
8250                 }
8251                 err = check_helper_mem_access(env, regno,
8252                                               meta->map_ptr->key_size, false,
8253                                               NULL);
8254                 break;
8255         case ARG_PTR_TO_MAP_VALUE:
8256                 if (type_may_be_null(arg_type) && register_is_null(reg))
8257                         return 0;
8258
8259                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8260                  * check [value, value + map->value_size) validity
8261                  */
8262                 if (!meta->map_ptr) {
8263                         /* kernel subsystem misconfigured verifier */
8264                         verbose(env, "invalid map_ptr to access map->value\n");
8265                         return -EACCES;
8266                 }
8267                 meta->raw_mode = arg_type & MEM_UNINIT;
8268                 err = check_helper_mem_access(env, regno,
8269                                               meta->map_ptr->value_size, false,
8270                                               meta);
8271                 break;
8272         case ARG_PTR_TO_PERCPU_BTF_ID:
8273                 if (!reg->btf_id) {
8274                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8275                         return -EACCES;
8276                 }
8277                 meta->ret_btf = reg->btf;
8278                 meta->ret_btf_id = reg->btf_id;
8279                 break;
8280         case ARG_PTR_TO_SPIN_LOCK:
8281                 if (in_rbtree_lock_required_cb(env)) {
8282                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8283                         return -EACCES;
8284                 }
8285                 if (meta->func_id == BPF_FUNC_spin_lock) {
8286                         err = process_spin_lock(env, regno, true);
8287                         if (err)
8288                                 return err;
8289                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8290                         err = process_spin_lock(env, regno, false);
8291                         if (err)
8292                                 return err;
8293                 } else {
8294                         verbose(env, "verifier internal error\n");
8295                         return -EFAULT;
8296                 }
8297                 break;
8298         case ARG_PTR_TO_TIMER:
8299                 err = process_timer_func(env, regno, meta);
8300                 if (err)
8301                         return err;
8302                 break;
8303         case ARG_PTR_TO_FUNC:
8304                 meta->subprogno = reg->subprogno;
8305                 break;
8306         case ARG_PTR_TO_MEM:
8307                 /* The access to this pointer is only checked when we hit the
8308                  * next is_mem_size argument below.
8309                  */
8310                 meta->raw_mode = arg_type & MEM_UNINIT;
8311                 if (arg_type & MEM_FIXED_SIZE) {
8312                         err = check_helper_mem_access(env, regno,
8313                                                       fn->arg_size[arg], false,
8314                                                       meta);
8315                 }
8316                 break;
8317         case ARG_CONST_SIZE:
8318                 err = check_mem_size_reg(env, reg, regno, false, meta);
8319                 break;
8320         case ARG_CONST_SIZE_OR_ZERO:
8321                 err = check_mem_size_reg(env, reg, regno, true, meta);
8322                 break;
8323         case ARG_PTR_TO_DYNPTR:
8324                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8325                 if (err)
8326                         return err;
8327                 break;
8328         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8329                 if (!tnum_is_const(reg->var_off)) {
8330                         verbose(env, "R%d is not a known constant'\n",
8331                                 regno);
8332                         return -EACCES;
8333                 }
8334                 meta->mem_size = reg->var_off.value;
8335                 err = mark_chain_precision(env, regno);
8336                 if (err)
8337                         return err;
8338                 break;
8339         case ARG_PTR_TO_INT:
8340         case ARG_PTR_TO_LONG:
8341         {
8342                 int size = int_ptr_type_to_size(arg_type);
8343
8344                 err = check_helper_mem_access(env, regno, size, false, meta);
8345                 if (err)
8346                         return err;
8347                 err = check_ptr_alignment(env, reg, 0, size, true);
8348                 break;
8349         }
8350         case ARG_PTR_TO_CONST_STR:
8351         {
8352                 struct bpf_map *map = reg->map_ptr;
8353                 int map_off;
8354                 u64 map_addr;
8355                 char *str_ptr;
8356
8357                 if (!bpf_map_is_rdonly(map)) {
8358                         verbose(env, "R%d does not point to a readonly map'\n", regno);
8359                         return -EACCES;
8360                 }
8361
8362                 if (!tnum_is_const(reg->var_off)) {
8363                         verbose(env, "R%d is not a constant address'\n", regno);
8364                         return -EACCES;
8365                 }
8366
8367                 if (!map->ops->map_direct_value_addr) {
8368                         verbose(env, "no direct value access support for this map type\n");
8369                         return -EACCES;
8370                 }
8371
8372                 err = check_map_access(env, regno, reg->off,
8373                                        map->value_size - reg->off, false,
8374                                        ACCESS_HELPER);
8375                 if (err)
8376                         return err;
8377
8378                 map_off = reg->off + reg->var_off.value;
8379                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8380                 if (err) {
8381                         verbose(env, "direct value access on string failed\n");
8382                         return err;
8383                 }
8384
8385                 str_ptr = (char *)(long)(map_addr);
8386                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8387                         verbose(env, "string is not zero-terminated\n");
8388                         return -EINVAL;
8389                 }
8390                 break;
8391         }
8392         case ARG_PTR_TO_KPTR:
8393                 err = process_kptr_func(env, regno, meta);
8394                 if (err)
8395                         return err;
8396                 break;
8397         }
8398
8399         return err;
8400 }
8401
8402 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8403 {
8404         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8405         enum bpf_prog_type type = resolve_prog_type(env->prog);
8406
8407         if (func_id != BPF_FUNC_map_update_elem)
8408                 return false;
8409
8410         /* It's not possible to get access to a locked struct sock in these
8411          * contexts, so updating is safe.
8412          */
8413         switch (type) {
8414         case BPF_PROG_TYPE_TRACING:
8415                 if (eatype == BPF_TRACE_ITER)
8416                         return true;
8417                 break;
8418         case BPF_PROG_TYPE_SOCKET_FILTER:
8419         case BPF_PROG_TYPE_SCHED_CLS:
8420         case BPF_PROG_TYPE_SCHED_ACT:
8421         case BPF_PROG_TYPE_XDP:
8422         case BPF_PROG_TYPE_SK_REUSEPORT:
8423         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8424         case BPF_PROG_TYPE_SK_LOOKUP:
8425                 return true;
8426         default:
8427                 break;
8428         }
8429
8430         verbose(env, "cannot update sockmap in this context\n");
8431         return false;
8432 }
8433
8434 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8435 {
8436         return env->prog->jit_requested &&
8437                bpf_jit_supports_subprog_tailcalls();
8438 }
8439
8440 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8441                                         struct bpf_map *map, int func_id)
8442 {
8443         if (!map)
8444                 return 0;
8445
8446         /* We need a two way check, first is from map perspective ... */
8447         switch (map->map_type) {
8448         case BPF_MAP_TYPE_PROG_ARRAY:
8449                 if (func_id != BPF_FUNC_tail_call)
8450                         goto error;
8451                 break;
8452         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8453                 if (func_id != BPF_FUNC_perf_event_read &&
8454                     func_id != BPF_FUNC_perf_event_output &&
8455                     func_id != BPF_FUNC_skb_output &&
8456                     func_id != BPF_FUNC_perf_event_read_value &&
8457                     func_id != BPF_FUNC_xdp_output)
8458                         goto error;
8459                 break;
8460         case BPF_MAP_TYPE_RINGBUF:
8461                 if (func_id != BPF_FUNC_ringbuf_output &&
8462                     func_id != BPF_FUNC_ringbuf_reserve &&
8463                     func_id != BPF_FUNC_ringbuf_query &&
8464                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8465                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8466                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8467                         goto error;
8468                 break;
8469         case BPF_MAP_TYPE_USER_RINGBUF:
8470                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8471                         goto error;
8472                 break;
8473         case BPF_MAP_TYPE_STACK_TRACE:
8474                 if (func_id != BPF_FUNC_get_stackid)
8475                         goto error;
8476                 break;
8477         case BPF_MAP_TYPE_CGROUP_ARRAY:
8478                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8479                     func_id != BPF_FUNC_current_task_under_cgroup)
8480                         goto error;
8481                 break;
8482         case BPF_MAP_TYPE_CGROUP_STORAGE:
8483         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8484                 if (func_id != BPF_FUNC_get_local_storage)
8485                         goto error;
8486                 break;
8487         case BPF_MAP_TYPE_DEVMAP:
8488         case BPF_MAP_TYPE_DEVMAP_HASH:
8489                 if (func_id != BPF_FUNC_redirect_map &&
8490                     func_id != BPF_FUNC_map_lookup_elem)
8491                         goto error;
8492                 break;
8493         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8494          * appear.
8495          */
8496         case BPF_MAP_TYPE_CPUMAP:
8497                 if (func_id != BPF_FUNC_redirect_map)
8498                         goto error;
8499                 break;
8500         case BPF_MAP_TYPE_XSKMAP:
8501                 if (func_id != BPF_FUNC_redirect_map &&
8502                     func_id != BPF_FUNC_map_lookup_elem)
8503                         goto error;
8504                 break;
8505         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8506         case BPF_MAP_TYPE_HASH_OF_MAPS:
8507                 if (func_id != BPF_FUNC_map_lookup_elem)
8508                         goto error;
8509                 break;
8510         case BPF_MAP_TYPE_SOCKMAP:
8511                 if (func_id != BPF_FUNC_sk_redirect_map &&
8512                     func_id != BPF_FUNC_sock_map_update &&
8513                     func_id != BPF_FUNC_map_delete_elem &&
8514                     func_id != BPF_FUNC_msg_redirect_map &&
8515                     func_id != BPF_FUNC_sk_select_reuseport &&
8516                     func_id != BPF_FUNC_map_lookup_elem &&
8517                     !may_update_sockmap(env, func_id))
8518                         goto error;
8519                 break;
8520         case BPF_MAP_TYPE_SOCKHASH:
8521                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8522                     func_id != BPF_FUNC_sock_hash_update &&
8523                     func_id != BPF_FUNC_map_delete_elem &&
8524                     func_id != BPF_FUNC_msg_redirect_hash &&
8525                     func_id != BPF_FUNC_sk_select_reuseport &&
8526                     func_id != BPF_FUNC_map_lookup_elem &&
8527                     !may_update_sockmap(env, func_id))
8528                         goto error;
8529                 break;
8530         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8531                 if (func_id != BPF_FUNC_sk_select_reuseport)
8532                         goto error;
8533                 break;
8534         case BPF_MAP_TYPE_QUEUE:
8535         case BPF_MAP_TYPE_STACK:
8536                 if (func_id != BPF_FUNC_map_peek_elem &&
8537                     func_id != BPF_FUNC_map_pop_elem &&
8538                     func_id != BPF_FUNC_map_push_elem)
8539                         goto error;
8540                 break;
8541         case BPF_MAP_TYPE_SK_STORAGE:
8542                 if (func_id != BPF_FUNC_sk_storage_get &&
8543                     func_id != BPF_FUNC_sk_storage_delete &&
8544                     func_id != BPF_FUNC_kptr_xchg)
8545                         goto error;
8546                 break;
8547         case BPF_MAP_TYPE_INODE_STORAGE:
8548                 if (func_id != BPF_FUNC_inode_storage_get &&
8549                     func_id != BPF_FUNC_inode_storage_delete &&
8550                     func_id != BPF_FUNC_kptr_xchg)
8551                         goto error;
8552                 break;
8553         case BPF_MAP_TYPE_TASK_STORAGE:
8554                 if (func_id != BPF_FUNC_task_storage_get &&
8555                     func_id != BPF_FUNC_task_storage_delete &&
8556                     func_id != BPF_FUNC_kptr_xchg)
8557                         goto error;
8558                 break;
8559         case BPF_MAP_TYPE_CGRP_STORAGE:
8560                 if (func_id != BPF_FUNC_cgrp_storage_get &&
8561                     func_id != BPF_FUNC_cgrp_storage_delete &&
8562                     func_id != BPF_FUNC_kptr_xchg)
8563                         goto error;
8564                 break;
8565         case BPF_MAP_TYPE_BLOOM_FILTER:
8566                 if (func_id != BPF_FUNC_map_peek_elem &&
8567                     func_id != BPF_FUNC_map_push_elem)
8568                         goto error;
8569                 break;
8570         default:
8571                 break;
8572         }
8573
8574         /* ... and second from the function itself. */
8575         switch (func_id) {
8576         case BPF_FUNC_tail_call:
8577                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8578                         goto error;
8579                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8580                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8581                         return -EINVAL;
8582                 }
8583                 break;
8584         case BPF_FUNC_perf_event_read:
8585         case BPF_FUNC_perf_event_output:
8586         case BPF_FUNC_perf_event_read_value:
8587         case BPF_FUNC_skb_output:
8588         case BPF_FUNC_xdp_output:
8589                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8590                         goto error;
8591                 break;
8592         case BPF_FUNC_ringbuf_output:
8593         case BPF_FUNC_ringbuf_reserve:
8594         case BPF_FUNC_ringbuf_query:
8595         case BPF_FUNC_ringbuf_reserve_dynptr:
8596         case BPF_FUNC_ringbuf_submit_dynptr:
8597         case BPF_FUNC_ringbuf_discard_dynptr:
8598                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8599                         goto error;
8600                 break;
8601         case BPF_FUNC_user_ringbuf_drain:
8602                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8603                         goto error;
8604                 break;
8605         case BPF_FUNC_get_stackid:
8606                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8607                         goto error;
8608                 break;
8609         case BPF_FUNC_current_task_under_cgroup:
8610         case BPF_FUNC_skb_under_cgroup:
8611                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8612                         goto error;
8613                 break;
8614         case BPF_FUNC_redirect_map:
8615                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8616                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8617                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
8618                     map->map_type != BPF_MAP_TYPE_XSKMAP)
8619                         goto error;
8620                 break;
8621         case BPF_FUNC_sk_redirect_map:
8622         case BPF_FUNC_msg_redirect_map:
8623         case BPF_FUNC_sock_map_update:
8624                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8625                         goto error;
8626                 break;
8627         case BPF_FUNC_sk_redirect_hash:
8628         case BPF_FUNC_msg_redirect_hash:
8629         case BPF_FUNC_sock_hash_update:
8630                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8631                         goto error;
8632                 break;
8633         case BPF_FUNC_get_local_storage:
8634                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8635                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8636                         goto error;
8637                 break;
8638         case BPF_FUNC_sk_select_reuseport:
8639                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8640                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8641                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
8642                         goto error;
8643                 break;
8644         case BPF_FUNC_map_pop_elem:
8645                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8646                     map->map_type != BPF_MAP_TYPE_STACK)
8647                         goto error;
8648                 break;
8649         case BPF_FUNC_map_peek_elem:
8650         case BPF_FUNC_map_push_elem:
8651                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8652                     map->map_type != BPF_MAP_TYPE_STACK &&
8653                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8654                         goto error;
8655                 break;
8656         case BPF_FUNC_map_lookup_percpu_elem:
8657                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8658                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8659                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8660                         goto error;
8661                 break;
8662         case BPF_FUNC_sk_storage_get:
8663         case BPF_FUNC_sk_storage_delete:
8664                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8665                         goto error;
8666                 break;
8667         case BPF_FUNC_inode_storage_get:
8668         case BPF_FUNC_inode_storage_delete:
8669                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8670                         goto error;
8671                 break;
8672         case BPF_FUNC_task_storage_get:
8673         case BPF_FUNC_task_storage_delete:
8674                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8675                         goto error;
8676                 break;
8677         case BPF_FUNC_cgrp_storage_get:
8678         case BPF_FUNC_cgrp_storage_delete:
8679                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8680                         goto error;
8681                 break;
8682         default:
8683                 break;
8684         }
8685
8686         return 0;
8687 error:
8688         verbose(env, "cannot pass map_type %d into func %s#%d\n",
8689                 map->map_type, func_id_name(func_id), func_id);
8690         return -EINVAL;
8691 }
8692
8693 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8694 {
8695         int count = 0;
8696
8697         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8698                 count++;
8699         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8700                 count++;
8701         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8702                 count++;
8703         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8704                 count++;
8705         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8706                 count++;
8707
8708         /* We only support one arg being in raw mode at the moment,
8709          * which is sufficient for the helper functions we have
8710          * right now.
8711          */
8712         return count <= 1;
8713 }
8714
8715 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8716 {
8717         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8718         bool has_size = fn->arg_size[arg] != 0;
8719         bool is_next_size = false;
8720
8721         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8722                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8723
8724         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8725                 return is_next_size;
8726
8727         return has_size == is_next_size || is_next_size == is_fixed;
8728 }
8729
8730 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8731 {
8732         /* bpf_xxx(..., buf, len) call will access 'len'
8733          * bytes from memory 'buf'. Both arg types need
8734          * to be paired, so make sure there's no buggy
8735          * helper function specification.
8736          */
8737         if (arg_type_is_mem_size(fn->arg1_type) ||
8738             check_args_pair_invalid(fn, 0) ||
8739             check_args_pair_invalid(fn, 1) ||
8740             check_args_pair_invalid(fn, 2) ||
8741             check_args_pair_invalid(fn, 3) ||
8742             check_args_pair_invalid(fn, 4))
8743                 return false;
8744
8745         return true;
8746 }
8747
8748 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8749 {
8750         int i;
8751
8752         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8753                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8754                         return !!fn->arg_btf_id[i];
8755                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8756                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
8757                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8758                     /* arg_btf_id and arg_size are in a union. */
8759                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8760                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8761                         return false;
8762         }
8763
8764         return true;
8765 }
8766
8767 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8768 {
8769         return check_raw_mode_ok(fn) &&
8770                check_arg_pair_ok(fn) &&
8771                check_btf_id_ok(fn) ? 0 : -EINVAL;
8772 }
8773
8774 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8775  * are now invalid, so turn them into unknown SCALAR_VALUE.
8776  *
8777  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8778  * since these slices point to packet data.
8779  */
8780 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8781 {
8782         struct bpf_func_state *state;
8783         struct bpf_reg_state *reg;
8784
8785         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8786                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8787                         mark_reg_invalid(env, reg);
8788         }));
8789 }
8790
8791 enum {
8792         AT_PKT_END = -1,
8793         BEYOND_PKT_END = -2,
8794 };
8795
8796 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8797 {
8798         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8799         struct bpf_reg_state *reg = &state->regs[regn];
8800
8801         if (reg->type != PTR_TO_PACKET)
8802                 /* PTR_TO_PACKET_META is not supported yet */
8803                 return;
8804
8805         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8806          * How far beyond pkt_end it goes is unknown.
8807          * if (!range_open) it's the case of pkt >= pkt_end
8808          * if (range_open) it's the case of pkt > pkt_end
8809          * hence this pointer is at least 1 byte bigger than pkt_end
8810          */
8811         if (range_open)
8812                 reg->range = BEYOND_PKT_END;
8813         else
8814                 reg->range = AT_PKT_END;
8815 }
8816
8817 /* The pointer with the specified id has released its reference to kernel
8818  * resources. Identify all copies of the same pointer and clear the reference.
8819  */
8820 static int release_reference(struct bpf_verifier_env *env,
8821                              int ref_obj_id)
8822 {
8823         struct bpf_func_state *state;
8824         struct bpf_reg_state *reg;
8825         int err;
8826
8827         err = release_reference_state(cur_func(env), ref_obj_id);
8828         if (err)
8829                 return err;
8830
8831         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8832                 if (reg->ref_obj_id == ref_obj_id)
8833                         mark_reg_invalid(env, reg);
8834         }));
8835
8836         return 0;
8837 }
8838
8839 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8840 {
8841         struct bpf_func_state *unused;
8842         struct bpf_reg_state *reg;
8843
8844         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8845                 if (type_is_non_owning_ref(reg->type))
8846                         mark_reg_invalid(env, reg);
8847         }));
8848 }
8849
8850 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8851                                     struct bpf_reg_state *regs)
8852 {
8853         int i;
8854
8855         /* after the call registers r0 - r5 were scratched */
8856         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8857                 mark_reg_not_init(env, regs, caller_saved[i]);
8858                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8859         }
8860 }
8861
8862 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8863                                    struct bpf_func_state *caller,
8864                                    struct bpf_func_state *callee,
8865                                    int insn_idx);
8866
8867 static int set_callee_state(struct bpf_verifier_env *env,
8868                             struct bpf_func_state *caller,
8869                             struct bpf_func_state *callee, int insn_idx);
8870
8871 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8872                              int *insn_idx, int subprog,
8873                              set_callee_state_fn set_callee_state_cb)
8874 {
8875         struct bpf_verifier_state *state = env->cur_state;
8876         struct bpf_func_state *caller, *callee;
8877         int err;
8878
8879         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8880                 verbose(env, "the call stack of %d frames is too deep\n",
8881                         state->curframe + 2);
8882                 return -E2BIG;
8883         }
8884
8885         caller = state->frame[state->curframe];
8886         if (state->frame[state->curframe + 1]) {
8887                 verbose(env, "verifier bug. Frame %d already allocated\n",
8888                         state->curframe + 1);
8889                 return -EFAULT;
8890         }
8891
8892         err = btf_check_subprog_call(env, subprog, caller->regs);
8893         if (err == -EFAULT)
8894                 return err;
8895         if (subprog_is_global(env, subprog)) {
8896                 if (err) {
8897                         verbose(env, "Caller passes invalid args into func#%d\n",
8898                                 subprog);
8899                         return err;
8900                 } else {
8901                         if (env->log.level & BPF_LOG_LEVEL)
8902                                 verbose(env,
8903                                         "Func#%d is global and valid. Skipping.\n",
8904                                         subprog);
8905                         clear_caller_saved_regs(env, caller->regs);
8906
8907                         /* All global functions return a 64-bit SCALAR_VALUE */
8908                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
8909                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8910
8911                         /* continue with next insn after call */
8912                         return 0;
8913                 }
8914         }
8915
8916         /* set_callee_state is used for direct subprog calls, but we are
8917          * interested in validating only BPF helpers that can call subprogs as
8918          * callbacks
8919          */
8920         if (set_callee_state_cb != set_callee_state) {
8921                 if (bpf_pseudo_kfunc_call(insn) &&
8922                     !is_callback_calling_kfunc(insn->imm)) {
8923                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8924                                 func_id_name(insn->imm), insn->imm);
8925                         return -EFAULT;
8926                 } else if (!bpf_pseudo_kfunc_call(insn) &&
8927                            !is_callback_calling_function(insn->imm)) { /* helper */
8928                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8929                                 func_id_name(insn->imm), insn->imm);
8930                         return -EFAULT;
8931                 }
8932         }
8933
8934         if (insn->code == (BPF_JMP | BPF_CALL) &&
8935             insn->src_reg == 0 &&
8936             insn->imm == BPF_FUNC_timer_set_callback) {
8937                 struct bpf_verifier_state *async_cb;
8938
8939                 /* there is no real recursion here. timer callbacks are async */
8940                 env->subprog_info[subprog].is_async_cb = true;
8941                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8942                                          *insn_idx, subprog);
8943                 if (!async_cb)
8944                         return -EFAULT;
8945                 callee = async_cb->frame[0];
8946                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8947
8948                 /* Convert bpf_timer_set_callback() args into timer callback args */
8949                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8950                 if (err)
8951                         return err;
8952
8953                 clear_caller_saved_regs(env, caller->regs);
8954                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8955                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8956                 /* continue with next insn after call */
8957                 return 0;
8958         }
8959
8960         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8961         if (!callee)
8962                 return -ENOMEM;
8963         state->frame[state->curframe + 1] = callee;
8964
8965         /* callee cannot access r0, r6 - r9 for reading and has to write
8966          * into its own stack before reading from it.
8967          * callee can read/write into caller's stack
8968          */
8969         init_func_state(env, callee,
8970                         /* remember the callsite, it will be used by bpf_exit */
8971                         *insn_idx /* callsite */,
8972                         state->curframe + 1 /* frameno within this callchain */,
8973                         subprog /* subprog number within this prog */);
8974
8975         /* Transfer references to the callee */
8976         err = copy_reference_state(callee, caller);
8977         if (err)
8978                 goto err_out;
8979
8980         err = set_callee_state_cb(env, caller, callee, *insn_idx);
8981         if (err)
8982                 goto err_out;
8983
8984         clear_caller_saved_regs(env, caller->regs);
8985
8986         /* only increment it after check_reg_arg() finished */
8987         state->curframe++;
8988
8989         /* and go analyze first insn of the callee */
8990         *insn_idx = env->subprog_info[subprog].start - 1;
8991
8992         if (env->log.level & BPF_LOG_LEVEL) {
8993                 verbose(env, "caller:\n");
8994                 print_verifier_state(env, caller, true);
8995                 verbose(env, "callee:\n");
8996                 print_verifier_state(env, callee, true);
8997         }
8998         return 0;
8999
9000 err_out:
9001         free_func_state(callee);
9002         state->frame[state->curframe + 1] = NULL;
9003         return err;
9004 }
9005
9006 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9007                                    struct bpf_func_state *caller,
9008                                    struct bpf_func_state *callee)
9009 {
9010         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9011          *      void *callback_ctx, u64 flags);
9012          * callback_fn(struct bpf_map *map, void *key, void *value,
9013          *      void *callback_ctx);
9014          */
9015         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9016
9017         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9018         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9019         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9020
9021         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9022         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9023         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9024
9025         /* pointer to stack or null */
9026         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9027
9028         /* unused */
9029         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9030         return 0;
9031 }
9032
9033 static int set_callee_state(struct bpf_verifier_env *env,
9034                             struct bpf_func_state *caller,
9035                             struct bpf_func_state *callee, int insn_idx)
9036 {
9037         int i;
9038
9039         /* copy r1 - r5 args that callee can access.  The copy includes parent
9040          * pointers, which connects us up to the liveness chain
9041          */
9042         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9043                 callee->regs[i] = caller->regs[i];
9044         return 0;
9045 }
9046
9047 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9048                            int *insn_idx)
9049 {
9050         int subprog, target_insn;
9051
9052         target_insn = *insn_idx + insn->imm + 1;
9053         subprog = find_subprog(env, target_insn);
9054         if (subprog < 0) {
9055                 verbose(env, "verifier bug. No program starts at insn %d\n",
9056                         target_insn);
9057                 return -EFAULT;
9058         }
9059
9060         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9061 }
9062
9063 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9064                                        struct bpf_func_state *caller,
9065                                        struct bpf_func_state *callee,
9066                                        int insn_idx)
9067 {
9068         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9069         struct bpf_map *map;
9070         int err;
9071
9072         if (bpf_map_ptr_poisoned(insn_aux)) {
9073                 verbose(env, "tail_call abusing map_ptr\n");
9074                 return -EINVAL;
9075         }
9076
9077         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9078         if (!map->ops->map_set_for_each_callback_args ||
9079             !map->ops->map_for_each_callback) {
9080                 verbose(env, "callback function not allowed for map\n");
9081                 return -ENOTSUPP;
9082         }
9083
9084         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9085         if (err)
9086                 return err;
9087
9088         callee->in_callback_fn = true;
9089         callee->callback_ret_range = tnum_range(0, 1);
9090         return 0;
9091 }
9092
9093 static int set_loop_callback_state(struct bpf_verifier_env *env,
9094                                    struct bpf_func_state *caller,
9095                                    struct bpf_func_state *callee,
9096                                    int insn_idx)
9097 {
9098         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9099          *          u64 flags);
9100          * callback_fn(u32 index, void *callback_ctx);
9101          */
9102         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9103         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9104
9105         /* unused */
9106         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9107         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9108         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9109
9110         callee->in_callback_fn = true;
9111         callee->callback_ret_range = tnum_range(0, 1);
9112         return 0;
9113 }
9114
9115 static int set_timer_callback_state(struct bpf_verifier_env *env,
9116                                     struct bpf_func_state *caller,
9117                                     struct bpf_func_state *callee,
9118                                     int insn_idx)
9119 {
9120         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9121
9122         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9123          * callback_fn(struct bpf_map *map, void *key, void *value);
9124          */
9125         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9126         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9127         callee->regs[BPF_REG_1].map_ptr = map_ptr;
9128
9129         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9130         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9131         callee->regs[BPF_REG_2].map_ptr = map_ptr;
9132
9133         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9134         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9135         callee->regs[BPF_REG_3].map_ptr = map_ptr;
9136
9137         /* unused */
9138         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9139         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9140         callee->in_async_callback_fn = true;
9141         callee->callback_ret_range = tnum_range(0, 1);
9142         return 0;
9143 }
9144
9145 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9146                                        struct bpf_func_state *caller,
9147                                        struct bpf_func_state *callee,
9148                                        int insn_idx)
9149 {
9150         /* bpf_find_vma(struct task_struct *task, u64 addr,
9151          *               void *callback_fn, void *callback_ctx, u64 flags)
9152          * (callback_fn)(struct task_struct *task,
9153          *               struct vm_area_struct *vma, void *callback_ctx);
9154          */
9155         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9156
9157         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9158         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9159         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9160         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9161
9162         /* pointer to stack or null */
9163         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9164
9165         /* unused */
9166         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9167         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9168         callee->in_callback_fn = true;
9169         callee->callback_ret_range = tnum_range(0, 1);
9170         return 0;
9171 }
9172
9173 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9174                                            struct bpf_func_state *caller,
9175                                            struct bpf_func_state *callee,
9176                                            int insn_idx)
9177 {
9178         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9179          *                        callback_ctx, u64 flags);
9180          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9181          */
9182         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9183         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9184         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9185
9186         /* unused */
9187         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9188         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9189         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9190
9191         callee->in_callback_fn = true;
9192         callee->callback_ret_range = tnum_range(0, 1);
9193         return 0;
9194 }
9195
9196 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9197                                          struct bpf_func_state *caller,
9198                                          struct bpf_func_state *callee,
9199                                          int insn_idx)
9200 {
9201         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9202          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9203          *
9204          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9205          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9206          * by this point, so look at 'root'
9207          */
9208         struct btf_field *field;
9209
9210         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9211                                       BPF_RB_ROOT);
9212         if (!field || !field->graph_root.value_btf_id)
9213                 return -EFAULT;
9214
9215         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9216         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9217         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9218         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9219
9220         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9221         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9222         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9223         callee->in_callback_fn = true;
9224         callee->callback_ret_range = tnum_range(0, 1);
9225         return 0;
9226 }
9227
9228 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9229
9230 /* Are we currently verifying the callback for a rbtree helper that must
9231  * be called with lock held? If so, no need to complain about unreleased
9232  * lock
9233  */
9234 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9235 {
9236         struct bpf_verifier_state *state = env->cur_state;
9237         struct bpf_insn *insn = env->prog->insnsi;
9238         struct bpf_func_state *callee;
9239         int kfunc_btf_id;
9240
9241         if (!state->curframe)
9242                 return false;
9243
9244         callee = state->frame[state->curframe];
9245
9246         if (!callee->in_callback_fn)
9247                 return false;
9248
9249         kfunc_btf_id = insn[callee->callsite].imm;
9250         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9251 }
9252
9253 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9254 {
9255         struct bpf_verifier_state *state = env->cur_state;
9256         struct bpf_func_state *caller, *callee;
9257         struct bpf_reg_state *r0;
9258         int err;
9259
9260         callee = state->frame[state->curframe];
9261         r0 = &callee->regs[BPF_REG_0];
9262         if (r0->type == PTR_TO_STACK) {
9263                 /* technically it's ok to return caller's stack pointer
9264                  * (or caller's caller's pointer) back to the caller,
9265                  * since these pointers are valid. Only current stack
9266                  * pointer will be invalid as soon as function exits,
9267                  * but let's be conservative
9268                  */
9269                 verbose(env, "cannot return stack pointer to the caller\n");
9270                 return -EINVAL;
9271         }
9272
9273         caller = state->frame[state->curframe - 1];
9274         if (callee->in_callback_fn) {
9275                 /* enforce R0 return value range [0, 1]. */
9276                 struct tnum range = callee->callback_ret_range;
9277
9278                 if (r0->type != SCALAR_VALUE) {
9279                         verbose(env, "R0 not a scalar value\n");
9280                         return -EACCES;
9281                 }
9282                 if (!tnum_in(range, r0->var_off)) {
9283                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9284                         return -EINVAL;
9285                 }
9286         } else {
9287                 /* return to the caller whatever r0 had in the callee */
9288                 caller->regs[BPF_REG_0] = *r0;
9289         }
9290
9291         /* callback_fn frame should have released its own additions to parent's
9292          * reference state at this point, or check_reference_leak would
9293          * complain, hence it must be the same as the caller. There is no need
9294          * to copy it back.
9295          */
9296         if (!callee->in_callback_fn) {
9297                 /* Transfer references to the caller */
9298                 err = copy_reference_state(caller, callee);
9299                 if (err)
9300                         return err;
9301         }
9302
9303         *insn_idx = callee->callsite + 1;
9304         if (env->log.level & BPF_LOG_LEVEL) {
9305                 verbose(env, "returning from callee:\n");
9306                 print_verifier_state(env, callee, true);
9307                 verbose(env, "to caller at %d:\n", *insn_idx);
9308                 print_verifier_state(env, caller, true);
9309         }
9310         /* clear everything in the callee */
9311         free_func_state(callee);
9312         state->frame[state->curframe--] = NULL;
9313         return 0;
9314 }
9315
9316 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9317                                    int func_id,
9318                                    struct bpf_call_arg_meta *meta)
9319 {
9320         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9321
9322         if (ret_type != RET_INTEGER)
9323                 return;
9324
9325         switch (func_id) {
9326         case BPF_FUNC_get_stack:
9327         case BPF_FUNC_get_task_stack:
9328         case BPF_FUNC_probe_read_str:
9329         case BPF_FUNC_probe_read_kernel_str:
9330         case BPF_FUNC_probe_read_user_str:
9331                 ret_reg->smax_value = meta->msize_max_value;
9332                 ret_reg->s32_max_value = meta->msize_max_value;
9333                 ret_reg->smin_value = -MAX_ERRNO;
9334                 ret_reg->s32_min_value = -MAX_ERRNO;
9335                 reg_bounds_sync(ret_reg);
9336                 break;
9337         case BPF_FUNC_get_smp_processor_id:
9338                 ret_reg->umax_value = nr_cpu_ids - 1;
9339                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9340                 ret_reg->smax_value = nr_cpu_ids - 1;
9341                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9342                 ret_reg->umin_value = 0;
9343                 ret_reg->u32_min_value = 0;
9344                 ret_reg->smin_value = 0;
9345                 ret_reg->s32_min_value = 0;
9346                 reg_bounds_sync(ret_reg);
9347                 break;
9348         }
9349 }
9350
9351 static int
9352 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9353                 int func_id, int insn_idx)
9354 {
9355         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9356         struct bpf_map *map = meta->map_ptr;
9357
9358         if (func_id != BPF_FUNC_tail_call &&
9359             func_id != BPF_FUNC_map_lookup_elem &&
9360             func_id != BPF_FUNC_map_update_elem &&
9361             func_id != BPF_FUNC_map_delete_elem &&
9362             func_id != BPF_FUNC_map_push_elem &&
9363             func_id != BPF_FUNC_map_pop_elem &&
9364             func_id != BPF_FUNC_map_peek_elem &&
9365             func_id != BPF_FUNC_for_each_map_elem &&
9366             func_id != BPF_FUNC_redirect_map &&
9367             func_id != BPF_FUNC_map_lookup_percpu_elem)
9368                 return 0;
9369
9370         if (map == NULL) {
9371                 verbose(env, "kernel subsystem misconfigured verifier\n");
9372                 return -EINVAL;
9373         }
9374
9375         /* In case of read-only, some additional restrictions
9376          * need to be applied in order to prevent altering the
9377          * state of the map from program side.
9378          */
9379         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9380             (func_id == BPF_FUNC_map_delete_elem ||
9381              func_id == BPF_FUNC_map_update_elem ||
9382              func_id == BPF_FUNC_map_push_elem ||
9383              func_id == BPF_FUNC_map_pop_elem)) {
9384                 verbose(env, "write into map forbidden\n");
9385                 return -EACCES;
9386         }
9387
9388         if (!BPF_MAP_PTR(aux->map_ptr_state))
9389                 bpf_map_ptr_store(aux, meta->map_ptr,
9390                                   !meta->map_ptr->bypass_spec_v1);
9391         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9392                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9393                                   !meta->map_ptr->bypass_spec_v1);
9394         return 0;
9395 }
9396
9397 static int
9398 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9399                 int func_id, int insn_idx)
9400 {
9401         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9402         struct bpf_reg_state *regs = cur_regs(env), *reg;
9403         struct bpf_map *map = meta->map_ptr;
9404         u64 val, max;
9405         int err;
9406
9407         if (func_id != BPF_FUNC_tail_call)
9408                 return 0;
9409         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9410                 verbose(env, "kernel subsystem misconfigured verifier\n");
9411                 return -EINVAL;
9412         }
9413
9414         reg = &regs[BPF_REG_3];
9415         val = reg->var_off.value;
9416         max = map->max_entries;
9417
9418         if (!(register_is_const(reg) && val < max)) {
9419                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9420                 return 0;
9421         }
9422
9423         err = mark_chain_precision(env, BPF_REG_3);
9424         if (err)
9425                 return err;
9426         if (bpf_map_key_unseen(aux))
9427                 bpf_map_key_store(aux, val);
9428         else if (!bpf_map_key_poisoned(aux) &&
9429                   bpf_map_key_immediate(aux) != val)
9430                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9431         return 0;
9432 }
9433
9434 static int check_reference_leak(struct bpf_verifier_env *env)
9435 {
9436         struct bpf_func_state *state = cur_func(env);
9437         bool refs_lingering = false;
9438         int i;
9439
9440         if (state->frameno && !state->in_callback_fn)
9441                 return 0;
9442
9443         for (i = 0; i < state->acquired_refs; i++) {
9444                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9445                         continue;
9446                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9447                         state->refs[i].id, state->refs[i].insn_idx);
9448                 refs_lingering = true;
9449         }
9450         return refs_lingering ? -EINVAL : 0;
9451 }
9452
9453 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9454                                    struct bpf_reg_state *regs)
9455 {
9456         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9457         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9458         struct bpf_map *fmt_map = fmt_reg->map_ptr;
9459         struct bpf_bprintf_data data = {};
9460         int err, fmt_map_off, num_args;
9461         u64 fmt_addr;
9462         char *fmt;
9463
9464         /* data must be an array of u64 */
9465         if (data_len_reg->var_off.value % 8)
9466                 return -EINVAL;
9467         num_args = data_len_reg->var_off.value / 8;
9468
9469         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9470          * and map_direct_value_addr is set.
9471          */
9472         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9473         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9474                                                   fmt_map_off);
9475         if (err) {
9476                 verbose(env, "verifier bug\n");
9477                 return -EFAULT;
9478         }
9479         fmt = (char *)(long)fmt_addr + fmt_map_off;
9480
9481         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9482          * can focus on validating the format specifiers.
9483          */
9484         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9485         if (err < 0)
9486                 verbose(env, "Invalid format string\n");
9487
9488         return err;
9489 }
9490
9491 static int check_get_func_ip(struct bpf_verifier_env *env)
9492 {
9493         enum bpf_prog_type type = resolve_prog_type(env->prog);
9494         int func_id = BPF_FUNC_get_func_ip;
9495
9496         if (type == BPF_PROG_TYPE_TRACING) {
9497                 if (!bpf_prog_has_trampoline(env->prog)) {
9498                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9499                                 func_id_name(func_id), func_id);
9500                         return -ENOTSUPP;
9501                 }
9502                 return 0;
9503         } else if (type == BPF_PROG_TYPE_KPROBE) {
9504                 return 0;
9505         }
9506
9507         verbose(env, "func %s#%d not supported for program type %d\n",
9508                 func_id_name(func_id), func_id, type);
9509         return -ENOTSUPP;
9510 }
9511
9512 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9513 {
9514         return &env->insn_aux_data[env->insn_idx];
9515 }
9516
9517 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9518 {
9519         struct bpf_reg_state *regs = cur_regs(env);
9520         struct bpf_reg_state *reg = &regs[BPF_REG_4];
9521         bool reg_is_null = register_is_null(reg);
9522
9523         if (reg_is_null)
9524                 mark_chain_precision(env, BPF_REG_4);
9525
9526         return reg_is_null;
9527 }
9528
9529 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9530 {
9531         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9532
9533         if (!state->initialized) {
9534                 state->initialized = 1;
9535                 state->fit_for_inline = loop_flag_is_zero(env);
9536                 state->callback_subprogno = subprogno;
9537                 return;
9538         }
9539
9540         if (!state->fit_for_inline)
9541                 return;
9542
9543         state->fit_for_inline = (loop_flag_is_zero(env) &&
9544                                  state->callback_subprogno == subprogno);
9545 }
9546
9547 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9548                              int *insn_idx_p)
9549 {
9550         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9551         const struct bpf_func_proto *fn = NULL;
9552         enum bpf_return_type ret_type;
9553         enum bpf_type_flag ret_flag;
9554         struct bpf_reg_state *regs;
9555         struct bpf_call_arg_meta meta;
9556         int insn_idx = *insn_idx_p;
9557         bool changes_data;
9558         int i, err, func_id;
9559
9560         /* find function prototype */
9561         func_id = insn->imm;
9562         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9563                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9564                         func_id);
9565                 return -EINVAL;
9566         }
9567
9568         if (env->ops->get_func_proto)
9569                 fn = env->ops->get_func_proto(func_id, env->prog);
9570         if (!fn) {
9571                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9572                         func_id);
9573                 return -EINVAL;
9574         }
9575
9576         /* eBPF programs must be GPL compatible to use GPL-ed functions */
9577         if (!env->prog->gpl_compatible && fn->gpl_only) {
9578                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9579                 return -EINVAL;
9580         }
9581
9582         if (fn->allowed && !fn->allowed(env->prog)) {
9583                 verbose(env, "helper call is not allowed in probe\n");
9584                 return -EINVAL;
9585         }
9586
9587         if (!env->prog->aux->sleepable && fn->might_sleep) {
9588                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9589                 return -EINVAL;
9590         }
9591
9592         /* With LD_ABS/IND some JITs save/restore skb from r1. */
9593         changes_data = bpf_helper_changes_pkt_data(fn->func);
9594         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9595                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9596                         func_id_name(func_id), func_id);
9597                 return -EINVAL;
9598         }
9599
9600         memset(&meta, 0, sizeof(meta));
9601         meta.pkt_access = fn->pkt_access;
9602
9603         err = check_func_proto(fn, func_id);
9604         if (err) {
9605                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9606                         func_id_name(func_id), func_id);
9607                 return err;
9608         }
9609
9610         if (env->cur_state->active_rcu_lock) {
9611                 if (fn->might_sleep) {
9612                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9613                                 func_id_name(func_id), func_id);
9614                         return -EINVAL;
9615                 }
9616
9617                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9618                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9619         }
9620
9621         meta.func_id = func_id;
9622         /* check args */
9623         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9624                 err = check_func_arg(env, i, &meta, fn, insn_idx);
9625                 if (err)
9626                         return err;
9627         }
9628
9629         err = record_func_map(env, &meta, func_id, insn_idx);
9630         if (err)
9631                 return err;
9632
9633         err = record_func_key(env, &meta, func_id, insn_idx);
9634         if (err)
9635                 return err;
9636
9637         /* Mark slots with STACK_MISC in case of raw mode, stack offset
9638          * is inferred from register state.
9639          */
9640         for (i = 0; i < meta.access_size; i++) {
9641                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9642                                        BPF_WRITE, -1, false, false);
9643                 if (err)
9644                         return err;
9645         }
9646
9647         regs = cur_regs(env);
9648
9649         if (meta.release_regno) {
9650                 err = -EINVAL;
9651                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9652                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9653                  * is safe to do directly.
9654                  */
9655                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9656                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9657                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9658                                 return -EFAULT;
9659                         }
9660                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9661                 } else if (meta.ref_obj_id) {
9662                         err = release_reference(env, meta.ref_obj_id);
9663                 } else if (register_is_null(&regs[meta.release_regno])) {
9664                         /* meta.ref_obj_id can only be 0 if register that is meant to be
9665                          * released is NULL, which must be > R0.
9666                          */
9667                         err = 0;
9668                 }
9669                 if (err) {
9670                         verbose(env, "func %s#%d reference has not been acquired before\n",
9671                                 func_id_name(func_id), func_id);
9672                         return err;
9673                 }
9674         }
9675
9676         switch (func_id) {
9677         case BPF_FUNC_tail_call:
9678                 err = check_reference_leak(env);
9679                 if (err) {
9680                         verbose(env, "tail_call would lead to reference leak\n");
9681                         return err;
9682                 }
9683                 break;
9684         case BPF_FUNC_get_local_storage:
9685                 /* check that flags argument in get_local_storage(map, flags) is 0,
9686                  * this is required because get_local_storage() can't return an error.
9687                  */
9688                 if (!register_is_null(&regs[BPF_REG_2])) {
9689                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9690                         return -EINVAL;
9691                 }
9692                 break;
9693         case BPF_FUNC_for_each_map_elem:
9694                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9695                                         set_map_elem_callback_state);
9696                 break;
9697         case BPF_FUNC_timer_set_callback:
9698                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9699                                         set_timer_callback_state);
9700                 break;
9701         case BPF_FUNC_find_vma:
9702                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9703                                         set_find_vma_callback_state);
9704                 break;
9705         case BPF_FUNC_snprintf:
9706                 err = check_bpf_snprintf_call(env, regs);
9707                 break;
9708         case BPF_FUNC_loop:
9709                 update_loop_inline_state(env, meta.subprogno);
9710                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9711                                         set_loop_callback_state);
9712                 break;
9713         case BPF_FUNC_dynptr_from_mem:
9714                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9715                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9716                                 reg_type_str(env, regs[BPF_REG_1].type));
9717                         return -EACCES;
9718                 }
9719                 break;
9720         case BPF_FUNC_set_retval:
9721                 if (prog_type == BPF_PROG_TYPE_LSM &&
9722                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9723                         if (!env->prog->aux->attach_func_proto->type) {
9724                                 /* Make sure programs that attach to void
9725                                  * hooks don't try to modify return value.
9726                                  */
9727                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9728                                 return -EINVAL;
9729                         }
9730                 }
9731                 break;
9732         case BPF_FUNC_dynptr_data:
9733         {
9734                 struct bpf_reg_state *reg;
9735                 int id, ref_obj_id;
9736
9737                 reg = get_dynptr_arg_reg(env, fn, regs);
9738                 if (!reg)
9739                         return -EFAULT;
9740
9741
9742                 if (meta.dynptr_id) {
9743                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9744                         return -EFAULT;
9745                 }
9746                 if (meta.ref_obj_id) {
9747                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9748                         return -EFAULT;
9749                 }
9750
9751                 id = dynptr_id(env, reg);
9752                 if (id < 0) {
9753                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9754                         return id;
9755                 }
9756
9757                 ref_obj_id = dynptr_ref_obj_id(env, reg);
9758                 if (ref_obj_id < 0) {
9759                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9760                         return ref_obj_id;
9761                 }
9762
9763                 meta.dynptr_id = id;
9764                 meta.ref_obj_id = ref_obj_id;
9765
9766                 break;
9767         }
9768         case BPF_FUNC_dynptr_write:
9769         {
9770                 enum bpf_dynptr_type dynptr_type;
9771                 struct bpf_reg_state *reg;
9772
9773                 reg = get_dynptr_arg_reg(env, fn, regs);
9774                 if (!reg)
9775                         return -EFAULT;
9776
9777                 dynptr_type = dynptr_get_type(env, reg);
9778                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9779                         return -EFAULT;
9780
9781                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9782                         /* this will trigger clear_all_pkt_pointers(), which will
9783                          * invalidate all dynptr slices associated with the skb
9784                          */
9785                         changes_data = true;
9786
9787                 break;
9788         }
9789         case BPF_FUNC_user_ringbuf_drain:
9790                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9791                                         set_user_ringbuf_callback_state);
9792                 break;
9793         }
9794
9795         if (err)
9796                 return err;
9797
9798         /* reset caller saved regs */
9799         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9800                 mark_reg_not_init(env, regs, caller_saved[i]);
9801                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9802         }
9803
9804         /* helper call returns 64-bit value. */
9805         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9806
9807         /* update return register (already marked as written above) */
9808         ret_type = fn->ret_type;
9809         ret_flag = type_flag(ret_type);
9810
9811         switch (base_type(ret_type)) {
9812         case RET_INTEGER:
9813                 /* sets type to SCALAR_VALUE */
9814                 mark_reg_unknown(env, regs, BPF_REG_0);
9815                 break;
9816         case RET_VOID:
9817                 regs[BPF_REG_0].type = NOT_INIT;
9818                 break;
9819         case RET_PTR_TO_MAP_VALUE:
9820                 /* There is no offset yet applied, variable or fixed */
9821                 mark_reg_known_zero(env, regs, BPF_REG_0);
9822                 /* remember map_ptr, so that check_map_access()
9823                  * can check 'value_size' boundary of memory access
9824                  * to map element returned from bpf_map_lookup_elem()
9825                  */
9826                 if (meta.map_ptr == NULL) {
9827                         verbose(env,
9828                                 "kernel subsystem misconfigured verifier\n");
9829                         return -EINVAL;
9830                 }
9831                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9832                 regs[BPF_REG_0].map_uid = meta.map_uid;
9833                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9834                 if (!type_may_be_null(ret_type) &&
9835                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9836                         regs[BPF_REG_0].id = ++env->id_gen;
9837                 }
9838                 break;
9839         case RET_PTR_TO_SOCKET:
9840                 mark_reg_known_zero(env, regs, BPF_REG_0);
9841                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9842                 break;
9843         case RET_PTR_TO_SOCK_COMMON:
9844                 mark_reg_known_zero(env, regs, BPF_REG_0);
9845                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9846                 break;
9847         case RET_PTR_TO_TCP_SOCK:
9848                 mark_reg_known_zero(env, regs, BPF_REG_0);
9849                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9850                 break;
9851         case RET_PTR_TO_MEM:
9852                 mark_reg_known_zero(env, regs, BPF_REG_0);
9853                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9854                 regs[BPF_REG_0].mem_size = meta.mem_size;
9855                 break;
9856         case RET_PTR_TO_MEM_OR_BTF_ID:
9857         {
9858                 const struct btf_type *t;
9859
9860                 mark_reg_known_zero(env, regs, BPF_REG_0);
9861                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9862                 if (!btf_type_is_struct(t)) {
9863                         u32 tsize;
9864                         const struct btf_type *ret;
9865                         const char *tname;
9866
9867                         /* resolve the type size of ksym. */
9868                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9869                         if (IS_ERR(ret)) {
9870                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9871                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9872                                         tname, PTR_ERR(ret));
9873                                 return -EINVAL;
9874                         }
9875                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9876                         regs[BPF_REG_0].mem_size = tsize;
9877                 } else {
9878                         /* MEM_RDONLY may be carried from ret_flag, but it
9879                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9880                          * it will confuse the check of PTR_TO_BTF_ID in
9881                          * check_mem_access().
9882                          */
9883                         ret_flag &= ~MEM_RDONLY;
9884
9885                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9886                         regs[BPF_REG_0].btf = meta.ret_btf;
9887                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9888                 }
9889                 break;
9890         }
9891         case RET_PTR_TO_BTF_ID:
9892         {
9893                 struct btf *ret_btf;
9894                 int ret_btf_id;
9895
9896                 mark_reg_known_zero(env, regs, BPF_REG_0);
9897                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9898                 if (func_id == BPF_FUNC_kptr_xchg) {
9899                         ret_btf = meta.kptr_field->kptr.btf;
9900                         ret_btf_id = meta.kptr_field->kptr.btf_id;
9901                         if (!btf_is_kernel(ret_btf))
9902                                 regs[BPF_REG_0].type |= MEM_ALLOC;
9903                 } else {
9904                         if (fn->ret_btf_id == BPF_PTR_POISON) {
9905                                 verbose(env, "verifier internal error:");
9906                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9907                                         func_id_name(func_id));
9908                                 return -EINVAL;
9909                         }
9910                         ret_btf = btf_vmlinux;
9911                         ret_btf_id = *fn->ret_btf_id;
9912                 }
9913                 if (ret_btf_id == 0) {
9914                         verbose(env, "invalid return type %u of func %s#%d\n",
9915                                 base_type(ret_type), func_id_name(func_id),
9916                                 func_id);
9917                         return -EINVAL;
9918                 }
9919                 regs[BPF_REG_0].btf = ret_btf;
9920                 regs[BPF_REG_0].btf_id = ret_btf_id;
9921                 break;
9922         }
9923         default:
9924                 verbose(env, "unknown return type %u of func %s#%d\n",
9925                         base_type(ret_type), func_id_name(func_id), func_id);
9926                 return -EINVAL;
9927         }
9928
9929         if (type_may_be_null(regs[BPF_REG_0].type))
9930                 regs[BPF_REG_0].id = ++env->id_gen;
9931
9932         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9933                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9934                         func_id_name(func_id), func_id);
9935                 return -EFAULT;
9936         }
9937
9938         if (is_dynptr_ref_function(func_id))
9939                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9940
9941         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9942                 /* For release_reference() */
9943                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9944         } else if (is_acquire_function(func_id, meta.map_ptr)) {
9945                 int id = acquire_reference_state(env, insn_idx);
9946
9947                 if (id < 0)
9948                         return id;
9949                 /* For mark_ptr_or_null_reg() */
9950                 regs[BPF_REG_0].id = id;
9951                 /* For release_reference() */
9952                 regs[BPF_REG_0].ref_obj_id = id;
9953         }
9954
9955         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9956
9957         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9958         if (err)
9959                 return err;
9960
9961         if ((func_id == BPF_FUNC_get_stack ||
9962              func_id == BPF_FUNC_get_task_stack) &&
9963             !env->prog->has_callchain_buf) {
9964                 const char *err_str;
9965
9966 #ifdef CONFIG_PERF_EVENTS
9967                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9968                 err_str = "cannot get callchain buffer for func %s#%d\n";
9969 #else
9970                 err = -ENOTSUPP;
9971                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9972 #endif
9973                 if (err) {
9974                         verbose(env, err_str, func_id_name(func_id), func_id);
9975                         return err;
9976                 }
9977
9978                 env->prog->has_callchain_buf = true;
9979         }
9980
9981         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9982                 env->prog->call_get_stack = true;
9983
9984         if (func_id == BPF_FUNC_get_func_ip) {
9985                 if (check_get_func_ip(env))
9986                         return -ENOTSUPP;
9987                 env->prog->call_get_func_ip = true;
9988         }
9989
9990         if (changes_data)
9991                 clear_all_pkt_pointers(env);
9992         return 0;
9993 }
9994
9995 /* mark_btf_func_reg_size() is used when the reg size is determined by
9996  * the BTF func_proto's return value size and argument.
9997  */
9998 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9999                                    size_t reg_size)
10000 {
10001         struct bpf_reg_state *reg = &cur_regs(env)[regno];
10002
10003         if (regno == BPF_REG_0) {
10004                 /* Function return value */
10005                 reg->live |= REG_LIVE_WRITTEN;
10006                 reg->subreg_def = reg_size == sizeof(u64) ?
10007                         DEF_NOT_SUBREG : env->insn_idx + 1;
10008         } else {
10009                 /* Function argument */
10010                 if (reg_size == sizeof(u64)) {
10011                         mark_insn_zext(env, reg);
10012                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10013                 } else {
10014                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10015                 }
10016         }
10017 }
10018
10019 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10020 {
10021         return meta->kfunc_flags & KF_ACQUIRE;
10022 }
10023
10024 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10025 {
10026         return meta->kfunc_flags & KF_RELEASE;
10027 }
10028
10029 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10030 {
10031         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10032 }
10033
10034 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10035 {
10036         return meta->kfunc_flags & KF_SLEEPABLE;
10037 }
10038
10039 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10040 {
10041         return meta->kfunc_flags & KF_DESTRUCTIVE;
10042 }
10043
10044 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10045 {
10046         return meta->kfunc_flags & KF_RCU;
10047 }
10048
10049 static bool __kfunc_param_match_suffix(const struct btf *btf,
10050                                        const struct btf_param *arg,
10051                                        const char *suffix)
10052 {
10053         int suffix_len = strlen(suffix), len;
10054         const char *param_name;
10055
10056         /* In the future, this can be ported to use BTF tagging */
10057         param_name = btf_name_by_offset(btf, arg->name_off);
10058         if (str_is_empty(param_name))
10059                 return false;
10060         len = strlen(param_name);
10061         if (len < suffix_len)
10062                 return false;
10063         param_name += len - suffix_len;
10064         return !strncmp(param_name, suffix, suffix_len);
10065 }
10066
10067 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10068                                   const struct btf_param *arg,
10069                                   const struct bpf_reg_state *reg)
10070 {
10071         const struct btf_type *t;
10072
10073         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10074         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10075                 return false;
10076
10077         return __kfunc_param_match_suffix(btf, arg, "__sz");
10078 }
10079
10080 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10081                                         const struct btf_param *arg,
10082                                         const struct bpf_reg_state *reg)
10083 {
10084         const struct btf_type *t;
10085
10086         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10087         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10088                 return false;
10089
10090         return __kfunc_param_match_suffix(btf, arg, "__szk");
10091 }
10092
10093 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10094 {
10095         return __kfunc_param_match_suffix(btf, arg, "__opt");
10096 }
10097
10098 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10099 {
10100         return __kfunc_param_match_suffix(btf, arg, "__k");
10101 }
10102
10103 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10104 {
10105         return __kfunc_param_match_suffix(btf, arg, "__ign");
10106 }
10107
10108 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10109 {
10110         return __kfunc_param_match_suffix(btf, arg, "__alloc");
10111 }
10112
10113 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10114 {
10115         return __kfunc_param_match_suffix(btf, arg, "__uninit");
10116 }
10117
10118 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10119 {
10120         return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10121 }
10122
10123 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10124                                           const struct btf_param *arg,
10125                                           const char *name)
10126 {
10127         int len, target_len = strlen(name);
10128         const char *param_name;
10129
10130         param_name = btf_name_by_offset(btf, arg->name_off);
10131         if (str_is_empty(param_name))
10132                 return false;
10133         len = strlen(param_name);
10134         if (len != target_len)
10135                 return false;
10136         if (strcmp(param_name, name))
10137                 return false;
10138
10139         return true;
10140 }
10141
10142 enum {
10143         KF_ARG_DYNPTR_ID,
10144         KF_ARG_LIST_HEAD_ID,
10145         KF_ARG_LIST_NODE_ID,
10146         KF_ARG_RB_ROOT_ID,
10147         KF_ARG_RB_NODE_ID,
10148 };
10149
10150 BTF_ID_LIST(kf_arg_btf_ids)
10151 BTF_ID(struct, bpf_dynptr_kern)
10152 BTF_ID(struct, bpf_list_head)
10153 BTF_ID(struct, bpf_list_node)
10154 BTF_ID(struct, bpf_rb_root)
10155 BTF_ID(struct, bpf_rb_node)
10156
10157 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10158                                     const struct btf_param *arg, int type)
10159 {
10160         const struct btf_type *t;
10161         u32 res_id;
10162
10163         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10164         if (!t)
10165                 return false;
10166         if (!btf_type_is_ptr(t))
10167                 return false;
10168         t = btf_type_skip_modifiers(btf, t->type, &res_id);
10169         if (!t)
10170                 return false;
10171         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10172 }
10173
10174 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10175 {
10176         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10177 }
10178
10179 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10180 {
10181         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10182 }
10183
10184 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10185 {
10186         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10187 }
10188
10189 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10190 {
10191         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10192 }
10193
10194 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10195 {
10196         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10197 }
10198
10199 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10200                                   const struct btf_param *arg)
10201 {
10202         const struct btf_type *t;
10203
10204         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10205         if (!t)
10206                 return false;
10207
10208         return true;
10209 }
10210
10211 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10212 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10213                                         const struct btf *btf,
10214                                         const struct btf_type *t, int rec)
10215 {
10216         const struct btf_type *member_type;
10217         const struct btf_member *member;
10218         u32 i;
10219
10220         if (!btf_type_is_struct(t))
10221                 return false;
10222
10223         for_each_member(i, t, member) {
10224                 const struct btf_array *array;
10225
10226                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10227                 if (btf_type_is_struct(member_type)) {
10228                         if (rec >= 3) {
10229                                 verbose(env, "max struct nesting depth exceeded\n");
10230                                 return false;
10231                         }
10232                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10233                                 return false;
10234                         continue;
10235                 }
10236                 if (btf_type_is_array(member_type)) {
10237                         array = btf_array(member_type);
10238                         if (!array->nelems)
10239                                 return false;
10240                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10241                         if (!btf_type_is_scalar(member_type))
10242                                 return false;
10243                         continue;
10244                 }
10245                 if (!btf_type_is_scalar(member_type))
10246                         return false;
10247         }
10248         return true;
10249 }
10250
10251 enum kfunc_ptr_arg_type {
10252         KF_ARG_PTR_TO_CTX,
10253         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10254         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10255         KF_ARG_PTR_TO_DYNPTR,
10256         KF_ARG_PTR_TO_ITER,
10257         KF_ARG_PTR_TO_LIST_HEAD,
10258         KF_ARG_PTR_TO_LIST_NODE,
10259         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10260         KF_ARG_PTR_TO_MEM,
10261         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10262         KF_ARG_PTR_TO_CALLBACK,
10263         KF_ARG_PTR_TO_RB_ROOT,
10264         KF_ARG_PTR_TO_RB_NODE,
10265 };
10266
10267 enum special_kfunc_type {
10268         KF_bpf_obj_new_impl,
10269         KF_bpf_obj_drop_impl,
10270         KF_bpf_refcount_acquire_impl,
10271         KF_bpf_list_push_front_impl,
10272         KF_bpf_list_push_back_impl,
10273         KF_bpf_list_pop_front,
10274         KF_bpf_list_pop_back,
10275         KF_bpf_cast_to_kern_ctx,
10276         KF_bpf_rdonly_cast,
10277         KF_bpf_rcu_read_lock,
10278         KF_bpf_rcu_read_unlock,
10279         KF_bpf_rbtree_remove,
10280         KF_bpf_rbtree_add_impl,
10281         KF_bpf_rbtree_first,
10282         KF_bpf_dynptr_from_skb,
10283         KF_bpf_dynptr_from_xdp,
10284         KF_bpf_dynptr_slice,
10285         KF_bpf_dynptr_slice_rdwr,
10286         KF_bpf_dynptr_clone,
10287 };
10288
10289 BTF_SET_START(special_kfunc_set)
10290 BTF_ID(func, bpf_obj_new_impl)
10291 BTF_ID(func, bpf_obj_drop_impl)
10292 BTF_ID(func, bpf_refcount_acquire_impl)
10293 BTF_ID(func, bpf_list_push_front_impl)
10294 BTF_ID(func, bpf_list_push_back_impl)
10295 BTF_ID(func, bpf_list_pop_front)
10296 BTF_ID(func, bpf_list_pop_back)
10297 BTF_ID(func, bpf_cast_to_kern_ctx)
10298 BTF_ID(func, bpf_rdonly_cast)
10299 BTF_ID(func, bpf_rbtree_remove)
10300 BTF_ID(func, bpf_rbtree_add_impl)
10301 BTF_ID(func, bpf_rbtree_first)
10302 BTF_ID(func, bpf_dynptr_from_skb)
10303 BTF_ID(func, bpf_dynptr_from_xdp)
10304 BTF_ID(func, bpf_dynptr_slice)
10305 BTF_ID(func, bpf_dynptr_slice_rdwr)
10306 BTF_ID(func, bpf_dynptr_clone)
10307 BTF_SET_END(special_kfunc_set)
10308
10309 BTF_ID_LIST(special_kfunc_list)
10310 BTF_ID(func, bpf_obj_new_impl)
10311 BTF_ID(func, bpf_obj_drop_impl)
10312 BTF_ID(func, bpf_refcount_acquire_impl)
10313 BTF_ID(func, bpf_list_push_front_impl)
10314 BTF_ID(func, bpf_list_push_back_impl)
10315 BTF_ID(func, bpf_list_pop_front)
10316 BTF_ID(func, bpf_list_pop_back)
10317 BTF_ID(func, bpf_cast_to_kern_ctx)
10318 BTF_ID(func, bpf_rdonly_cast)
10319 BTF_ID(func, bpf_rcu_read_lock)
10320 BTF_ID(func, bpf_rcu_read_unlock)
10321 BTF_ID(func, bpf_rbtree_remove)
10322 BTF_ID(func, bpf_rbtree_add_impl)
10323 BTF_ID(func, bpf_rbtree_first)
10324 BTF_ID(func, bpf_dynptr_from_skb)
10325 BTF_ID(func, bpf_dynptr_from_xdp)
10326 BTF_ID(func, bpf_dynptr_slice)
10327 BTF_ID(func, bpf_dynptr_slice_rdwr)
10328 BTF_ID(func, bpf_dynptr_clone)
10329
10330 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10331 {
10332         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10333             meta->arg_owning_ref) {
10334                 return false;
10335         }
10336
10337         return meta->kfunc_flags & KF_RET_NULL;
10338 }
10339
10340 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10341 {
10342         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10343 }
10344
10345 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10346 {
10347         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10348 }
10349
10350 static enum kfunc_ptr_arg_type
10351 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10352                        struct bpf_kfunc_call_arg_meta *meta,
10353                        const struct btf_type *t, const struct btf_type *ref_t,
10354                        const char *ref_tname, const struct btf_param *args,
10355                        int argno, int nargs)
10356 {
10357         u32 regno = argno + 1;
10358         struct bpf_reg_state *regs = cur_regs(env);
10359         struct bpf_reg_state *reg = &regs[regno];
10360         bool arg_mem_size = false;
10361
10362         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10363                 return KF_ARG_PTR_TO_CTX;
10364
10365         /* In this function, we verify the kfunc's BTF as per the argument type,
10366          * leaving the rest of the verification with respect to the register
10367          * type to our caller. When a set of conditions hold in the BTF type of
10368          * arguments, we resolve it to a known kfunc_ptr_arg_type.
10369          */
10370         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10371                 return KF_ARG_PTR_TO_CTX;
10372
10373         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10374                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10375
10376         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10377                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10378
10379         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10380                 return KF_ARG_PTR_TO_DYNPTR;
10381
10382         if (is_kfunc_arg_iter(meta, argno))
10383                 return KF_ARG_PTR_TO_ITER;
10384
10385         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10386                 return KF_ARG_PTR_TO_LIST_HEAD;
10387
10388         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10389                 return KF_ARG_PTR_TO_LIST_NODE;
10390
10391         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10392                 return KF_ARG_PTR_TO_RB_ROOT;
10393
10394         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10395                 return KF_ARG_PTR_TO_RB_NODE;
10396
10397         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10398                 if (!btf_type_is_struct(ref_t)) {
10399                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10400                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10401                         return -EINVAL;
10402                 }
10403                 return KF_ARG_PTR_TO_BTF_ID;
10404         }
10405
10406         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10407                 return KF_ARG_PTR_TO_CALLBACK;
10408
10409
10410         if (argno + 1 < nargs &&
10411             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10412              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10413                 arg_mem_size = true;
10414
10415         /* This is the catch all argument type of register types supported by
10416          * check_helper_mem_access. However, we only allow when argument type is
10417          * pointer to scalar, or struct composed (recursively) of scalars. When
10418          * arg_mem_size is true, the pointer can be void *.
10419          */
10420         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10421             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10422                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10423                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10424                 return -EINVAL;
10425         }
10426         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10427 }
10428
10429 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10430                                         struct bpf_reg_state *reg,
10431                                         const struct btf_type *ref_t,
10432                                         const char *ref_tname, u32 ref_id,
10433                                         struct bpf_kfunc_call_arg_meta *meta,
10434                                         int argno)
10435 {
10436         const struct btf_type *reg_ref_t;
10437         bool strict_type_match = false;
10438         const struct btf *reg_btf;
10439         const char *reg_ref_tname;
10440         u32 reg_ref_id;
10441
10442         if (base_type(reg->type) == PTR_TO_BTF_ID) {
10443                 reg_btf = reg->btf;
10444                 reg_ref_id = reg->btf_id;
10445         } else {
10446                 reg_btf = btf_vmlinux;
10447                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10448         }
10449
10450         /* Enforce strict type matching for calls to kfuncs that are acquiring
10451          * or releasing a reference, or are no-cast aliases. We do _not_
10452          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10453          * as we want to enable BPF programs to pass types that are bitwise
10454          * equivalent without forcing them to explicitly cast with something
10455          * like bpf_cast_to_kern_ctx().
10456          *
10457          * For example, say we had a type like the following:
10458          *
10459          * struct bpf_cpumask {
10460          *      cpumask_t cpumask;
10461          *      refcount_t usage;
10462          * };
10463          *
10464          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10465          * to a struct cpumask, so it would be safe to pass a struct
10466          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10467          *
10468          * The philosophy here is similar to how we allow scalars of different
10469          * types to be passed to kfuncs as long as the size is the same. The
10470          * only difference here is that we're simply allowing
10471          * btf_struct_ids_match() to walk the struct at the 0th offset, and
10472          * resolve types.
10473          */
10474         if (is_kfunc_acquire(meta) ||
10475             (is_kfunc_release(meta) && reg->ref_obj_id) ||
10476             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10477                 strict_type_match = true;
10478
10479         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10480
10481         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10482         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10483         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10484                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10485                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10486                         btf_type_str(reg_ref_t), reg_ref_tname);
10487                 return -EINVAL;
10488         }
10489         return 0;
10490 }
10491
10492 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10493 {
10494         struct bpf_verifier_state *state = env->cur_state;
10495         struct btf_record *rec = reg_btf_record(reg);
10496
10497         if (!state->active_lock.ptr) {
10498                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10499                 return -EFAULT;
10500         }
10501
10502         if (type_flag(reg->type) & NON_OWN_REF) {
10503                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10504                 return -EFAULT;
10505         }
10506
10507         reg->type |= NON_OWN_REF;
10508         if (rec->refcount_off >= 0)
10509                 reg->type |= MEM_RCU;
10510
10511         return 0;
10512 }
10513
10514 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10515 {
10516         struct bpf_func_state *state, *unused;
10517         struct bpf_reg_state *reg;
10518         int i;
10519
10520         state = cur_func(env);
10521
10522         if (!ref_obj_id) {
10523                 verbose(env, "verifier internal error: ref_obj_id is zero for "
10524                              "owning -> non-owning conversion\n");
10525                 return -EFAULT;
10526         }
10527
10528         for (i = 0; i < state->acquired_refs; i++) {
10529                 if (state->refs[i].id != ref_obj_id)
10530                         continue;
10531
10532                 /* Clear ref_obj_id here so release_reference doesn't clobber
10533                  * the whole reg
10534                  */
10535                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10536                         if (reg->ref_obj_id == ref_obj_id) {
10537                                 reg->ref_obj_id = 0;
10538                                 ref_set_non_owning(env, reg);
10539                         }
10540                 }));
10541                 return 0;
10542         }
10543
10544         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10545         return -EFAULT;
10546 }
10547
10548 /* Implementation details:
10549  *
10550  * Each register points to some region of memory, which we define as an
10551  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10552  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10553  * allocation. The lock and the data it protects are colocated in the same
10554  * memory region.
10555  *
10556  * Hence, everytime a register holds a pointer value pointing to such
10557  * allocation, the verifier preserves a unique reg->id for it.
10558  *
10559  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10560  * bpf_spin_lock is called.
10561  *
10562  * To enable this, lock state in the verifier captures two values:
10563  *      active_lock.ptr = Register's type specific pointer
10564  *      active_lock.id  = A unique ID for each register pointer value
10565  *
10566  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10567  * supported register types.
10568  *
10569  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10570  * allocated objects is the reg->btf pointer.
10571  *
10572  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10573  * can establish the provenance of the map value statically for each distinct
10574  * lookup into such maps. They always contain a single map value hence unique
10575  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10576  *
10577  * So, in case of global variables, they use array maps with max_entries = 1,
10578  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10579  * into the same map value as max_entries is 1, as described above).
10580  *
10581  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10582  * outer map pointer (in verifier context), but each lookup into an inner map
10583  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10584  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10585  * will get different reg->id assigned to each lookup, hence different
10586  * active_lock.id.
10587  *
10588  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10589  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10590  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10591  */
10592 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10593 {
10594         void *ptr;
10595         u32 id;
10596
10597         switch ((int)reg->type) {
10598         case PTR_TO_MAP_VALUE:
10599                 ptr = reg->map_ptr;
10600                 break;
10601         case PTR_TO_BTF_ID | MEM_ALLOC:
10602                 ptr = reg->btf;
10603                 break;
10604         default:
10605                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10606                 return -EFAULT;
10607         }
10608         id = reg->id;
10609
10610         if (!env->cur_state->active_lock.ptr)
10611                 return -EINVAL;
10612         if (env->cur_state->active_lock.ptr != ptr ||
10613             env->cur_state->active_lock.id != id) {
10614                 verbose(env, "held lock and object are not in the same allocation\n");
10615                 return -EINVAL;
10616         }
10617         return 0;
10618 }
10619
10620 static bool is_bpf_list_api_kfunc(u32 btf_id)
10621 {
10622         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10623                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10624                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10625                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10626 }
10627
10628 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10629 {
10630         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10631                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10632                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10633 }
10634
10635 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10636 {
10637         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10638                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10639 }
10640
10641 static bool is_callback_calling_kfunc(u32 btf_id)
10642 {
10643         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10644 }
10645
10646 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10647 {
10648         return is_bpf_rbtree_api_kfunc(btf_id);
10649 }
10650
10651 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10652                                           enum btf_field_type head_field_type,
10653                                           u32 kfunc_btf_id)
10654 {
10655         bool ret;
10656
10657         switch (head_field_type) {
10658         case BPF_LIST_HEAD:
10659                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10660                 break;
10661         case BPF_RB_ROOT:
10662                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10663                 break;
10664         default:
10665                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10666                         btf_field_type_name(head_field_type));
10667                 return false;
10668         }
10669
10670         if (!ret)
10671                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10672                         btf_field_type_name(head_field_type));
10673         return ret;
10674 }
10675
10676 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10677                                           enum btf_field_type node_field_type,
10678                                           u32 kfunc_btf_id)
10679 {
10680         bool ret;
10681
10682         switch (node_field_type) {
10683         case BPF_LIST_NODE:
10684                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10685                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10686                 break;
10687         case BPF_RB_NODE:
10688                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10689                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10690                 break;
10691         default:
10692                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10693                         btf_field_type_name(node_field_type));
10694                 return false;
10695         }
10696
10697         if (!ret)
10698                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10699                         btf_field_type_name(node_field_type));
10700         return ret;
10701 }
10702
10703 static int
10704 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10705                                    struct bpf_reg_state *reg, u32 regno,
10706                                    struct bpf_kfunc_call_arg_meta *meta,
10707                                    enum btf_field_type head_field_type,
10708                                    struct btf_field **head_field)
10709 {
10710         const char *head_type_name;
10711         struct btf_field *field;
10712         struct btf_record *rec;
10713         u32 head_off;
10714
10715         if (meta->btf != btf_vmlinux) {
10716                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10717                 return -EFAULT;
10718         }
10719
10720         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10721                 return -EFAULT;
10722
10723         head_type_name = btf_field_type_name(head_field_type);
10724         if (!tnum_is_const(reg->var_off)) {
10725                 verbose(env,
10726                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10727                         regno, head_type_name);
10728                 return -EINVAL;
10729         }
10730
10731         rec = reg_btf_record(reg);
10732         head_off = reg->off + reg->var_off.value;
10733         field = btf_record_find(rec, head_off, head_field_type);
10734         if (!field) {
10735                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10736                 return -EINVAL;
10737         }
10738
10739         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10740         if (check_reg_allocation_locked(env, reg)) {
10741                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10742                         rec->spin_lock_off, head_type_name);
10743                 return -EINVAL;
10744         }
10745
10746         if (*head_field) {
10747                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10748                 return -EFAULT;
10749         }
10750         *head_field = field;
10751         return 0;
10752 }
10753
10754 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10755                                            struct bpf_reg_state *reg, u32 regno,
10756                                            struct bpf_kfunc_call_arg_meta *meta)
10757 {
10758         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10759                                                           &meta->arg_list_head.field);
10760 }
10761
10762 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10763                                              struct bpf_reg_state *reg, u32 regno,
10764                                              struct bpf_kfunc_call_arg_meta *meta)
10765 {
10766         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10767                                                           &meta->arg_rbtree_root.field);
10768 }
10769
10770 static int
10771 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10772                                    struct bpf_reg_state *reg, u32 regno,
10773                                    struct bpf_kfunc_call_arg_meta *meta,
10774                                    enum btf_field_type head_field_type,
10775                                    enum btf_field_type node_field_type,
10776                                    struct btf_field **node_field)
10777 {
10778         const char *node_type_name;
10779         const struct btf_type *et, *t;
10780         struct btf_field *field;
10781         u32 node_off;
10782
10783         if (meta->btf != btf_vmlinux) {
10784                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10785                 return -EFAULT;
10786         }
10787
10788         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10789                 return -EFAULT;
10790
10791         node_type_name = btf_field_type_name(node_field_type);
10792         if (!tnum_is_const(reg->var_off)) {
10793                 verbose(env,
10794                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10795                         regno, node_type_name);
10796                 return -EINVAL;
10797         }
10798
10799         node_off = reg->off + reg->var_off.value;
10800         field = reg_find_field_offset(reg, node_off, node_field_type);
10801         if (!field || field->offset != node_off) {
10802                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10803                 return -EINVAL;
10804         }
10805
10806         field = *node_field;
10807
10808         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10809         t = btf_type_by_id(reg->btf, reg->btf_id);
10810         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10811                                   field->graph_root.value_btf_id, true)) {
10812                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10813                         "in struct %s, but arg is at offset=%d in struct %s\n",
10814                         btf_field_type_name(head_field_type),
10815                         btf_field_type_name(node_field_type),
10816                         field->graph_root.node_offset,
10817                         btf_name_by_offset(field->graph_root.btf, et->name_off),
10818                         node_off, btf_name_by_offset(reg->btf, t->name_off));
10819                 return -EINVAL;
10820         }
10821         meta->arg_btf = reg->btf;
10822         meta->arg_btf_id = reg->btf_id;
10823
10824         if (node_off != field->graph_root.node_offset) {
10825                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10826                         node_off, btf_field_type_name(node_field_type),
10827                         field->graph_root.node_offset,
10828                         btf_name_by_offset(field->graph_root.btf, et->name_off));
10829                 return -EINVAL;
10830         }
10831
10832         return 0;
10833 }
10834
10835 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10836                                            struct bpf_reg_state *reg, u32 regno,
10837                                            struct bpf_kfunc_call_arg_meta *meta)
10838 {
10839         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10840                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
10841                                                   &meta->arg_list_head.field);
10842 }
10843
10844 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10845                                              struct bpf_reg_state *reg, u32 regno,
10846                                              struct bpf_kfunc_call_arg_meta *meta)
10847 {
10848         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10849                                                   BPF_RB_ROOT, BPF_RB_NODE,
10850                                                   &meta->arg_rbtree_root.field);
10851 }
10852
10853 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10854                             int insn_idx)
10855 {
10856         const char *func_name = meta->func_name, *ref_tname;
10857         const struct btf *btf = meta->btf;
10858         const struct btf_param *args;
10859         struct btf_record *rec;
10860         u32 i, nargs;
10861         int ret;
10862
10863         args = (const struct btf_param *)(meta->func_proto + 1);
10864         nargs = btf_type_vlen(meta->func_proto);
10865         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10866                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10867                         MAX_BPF_FUNC_REG_ARGS);
10868                 return -EINVAL;
10869         }
10870
10871         /* Check that BTF function arguments match actual types that the
10872          * verifier sees.
10873          */
10874         for (i = 0; i < nargs; i++) {
10875                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10876                 const struct btf_type *t, *ref_t, *resolve_ret;
10877                 enum bpf_arg_type arg_type = ARG_DONTCARE;
10878                 u32 regno = i + 1, ref_id, type_size;
10879                 bool is_ret_buf_sz = false;
10880                 int kf_arg_type;
10881
10882                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10883
10884                 if (is_kfunc_arg_ignore(btf, &args[i]))
10885                         continue;
10886
10887                 if (btf_type_is_scalar(t)) {
10888                         if (reg->type != SCALAR_VALUE) {
10889                                 verbose(env, "R%d is not a scalar\n", regno);
10890                                 return -EINVAL;
10891                         }
10892
10893                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10894                                 if (meta->arg_constant.found) {
10895                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10896                                         return -EFAULT;
10897                                 }
10898                                 if (!tnum_is_const(reg->var_off)) {
10899                                         verbose(env, "R%d must be a known constant\n", regno);
10900                                         return -EINVAL;
10901                                 }
10902                                 ret = mark_chain_precision(env, regno);
10903                                 if (ret < 0)
10904                                         return ret;
10905                                 meta->arg_constant.found = true;
10906                                 meta->arg_constant.value = reg->var_off.value;
10907                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10908                                 meta->r0_rdonly = true;
10909                                 is_ret_buf_sz = true;
10910                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10911                                 is_ret_buf_sz = true;
10912                         }
10913
10914                         if (is_ret_buf_sz) {
10915                                 if (meta->r0_size) {
10916                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10917                                         return -EINVAL;
10918                                 }
10919
10920                                 if (!tnum_is_const(reg->var_off)) {
10921                                         verbose(env, "R%d is not a const\n", regno);
10922                                         return -EINVAL;
10923                                 }
10924
10925                                 meta->r0_size = reg->var_off.value;
10926                                 ret = mark_chain_precision(env, regno);
10927                                 if (ret)
10928                                         return ret;
10929                         }
10930                         continue;
10931                 }
10932
10933                 if (!btf_type_is_ptr(t)) {
10934                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10935                         return -EINVAL;
10936                 }
10937
10938                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10939                     (register_is_null(reg) || type_may_be_null(reg->type))) {
10940                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10941                         return -EACCES;
10942                 }
10943
10944                 if (reg->ref_obj_id) {
10945                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
10946                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10947                                         regno, reg->ref_obj_id,
10948                                         meta->ref_obj_id);
10949                                 return -EFAULT;
10950                         }
10951                         meta->ref_obj_id = reg->ref_obj_id;
10952                         if (is_kfunc_release(meta))
10953                                 meta->release_regno = regno;
10954                 }
10955
10956                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10957                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10958
10959                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10960                 if (kf_arg_type < 0)
10961                         return kf_arg_type;
10962
10963                 switch (kf_arg_type) {
10964                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10965                 case KF_ARG_PTR_TO_BTF_ID:
10966                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10967                                 break;
10968
10969                         if (!is_trusted_reg(reg)) {
10970                                 if (!is_kfunc_rcu(meta)) {
10971                                         verbose(env, "R%d must be referenced or trusted\n", regno);
10972                                         return -EINVAL;
10973                                 }
10974                                 if (!is_rcu_reg(reg)) {
10975                                         verbose(env, "R%d must be a rcu pointer\n", regno);
10976                                         return -EINVAL;
10977                                 }
10978                         }
10979
10980                         fallthrough;
10981                 case KF_ARG_PTR_TO_CTX:
10982                         /* Trusted arguments have the same offset checks as release arguments */
10983                         arg_type |= OBJ_RELEASE;
10984                         break;
10985                 case KF_ARG_PTR_TO_DYNPTR:
10986                 case KF_ARG_PTR_TO_ITER:
10987                 case KF_ARG_PTR_TO_LIST_HEAD:
10988                 case KF_ARG_PTR_TO_LIST_NODE:
10989                 case KF_ARG_PTR_TO_RB_ROOT:
10990                 case KF_ARG_PTR_TO_RB_NODE:
10991                 case KF_ARG_PTR_TO_MEM:
10992                 case KF_ARG_PTR_TO_MEM_SIZE:
10993                 case KF_ARG_PTR_TO_CALLBACK:
10994                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10995                         /* Trusted by default */
10996                         break;
10997                 default:
10998                         WARN_ON_ONCE(1);
10999                         return -EFAULT;
11000                 }
11001
11002                 if (is_kfunc_release(meta) && reg->ref_obj_id)
11003                         arg_type |= OBJ_RELEASE;
11004                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11005                 if (ret < 0)
11006                         return ret;
11007
11008                 switch (kf_arg_type) {
11009                 case KF_ARG_PTR_TO_CTX:
11010                         if (reg->type != PTR_TO_CTX) {
11011                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11012                                 return -EINVAL;
11013                         }
11014
11015                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11016                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11017                                 if (ret < 0)
11018                                         return -EINVAL;
11019                                 meta->ret_btf_id  = ret;
11020                         }
11021                         break;
11022                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11023                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11024                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11025                                 return -EINVAL;
11026                         }
11027                         if (!reg->ref_obj_id) {
11028                                 verbose(env, "allocated object must be referenced\n");
11029                                 return -EINVAL;
11030                         }
11031                         if (meta->btf == btf_vmlinux &&
11032                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11033                                 meta->arg_btf = reg->btf;
11034                                 meta->arg_btf_id = reg->btf_id;
11035                         }
11036                         break;
11037                 case KF_ARG_PTR_TO_DYNPTR:
11038                 {
11039                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11040                         int clone_ref_obj_id = 0;
11041
11042                         if (reg->type != PTR_TO_STACK &&
11043                             reg->type != CONST_PTR_TO_DYNPTR) {
11044                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11045                                 return -EINVAL;
11046                         }
11047
11048                         if (reg->type == CONST_PTR_TO_DYNPTR)
11049                                 dynptr_arg_type |= MEM_RDONLY;
11050
11051                         if (is_kfunc_arg_uninit(btf, &args[i]))
11052                                 dynptr_arg_type |= MEM_UNINIT;
11053
11054                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11055                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11056                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11057                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11058                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11059                                    (dynptr_arg_type & MEM_UNINIT)) {
11060                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11061
11062                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11063                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11064                                         return -EFAULT;
11065                                 }
11066
11067                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11068                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11069                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11070                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11071                                         return -EFAULT;
11072                                 }
11073                         }
11074
11075                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11076                         if (ret < 0)
11077                                 return ret;
11078
11079                         if (!(dynptr_arg_type & MEM_UNINIT)) {
11080                                 int id = dynptr_id(env, reg);
11081
11082                                 if (id < 0) {
11083                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11084                                         return id;
11085                                 }
11086                                 meta->initialized_dynptr.id = id;
11087                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11088                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11089                         }
11090
11091                         break;
11092                 }
11093                 case KF_ARG_PTR_TO_ITER:
11094                         ret = process_iter_arg(env, regno, insn_idx, meta);
11095                         if (ret < 0)
11096                                 return ret;
11097                         break;
11098                 case KF_ARG_PTR_TO_LIST_HEAD:
11099                         if (reg->type != PTR_TO_MAP_VALUE &&
11100                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11101                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11102                                 return -EINVAL;
11103                         }
11104                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11105                                 verbose(env, "allocated object must be referenced\n");
11106                                 return -EINVAL;
11107                         }
11108                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11109                         if (ret < 0)
11110                                 return ret;
11111                         break;
11112                 case KF_ARG_PTR_TO_RB_ROOT:
11113                         if (reg->type != PTR_TO_MAP_VALUE &&
11114                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11115                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11116                                 return -EINVAL;
11117                         }
11118                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11119                                 verbose(env, "allocated object must be referenced\n");
11120                                 return -EINVAL;
11121                         }
11122                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11123                         if (ret < 0)
11124                                 return ret;
11125                         break;
11126                 case KF_ARG_PTR_TO_LIST_NODE:
11127                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11128                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11129                                 return -EINVAL;
11130                         }
11131                         if (!reg->ref_obj_id) {
11132                                 verbose(env, "allocated object must be referenced\n");
11133                                 return -EINVAL;
11134                         }
11135                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11136                         if (ret < 0)
11137                                 return ret;
11138                         break;
11139                 case KF_ARG_PTR_TO_RB_NODE:
11140                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11141                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11142                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
11143                                         return -EINVAL;
11144                                 }
11145                                 if (in_rbtree_lock_required_cb(env)) {
11146                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11147                                         return -EINVAL;
11148                                 }
11149                         } else {
11150                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11151                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
11152                                         return -EINVAL;
11153                                 }
11154                                 if (!reg->ref_obj_id) {
11155                                         verbose(env, "allocated object must be referenced\n");
11156                                         return -EINVAL;
11157                                 }
11158                         }
11159
11160                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11161                         if (ret < 0)
11162                                 return ret;
11163                         break;
11164                 case KF_ARG_PTR_TO_BTF_ID:
11165                         /* Only base_type is checked, further checks are done here */
11166                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11167                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11168                             !reg2btf_ids[base_type(reg->type)]) {
11169                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11170                                 verbose(env, "expected %s or socket\n",
11171                                         reg_type_str(env, base_type(reg->type) |
11172                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11173                                 return -EINVAL;
11174                         }
11175                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11176                         if (ret < 0)
11177                                 return ret;
11178                         break;
11179                 case KF_ARG_PTR_TO_MEM:
11180                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11181                         if (IS_ERR(resolve_ret)) {
11182                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11183                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11184                                 return -EINVAL;
11185                         }
11186                         ret = check_mem_reg(env, reg, regno, type_size);
11187                         if (ret < 0)
11188                                 return ret;
11189                         break;
11190                 case KF_ARG_PTR_TO_MEM_SIZE:
11191                 {
11192                         struct bpf_reg_state *buff_reg = &regs[regno];
11193                         const struct btf_param *buff_arg = &args[i];
11194                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11195                         const struct btf_param *size_arg = &args[i + 1];
11196
11197                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11198                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11199                                 if (ret < 0) {
11200                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11201                                         return ret;
11202                                 }
11203                         }
11204
11205                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11206                                 if (meta->arg_constant.found) {
11207                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11208                                         return -EFAULT;
11209                                 }
11210                                 if (!tnum_is_const(size_reg->var_off)) {
11211                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11212                                         return -EINVAL;
11213                                 }
11214                                 meta->arg_constant.found = true;
11215                                 meta->arg_constant.value = size_reg->var_off.value;
11216                         }
11217
11218                         /* Skip next '__sz' or '__szk' argument */
11219                         i++;
11220                         break;
11221                 }
11222                 case KF_ARG_PTR_TO_CALLBACK:
11223                         if (reg->type != PTR_TO_FUNC) {
11224                                 verbose(env, "arg%d expected pointer to func\n", i);
11225                                 return -EINVAL;
11226                         }
11227                         meta->subprogno = reg->subprogno;
11228                         break;
11229                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11230                         if (!type_is_ptr_alloc_obj(reg->type)) {
11231                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11232                                 return -EINVAL;
11233                         }
11234                         if (!type_is_non_owning_ref(reg->type))
11235                                 meta->arg_owning_ref = true;
11236
11237                         rec = reg_btf_record(reg);
11238                         if (!rec) {
11239                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11240                                 return -EFAULT;
11241                         }
11242
11243                         if (rec->refcount_off < 0) {
11244                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11245                                 return -EINVAL;
11246                         }
11247
11248                         meta->arg_btf = reg->btf;
11249                         meta->arg_btf_id = reg->btf_id;
11250                         break;
11251                 }
11252         }
11253
11254         if (is_kfunc_release(meta) && !meta->release_regno) {
11255                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11256                         func_name);
11257                 return -EINVAL;
11258         }
11259
11260         return 0;
11261 }
11262
11263 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11264                             struct bpf_insn *insn,
11265                             struct bpf_kfunc_call_arg_meta *meta,
11266                             const char **kfunc_name)
11267 {
11268         const struct btf_type *func, *func_proto;
11269         u32 func_id, *kfunc_flags;
11270         const char *func_name;
11271         struct btf *desc_btf;
11272
11273         if (kfunc_name)
11274                 *kfunc_name = NULL;
11275
11276         if (!insn->imm)
11277                 return -EINVAL;
11278
11279         desc_btf = find_kfunc_desc_btf(env, insn->off);
11280         if (IS_ERR(desc_btf))
11281                 return PTR_ERR(desc_btf);
11282
11283         func_id = insn->imm;
11284         func = btf_type_by_id(desc_btf, func_id);
11285         func_name = btf_name_by_offset(desc_btf, func->name_off);
11286         if (kfunc_name)
11287                 *kfunc_name = func_name;
11288         func_proto = btf_type_by_id(desc_btf, func->type);
11289
11290         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11291         if (!kfunc_flags) {
11292                 return -EACCES;
11293         }
11294
11295         memset(meta, 0, sizeof(*meta));
11296         meta->btf = desc_btf;
11297         meta->func_id = func_id;
11298         meta->kfunc_flags = *kfunc_flags;
11299         meta->func_proto = func_proto;
11300         meta->func_name = func_name;
11301
11302         return 0;
11303 }
11304
11305 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11306                             int *insn_idx_p)
11307 {
11308         const struct btf_type *t, *ptr_type;
11309         u32 i, nargs, ptr_type_id, release_ref_obj_id;
11310         struct bpf_reg_state *regs = cur_regs(env);
11311         const char *func_name, *ptr_type_name;
11312         bool sleepable, rcu_lock, rcu_unlock;
11313         struct bpf_kfunc_call_arg_meta meta;
11314         struct bpf_insn_aux_data *insn_aux;
11315         int err, insn_idx = *insn_idx_p;
11316         const struct btf_param *args;
11317         const struct btf_type *ret_t;
11318         struct btf *desc_btf;
11319
11320         /* skip for now, but return error when we find this in fixup_kfunc_call */
11321         if (!insn->imm)
11322                 return 0;
11323
11324         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11325         if (err == -EACCES && func_name)
11326                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11327         if (err)
11328                 return err;
11329         desc_btf = meta.btf;
11330         insn_aux = &env->insn_aux_data[insn_idx];
11331
11332         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11333
11334         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11335                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11336                 return -EACCES;
11337         }
11338
11339         sleepable = is_kfunc_sleepable(&meta);
11340         if (sleepable && !env->prog->aux->sleepable) {
11341                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11342                 return -EACCES;
11343         }
11344
11345         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11346         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11347
11348         if (env->cur_state->active_rcu_lock) {
11349                 struct bpf_func_state *state;
11350                 struct bpf_reg_state *reg;
11351
11352                 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11353                         verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11354                         return -EACCES;
11355                 }
11356
11357                 if (rcu_lock) {
11358                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11359                         return -EINVAL;
11360                 } else if (rcu_unlock) {
11361                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11362                                 if (reg->type & MEM_RCU) {
11363                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11364                                         reg->type |= PTR_UNTRUSTED;
11365                                 }
11366                         }));
11367                         env->cur_state->active_rcu_lock = false;
11368                 } else if (sleepable) {
11369                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11370                         return -EACCES;
11371                 }
11372         } else if (rcu_lock) {
11373                 env->cur_state->active_rcu_lock = true;
11374         } else if (rcu_unlock) {
11375                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11376                 return -EINVAL;
11377         }
11378
11379         /* Check the arguments */
11380         err = check_kfunc_args(env, &meta, insn_idx);
11381         if (err < 0)
11382                 return err;
11383         /* In case of release function, we get register number of refcounted
11384          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11385          */
11386         if (meta.release_regno) {
11387                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11388                 if (err) {
11389                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11390                                 func_name, meta.func_id);
11391                         return err;
11392                 }
11393         }
11394
11395         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11396             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11397             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11398                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11399                 insn_aux->insert_off = regs[BPF_REG_2].off;
11400                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11401                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11402                 if (err) {
11403                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11404                                 func_name, meta.func_id);
11405                         return err;
11406                 }
11407
11408                 err = release_reference(env, release_ref_obj_id);
11409                 if (err) {
11410                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11411                                 func_name, meta.func_id);
11412                         return err;
11413                 }
11414         }
11415
11416         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11417                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11418                                         set_rbtree_add_callback_state);
11419                 if (err) {
11420                         verbose(env, "kfunc %s#%d failed callback verification\n",
11421                                 func_name, meta.func_id);
11422                         return err;
11423                 }
11424         }
11425
11426         for (i = 0; i < CALLER_SAVED_REGS; i++)
11427                 mark_reg_not_init(env, regs, caller_saved[i]);
11428
11429         /* Check return type */
11430         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11431
11432         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11433                 /* Only exception is bpf_obj_new_impl */
11434                 if (meta.btf != btf_vmlinux ||
11435                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11436                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11437                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11438                         return -EINVAL;
11439                 }
11440         }
11441
11442         if (btf_type_is_scalar(t)) {
11443                 mark_reg_unknown(env, regs, BPF_REG_0);
11444                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11445         } else if (btf_type_is_ptr(t)) {
11446                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11447
11448                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11449                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11450                                 struct btf *ret_btf;
11451                                 u32 ret_btf_id;
11452
11453                                 if (unlikely(!bpf_global_ma_set))
11454                                         return -ENOMEM;
11455
11456                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11457                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11458                                         return -EINVAL;
11459                                 }
11460
11461                                 ret_btf = env->prog->aux->btf;
11462                                 ret_btf_id = meta.arg_constant.value;
11463
11464                                 /* This may be NULL due to user not supplying a BTF */
11465                                 if (!ret_btf) {
11466                                         verbose(env, "bpf_obj_new requires prog BTF\n");
11467                                         return -EINVAL;
11468                                 }
11469
11470                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11471                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11472                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11473                                         return -EINVAL;
11474                                 }
11475
11476                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11477                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11478                                 regs[BPF_REG_0].btf = ret_btf;
11479                                 regs[BPF_REG_0].btf_id = ret_btf_id;
11480
11481                                 insn_aux->obj_new_size = ret_t->size;
11482                                 insn_aux->kptr_struct_meta =
11483                                         btf_find_struct_meta(ret_btf, ret_btf_id);
11484                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11485                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11486                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11487                                 regs[BPF_REG_0].btf = meta.arg_btf;
11488                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11489
11490                                 insn_aux->kptr_struct_meta =
11491                                         btf_find_struct_meta(meta.arg_btf,
11492                                                              meta.arg_btf_id);
11493                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11494                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11495                                 struct btf_field *field = meta.arg_list_head.field;
11496
11497                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11498                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11499                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11500                                 struct btf_field *field = meta.arg_rbtree_root.field;
11501
11502                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11503                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11504                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11505                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11506                                 regs[BPF_REG_0].btf = desc_btf;
11507                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11508                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11509                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11510                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
11511                                         verbose(env,
11512                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11513                                         return -EINVAL;
11514                                 }
11515
11516                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11517                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11518                                 regs[BPF_REG_0].btf = desc_btf;
11519                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11520                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11521                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11522                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11523
11524                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11525
11526                                 if (!meta.arg_constant.found) {
11527                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11528                                         return -EFAULT;
11529                                 }
11530
11531                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11532
11533                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11534                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11535
11536                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11537                                         regs[BPF_REG_0].type |= MEM_RDONLY;
11538                                 } else {
11539                                         /* this will set env->seen_direct_write to true */
11540                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11541                                                 verbose(env, "the prog does not allow writes to packet data\n");
11542                                                 return -EINVAL;
11543                                         }
11544                                 }
11545
11546                                 if (!meta.initialized_dynptr.id) {
11547                                         verbose(env, "verifier internal error: no dynptr id\n");
11548                                         return -EFAULT;
11549                                 }
11550                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11551
11552                                 /* we don't need to set BPF_REG_0's ref obj id
11553                                  * because packet slices are not refcounted (see
11554                                  * dynptr_type_refcounted)
11555                                  */
11556                         } else {
11557                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
11558                                         meta.func_name);
11559                                 return -EFAULT;
11560                         }
11561                 } else if (!__btf_type_is_struct(ptr_type)) {
11562                         if (!meta.r0_size) {
11563                                 __u32 sz;
11564
11565                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11566                                         meta.r0_size = sz;
11567                                         meta.r0_rdonly = true;
11568                                 }
11569                         }
11570                         if (!meta.r0_size) {
11571                                 ptr_type_name = btf_name_by_offset(desc_btf,
11572                                                                    ptr_type->name_off);
11573                                 verbose(env,
11574                                         "kernel function %s returns pointer type %s %s is not supported\n",
11575                                         func_name,
11576                                         btf_type_str(ptr_type),
11577                                         ptr_type_name);
11578                                 return -EINVAL;
11579                         }
11580
11581                         mark_reg_known_zero(env, regs, BPF_REG_0);
11582                         regs[BPF_REG_0].type = PTR_TO_MEM;
11583                         regs[BPF_REG_0].mem_size = meta.r0_size;
11584
11585                         if (meta.r0_rdonly)
11586                                 regs[BPF_REG_0].type |= MEM_RDONLY;
11587
11588                         /* Ensures we don't access the memory after a release_reference() */
11589                         if (meta.ref_obj_id)
11590                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11591                 } else {
11592                         mark_reg_known_zero(env, regs, BPF_REG_0);
11593                         regs[BPF_REG_0].btf = desc_btf;
11594                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11595                         regs[BPF_REG_0].btf_id = ptr_type_id;
11596                 }
11597
11598                 if (is_kfunc_ret_null(&meta)) {
11599                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11600                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11601                         regs[BPF_REG_0].id = ++env->id_gen;
11602                 }
11603                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11604                 if (is_kfunc_acquire(&meta)) {
11605                         int id = acquire_reference_state(env, insn_idx);
11606
11607                         if (id < 0)
11608                                 return id;
11609                         if (is_kfunc_ret_null(&meta))
11610                                 regs[BPF_REG_0].id = id;
11611                         regs[BPF_REG_0].ref_obj_id = id;
11612                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11613                         ref_set_non_owning(env, &regs[BPF_REG_0]);
11614                 }
11615
11616                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11617                         regs[BPF_REG_0].id = ++env->id_gen;
11618         } else if (btf_type_is_void(t)) {
11619                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11620                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11621                                 insn_aux->kptr_struct_meta =
11622                                         btf_find_struct_meta(meta.arg_btf,
11623                                                              meta.arg_btf_id);
11624                         }
11625                 }
11626         }
11627
11628         nargs = btf_type_vlen(meta.func_proto);
11629         args = (const struct btf_param *)(meta.func_proto + 1);
11630         for (i = 0; i < nargs; i++) {
11631                 u32 regno = i + 1;
11632
11633                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11634                 if (btf_type_is_ptr(t))
11635                         mark_btf_func_reg_size(env, regno, sizeof(void *));
11636                 else
11637                         /* scalar. ensured by btf_check_kfunc_arg_match() */
11638                         mark_btf_func_reg_size(env, regno, t->size);
11639         }
11640
11641         if (is_iter_next_kfunc(&meta)) {
11642                 err = process_iter_next_call(env, insn_idx, &meta);
11643                 if (err)
11644                         return err;
11645         }
11646
11647         return 0;
11648 }
11649
11650 static bool signed_add_overflows(s64 a, s64 b)
11651 {
11652         /* Do the add in u64, where overflow is well-defined */
11653         s64 res = (s64)((u64)a + (u64)b);
11654
11655         if (b < 0)
11656                 return res > a;
11657         return res < a;
11658 }
11659
11660 static bool signed_add32_overflows(s32 a, s32 b)
11661 {
11662         /* Do the add in u32, where overflow is well-defined */
11663         s32 res = (s32)((u32)a + (u32)b);
11664
11665         if (b < 0)
11666                 return res > a;
11667         return res < a;
11668 }
11669
11670 static bool signed_sub_overflows(s64 a, s64 b)
11671 {
11672         /* Do the sub in u64, where overflow is well-defined */
11673         s64 res = (s64)((u64)a - (u64)b);
11674
11675         if (b < 0)
11676                 return res < a;
11677         return res > a;
11678 }
11679
11680 static bool signed_sub32_overflows(s32 a, s32 b)
11681 {
11682         /* Do the sub in u32, where overflow is well-defined */
11683         s32 res = (s32)((u32)a - (u32)b);
11684
11685         if (b < 0)
11686                 return res < a;
11687         return res > a;
11688 }
11689
11690 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11691                                   const struct bpf_reg_state *reg,
11692                                   enum bpf_reg_type type)
11693 {
11694         bool known = tnum_is_const(reg->var_off);
11695         s64 val = reg->var_off.value;
11696         s64 smin = reg->smin_value;
11697
11698         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11699                 verbose(env, "math between %s pointer and %lld is not allowed\n",
11700                         reg_type_str(env, type), val);
11701                 return false;
11702         }
11703
11704         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11705                 verbose(env, "%s pointer offset %d is not allowed\n",
11706                         reg_type_str(env, type), reg->off);
11707                 return false;
11708         }
11709
11710         if (smin == S64_MIN) {
11711                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11712                         reg_type_str(env, type));
11713                 return false;
11714         }
11715
11716         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11717                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11718                         smin, reg_type_str(env, type));
11719                 return false;
11720         }
11721
11722         return true;
11723 }
11724
11725 enum {
11726         REASON_BOUNDS   = -1,
11727         REASON_TYPE     = -2,
11728         REASON_PATHS    = -3,
11729         REASON_LIMIT    = -4,
11730         REASON_STACK    = -5,
11731 };
11732
11733 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11734                               u32 *alu_limit, bool mask_to_left)
11735 {
11736         u32 max = 0, ptr_limit = 0;
11737
11738         switch (ptr_reg->type) {
11739         case PTR_TO_STACK:
11740                 /* Offset 0 is out-of-bounds, but acceptable start for the
11741                  * left direction, see BPF_REG_FP. Also, unknown scalar
11742                  * offset where we would need to deal with min/max bounds is
11743                  * currently prohibited for unprivileged.
11744                  */
11745                 max = MAX_BPF_STACK + mask_to_left;
11746                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11747                 break;
11748         case PTR_TO_MAP_VALUE:
11749                 max = ptr_reg->map_ptr->value_size;
11750                 ptr_limit = (mask_to_left ?
11751                              ptr_reg->smin_value :
11752                              ptr_reg->umax_value) + ptr_reg->off;
11753                 break;
11754         default:
11755                 return REASON_TYPE;
11756         }
11757
11758         if (ptr_limit >= max)
11759                 return REASON_LIMIT;
11760         *alu_limit = ptr_limit;
11761         return 0;
11762 }
11763
11764 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11765                                     const struct bpf_insn *insn)
11766 {
11767         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11768 }
11769
11770 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11771                                        u32 alu_state, u32 alu_limit)
11772 {
11773         /* If we arrived here from different branches with different
11774          * state or limits to sanitize, then this won't work.
11775          */
11776         if (aux->alu_state &&
11777             (aux->alu_state != alu_state ||
11778              aux->alu_limit != alu_limit))
11779                 return REASON_PATHS;
11780
11781         /* Corresponding fixup done in do_misc_fixups(). */
11782         aux->alu_state = alu_state;
11783         aux->alu_limit = alu_limit;
11784         return 0;
11785 }
11786
11787 static int sanitize_val_alu(struct bpf_verifier_env *env,
11788                             struct bpf_insn *insn)
11789 {
11790         struct bpf_insn_aux_data *aux = cur_aux(env);
11791
11792         if (can_skip_alu_sanitation(env, insn))
11793                 return 0;
11794
11795         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11796 }
11797
11798 static bool sanitize_needed(u8 opcode)
11799 {
11800         return opcode == BPF_ADD || opcode == BPF_SUB;
11801 }
11802
11803 struct bpf_sanitize_info {
11804         struct bpf_insn_aux_data aux;
11805         bool mask_to_left;
11806 };
11807
11808 static struct bpf_verifier_state *
11809 sanitize_speculative_path(struct bpf_verifier_env *env,
11810                           const struct bpf_insn *insn,
11811                           u32 next_idx, u32 curr_idx)
11812 {
11813         struct bpf_verifier_state *branch;
11814         struct bpf_reg_state *regs;
11815
11816         branch = push_stack(env, next_idx, curr_idx, true);
11817         if (branch && insn) {
11818                 regs = branch->frame[branch->curframe]->regs;
11819                 if (BPF_SRC(insn->code) == BPF_K) {
11820                         mark_reg_unknown(env, regs, insn->dst_reg);
11821                 } else if (BPF_SRC(insn->code) == BPF_X) {
11822                         mark_reg_unknown(env, regs, insn->dst_reg);
11823                         mark_reg_unknown(env, regs, insn->src_reg);
11824                 }
11825         }
11826         return branch;
11827 }
11828
11829 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11830                             struct bpf_insn *insn,
11831                             const struct bpf_reg_state *ptr_reg,
11832                             const struct bpf_reg_state *off_reg,
11833                             struct bpf_reg_state *dst_reg,
11834                             struct bpf_sanitize_info *info,
11835                             const bool commit_window)
11836 {
11837         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11838         struct bpf_verifier_state *vstate = env->cur_state;
11839         bool off_is_imm = tnum_is_const(off_reg->var_off);
11840         bool off_is_neg = off_reg->smin_value < 0;
11841         bool ptr_is_dst_reg = ptr_reg == dst_reg;
11842         u8 opcode = BPF_OP(insn->code);
11843         u32 alu_state, alu_limit;
11844         struct bpf_reg_state tmp;
11845         bool ret;
11846         int err;
11847
11848         if (can_skip_alu_sanitation(env, insn))
11849                 return 0;
11850
11851         /* We already marked aux for masking from non-speculative
11852          * paths, thus we got here in the first place. We only care
11853          * to explore bad access from here.
11854          */
11855         if (vstate->speculative)
11856                 goto do_sim;
11857
11858         if (!commit_window) {
11859                 if (!tnum_is_const(off_reg->var_off) &&
11860                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11861                         return REASON_BOUNDS;
11862
11863                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11864                                      (opcode == BPF_SUB && !off_is_neg);
11865         }
11866
11867         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11868         if (err < 0)
11869                 return err;
11870
11871         if (commit_window) {
11872                 /* In commit phase we narrow the masking window based on
11873                  * the observed pointer move after the simulated operation.
11874                  */
11875                 alu_state = info->aux.alu_state;
11876                 alu_limit = abs(info->aux.alu_limit - alu_limit);
11877         } else {
11878                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11879                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11880                 alu_state |= ptr_is_dst_reg ?
11881                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11882
11883                 /* Limit pruning on unknown scalars to enable deep search for
11884                  * potential masking differences from other program paths.
11885                  */
11886                 if (!off_is_imm)
11887                         env->explore_alu_limits = true;
11888         }
11889
11890         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11891         if (err < 0)
11892                 return err;
11893 do_sim:
11894         /* If we're in commit phase, we're done here given we already
11895          * pushed the truncated dst_reg into the speculative verification
11896          * stack.
11897          *
11898          * Also, when register is a known constant, we rewrite register-based
11899          * operation to immediate-based, and thus do not need masking (and as
11900          * a consequence, do not need to simulate the zero-truncation either).
11901          */
11902         if (commit_window || off_is_imm)
11903                 return 0;
11904
11905         /* Simulate and find potential out-of-bounds access under
11906          * speculative execution from truncation as a result of
11907          * masking when off was not within expected range. If off
11908          * sits in dst, then we temporarily need to move ptr there
11909          * to simulate dst (== 0) +/-= ptr. Needed, for example,
11910          * for cases where we use K-based arithmetic in one direction
11911          * and truncated reg-based in the other in order to explore
11912          * bad access.
11913          */
11914         if (!ptr_is_dst_reg) {
11915                 tmp = *dst_reg;
11916                 copy_register_state(dst_reg, ptr_reg);
11917         }
11918         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11919                                         env->insn_idx);
11920         if (!ptr_is_dst_reg && ret)
11921                 *dst_reg = tmp;
11922         return !ret ? REASON_STACK : 0;
11923 }
11924
11925 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11926 {
11927         struct bpf_verifier_state *vstate = env->cur_state;
11928
11929         /* If we simulate paths under speculation, we don't update the
11930          * insn as 'seen' such that when we verify unreachable paths in
11931          * the non-speculative domain, sanitize_dead_code() can still
11932          * rewrite/sanitize them.
11933          */
11934         if (!vstate->speculative)
11935                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11936 }
11937
11938 static int sanitize_err(struct bpf_verifier_env *env,
11939                         const struct bpf_insn *insn, int reason,
11940                         const struct bpf_reg_state *off_reg,
11941                         const struct bpf_reg_state *dst_reg)
11942 {
11943         static const char *err = "pointer arithmetic with it prohibited for !root";
11944         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11945         u32 dst = insn->dst_reg, src = insn->src_reg;
11946
11947         switch (reason) {
11948         case REASON_BOUNDS:
11949                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11950                         off_reg == dst_reg ? dst : src, err);
11951                 break;
11952         case REASON_TYPE:
11953                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11954                         off_reg == dst_reg ? src : dst, err);
11955                 break;
11956         case REASON_PATHS:
11957                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11958                         dst, op, err);
11959                 break;
11960         case REASON_LIMIT:
11961                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11962                         dst, op, err);
11963                 break;
11964         case REASON_STACK:
11965                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11966                         dst, err);
11967                 break;
11968         default:
11969                 verbose(env, "verifier internal error: unknown reason (%d)\n",
11970                         reason);
11971                 break;
11972         }
11973
11974         return -EACCES;
11975 }
11976
11977 /* check that stack access falls within stack limits and that 'reg' doesn't
11978  * have a variable offset.
11979  *
11980  * Variable offset is prohibited for unprivileged mode for simplicity since it
11981  * requires corresponding support in Spectre masking for stack ALU.  See also
11982  * retrieve_ptr_limit().
11983  *
11984  *
11985  * 'off' includes 'reg->off'.
11986  */
11987 static int check_stack_access_for_ptr_arithmetic(
11988                                 struct bpf_verifier_env *env,
11989                                 int regno,
11990                                 const struct bpf_reg_state *reg,
11991                                 int off)
11992 {
11993         if (!tnum_is_const(reg->var_off)) {
11994                 char tn_buf[48];
11995
11996                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11997                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11998                         regno, tn_buf, off);
11999                 return -EACCES;
12000         }
12001
12002         if (off >= 0 || off < -MAX_BPF_STACK) {
12003                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12004                         "prohibited for !root; off=%d\n", regno, off);
12005                 return -EACCES;
12006         }
12007
12008         return 0;
12009 }
12010
12011 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12012                                  const struct bpf_insn *insn,
12013                                  const struct bpf_reg_state *dst_reg)
12014 {
12015         u32 dst = insn->dst_reg;
12016
12017         /* For unprivileged we require that resulting offset must be in bounds
12018          * in order to be able to sanitize access later on.
12019          */
12020         if (env->bypass_spec_v1)
12021                 return 0;
12022
12023         switch (dst_reg->type) {
12024         case PTR_TO_STACK:
12025                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12026                                         dst_reg->off + dst_reg->var_off.value))
12027                         return -EACCES;
12028                 break;
12029         case PTR_TO_MAP_VALUE:
12030                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12031                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12032                                 "prohibited for !root\n", dst);
12033                         return -EACCES;
12034                 }
12035                 break;
12036         default:
12037                 break;
12038         }
12039
12040         return 0;
12041 }
12042
12043 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12044  * Caller should also handle BPF_MOV case separately.
12045  * If we return -EACCES, caller may want to try again treating pointer as a
12046  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12047  */
12048 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12049                                    struct bpf_insn *insn,
12050                                    const struct bpf_reg_state *ptr_reg,
12051                                    const struct bpf_reg_state *off_reg)
12052 {
12053         struct bpf_verifier_state *vstate = env->cur_state;
12054         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12055         struct bpf_reg_state *regs = state->regs, *dst_reg;
12056         bool known = tnum_is_const(off_reg->var_off);
12057         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12058             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12059         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12060             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12061         struct bpf_sanitize_info info = {};
12062         u8 opcode = BPF_OP(insn->code);
12063         u32 dst = insn->dst_reg;
12064         int ret;
12065
12066         dst_reg = &regs[dst];
12067
12068         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12069             smin_val > smax_val || umin_val > umax_val) {
12070                 /* Taint dst register if offset had invalid bounds derived from
12071                  * e.g. dead branches.
12072                  */
12073                 __mark_reg_unknown(env, dst_reg);
12074                 return 0;
12075         }
12076
12077         if (BPF_CLASS(insn->code) != BPF_ALU64) {
12078                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12079                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12080                         __mark_reg_unknown(env, dst_reg);
12081                         return 0;
12082                 }
12083
12084                 verbose(env,
12085                         "R%d 32-bit pointer arithmetic prohibited\n",
12086                         dst);
12087                 return -EACCES;
12088         }
12089
12090         if (ptr_reg->type & PTR_MAYBE_NULL) {
12091                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12092                         dst, reg_type_str(env, ptr_reg->type));
12093                 return -EACCES;
12094         }
12095
12096         switch (base_type(ptr_reg->type)) {
12097         case CONST_PTR_TO_MAP:
12098                 /* smin_val represents the known value */
12099                 if (known && smin_val == 0 && opcode == BPF_ADD)
12100                         break;
12101                 fallthrough;
12102         case PTR_TO_PACKET_END:
12103         case PTR_TO_SOCKET:
12104         case PTR_TO_SOCK_COMMON:
12105         case PTR_TO_TCP_SOCK:
12106         case PTR_TO_XDP_SOCK:
12107                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12108                         dst, reg_type_str(env, ptr_reg->type));
12109                 return -EACCES;
12110         default:
12111                 break;
12112         }
12113
12114         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12115          * The id may be overwritten later if we create a new variable offset.
12116          */
12117         dst_reg->type = ptr_reg->type;
12118         dst_reg->id = ptr_reg->id;
12119
12120         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12121             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12122                 return -EINVAL;
12123
12124         /* pointer types do not carry 32-bit bounds at the moment. */
12125         __mark_reg32_unbounded(dst_reg);
12126
12127         if (sanitize_needed(opcode)) {
12128                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12129                                        &info, false);
12130                 if (ret < 0)
12131                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12132         }
12133
12134         switch (opcode) {
12135         case BPF_ADD:
12136                 /* We can take a fixed offset as long as it doesn't overflow
12137                  * the s32 'off' field
12138                  */
12139                 if (known && (ptr_reg->off + smin_val ==
12140                               (s64)(s32)(ptr_reg->off + smin_val))) {
12141                         /* pointer += K.  Accumulate it into fixed offset */
12142                         dst_reg->smin_value = smin_ptr;
12143                         dst_reg->smax_value = smax_ptr;
12144                         dst_reg->umin_value = umin_ptr;
12145                         dst_reg->umax_value = umax_ptr;
12146                         dst_reg->var_off = ptr_reg->var_off;
12147                         dst_reg->off = ptr_reg->off + smin_val;
12148                         dst_reg->raw = ptr_reg->raw;
12149                         break;
12150                 }
12151                 /* A new variable offset is created.  Note that off_reg->off
12152                  * == 0, since it's a scalar.
12153                  * dst_reg gets the pointer type and since some positive
12154                  * integer value was added to the pointer, give it a new 'id'
12155                  * if it's a PTR_TO_PACKET.
12156                  * this creates a new 'base' pointer, off_reg (variable) gets
12157                  * added into the variable offset, and we copy the fixed offset
12158                  * from ptr_reg.
12159                  */
12160                 if (signed_add_overflows(smin_ptr, smin_val) ||
12161                     signed_add_overflows(smax_ptr, smax_val)) {
12162                         dst_reg->smin_value = S64_MIN;
12163                         dst_reg->smax_value = S64_MAX;
12164                 } else {
12165                         dst_reg->smin_value = smin_ptr + smin_val;
12166                         dst_reg->smax_value = smax_ptr + smax_val;
12167                 }
12168                 if (umin_ptr + umin_val < umin_ptr ||
12169                     umax_ptr + umax_val < umax_ptr) {
12170                         dst_reg->umin_value = 0;
12171                         dst_reg->umax_value = U64_MAX;
12172                 } else {
12173                         dst_reg->umin_value = umin_ptr + umin_val;
12174                         dst_reg->umax_value = umax_ptr + umax_val;
12175                 }
12176                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12177                 dst_reg->off = ptr_reg->off;
12178                 dst_reg->raw = ptr_reg->raw;
12179                 if (reg_is_pkt_pointer(ptr_reg)) {
12180                         dst_reg->id = ++env->id_gen;
12181                         /* something was added to pkt_ptr, set range to zero */
12182                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12183                 }
12184                 break;
12185         case BPF_SUB:
12186                 if (dst_reg == off_reg) {
12187                         /* scalar -= pointer.  Creates an unknown scalar */
12188                         verbose(env, "R%d tried to subtract pointer from scalar\n",
12189                                 dst);
12190                         return -EACCES;
12191                 }
12192                 /* We don't allow subtraction from FP, because (according to
12193                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12194                  * be able to deal with it.
12195                  */
12196                 if (ptr_reg->type == PTR_TO_STACK) {
12197                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12198                                 dst);
12199                         return -EACCES;
12200                 }
12201                 if (known && (ptr_reg->off - smin_val ==
12202                               (s64)(s32)(ptr_reg->off - smin_val))) {
12203                         /* pointer -= K.  Subtract it from fixed offset */
12204                         dst_reg->smin_value = smin_ptr;
12205                         dst_reg->smax_value = smax_ptr;
12206                         dst_reg->umin_value = umin_ptr;
12207                         dst_reg->umax_value = umax_ptr;
12208                         dst_reg->var_off = ptr_reg->var_off;
12209                         dst_reg->id = ptr_reg->id;
12210                         dst_reg->off = ptr_reg->off - smin_val;
12211                         dst_reg->raw = ptr_reg->raw;
12212                         break;
12213                 }
12214                 /* A new variable offset is created.  If the subtrahend is known
12215                  * nonnegative, then any reg->range we had before is still good.
12216                  */
12217                 if (signed_sub_overflows(smin_ptr, smax_val) ||
12218                     signed_sub_overflows(smax_ptr, smin_val)) {
12219                         /* Overflow possible, we know nothing */
12220                         dst_reg->smin_value = S64_MIN;
12221                         dst_reg->smax_value = S64_MAX;
12222                 } else {
12223                         dst_reg->smin_value = smin_ptr - smax_val;
12224                         dst_reg->smax_value = smax_ptr - smin_val;
12225                 }
12226                 if (umin_ptr < umax_val) {
12227                         /* Overflow possible, we know nothing */
12228                         dst_reg->umin_value = 0;
12229                         dst_reg->umax_value = U64_MAX;
12230                 } else {
12231                         /* Cannot overflow (as long as bounds are consistent) */
12232                         dst_reg->umin_value = umin_ptr - umax_val;
12233                         dst_reg->umax_value = umax_ptr - umin_val;
12234                 }
12235                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12236                 dst_reg->off = ptr_reg->off;
12237                 dst_reg->raw = ptr_reg->raw;
12238                 if (reg_is_pkt_pointer(ptr_reg)) {
12239                         dst_reg->id = ++env->id_gen;
12240                         /* something was added to pkt_ptr, set range to zero */
12241                         if (smin_val < 0)
12242                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12243                 }
12244                 break;
12245         case BPF_AND:
12246         case BPF_OR:
12247         case BPF_XOR:
12248                 /* bitwise ops on pointers are troublesome, prohibit. */
12249                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12250                         dst, bpf_alu_string[opcode >> 4]);
12251                 return -EACCES;
12252         default:
12253                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12254                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12255                         dst, bpf_alu_string[opcode >> 4]);
12256                 return -EACCES;
12257         }
12258
12259         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12260                 return -EINVAL;
12261         reg_bounds_sync(dst_reg);
12262         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12263                 return -EACCES;
12264         if (sanitize_needed(opcode)) {
12265                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12266                                        &info, true);
12267                 if (ret < 0)
12268                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12269         }
12270
12271         return 0;
12272 }
12273
12274 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12275                                  struct bpf_reg_state *src_reg)
12276 {
12277         s32 smin_val = src_reg->s32_min_value;
12278         s32 smax_val = src_reg->s32_max_value;
12279         u32 umin_val = src_reg->u32_min_value;
12280         u32 umax_val = src_reg->u32_max_value;
12281
12282         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12283             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12284                 dst_reg->s32_min_value = S32_MIN;
12285                 dst_reg->s32_max_value = S32_MAX;
12286         } else {
12287                 dst_reg->s32_min_value += smin_val;
12288                 dst_reg->s32_max_value += smax_val;
12289         }
12290         if (dst_reg->u32_min_value + umin_val < umin_val ||
12291             dst_reg->u32_max_value + umax_val < umax_val) {
12292                 dst_reg->u32_min_value = 0;
12293                 dst_reg->u32_max_value = U32_MAX;
12294         } else {
12295                 dst_reg->u32_min_value += umin_val;
12296                 dst_reg->u32_max_value += umax_val;
12297         }
12298 }
12299
12300 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12301                                struct bpf_reg_state *src_reg)
12302 {
12303         s64 smin_val = src_reg->smin_value;
12304         s64 smax_val = src_reg->smax_value;
12305         u64 umin_val = src_reg->umin_value;
12306         u64 umax_val = src_reg->umax_value;
12307
12308         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12309             signed_add_overflows(dst_reg->smax_value, smax_val)) {
12310                 dst_reg->smin_value = S64_MIN;
12311                 dst_reg->smax_value = S64_MAX;
12312         } else {
12313                 dst_reg->smin_value += smin_val;
12314                 dst_reg->smax_value += smax_val;
12315         }
12316         if (dst_reg->umin_value + umin_val < umin_val ||
12317             dst_reg->umax_value + umax_val < umax_val) {
12318                 dst_reg->umin_value = 0;
12319                 dst_reg->umax_value = U64_MAX;
12320         } else {
12321                 dst_reg->umin_value += umin_val;
12322                 dst_reg->umax_value += umax_val;
12323         }
12324 }
12325
12326 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12327                                  struct bpf_reg_state *src_reg)
12328 {
12329         s32 smin_val = src_reg->s32_min_value;
12330         s32 smax_val = src_reg->s32_max_value;
12331         u32 umin_val = src_reg->u32_min_value;
12332         u32 umax_val = src_reg->u32_max_value;
12333
12334         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12335             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12336                 /* Overflow possible, we know nothing */
12337                 dst_reg->s32_min_value = S32_MIN;
12338                 dst_reg->s32_max_value = S32_MAX;
12339         } else {
12340                 dst_reg->s32_min_value -= smax_val;
12341                 dst_reg->s32_max_value -= smin_val;
12342         }
12343         if (dst_reg->u32_min_value < umax_val) {
12344                 /* Overflow possible, we know nothing */
12345                 dst_reg->u32_min_value = 0;
12346                 dst_reg->u32_max_value = U32_MAX;
12347         } else {
12348                 /* Cannot overflow (as long as bounds are consistent) */
12349                 dst_reg->u32_min_value -= umax_val;
12350                 dst_reg->u32_max_value -= umin_val;
12351         }
12352 }
12353
12354 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12355                                struct bpf_reg_state *src_reg)
12356 {
12357         s64 smin_val = src_reg->smin_value;
12358         s64 smax_val = src_reg->smax_value;
12359         u64 umin_val = src_reg->umin_value;
12360         u64 umax_val = src_reg->umax_value;
12361
12362         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12363             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12364                 /* Overflow possible, we know nothing */
12365                 dst_reg->smin_value = S64_MIN;
12366                 dst_reg->smax_value = S64_MAX;
12367         } else {
12368                 dst_reg->smin_value -= smax_val;
12369                 dst_reg->smax_value -= smin_val;
12370         }
12371         if (dst_reg->umin_value < umax_val) {
12372                 /* Overflow possible, we know nothing */
12373                 dst_reg->umin_value = 0;
12374                 dst_reg->umax_value = U64_MAX;
12375         } else {
12376                 /* Cannot overflow (as long as bounds are consistent) */
12377                 dst_reg->umin_value -= umax_val;
12378                 dst_reg->umax_value -= umin_val;
12379         }
12380 }
12381
12382 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12383                                  struct bpf_reg_state *src_reg)
12384 {
12385         s32 smin_val = src_reg->s32_min_value;
12386         u32 umin_val = src_reg->u32_min_value;
12387         u32 umax_val = src_reg->u32_max_value;
12388
12389         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12390                 /* Ain't nobody got time to multiply that sign */
12391                 __mark_reg32_unbounded(dst_reg);
12392                 return;
12393         }
12394         /* Both values are positive, so we can work with unsigned and
12395          * copy the result to signed (unless it exceeds S32_MAX).
12396          */
12397         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12398                 /* Potential overflow, we know nothing */
12399                 __mark_reg32_unbounded(dst_reg);
12400                 return;
12401         }
12402         dst_reg->u32_min_value *= umin_val;
12403         dst_reg->u32_max_value *= umax_val;
12404         if (dst_reg->u32_max_value > S32_MAX) {
12405                 /* Overflow possible, we know nothing */
12406                 dst_reg->s32_min_value = S32_MIN;
12407                 dst_reg->s32_max_value = S32_MAX;
12408         } else {
12409                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12410                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12411         }
12412 }
12413
12414 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12415                                struct bpf_reg_state *src_reg)
12416 {
12417         s64 smin_val = src_reg->smin_value;
12418         u64 umin_val = src_reg->umin_value;
12419         u64 umax_val = src_reg->umax_value;
12420
12421         if (smin_val < 0 || dst_reg->smin_value < 0) {
12422                 /* Ain't nobody got time to multiply that sign */
12423                 __mark_reg64_unbounded(dst_reg);
12424                 return;
12425         }
12426         /* Both values are positive, so we can work with unsigned and
12427          * copy the result to signed (unless it exceeds S64_MAX).
12428          */
12429         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12430                 /* Potential overflow, we know nothing */
12431                 __mark_reg64_unbounded(dst_reg);
12432                 return;
12433         }
12434         dst_reg->umin_value *= umin_val;
12435         dst_reg->umax_value *= umax_val;
12436         if (dst_reg->umax_value > S64_MAX) {
12437                 /* Overflow possible, we know nothing */
12438                 dst_reg->smin_value = S64_MIN;
12439                 dst_reg->smax_value = S64_MAX;
12440         } else {
12441                 dst_reg->smin_value = dst_reg->umin_value;
12442                 dst_reg->smax_value = dst_reg->umax_value;
12443         }
12444 }
12445
12446 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12447                                  struct bpf_reg_state *src_reg)
12448 {
12449         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12450         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12451         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12452         s32 smin_val = src_reg->s32_min_value;
12453         u32 umax_val = src_reg->u32_max_value;
12454
12455         if (src_known && dst_known) {
12456                 __mark_reg32_known(dst_reg, var32_off.value);
12457                 return;
12458         }
12459
12460         /* We get our minimum from the var_off, since that's inherently
12461          * bitwise.  Our maximum is the minimum of the operands' maxima.
12462          */
12463         dst_reg->u32_min_value = var32_off.value;
12464         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12465         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12466                 /* Lose signed bounds when ANDing negative numbers,
12467                  * ain't nobody got time for that.
12468                  */
12469                 dst_reg->s32_min_value = S32_MIN;
12470                 dst_reg->s32_max_value = S32_MAX;
12471         } else {
12472                 /* ANDing two positives gives a positive, so safe to
12473                  * cast result into s64.
12474                  */
12475                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12476                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12477         }
12478 }
12479
12480 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12481                                struct bpf_reg_state *src_reg)
12482 {
12483         bool src_known = tnum_is_const(src_reg->var_off);
12484         bool dst_known = tnum_is_const(dst_reg->var_off);
12485         s64 smin_val = src_reg->smin_value;
12486         u64 umax_val = src_reg->umax_value;
12487
12488         if (src_known && dst_known) {
12489                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12490                 return;
12491         }
12492
12493         /* We get our minimum from the var_off, since that's inherently
12494          * bitwise.  Our maximum is the minimum of the operands' maxima.
12495          */
12496         dst_reg->umin_value = dst_reg->var_off.value;
12497         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12498         if (dst_reg->smin_value < 0 || smin_val < 0) {
12499                 /* Lose signed bounds when ANDing negative numbers,
12500                  * ain't nobody got time for that.
12501                  */
12502                 dst_reg->smin_value = S64_MIN;
12503                 dst_reg->smax_value = S64_MAX;
12504         } else {
12505                 /* ANDing two positives gives a positive, so safe to
12506                  * cast result into s64.
12507                  */
12508                 dst_reg->smin_value = dst_reg->umin_value;
12509                 dst_reg->smax_value = dst_reg->umax_value;
12510         }
12511         /* We may learn something more from the var_off */
12512         __update_reg_bounds(dst_reg);
12513 }
12514
12515 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12516                                 struct bpf_reg_state *src_reg)
12517 {
12518         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12519         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12520         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12521         s32 smin_val = src_reg->s32_min_value;
12522         u32 umin_val = src_reg->u32_min_value;
12523
12524         if (src_known && dst_known) {
12525                 __mark_reg32_known(dst_reg, var32_off.value);
12526                 return;
12527         }
12528
12529         /* We get our maximum from the var_off, and our minimum is the
12530          * maximum of the operands' minima
12531          */
12532         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12533         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12534         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12535                 /* Lose signed bounds when ORing negative numbers,
12536                  * ain't nobody got time for that.
12537                  */
12538                 dst_reg->s32_min_value = S32_MIN;
12539                 dst_reg->s32_max_value = S32_MAX;
12540         } else {
12541                 /* ORing two positives gives a positive, so safe to
12542                  * cast result into s64.
12543                  */
12544                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12545                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12546         }
12547 }
12548
12549 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12550                               struct bpf_reg_state *src_reg)
12551 {
12552         bool src_known = tnum_is_const(src_reg->var_off);
12553         bool dst_known = tnum_is_const(dst_reg->var_off);
12554         s64 smin_val = src_reg->smin_value;
12555         u64 umin_val = src_reg->umin_value;
12556
12557         if (src_known && dst_known) {
12558                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12559                 return;
12560         }
12561
12562         /* We get our maximum from the var_off, and our minimum is the
12563          * maximum of the operands' minima
12564          */
12565         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12566         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12567         if (dst_reg->smin_value < 0 || smin_val < 0) {
12568                 /* Lose signed bounds when ORing negative numbers,
12569                  * ain't nobody got time for that.
12570                  */
12571                 dst_reg->smin_value = S64_MIN;
12572                 dst_reg->smax_value = S64_MAX;
12573         } else {
12574                 /* ORing two positives gives a positive, so safe to
12575                  * cast result into s64.
12576                  */
12577                 dst_reg->smin_value = dst_reg->umin_value;
12578                 dst_reg->smax_value = dst_reg->umax_value;
12579         }
12580         /* We may learn something more from the var_off */
12581         __update_reg_bounds(dst_reg);
12582 }
12583
12584 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12585                                  struct bpf_reg_state *src_reg)
12586 {
12587         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12588         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12589         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12590         s32 smin_val = src_reg->s32_min_value;
12591
12592         if (src_known && dst_known) {
12593                 __mark_reg32_known(dst_reg, var32_off.value);
12594                 return;
12595         }
12596
12597         /* We get both minimum and maximum from the var32_off. */
12598         dst_reg->u32_min_value = var32_off.value;
12599         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12600
12601         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12602                 /* XORing two positive sign numbers gives a positive,
12603                  * so safe to cast u32 result into s32.
12604                  */
12605                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12606                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12607         } else {
12608                 dst_reg->s32_min_value = S32_MIN;
12609                 dst_reg->s32_max_value = S32_MAX;
12610         }
12611 }
12612
12613 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12614                                struct bpf_reg_state *src_reg)
12615 {
12616         bool src_known = tnum_is_const(src_reg->var_off);
12617         bool dst_known = tnum_is_const(dst_reg->var_off);
12618         s64 smin_val = src_reg->smin_value;
12619
12620         if (src_known && dst_known) {
12621                 /* dst_reg->var_off.value has been updated earlier */
12622                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12623                 return;
12624         }
12625
12626         /* We get both minimum and maximum from the var_off. */
12627         dst_reg->umin_value = dst_reg->var_off.value;
12628         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12629
12630         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12631                 /* XORing two positive sign numbers gives a positive,
12632                  * so safe to cast u64 result into s64.
12633                  */
12634                 dst_reg->smin_value = dst_reg->umin_value;
12635                 dst_reg->smax_value = dst_reg->umax_value;
12636         } else {
12637                 dst_reg->smin_value = S64_MIN;
12638                 dst_reg->smax_value = S64_MAX;
12639         }
12640
12641         __update_reg_bounds(dst_reg);
12642 }
12643
12644 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12645                                    u64 umin_val, u64 umax_val)
12646 {
12647         /* We lose all sign bit information (except what we can pick
12648          * up from var_off)
12649          */
12650         dst_reg->s32_min_value = S32_MIN;
12651         dst_reg->s32_max_value = S32_MAX;
12652         /* If we might shift our top bit out, then we know nothing */
12653         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12654                 dst_reg->u32_min_value = 0;
12655                 dst_reg->u32_max_value = U32_MAX;
12656         } else {
12657                 dst_reg->u32_min_value <<= umin_val;
12658                 dst_reg->u32_max_value <<= umax_val;
12659         }
12660 }
12661
12662 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12663                                  struct bpf_reg_state *src_reg)
12664 {
12665         u32 umax_val = src_reg->u32_max_value;
12666         u32 umin_val = src_reg->u32_min_value;
12667         /* u32 alu operation will zext upper bits */
12668         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12669
12670         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12671         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12672         /* Not required but being careful mark reg64 bounds as unknown so
12673          * that we are forced to pick them up from tnum and zext later and
12674          * if some path skips this step we are still safe.
12675          */
12676         __mark_reg64_unbounded(dst_reg);
12677         __update_reg32_bounds(dst_reg);
12678 }
12679
12680 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12681                                    u64 umin_val, u64 umax_val)
12682 {
12683         /* Special case <<32 because it is a common compiler pattern to sign
12684          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12685          * positive we know this shift will also be positive so we can track
12686          * bounds correctly. Otherwise we lose all sign bit information except
12687          * what we can pick up from var_off. Perhaps we can generalize this
12688          * later to shifts of any length.
12689          */
12690         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12691                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12692         else
12693                 dst_reg->smax_value = S64_MAX;
12694
12695         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12696                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12697         else
12698                 dst_reg->smin_value = S64_MIN;
12699
12700         /* If we might shift our top bit out, then we know nothing */
12701         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12702                 dst_reg->umin_value = 0;
12703                 dst_reg->umax_value = U64_MAX;
12704         } else {
12705                 dst_reg->umin_value <<= umin_val;
12706                 dst_reg->umax_value <<= umax_val;
12707         }
12708 }
12709
12710 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12711                                struct bpf_reg_state *src_reg)
12712 {
12713         u64 umax_val = src_reg->umax_value;
12714         u64 umin_val = src_reg->umin_value;
12715
12716         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12717         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12718         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12719
12720         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12721         /* We may learn something more from the var_off */
12722         __update_reg_bounds(dst_reg);
12723 }
12724
12725 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12726                                  struct bpf_reg_state *src_reg)
12727 {
12728         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12729         u32 umax_val = src_reg->u32_max_value;
12730         u32 umin_val = src_reg->u32_min_value;
12731
12732         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12733          * be negative, then either:
12734          * 1) src_reg might be zero, so the sign bit of the result is
12735          *    unknown, so we lose our signed bounds
12736          * 2) it's known negative, thus the unsigned bounds capture the
12737          *    signed bounds
12738          * 3) the signed bounds cross zero, so they tell us nothing
12739          *    about the result
12740          * If the value in dst_reg is known nonnegative, then again the
12741          * unsigned bounds capture the signed bounds.
12742          * Thus, in all cases it suffices to blow away our signed bounds
12743          * and rely on inferring new ones from the unsigned bounds and
12744          * var_off of the result.
12745          */
12746         dst_reg->s32_min_value = S32_MIN;
12747         dst_reg->s32_max_value = S32_MAX;
12748
12749         dst_reg->var_off = tnum_rshift(subreg, umin_val);
12750         dst_reg->u32_min_value >>= umax_val;
12751         dst_reg->u32_max_value >>= umin_val;
12752
12753         __mark_reg64_unbounded(dst_reg);
12754         __update_reg32_bounds(dst_reg);
12755 }
12756
12757 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12758                                struct bpf_reg_state *src_reg)
12759 {
12760         u64 umax_val = src_reg->umax_value;
12761         u64 umin_val = src_reg->umin_value;
12762
12763         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12764          * be negative, then either:
12765          * 1) src_reg might be zero, so the sign bit of the result is
12766          *    unknown, so we lose our signed bounds
12767          * 2) it's known negative, thus the unsigned bounds capture the
12768          *    signed bounds
12769          * 3) the signed bounds cross zero, so they tell us nothing
12770          *    about the result
12771          * If the value in dst_reg is known nonnegative, then again the
12772          * unsigned bounds capture the signed bounds.
12773          * Thus, in all cases it suffices to blow away our signed bounds
12774          * and rely on inferring new ones from the unsigned bounds and
12775          * var_off of the result.
12776          */
12777         dst_reg->smin_value = S64_MIN;
12778         dst_reg->smax_value = S64_MAX;
12779         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12780         dst_reg->umin_value >>= umax_val;
12781         dst_reg->umax_value >>= umin_val;
12782
12783         /* Its not easy to operate on alu32 bounds here because it depends
12784          * on bits being shifted in. Take easy way out and mark unbounded
12785          * so we can recalculate later from tnum.
12786          */
12787         __mark_reg32_unbounded(dst_reg);
12788         __update_reg_bounds(dst_reg);
12789 }
12790
12791 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12792                                   struct bpf_reg_state *src_reg)
12793 {
12794         u64 umin_val = src_reg->u32_min_value;
12795
12796         /* Upon reaching here, src_known is true and
12797          * umax_val is equal to umin_val.
12798          */
12799         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12800         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12801
12802         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12803
12804         /* blow away the dst_reg umin_value/umax_value and rely on
12805          * dst_reg var_off to refine the result.
12806          */
12807         dst_reg->u32_min_value = 0;
12808         dst_reg->u32_max_value = U32_MAX;
12809
12810         __mark_reg64_unbounded(dst_reg);
12811         __update_reg32_bounds(dst_reg);
12812 }
12813
12814 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12815                                 struct bpf_reg_state *src_reg)
12816 {
12817         u64 umin_val = src_reg->umin_value;
12818
12819         /* Upon reaching here, src_known is true and umax_val is equal
12820          * to umin_val.
12821          */
12822         dst_reg->smin_value >>= umin_val;
12823         dst_reg->smax_value >>= umin_val;
12824
12825         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12826
12827         /* blow away the dst_reg umin_value/umax_value and rely on
12828          * dst_reg var_off to refine the result.
12829          */
12830         dst_reg->umin_value = 0;
12831         dst_reg->umax_value = U64_MAX;
12832
12833         /* Its not easy to operate on alu32 bounds here because it depends
12834          * on bits being shifted in from upper 32-bits. Take easy way out
12835          * and mark unbounded so we can recalculate later from tnum.
12836          */
12837         __mark_reg32_unbounded(dst_reg);
12838         __update_reg_bounds(dst_reg);
12839 }
12840
12841 /* WARNING: This function does calculations on 64-bit values, but the actual
12842  * execution may occur on 32-bit values. Therefore, things like bitshifts
12843  * need extra checks in the 32-bit case.
12844  */
12845 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12846                                       struct bpf_insn *insn,
12847                                       struct bpf_reg_state *dst_reg,
12848                                       struct bpf_reg_state src_reg)
12849 {
12850         struct bpf_reg_state *regs = cur_regs(env);
12851         u8 opcode = BPF_OP(insn->code);
12852         bool src_known;
12853         s64 smin_val, smax_val;
12854         u64 umin_val, umax_val;
12855         s32 s32_min_val, s32_max_val;
12856         u32 u32_min_val, u32_max_val;
12857         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12858         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12859         int ret;
12860
12861         smin_val = src_reg.smin_value;
12862         smax_val = src_reg.smax_value;
12863         umin_val = src_reg.umin_value;
12864         umax_val = src_reg.umax_value;
12865
12866         s32_min_val = src_reg.s32_min_value;
12867         s32_max_val = src_reg.s32_max_value;
12868         u32_min_val = src_reg.u32_min_value;
12869         u32_max_val = src_reg.u32_max_value;
12870
12871         if (alu32) {
12872                 src_known = tnum_subreg_is_const(src_reg.var_off);
12873                 if ((src_known &&
12874                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12875                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12876                         /* Taint dst register if offset had invalid bounds
12877                          * derived from e.g. dead branches.
12878                          */
12879                         __mark_reg_unknown(env, dst_reg);
12880                         return 0;
12881                 }
12882         } else {
12883                 src_known = tnum_is_const(src_reg.var_off);
12884                 if ((src_known &&
12885                      (smin_val != smax_val || umin_val != umax_val)) ||
12886                     smin_val > smax_val || umin_val > umax_val) {
12887                         /* Taint dst register if offset had invalid bounds
12888                          * derived from e.g. dead branches.
12889                          */
12890                         __mark_reg_unknown(env, dst_reg);
12891                         return 0;
12892                 }
12893         }
12894
12895         if (!src_known &&
12896             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12897                 __mark_reg_unknown(env, dst_reg);
12898                 return 0;
12899         }
12900
12901         if (sanitize_needed(opcode)) {
12902                 ret = sanitize_val_alu(env, insn);
12903                 if (ret < 0)
12904                         return sanitize_err(env, insn, ret, NULL, NULL);
12905         }
12906
12907         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12908          * There are two classes of instructions: The first class we track both
12909          * alu32 and alu64 sign/unsigned bounds independently this provides the
12910          * greatest amount of precision when alu operations are mixed with jmp32
12911          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12912          * and BPF_OR. This is possible because these ops have fairly easy to
12913          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12914          * See alu32 verifier tests for examples. The second class of
12915          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12916          * with regards to tracking sign/unsigned bounds because the bits may
12917          * cross subreg boundaries in the alu64 case. When this happens we mark
12918          * the reg unbounded in the subreg bound space and use the resulting
12919          * tnum to calculate an approximation of the sign/unsigned bounds.
12920          */
12921         switch (opcode) {
12922         case BPF_ADD:
12923                 scalar32_min_max_add(dst_reg, &src_reg);
12924                 scalar_min_max_add(dst_reg, &src_reg);
12925                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12926                 break;
12927         case BPF_SUB:
12928                 scalar32_min_max_sub(dst_reg, &src_reg);
12929                 scalar_min_max_sub(dst_reg, &src_reg);
12930                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12931                 break;
12932         case BPF_MUL:
12933                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12934                 scalar32_min_max_mul(dst_reg, &src_reg);
12935                 scalar_min_max_mul(dst_reg, &src_reg);
12936                 break;
12937         case BPF_AND:
12938                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12939                 scalar32_min_max_and(dst_reg, &src_reg);
12940                 scalar_min_max_and(dst_reg, &src_reg);
12941                 break;
12942         case BPF_OR:
12943                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12944                 scalar32_min_max_or(dst_reg, &src_reg);
12945                 scalar_min_max_or(dst_reg, &src_reg);
12946                 break;
12947         case BPF_XOR:
12948                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12949                 scalar32_min_max_xor(dst_reg, &src_reg);
12950                 scalar_min_max_xor(dst_reg, &src_reg);
12951                 break;
12952         case BPF_LSH:
12953                 if (umax_val >= insn_bitness) {
12954                         /* Shifts greater than 31 or 63 are undefined.
12955                          * This includes shifts by a negative number.
12956                          */
12957                         mark_reg_unknown(env, regs, insn->dst_reg);
12958                         break;
12959                 }
12960                 if (alu32)
12961                         scalar32_min_max_lsh(dst_reg, &src_reg);
12962                 else
12963                         scalar_min_max_lsh(dst_reg, &src_reg);
12964                 break;
12965         case BPF_RSH:
12966                 if (umax_val >= insn_bitness) {
12967                         /* Shifts greater than 31 or 63 are undefined.
12968                          * This includes shifts by a negative number.
12969                          */
12970                         mark_reg_unknown(env, regs, insn->dst_reg);
12971                         break;
12972                 }
12973                 if (alu32)
12974                         scalar32_min_max_rsh(dst_reg, &src_reg);
12975                 else
12976                         scalar_min_max_rsh(dst_reg, &src_reg);
12977                 break;
12978         case BPF_ARSH:
12979                 if (umax_val >= insn_bitness) {
12980                         /* Shifts greater than 31 or 63 are undefined.
12981                          * This includes shifts by a negative number.
12982                          */
12983                         mark_reg_unknown(env, regs, insn->dst_reg);
12984                         break;
12985                 }
12986                 if (alu32)
12987                         scalar32_min_max_arsh(dst_reg, &src_reg);
12988                 else
12989                         scalar_min_max_arsh(dst_reg, &src_reg);
12990                 break;
12991         default:
12992                 mark_reg_unknown(env, regs, insn->dst_reg);
12993                 break;
12994         }
12995
12996         /* ALU32 ops are zero extended into 64bit register */
12997         if (alu32)
12998                 zext_32_to_64(dst_reg);
12999         reg_bounds_sync(dst_reg);
13000         return 0;
13001 }
13002
13003 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13004  * and var_off.
13005  */
13006 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13007                                    struct bpf_insn *insn)
13008 {
13009         struct bpf_verifier_state *vstate = env->cur_state;
13010         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13011         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13012         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13013         u8 opcode = BPF_OP(insn->code);
13014         int err;
13015
13016         dst_reg = &regs[insn->dst_reg];
13017         src_reg = NULL;
13018         if (dst_reg->type != SCALAR_VALUE)
13019                 ptr_reg = dst_reg;
13020         else
13021                 /* Make sure ID is cleared otherwise dst_reg min/max could be
13022                  * incorrectly propagated into other registers by find_equal_scalars()
13023                  */
13024                 dst_reg->id = 0;
13025         if (BPF_SRC(insn->code) == BPF_X) {
13026                 src_reg = &regs[insn->src_reg];
13027                 if (src_reg->type != SCALAR_VALUE) {
13028                         if (dst_reg->type != SCALAR_VALUE) {
13029                                 /* Combining two pointers by any ALU op yields
13030                                  * an arbitrary scalar. Disallow all math except
13031                                  * pointer subtraction
13032                                  */
13033                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13034                                         mark_reg_unknown(env, regs, insn->dst_reg);
13035                                         return 0;
13036                                 }
13037                                 verbose(env, "R%d pointer %s pointer prohibited\n",
13038                                         insn->dst_reg,
13039                                         bpf_alu_string[opcode >> 4]);
13040                                 return -EACCES;
13041                         } else {
13042                                 /* scalar += pointer
13043                                  * This is legal, but we have to reverse our
13044                                  * src/dest handling in computing the range
13045                                  */
13046                                 err = mark_chain_precision(env, insn->dst_reg);
13047                                 if (err)
13048                                         return err;
13049                                 return adjust_ptr_min_max_vals(env, insn,
13050                                                                src_reg, dst_reg);
13051                         }
13052                 } else if (ptr_reg) {
13053                         /* pointer += scalar */
13054                         err = mark_chain_precision(env, insn->src_reg);
13055                         if (err)
13056                                 return err;
13057                         return adjust_ptr_min_max_vals(env, insn,
13058                                                        dst_reg, src_reg);
13059                 } else if (dst_reg->precise) {
13060                         /* if dst_reg is precise, src_reg should be precise as well */
13061                         err = mark_chain_precision(env, insn->src_reg);
13062                         if (err)
13063                                 return err;
13064                 }
13065         } else {
13066                 /* Pretend the src is a reg with a known value, since we only
13067                  * need to be able to read from this state.
13068                  */
13069                 off_reg.type = SCALAR_VALUE;
13070                 __mark_reg_known(&off_reg, insn->imm);
13071                 src_reg = &off_reg;
13072                 if (ptr_reg) /* pointer += K */
13073                         return adjust_ptr_min_max_vals(env, insn,
13074                                                        ptr_reg, src_reg);
13075         }
13076
13077         /* Got here implies adding two SCALAR_VALUEs */
13078         if (WARN_ON_ONCE(ptr_reg)) {
13079                 print_verifier_state(env, state, true);
13080                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13081                 return -EINVAL;
13082         }
13083         if (WARN_ON(!src_reg)) {
13084                 print_verifier_state(env, state, true);
13085                 verbose(env, "verifier internal error: no src_reg\n");
13086                 return -EINVAL;
13087         }
13088         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13089 }
13090
13091 /* check validity of 32-bit and 64-bit arithmetic operations */
13092 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13093 {
13094         struct bpf_reg_state *regs = cur_regs(env);
13095         u8 opcode = BPF_OP(insn->code);
13096         int err;
13097
13098         if (opcode == BPF_END || opcode == BPF_NEG) {
13099                 if (opcode == BPF_NEG) {
13100                         if (BPF_SRC(insn->code) != BPF_K ||
13101                             insn->src_reg != BPF_REG_0 ||
13102                             insn->off != 0 || insn->imm != 0) {
13103                                 verbose(env, "BPF_NEG uses reserved fields\n");
13104                                 return -EINVAL;
13105                         }
13106                 } else {
13107                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13108                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13109                             (BPF_CLASS(insn->code) == BPF_ALU64 &&
13110                              BPF_SRC(insn->code) != BPF_TO_LE)) {
13111                                 verbose(env, "BPF_END uses reserved fields\n");
13112                                 return -EINVAL;
13113                         }
13114                 }
13115
13116                 /* check src operand */
13117                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13118                 if (err)
13119                         return err;
13120
13121                 if (is_pointer_value(env, insn->dst_reg)) {
13122                         verbose(env, "R%d pointer arithmetic prohibited\n",
13123                                 insn->dst_reg);
13124                         return -EACCES;
13125                 }
13126
13127                 /* check dest operand */
13128                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13129                 if (err)
13130                         return err;
13131
13132         } else if (opcode == BPF_MOV) {
13133
13134                 if (BPF_SRC(insn->code) == BPF_X) {
13135                         if (insn->imm != 0) {
13136                                 verbose(env, "BPF_MOV uses reserved fields\n");
13137                                 return -EINVAL;
13138                         }
13139
13140                         if (BPF_CLASS(insn->code) == BPF_ALU) {
13141                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13142                                         verbose(env, "BPF_MOV uses reserved fields\n");
13143                                         return -EINVAL;
13144                                 }
13145                         } else {
13146                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13147                                     insn->off != 32) {
13148                                         verbose(env, "BPF_MOV uses reserved fields\n");
13149                                         return -EINVAL;
13150                                 }
13151                         }
13152
13153                         /* check src operand */
13154                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13155                         if (err)
13156                                 return err;
13157                 } else {
13158                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13159                                 verbose(env, "BPF_MOV uses reserved fields\n");
13160                                 return -EINVAL;
13161                         }
13162                 }
13163
13164                 /* check dest operand, mark as required later */
13165                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13166                 if (err)
13167                         return err;
13168
13169                 if (BPF_SRC(insn->code) == BPF_X) {
13170                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
13171                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13172                         bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13173                                        !tnum_is_const(src_reg->var_off);
13174
13175                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13176                                 if (insn->off == 0) {
13177                                         /* case: R1 = R2
13178                                          * copy register state to dest reg
13179                                          */
13180                                         if (need_id)
13181                                                 /* Assign src and dst registers the same ID
13182                                                  * that will be used by find_equal_scalars()
13183                                                  * to propagate min/max range.
13184                                                  */
13185                                                 src_reg->id = ++env->id_gen;
13186                                         copy_register_state(dst_reg, src_reg);
13187                                         dst_reg->live |= REG_LIVE_WRITTEN;
13188                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13189                                 } else {
13190                                         /* case: R1 = (s8, s16 s32)R2 */
13191                                         if (is_pointer_value(env, insn->src_reg)) {
13192                                                 verbose(env,
13193                                                         "R%d sign-extension part of pointer\n",
13194                                                         insn->src_reg);
13195                                                 return -EACCES;
13196                                         } else if (src_reg->type == SCALAR_VALUE) {
13197                                                 bool no_sext;
13198
13199                                                 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13200                                                 if (no_sext && need_id)
13201                                                         src_reg->id = ++env->id_gen;
13202                                                 copy_register_state(dst_reg, src_reg);
13203                                                 if (!no_sext)
13204                                                         dst_reg->id = 0;
13205                                                 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13206                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13207                                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
13208                                         } else {
13209                                                 mark_reg_unknown(env, regs, insn->dst_reg);
13210                                         }
13211                                 }
13212                         } else {
13213                                 /* R1 = (u32) R2 */
13214                                 if (is_pointer_value(env, insn->src_reg)) {
13215                                         verbose(env,
13216                                                 "R%d partial copy of pointer\n",
13217                                                 insn->src_reg);
13218                                         return -EACCES;
13219                                 } else if (src_reg->type == SCALAR_VALUE) {
13220                                         if (insn->off == 0) {
13221                                                 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13222
13223                                                 if (is_src_reg_u32 && need_id)
13224                                                         src_reg->id = ++env->id_gen;
13225                                                 copy_register_state(dst_reg, src_reg);
13226                                                 /* Make sure ID is cleared if src_reg is not in u32
13227                                                  * range otherwise dst_reg min/max could be incorrectly
13228                                                  * propagated into src_reg by find_equal_scalars()
13229                                                  */
13230                                                 if (!is_src_reg_u32)
13231                                                         dst_reg->id = 0;
13232                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13233                                                 dst_reg->subreg_def = env->insn_idx + 1;
13234                                         } else {
13235                                                 /* case: W1 = (s8, s16)W2 */
13236                                                 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13237
13238                                                 if (no_sext && need_id)
13239                                                         src_reg->id = ++env->id_gen;
13240                                                 copy_register_state(dst_reg, src_reg);
13241                                                 if (!no_sext)
13242                                                         dst_reg->id = 0;
13243                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13244                                                 dst_reg->subreg_def = env->insn_idx + 1;
13245                                                 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13246                                         }
13247                                 } else {
13248                                         mark_reg_unknown(env, regs,
13249                                                          insn->dst_reg);
13250                                 }
13251                                 zext_32_to_64(dst_reg);
13252                                 reg_bounds_sync(dst_reg);
13253                         }
13254                 } else {
13255                         /* case: R = imm
13256                          * remember the value we stored into this reg
13257                          */
13258                         /* clear any state __mark_reg_known doesn't set */
13259                         mark_reg_unknown(env, regs, insn->dst_reg);
13260                         regs[insn->dst_reg].type = SCALAR_VALUE;
13261                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13262                                 __mark_reg_known(regs + insn->dst_reg,
13263                                                  insn->imm);
13264                         } else {
13265                                 __mark_reg_known(regs + insn->dst_reg,
13266                                                  (u32)insn->imm);
13267                         }
13268                 }
13269
13270         } else if (opcode > BPF_END) {
13271                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13272                 return -EINVAL;
13273
13274         } else {        /* all other ALU ops: and, sub, xor, add, ... */
13275
13276                 if (BPF_SRC(insn->code) == BPF_X) {
13277                         if (insn->imm != 0 || insn->off > 1 ||
13278                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13279                                 verbose(env, "BPF_ALU uses reserved fields\n");
13280                                 return -EINVAL;
13281                         }
13282                         /* check src1 operand */
13283                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13284                         if (err)
13285                                 return err;
13286                 } else {
13287                         if (insn->src_reg != BPF_REG_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                 }
13293
13294                 /* check src2 operand */
13295                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13296                 if (err)
13297                         return err;
13298
13299                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13300                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13301                         verbose(env, "div by zero\n");
13302                         return -EINVAL;
13303                 }
13304
13305                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13306                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13307                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13308
13309                         if (insn->imm < 0 || insn->imm >= size) {
13310                                 verbose(env, "invalid shift %d\n", insn->imm);
13311                                 return -EINVAL;
13312                         }
13313                 }
13314
13315                 /* check dest operand */
13316                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13317                 if (err)
13318                         return err;
13319
13320                 return adjust_reg_min_max_vals(env, insn);
13321         }
13322
13323         return 0;
13324 }
13325
13326 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13327                                    struct bpf_reg_state *dst_reg,
13328                                    enum bpf_reg_type type,
13329                                    bool range_right_open)
13330 {
13331         struct bpf_func_state *state;
13332         struct bpf_reg_state *reg;
13333         int new_range;
13334
13335         if (dst_reg->off < 0 ||
13336             (dst_reg->off == 0 && range_right_open))
13337                 /* This doesn't give us any range */
13338                 return;
13339
13340         if (dst_reg->umax_value > MAX_PACKET_OFF ||
13341             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13342                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
13343                  * than pkt_end, but that's because it's also less than pkt.
13344                  */
13345                 return;
13346
13347         new_range = dst_reg->off;
13348         if (range_right_open)
13349                 new_range++;
13350
13351         /* Examples for register markings:
13352          *
13353          * pkt_data in dst register:
13354          *
13355          *   r2 = r3;
13356          *   r2 += 8;
13357          *   if (r2 > pkt_end) goto <handle exception>
13358          *   <access okay>
13359          *
13360          *   r2 = r3;
13361          *   r2 += 8;
13362          *   if (r2 < pkt_end) goto <access okay>
13363          *   <handle exception>
13364          *
13365          *   Where:
13366          *     r2 == dst_reg, pkt_end == src_reg
13367          *     r2=pkt(id=n,off=8,r=0)
13368          *     r3=pkt(id=n,off=0,r=0)
13369          *
13370          * pkt_data in src register:
13371          *
13372          *   r2 = r3;
13373          *   r2 += 8;
13374          *   if (pkt_end >= r2) goto <access okay>
13375          *   <handle exception>
13376          *
13377          *   r2 = r3;
13378          *   r2 += 8;
13379          *   if (pkt_end <= r2) goto <handle exception>
13380          *   <access okay>
13381          *
13382          *   Where:
13383          *     pkt_end == dst_reg, r2 == src_reg
13384          *     r2=pkt(id=n,off=8,r=0)
13385          *     r3=pkt(id=n,off=0,r=0)
13386          *
13387          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13388          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13389          * and [r3, r3 + 8-1) respectively is safe to access depending on
13390          * the check.
13391          */
13392
13393         /* If our ids match, then we must have the same max_value.  And we
13394          * don't care about the other reg's fixed offset, since if it's too big
13395          * the range won't allow anything.
13396          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13397          */
13398         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13399                 if (reg->type == type && reg->id == dst_reg->id)
13400                         /* keep the maximum range already checked */
13401                         reg->range = max(reg->range, new_range);
13402         }));
13403 }
13404
13405 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13406 {
13407         struct tnum subreg = tnum_subreg(reg->var_off);
13408         s32 sval = (s32)val;
13409
13410         switch (opcode) {
13411         case BPF_JEQ:
13412                 if (tnum_is_const(subreg))
13413                         return !!tnum_equals_const(subreg, val);
13414                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13415                         return 0;
13416                 break;
13417         case BPF_JNE:
13418                 if (tnum_is_const(subreg))
13419                         return !tnum_equals_const(subreg, val);
13420                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13421                         return 1;
13422                 break;
13423         case BPF_JSET:
13424                 if ((~subreg.mask & subreg.value) & val)
13425                         return 1;
13426                 if (!((subreg.mask | subreg.value) & val))
13427                         return 0;
13428                 break;
13429         case BPF_JGT:
13430                 if (reg->u32_min_value > val)
13431                         return 1;
13432                 else if (reg->u32_max_value <= val)
13433                         return 0;
13434                 break;
13435         case BPF_JSGT:
13436                 if (reg->s32_min_value > sval)
13437                         return 1;
13438                 else if (reg->s32_max_value <= sval)
13439                         return 0;
13440                 break;
13441         case BPF_JLT:
13442                 if (reg->u32_max_value < val)
13443                         return 1;
13444                 else if (reg->u32_min_value >= val)
13445                         return 0;
13446                 break;
13447         case BPF_JSLT:
13448                 if (reg->s32_max_value < sval)
13449                         return 1;
13450                 else if (reg->s32_min_value >= sval)
13451                         return 0;
13452                 break;
13453         case BPF_JGE:
13454                 if (reg->u32_min_value >= val)
13455                         return 1;
13456                 else if (reg->u32_max_value < val)
13457                         return 0;
13458                 break;
13459         case BPF_JSGE:
13460                 if (reg->s32_min_value >= sval)
13461                         return 1;
13462                 else if (reg->s32_max_value < sval)
13463                         return 0;
13464                 break;
13465         case BPF_JLE:
13466                 if (reg->u32_max_value <= val)
13467                         return 1;
13468                 else if (reg->u32_min_value > val)
13469                         return 0;
13470                 break;
13471         case BPF_JSLE:
13472                 if (reg->s32_max_value <= sval)
13473                         return 1;
13474                 else if (reg->s32_min_value > sval)
13475                         return 0;
13476                 break;
13477         }
13478
13479         return -1;
13480 }
13481
13482
13483 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13484 {
13485         s64 sval = (s64)val;
13486
13487         switch (opcode) {
13488         case BPF_JEQ:
13489                 if (tnum_is_const(reg->var_off))
13490                         return !!tnum_equals_const(reg->var_off, val);
13491                 else if (val < reg->umin_value || val > reg->umax_value)
13492                         return 0;
13493                 break;
13494         case BPF_JNE:
13495                 if (tnum_is_const(reg->var_off))
13496                         return !tnum_equals_const(reg->var_off, val);
13497                 else if (val < reg->umin_value || val > reg->umax_value)
13498                         return 1;
13499                 break;
13500         case BPF_JSET:
13501                 if ((~reg->var_off.mask & reg->var_off.value) & val)
13502                         return 1;
13503                 if (!((reg->var_off.mask | reg->var_off.value) & val))
13504                         return 0;
13505                 break;
13506         case BPF_JGT:
13507                 if (reg->umin_value > val)
13508                         return 1;
13509                 else if (reg->umax_value <= val)
13510                         return 0;
13511                 break;
13512         case BPF_JSGT:
13513                 if (reg->smin_value > sval)
13514                         return 1;
13515                 else if (reg->smax_value <= sval)
13516                         return 0;
13517                 break;
13518         case BPF_JLT:
13519                 if (reg->umax_value < val)
13520                         return 1;
13521                 else if (reg->umin_value >= val)
13522                         return 0;
13523                 break;
13524         case BPF_JSLT:
13525                 if (reg->smax_value < sval)
13526                         return 1;
13527                 else if (reg->smin_value >= sval)
13528                         return 0;
13529                 break;
13530         case BPF_JGE:
13531                 if (reg->umin_value >= val)
13532                         return 1;
13533                 else if (reg->umax_value < val)
13534                         return 0;
13535                 break;
13536         case BPF_JSGE:
13537                 if (reg->smin_value >= sval)
13538                         return 1;
13539                 else if (reg->smax_value < sval)
13540                         return 0;
13541                 break;
13542         case BPF_JLE:
13543                 if (reg->umax_value <= val)
13544                         return 1;
13545                 else if (reg->umin_value > val)
13546                         return 0;
13547                 break;
13548         case BPF_JSLE:
13549                 if (reg->smax_value <= sval)
13550                         return 1;
13551                 else if (reg->smin_value > sval)
13552                         return 0;
13553                 break;
13554         }
13555
13556         return -1;
13557 }
13558
13559 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13560  * and return:
13561  *  1 - branch will be taken and "goto target" will be executed
13562  *  0 - branch will not be taken and fall-through to next insn
13563  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13564  *      range [0,10]
13565  */
13566 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13567                            bool is_jmp32)
13568 {
13569         if (__is_pointer_value(false, reg)) {
13570                 if (!reg_not_null(reg))
13571                         return -1;
13572
13573                 /* If pointer is valid tests against zero will fail so we can
13574                  * use this to direct branch taken.
13575                  */
13576                 if (val != 0)
13577                         return -1;
13578
13579                 switch (opcode) {
13580                 case BPF_JEQ:
13581                         return 0;
13582                 case BPF_JNE:
13583                         return 1;
13584                 default:
13585                         return -1;
13586                 }
13587         }
13588
13589         if (is_jmp32)
13590                 return is_branch32_taken(reg, val, opcode);
13591         return is_branch64_taken(reg, val, opcode);
13592 }
13593
13594 static int flip_opcode(u32 opcode)
13595 {
13596         /* How can we transform "a <op> b" into "b <op> a"? */
13597         static const u8 opcode_flip[16] = {
13598                 /* these stay the same */
13599                 [BPF_JEQ  >> 4] = BPF_JEQ,
13600                 [BPF_JNE  >> 4] = BPF_JNE,
13601                 [BPF_JSET >> 4] = BPF_JSET,
13602                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13603                 [BPF_JGE  >> 4] = BPF_JLE,
13604                 [BPF_JGT  >> 4] = BPF_JLT,
13605                 [BPF_JLE  >> 4] = BPF_JGE,
13606                 [BPF_JLT  >> 4] = BPF_JGT,
13607                 [BPF_JSGE >> 4] = BPF_JSLE,
13608                 [BPF_JSGT >> 4] = BPF_JSLT,
13609                 [BPF_JSLE >> 4] = BPF_JSGE,
13610                 [BPF_JSLT >> 4] = BPF_JSGT
13611         };
13612         return opcode_flip[opcode >> 4];
13613 }
13614
13615 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13616                                    struct bpf_reg_state *src_reg,
13617                                    u8 opcode)
13618 {
13619         struct bpf_reg_state *pkt;
13620
13621         if (src_reg->type == PTR_TO_PACKET_END) {
13622                 pkt = dst_reg;
13623         } else if (dst_reg->type == PTR_TO_PACKET_END) {
13624                 pkt = src_reg;
13625                 opcode = flip_opcode(opcode);
13626         } else {
13627                 return -1;
13628         }
13629
13630         if (pkt->range >= 0)
13631                 return -1;
13632
13633         switch (opcode) {
13634         case BPF_JLE:
13635                 /* pkt <= pkt_end */
13636                 fallthrough;
13637         case BPF_JGT:
13638                 /* pkt > pkt_end */
13639                 if (pkt->range == BEYOND_PKT_END)
13640                         /* pkt has at last one extra byte beyond pkt_end */
13641                         return opcode == BPF_JGT;
13642                 break;
13643         case BPF_JLT:
13644                 /* pkt < pkt_end */
13645                 fallthrough;
13646         case BPF_JGE:
13647                 /* pkt >= pkt_end */
13648                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13649                         return opcode == BPF_JGE;
13650                 break;
13651         }
13652         return -1;
13653 }
13654
13655 /* Adjusts the register min/max values in the case that the dst_reg is the
13656  * variable register that we are working on, and src_reg is a constant or we're
13657  * simply doing a BPF_K check.
13658  * In JEQ/JNE cases we also adjust the var_off values.
13659  */
13660 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13661                             struct bpf_reg_state *false_reg,
13662                             u64 val, u32 val32,
13663                             u8 opcode, bool is_jmp32)
13664 {
13665         struct tnum false_32off = tnum_subreg(false_reg->var_off);
13666         struct tnum false_64off = false_reg->var_off;
13667         struct tnum true_32off = tnum_subreg(true_reg->var_off);
13668         struct tnum true_64off = true_reg->var_off;
13669         s64 sval = (s64)val;
13670         s32 sval32 = (s32)val32;
13671
13672         /* If the dst_reg is a pointer, we can't learn anything about its
13673          * variable offset from the compare (unless src_reg were a pointer into
13674          * the same object, but we don't bother with that.
13675          * Since false_reg and true_reg have the same type by construction, we
13676          * only need to check one of them for pointerness.
13677          */
13678         if (__is_pointer_value(false, false_reg))
13679                 return;
13680
13681         switch (opcode) {
13682         /* JEQ/JNE comparison doesn't change the register equivalence.
13683          *
13684          * r1 = r2;
13685          * if (r1 == 42) goto label;
13686          * ...
13687          * label: // here both r1 and r2 are known to be 42.
13688          *
13689          * Hence when marking register as known preserve it's ID.
13690          */
13691         case BPF_JEQ:
13692                 if (is_jmp32) {
13693                         __mark_reg32_known(true_reg, val32);
13694                         true_32off = tnum_subreg(true_reg->var_off);
13695                 } else {
13696                         ___mark_reg_known(true_reg, val);
13697                         true_64off = true_reg->var_off;
13698                 }
13699                 break;
13700         case BPF_JNE:
13701                 if (is_jmp32) {
13702                         __mark_reg32_known(false_reg, val32);
13703                         false_32off = tnum_subreg(false_reg->var_off);
13704                 } else {
13705                         ___mark_reg_known(false_reg, val);
13706                         false_64off = false_reg->var_off;
13707                 }
13708                 break;
13709         case BPF_JSET:
13710                 if (is_jmp32) {
13711                         false_32off = tnum_and(false_32off, tnum_const(~val32));
13712                         if (is_power_of_2(val32))
13713                                 true_32off = tnum_or(true_32off,
13714                                                      tnum_const(val32));
13715                 } else {
13716                         false_64off = tnum_and(false_64off, tnum_const(~val));
13717                         if (is_power_of_2(val))
13718                                 true_64off = tnum_or(true_64off,
13719                                                      tnum_const(val));
13720                 }
13721                 break;
13722         case BPF_JGE:
13723         case BPF_JGT:
13724         {
13725                 if (is_jmp32) {
13726                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13727                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13728
13729                         false_reg->u32_max_value = min(false_reg->u32_max_value,
13730                                                        false_umax);
13731                         true_reg->u32_min_value = max(true_reg->u32_min_value,
13732                                                       true_umin);
13733                 } else {
13734                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13735                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13736
13737                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
13738                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
13739                 }
13740                 break;
13741         }
13742         case BPF_JSGE:
13743         case BPF_JSGT:
13744         {
13745                 if (is_jmp32) {
13746                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13747                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13748
13749                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13750                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13751                 } else {
13752                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13753                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13754
13755                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
13756                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
13757                 }
13758                 break;
13759         }
13760         case BPF_JLE:
13761         case BPF_JLT:
13762         {
13763                 if (is_jmp32) {
13764                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13765                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13766
13767                         false_reg->u32_min_value = max(false_reg->u32_min_value,
13768                                                        false_umin);
13769                         true_reg->u32_max_value = min(true_reg->u32_max_value,
13770                                                       true_umax);
13771                 } else {
13772                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13773                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13774
13775                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
13776                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
13777                 }
13778                 break;
13779         }
13780         case BPF_JSLE:
13781         case BPF_JSLT:
13782         {
13783                 if (is_jmp32) {
13784                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13785                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13786
13787                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13788                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13789                 } else {
13790                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13791                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13792
13793                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
13794                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
13795                 }
13796                 break;
13797         }
13798         default:
13799                 return;
13800         }
13801
13802         if (is_jmp32) {
13803                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13804                                              tnum_subreg(false_32off));
13805                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13806                                             tnum_subreg(true_32off));
13807                 __reg_combine_32_into_64(false_reg);
13808                 __reg_combine_32_into_64(true_reg);
13809         } else {
13810                 false_reg->var_off = false_64off;
13811                 true_reg->var_off = true_64off;
13812                 __reg_combine_64_into_32(false_reg);
13813                 __reg_combine_64_into_32(true_reg);
13814         }
13815 }
13816
13817 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13818  * the variable reg.
13819  */
13820 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13821                                 struct bpf_reg_state *false_reg,
13822                                 u64 val, u32 val32,
13823                                 u8 opcode, bool is_jmp32)
13824 {
13825         opcode = flip_opcode(opcode);
13826         /* This uses zero as "not present in table"; luckily the zero opcode,
13827          * BPF_JA, can't get here.
13828          */
13829         if (opcode)
13830                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13831 }
13832
13833 /* Regs are known to be equal, so intersect their min/max/var_off */
13834 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13835                                   struct bpf_reg_state *dst_reg)
13836 {
13837         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13838                                                         dst_reg->umin_value);
13839         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13840                                                         dst_reg->umax_value);
13841         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13842                                                         dst_reg->smin_value);
13843         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13844                                                         dst_reg->smax_value);
13845         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13846                                                              dst_reg->var_off);
13847         reg_bounds_sync(src_reg);
13848         reg_bounds_sync(dst_reg);
13849 }
13850
13851 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13852                                 struct bpf_reg_state *true_dst,
13853                                 struct bpf_reg_state *false_src,
13854                                 struct bpf_reg_state *false_dst,
13855                                 u8 opcode)
13856 {
13857         switch (opcode) {
13858         case BPF_JEQ:
13859                 __reg_combine_min_max(true_src, true_dst);
13860                 break;
13861         case BPF_JNE:
13862                 __reg_combine_min_max(false_src, false_dst);
13863                 break;
13864         }
13865 }
13866
13867 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13868                                  struct bpf_reg_state *reg, u32 id,
13869                                  bool is_null)
13870 {
13871         if (type_may_be_null(reg->type) && reg->id == id &&
13872             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13873                 /* Old offset (both fixed and variable parts) should have been
13874                  * known-zero, because we don't allow pointer arithmetic on
13875                  * pointers that might be NULL. If we see this happening, don't
13876                  * convert the register.
13877                  *
13878                  * But in some cases, some helpers that return local kptrs
13879                  * advance offset for the returned pointer. In those cases, it
13880                  * is fine to expect to see reg->off.
13881                  */
13882                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13883                         return;
13884                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13885                     WARN_ON_ONCE(reg->off))
13886                         return;
13887
13888                 if (is_null) {
13889                         reg->type = SCALAR_VALUE;
13890                         /* We don't need id and ref_obj_id from this point
13891                          * onwards anymore, thus we should better reset it,
13892                          * so that state pruning has chances to take effect.
13893                          */
13894                         reg->id = 0;
13895                         reg->ref_obj_id = 0;
13896
13897                         return;
13898                 }
13899
13900                 mark_ptr_not_null_reg(reg);
13901
13902                 if (!reg_may_point_to_spin_lock(reg)) {
13903                         /* For not-NULL ptr, reg->ref_obj_id will be reset
13904                          * in release_reference().
13905                          *
13906                          * reg->id is still used by spin_lock ptr. Other
13907                          * than spin_lock ptr type, reg->id can be reset.
13908                          */
13909                         reg->id = 0;
13910                 }
13911         }
13912 }
13913
13914 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13915  * be folded together at some point.
13916  */
13917 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13918                                   bool is_null)
13919 {
13920         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13921         struct bpf_reg_state *regs = state->regs, *reg;
13922         u32 ref_obj_id = regs[regno].ref_obj_id;
13923         u32 id = regs[regno].id;
13924
13925         if (ref_obj_id && ref_obj_id == id && is_null)
13926                 /* regs[regno] is in the " == NULL" branch.
13927                  * No one could have freed the reference state before
13928                  * doing the NULL check.
13929                  */
13930                 WARN_ON_ONCE(release_reference_state(state, id));
13931
13932         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13933                 mark_ptr_or_null_reg(state, reg, id, is_null);
13934         }));
13935 }
13936
13937 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13938                                    struct bpf_reg_state *dst_reg,
13939                                    struct bpf_reg_state *src_reg,
13940                                    struct bpf_verifier_state *this_branch,
13941                                    struct bpf_verifier_state *other_branch)
13942 {
13943         if (BPF_SRC(insn->code) != BPF_X)
13944                 return false;
13945
13946         /* Pointers are always 64-bit. */
13947         if (BPF_CLASS(insn->code) == BPF_JMP32)
13948                 return false;
13949
13950         switch (BPF_OP(insn->code)) {
13951         case BPF_JGT:
13952                 if ((dst_reg->type == PTR_TO_PACKET &&
13953                      src_reg->type == PTR_TO_PACKET_END) ||
13954                     (dst_reg->type == PTR_TO_PACKET_META &&
13955                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13956                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13957                         find_good_pkt_pointers(this_branch, dst_reg,
13958                                                dst_reg->type, false);
13959                         mark_pkt_end(other_branch, insn->dst_reg, true);
13960                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13961                             src_reg->type == PTR_TO_PACKET) ||
13962                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13963                             src_reg->type == PTR_TO_PACKET_META)) {
13964                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13965                         find_good_pkt_pointers(other_branch, src_reg,
13966                                                src_reg->type, true);
13967                         mark_pkt_end(this_branch, insn->src_reg, false);
13968                 } else {
13969                         return false;
13970                 }
13971                 break;
13972         case BPF_JLT:
13973                 if ((dst_reg->type == PTR_TO_PACKET &&
13974                      src_reg->type == PTR_TO_PACKET_END) ||
13975                     (dst_reg->type == PTR_TO_PACKET_META &&
13976                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13977                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13978                         find_good_pkt_pointers(other_branch, dst_reg,
13979                                                dst_reg->type, true);
13980                         mark_pkt_end(this_branch, insn->dst_reg, false);
13981                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13982                             src_reg->type == PTR_TO_PACKET) ||
13983                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13984                             src_reg->type == PTR_TO_PACKET_META)) {
13985                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13986                         find_good_pkt_pointers(this_branch, src_reg,
13987                                                src_reg->type, false);
13988                         mark_pkt_end(other_branch, insn->src_reg, true);
13989                 } else {
13990                         return false;
13991                 }
13992                 break;
13993         case BPF_JGE:
13994                 if ((dst_reg->type == PTR_TO_PACKET &&
13995                      src_reg->type == PTR_TO_PACKET_END) ||
13996                     (dst_reg->type == PTR_TO_PACKET_META &&
13997                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13998                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13999                         find_good_pkt_pointers(this_branch, dst_reg,
14000                                                dst_reg->type, true);
14001                         mark_pkt_end(other_branch, insn->dst_reg, false);
14002                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14003                             src_reg->type == PTR_TO_PACKET) ||
14004                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14005                             src_reg->type == PTR_TO_PACKET_META)) {
14006                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14007                         find_good_pkt_pointers(other_branch, src_reg,
14008                                                src_reg->type, false);
14009                         mark_pkt_end(this_branch, insn->src_reg, true);
14010                 } else {
14011                         return false;
14012                 }
14013                 break;
14014         case BPF_JLE:
14015                 if ((dst_reg->type == PTR_TO_PACKET &&
14016                      src_reg->type == PTR_TO_PACKET_END) ||
14017                     (dst_reg->type == PTR_TO_PACKET_META &&
14018                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14019                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14020                         find_good_pkt_pointers(other_branch, dst_reg,
14021                                                dst_reg->type, false);
14022                         mark_pkt_end(this_branch, insn->dst_reg, true);
14023                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14024                             src_reg->type == PTR_TO_PACKET) ||
14025                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14026                             src_reg->type == PTR_TO_PACKET_META)) {
14027                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14028                         find_good_pkt_pointers(this_branch, src_reg,
14029                                                src_reg->type, true);
14030                         mark_pkt_end(other_branch, insn->src_reg, false);
14031                 } else {
14032                         return false;
14033                 }
14034                 break;
14035         default:
14036                 return false;
14037         }
14038
14039         return true;
14040 }
14041
14042 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14043                                struct bpf_reg_state *known_reg)
14044 {
14045         struct bpf_func_state *state;
14046         struct bpf_reg_state *reg;
14047
14048         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14049                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14050                         copy_register_state(reg, known_reg);
14051         }));
14052 }
14053
14054 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14055                              struct bpf_insn *insn, int *insn_idx)
14056 {
14057         struct bpf_verifier_state *this_branch = env->cur_state;
14058         struct bpf_verifier_state *other_branch;
14059         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14060         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14061         struct bpf_reg_state *eq_branch_regs;
14062         u8 opcode = BPF_OP(insn->code);
14063         bool is_jmp32;
14064         int pred = -1;
14065         int err;
14066
14067         /* Only conditional jumps are expected to reach here. */
14068         if (opcode == BPF_JA || opcode > BPF_JSLE) {
14069                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14070                 return -EINVAL;
14071         }
14072
14073         /* check src2 operand */
14074         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14075         if (err)
14076                 return err;
14077
14078         dst_reg = &regs[insn->dst_reg];
14079         if (BPF_SRC(insn->code) == BPF_X) {
14080                 if (insn->imm != 0) {
14081                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14082                         return -EINVAL;
14083                 }
14084
14085                 /* check src1 operand */
14086                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14087                 if (err)
14088                         return err;
14089
14090                 src_reg = &regs[insn->src_reg];
14091                 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14092                     is_pointer_value(env, insn->src_reg)) {
14093                         verbose(env, "R%d pointer comparison prohibited\n",
14094                                 insn->src_reg);
14095                         return -EACCES;
14096                 }
14097         } else {
14098                 if (insn->src_reg != BPF_REG_0) {
14099                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14100                         return -EINVAL;
14101                 }
14102         }
14103
14104         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14105
14106         if (BPF_SRC(insn->code) == BPF_K) {
14107                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14108         } else if (src_reg->type == SCALAR_VALUE &&
14109                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14110                 pred = is_branch_taken(dst_reg,
14111                                        tnum_subreg(src_reg->var_off).value,
14112                                        opcode,
14113                                        is_jmp32);
14114         } else if (src_reg->type == SCALAR_VALUE &&
14115                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14116                 pred = is_branch_taken(dst_reg,
14117                                        src_reg->var_off.value,
14118                                        opcode,
14119                                        is_jmp32);
14120         } else if (dst_reg->type == SCALAR_VALUE &&
14121                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14122                 pred = is_branch_taken(src_reg,
14123                                        tnum_subreg(dst_reg->var_off).value,
14124                                        flip_opcode(opcode),
14125                                        is_jmp32);
14126         } else if (dst_reg->type == SCALAR_VALUE &&
14127                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14128                 pred = is_branch_taken(src_reg,
14129                                        dst_reg->var_off.value,
14130                                        flip_opcode(opcode),
14131                                        is_jmp32);
14132         } else if (reg_is_pkt_pointer_any(dst_reg) &&
14133                    reg_is_pkt_pointer_any(src_reg) &&
14134                    !is_jmp32) {
14135                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14136         }
14137
14138         if (pred >= 0) {
14139                 /* If we get here with a dst_reg pointer type it is because
14140                  * above is_branch_taken() special cased the 0 comparison.
14141                  */
14142                 if (!__is_pointer_value(false, dst_reg))
14143                         err = mark_chain_precision(env, insn->dst_reg);
14144                 if (BPF_SRC(insn->code) == BPF_X && !err &&
14145                     !__is_pointer_value(false, src_reg))
14146                         err = mark_chain_precision(env, insn->src_reg);
14147                 if (err)
14148                         return err;
14149         }
14150
14151         if (pred == 1) {
14152                 /* Only follow the goto, ignore fall-through. If needed, push
14153                  * the fall-through branch for simulation under speculative
14154                  * execution.
14155                  */
14156                 if (!env->bypass_spec_v1 &&
14157                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
14158                                                *insn_idx))
14159                         return -EFAULT;
14160                 if (env->log.level & BPF_LOG_LEVEL)
14161                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14162                 *insn_idx += insn->off;
14163                 return 0;
14164         } else if (pred == 0) {
14165                 /* Only follow the fall-through branch, since that's where the
14166                  * program will go. If needed, push the goto branch for
14167                  * simulation under speculative execution.
14168                  */
14169                 if (!env->bypass_spec_v1 &&
14170                     !sanitize_speculative_path(env, insn,
14171                                                *insn_idx + insn->off + 1,
14172                                                *insn_idx))
14173                         return -EFAULT;
14174                 if (env->log.level & BPF_LOG_LEVEL)
14175                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14176                 return 0;
14177         }
14178
14179         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14180                                   false);
14181         if (!other_branch)
14182                 return -EFAULT;
14183         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14184
14185         /* detect if we are comparing against a constant value so we can adjust
14186          * our min/max values for our dst register.
14187          * this is only legit if both are scalars (or pointers to the same
14188          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14189          * because otherwise the different base pointers mean the offsets aren't
14190          * comparable.
14191          */
14192         if (BPF_SRC(insn->code) == BPF_X) {
14193                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14194
14195                 if (dst_reg->type == SCALAR_VALUE &&
14196                     src_reg->type == SCALAR_VALUE) {
14197                         if (tnum_is_const(src_reg->var_off) ||
14198                             (is_jmp32 &&
14199                              tnum_is_const(tnum_subreg(src_reg->var_off))))
14200                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14201                                                 dst_reg,
14202                                                 src_reg->var_off.value,
14203                                                 tnum_subreg(src_reg->var_off).value,
14204                                                 opcode, is_jmp32);
14205                         else if (tnum_is_const(dst_reg->var_off) ||
14206                                  (is_jmp32 &&
14207                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
14208                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14209                                                     src_reg,
14210                                                     dst_reg->var_off.value,
14211                                                     tnum_subreg(dst_reg->var_off).value,
14212                                                     opcode, is_jmp32);
14213                         else if (!is_jmp32 &&
14214                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
14215                                 /* Comparing for equality, we can combine knowledge */
14216                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14217                                                     &other_branch_regs[insn->dst_reg],
14218                                                     src_reg, dst_reg, opcode);
14219                         if (src_reg->id &&
14220                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14221                                 find_equal_scalars(this_branch, src_reg);
14222                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14223                         }
14224
14225                 }
14226         } else if (dst_reg->type == SCALAR_VALUE) {
14227                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14228                                         dst_reg, insn->imm, (u32)insn->imm,
14229                                         opcode, is_jmp32);
14230         }
14231
14232         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14233             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14234                 find_equal_scalars(this_branch, dst_reg);
14235                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14236         }
14237
14238         /* if one pointer register is compared to another pointer
14239          * register check if PTR_MAYBE_NULL could be lifted.
14240          * E.g. register A - maybe null
14241          *      register B - not null
14242          * for JNE A, B, ... - A is not null in the false branch;
14243          * for JEQ A, B, ... - A is not null in the true branch.
14244          *
14245          * Since PTR_TO_BTF_ID points to a kernel struct that does
14246          * not need to be null checked by the BPF program, i.e.,
14247          * could be null even without PTR_MAYBE_NULL marking, so
14248          * only propagate nullness when neither reg is that type.
14249          */
14250         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14251             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14252             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14253             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14254             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14255                 eq_branch_regs = NULL;
14256                 switch (opcode) {
14257                 case BPF_JEQ:
14258                         eq_branch_regs = other_branch_regs;
14259                         break;
14260                 case BPF_JNE:
14261                         eq_branch_regs = regs;
14262                         break;
14263                 default:
14264                         /* do nothing */
14265                         break;
14266                 }
14267                 if (eq_branch_regs) {
14268                         if (type_may_be_null(src_reg->type))
14269                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14270                         else
14271                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14272                 }
14273         }
14274
14275         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14276          * NOTE: these optimizations below are related with pointer comparison
14277          *       which will never be JMP32.
14278          */
14279         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14280             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14281             type_may_be_null(dst_reg->type)) {
14282                 /* Mark all identical registers in each branch as either
14283                  * safe or unknown depending R == 0 or R != 0 conditional.
14284                  */
14285                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14286                                       opcode == BPF_JNE);
14287                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14288                                       opcode == BPF_JEQ);
14289         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14290                                            this_branch, other_branch) &&
14291                    is_pointer_value(env, insn->dst_reg)) {
14292                 verbose(env, "R%d pointer comparison prohibited\n",
14293                         insn->dst_reg);
14294                 return -EACCES;
14295         }
14296         if (env->log.level & BPF_LOG_LEVEL)
14297                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14298         return 0;
14299 }
14300
14301 /* verify BPF_LD_IMM64 instruction */
14302 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14303 {
14304         struct bpf_insn_aux_data *aux = cur_aux(env);
14305         struct bpf_reg_state *regs = cur_regs(env);
14306         struct bpf_reg_state *dst_reg;
14307         struct bpf_map *map;
14308         int err;
14309
14310         if (BPF_SIZE(insn->code) != BPF_DW) {
14311                 verbose(env, "invalid BPF_LD_IMM insn\n");
14312                 return -EINVAL;
14313         }
14314         if (insn->off != 0) {
14315                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14316                 return -EINVAL;
14317         }
14318
14319         err = check_reg_arg(env, insn->dst_reg, DST_OP);
14320         if (err)
14321                 return err;
14322
14323         dst_reg = &regs[insn->dst_reg];
14324         if (insn->src_reg == 0) {
14325                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14326
14327                 dst_reg->type = SCALAR_VALUE;
14328                 __mark_reg_known(&regs[insn->dst_reg], imm);
14329                 return 0;
14330         }
14331
14332         /* All special src_reg cases are listed below. From this point onwards
14333          * we either succeed and assign a corresponding dst_reg->type after
14334          * zeroing the offset, or fail and reject the program.
14335          */
14336         mark_reg_known_zero(env, regs, insn->dst_reg);
14337
14338         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14339                 dst_reg->type = aux->btf_var.reg_type;
14340                 switch (base_type(dst_reg->type)) {
14341                 case PTR_TO_MEM:
14342                         dst_reg->mem_size = aux->btf_var.mem_size;
14343                         break;
14344                 case PTR_TO_BTF_ID:
14345                         dst_reg->btf = aux->btf_var.btf;
14346                         dst_reg->btf_id = aux->btf_var.btf_id;
14347                         break;
14348                 default:
14349                         verbose(env, "bpf verifier is misconfigured\n");
14350                         return -EFAULT;
14351                 }
14352                 return 0;
14353         }
14354
14355         if (insn->src_reg == BPF_PSEUDO_FUNC) {
14356                 struct bpf_prog_aux *aux = env->prog->aux;
14357                 u32 subprogno = find_subprog(env,
14358                                              env->insn_idx + insn->imm + 1);
14359
14360                 if (!aux->func_info) {
14361                         verbose(env, "missing btf func_info\n");
14362                         return -EINVAL;
14363                 }
14364                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14365                         verbose(env, "callback function not static\n");
14366                         return -EINVAL;
14367                 }
14368
14369                 dst_reg->type = PTR_TO_FUNC;
14370                 dst_reg->subprogno = subprogno;
14371                 return 0;
14372         }
14373
14374         map = env->used_maps[aux->map_index];
14375         dst_reg->map_ptr = map;
14376
14377         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14378             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14379                 dst_reg->type = PTR_TO_MAP_VALUE;
14380                 dst_reg->off = aux->map_off;
14381                 WARN_ON_ONCE(map->max_entries != 1);
14382                 /* We want reg->id to be same (0) as map_value is not distinct */
14383         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14384                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14385                 dst_reg->type = CONST_PTR_TO_MAP;
14386         } else {
14387                 verbose(env, "bpf verifier is misconfigured\n");
14388                 return -EINVAL;
14389         }
14390
14391         return 0;
14392 }
14393
14394 static bool may_access_skb(enum bpf_prog_type type)
14395 {
14396         switch (type) {
14397         case BPF_PROG_TYPE_SOCKET_FILTER:
14398         case BPF_PROG_TYPE_SCHED_CLS:
14399         case BPF_PROG_TYPE_SCHED_ACT:
14400                 return true;
14401         default:
14402                 return false;
14403         }
14404 }
14405
14406 /* verify safety of LD_ABS|LD_IND instructions:
14407  * - they can only appear in the programs where ctx == skb
14408  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14409  *   preserve R6-R9, and store return value into R0
14410  *
14411  * Implicit input:
14412  *   ctx == skb == R6 == CTX
14413  *
14414  * Explicit input:
14415  *   SRC == any register
14416  *   IMM == 32-bit immediate
14417  *
14418  * Output:
14419  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14420  */
14421 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14422 {
14423         struct bpf_reg_state *regs = cur_regs(env);
14424         static const int ctx_reg = BPF_REG_6;
14425         u8 mode = BPF_MODE(insn->code);
14426         int i, err;
14427
14428         if (!may_access_skb(resolve_prog_type(env->prog))) {
14429                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14430                 return -EINVAL;
14431         }
14432
14433         if (!env->ops->gen_ld_abs) {
14434                 verbose(env, "bpf verifier is misconfigured\n");
14435                 return -EINVAL;
14436         }
14437
14438         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14439             BPF_SIZE(insn->code) == BPF_DW ||
14440             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14441                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14442                 return -EINVAL;
14443         }
14444
14445         /* check whether implicit source operand (register R6) is readable */
14446         err = check_reg_arg(env, ctx_reg, SRC_OP);
14447         if (err)
14448                 return err;
14449
14450         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14451          * gen_ld_abs() may terminate the program at runtime, leading to
14452          * reference leak.
14453          */
14454         err = check_reference_leak(env);
14455         if (err) {
14456                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14457                 return err;
14458         }
14459
14460         if (env->cur_state->active_lock.ptr) {
14461                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14462                 return -EINVAL;
14463         }
14464
14465         if (env->cur_state->active_rcu_lock) {
14466                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14467                 return -EINVAL;
14468         }
14469
14470         if (regs[ctx_reg].type != PTR_TO_CTX) {
14471                 verbose(env,
14472                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14473                 return -EINVAL;
14474         }
14475
14476         if (mode == BPF_IND) {
14477                 /* check explicit source operand */
14478                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14479                 if (err)
14480                         return err;
14481         }
14482
14483         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14484         if (err < 0)
14485                 return err;
14486
14487         /* reset caller saved regs to unreadable */
14488         for (i = 0; i < CALLER_SAVED_REGS; i++) {
14489                 mark_reg_not_init(env, regs, caller_saved[i]);
14490                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14491         }
14492
14493         /* mark destination R0 register as readable, since it contains
14494          * the value fetched from the packet.
14495          * Already marked as written above.
14496          */
14497         mark_reg_unknown(env, regs, BPF_REG_0);
14498         /* ld_abs load up to 32-bit skb data. */
14499         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14500         return 0;
14501 }
14502
14503 static int check_return_code(struct bpf_verifier_env *env)
14504 {
14505         struct tnum enforce_attach_type_range = tnum_unknown;
14506         const struct bpf_prog *prog = env->prog;
14507         struct bpf_reg_state *reg;
14508         struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14509         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14510         int err;
14511         struct bpf_func_state *frame = env->cur_state->frame[0];
14512         const bool is_subprog = frame->subprogno;
14513
14514         /* LSM and struct_ops func-ptr's return type could be "void" */
14515         if (!is_subprog) {
14516                 switch (prog_type) {
14517                 case BPF_PROG_TYPE_LSM:
14518                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
14519                                 /* See below, can be 0 or 0-1 depending on hook. */
14520                                 break;
14521                         fallthrough;
14522                 case BPF_PROG_TYPE_STRUCT_OPS:
14523                         if (!prog->aux->attach_func_proto->type)
14524                                 return 0;
14525                         break;
14526                 default:
14527                         break;
14528                 }
14529         }
14530
14531         /* eBPF calling convention is such that R0 is used
14532          * to return the value from eBPF program.
14533          * Make sure that it's readable at this time
14534          * of bpf_exit, which means that program wrote
14535          * something into it earlier
14536          */
14537         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14538         if (err)
14539                 return err;
14540
14541         if (is_pointer_value(env, BPF_REG_0)) {
14542                 verbose(env, "R0 leaks addr as return value\n");
14543                 return -EACCES;
14544         }
14545
14546         reg = cur_regs(env) + BPF_REG_0;
14547
14548         if (frame->in_async_callback_fn) {
14549                 /* enforce return zero from async callbacks like timer */
14550                 if (reg->type != SCALAR_VALUE) {
14551                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14552                                 reg_type_str(env, reg->type));
14553                         return -EINVAL;
14554                 }
14555
14556                 if (!tnum_in(const_0, reg->var_off)) {
14557                         verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14558                         return -EINVAL;
14559                 }
14560                 return 0;
14561         }
14562
14563         if (is_subprog) {
14564                 if (reg->type != SCALAR_VALUE) {
14565                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14566                                 reg_type_str(env, reg->type));
14567                         return -EINVAL;
14568                 }
14569                 return 0;
14570         }
14571
14572         switch (prog_type) {
14573         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14574                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14575                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14576                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14577                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14578                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14579                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14580                         range = tnum_range(1, 1);
14581                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14582                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14583                         range = tnum_range(0, 3);
14584                 break;
14585         case BPF_PROG_TYPE_CGROUP_SKB:
14586                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14587                         range = tnum_range(0, 3);
14588                         enforce_attach_type_range = tnum_range(2, 3);
14589                 }
14590                 break;
14591         case BPF_PROG_TYPE_CGROUP_SOCK:
14592         case BPF_PROG_TYPE_SOCK_OPS:
14593         case BPF_PROG_TYPE_CGROUP_DEVICE:
14594         case BPF_PROG_TYPE_CGROUP_SYSCTL:
14595         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14596                 break;
14597         case BPF_PROG_TYPE_RAW_TRACEPOINT:
14598                 if (!env->prog->aux->attach_btf_id)
14599                         return 0;
14600                 range = tnum_const(0);
14601                 break;
14602         case BPF_PROG_TYPE_TRACING:
14603                 switch (env->prog->expected_attach_type) {
14604                 case BPF_TRACE_FENTRY:
14605                 case BPF_TRACE_FEXIT:
14606                         range = tnum_const(0);
14607                         break;
14608                 case BPF_TRACE_RAW_TP:
14609                 case BPF_MODIFY_RETURN:
14610                         return 0;
14611                 case BPF_TRACE_ITER:
14612                         break;
14613                 default:
14614                         return -ENOTSUPP;
14615                 }
14616                 break;
14617         case BPF_PROG_TYPE_SK_LOOKUP:
14618                 range = tnum_range(SK_DROP, SK_PASS);
14619                 break;
14620
14621         case BPF_PROG_TYPE_LSM:
14622                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14623                         /* Regular BPF_PROG_TYPE_LSM programs can return
14624                          * any value.
14625                          */
14626                         return 0;
14627                 }
14628                 if (!env->prog->aux->attach_func_proto->type) {
14629                         /* Make sure programs that attach to void
14630                          * hooks don't try to modify return value.
14631                          */
14632                         range = tnum_range(1, 1);
14633                 }
14634                 break;
14635
14636         case BPF_PROG_TYPE_NETFILTER:
14637                 range = tnum_range(NF_DROP, NF_ACCEPT);
14638                 break;
14639         case BPF_PROG_TYPE_EXT:
14640                 /* freplace program can return anything as its return value
14641                  * depends on the to-be-replaced kernel func or bpf program.
14642                  */
14643         default:
14644                 return 0;
14645         }
14646
14647         if (reg->type != SCALAR_VALUE) {
14648                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14649                         reg_type_str(env, reg->type));
14650                 return -EINVAL;
14651         }
14652
14653         if (!tnum_in(range, reg->var_off)) {
14654                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14655                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14656                     prog_type == BPF_PROG_TYPE_LSM &&
14657                     !prog->aux->attach_func_proto->type)
14658                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14659                 return -EINVAL;
14660         }
14661
14662         if (!tnum_is_unknown(enforce_attach_type_range) &&
14663             tnum_in(enforce_attach_type_range, reg->var_off))
14664                 env->prog->enforce_expected_attach_type = 1;
14665         return 0;
14666 }
14667
14668 /* non-recursive DFS pseudo code
14669  * 1  procedure DFS-iterative(G,v):
14670  * 2      label v as discovered
14671  * 3      let S be a stack
14672  * 4      S.push(v)
14673  * 5      while S is not empty
14674  * 6            t <- S.peek()
14675  * 7            if t is what we're looking for:
14676  * 8                return t
14677  * 9            for all edges e in G.adjacentEdges(t) do
14678  * 10               if edge e is already labelled
14679  * 11                   continue with the next edge
14680  * 12               w <- G.adjacentVertex(t,e)
14681  * 13               if vertex w is not discovered and not explored
14682  * 14                   label e as tree-edge
14683  * 15                   label w as discovered
14684  * 16                   S.push(w)
14685  * 17                   continue at 5
14686  * 18               else if vertex w is discovered
14687  * 19                   label e as back-edge
14688  * 20               else
14689  * 21                   // vertex w is explored
14690  * 22                   label e as forward- or cross-edge
14691  * 23           label t as explored
14692  * 24           S.pop()
14693  *
14694  * convention:
14695  * 0x10 - discovered
14696  * 0x11 - discovered and fall-through edge labelled
14697  * 0x12 - discovered and fall-through and branch edges labelled
14698  * 0x20 - explored
14699  */
14700
14701 enum {
14702         DISCOVERED = 0x10,
14703         EXPLORED = 0x20,
14704         FALLTHROUGH = 1,
14705         BRANCH = 2,
14706 };
14707
14708 static u32 state_htab_size(struct bpf_verifier_env *env)
14709 {
14710         return env->prog->len;
14711 }
14712
14713 static struct bpf_verifier_state_list **explored_state(
14714                                         struct bpf_verifier_env *env,
14715                                         int idx)
14716 {
14717         struct bpf_verifier_state *cur = env->cur_state;
14718         struct bpf_func_state *state = cur->frame[cur->curframe];
14719
14720         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14721 }
14722
14723 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14724 {
14725         env->insn_aux_data[idx].prune_point = true;
14726 }
14727
14728 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14729 {
14730         return env->insn_aux_data[insn_idx].prune_point;
14731 }
14732
14733 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14734 {
14735         env->insn_aux_data[idx].force_checkpoint = true;
14736 }
14737
14738 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14739 {
14740         return env->insn_aux_data[insn_idx].force_checkpoint;
14741 }
14742
14743
14744 enum {
14745         DONE_EXPLORING = 0,
14746         KEEP_EXPLORING = 1,
14747 };
14748
14749 /* t, w, e - match pseudo-code above:
14750  * t - index of current instruction
14751  * w - next instruction
14752  * e - edge
14753  */
14754 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
14755 {
14756         int *insn_stack = env->cfg.insn_stack;
14757         int *insn_state = env->cfg.insn_state;
14758
14759         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14760                 return DONE_EXPLORING;
14761
14762         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14763                 return DONE_EXPLORING;
14764
14765         if (w < 0 || w >= env->prog->len) {
14766                 verbose_linfo(env, t, "%d: ", t);
14767                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14768                 return -EINVAL;
14769         }
14770
14771         if (e == BRANCH) {
14772                 /* mark branch target for state pruning */
14773                 mark_prune_point(env, w);
14774                 mark_jmp_point(env, w);
14775         }
14776
14777         if (insn_state[w] == 0) {
14778                 /* tree-edge */
14779                 insn_state[t] = DISCOVERED | e;
14780                 insn_state[w] = DISCOVERED;
14781                 if (env->cfg.cur_stack >= env->prog->len)
14782                         return -E2BIG;
14783                 insn_stack[env->cfg.cur_stack++] = w;
14784                 return KEEP_EXPLORING;
14785         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14786                 if (env->bpf_capable)
14787                         return DONE_EXPLORING;
14788                 verbose_linfo(env, t, "%d: ", t);
14789                 verbose_linfo(env, w, "%d: ", w);
14790                 verbose(env, "back-edge from insn %d to %d\n", t, w);
14791                 return -EINVAL;
14792         } else if (insn_state[w] == EXPLORED) {
14793                 /* forward- or cross-edge */
14794                 insn_state[t] = DISCOVERED | e;
14795         } else {
14796                 verbose(env, "insn state internal bug\n");
14797                 return -EFAULT;
14798         }
14799         return DONE_EXPLORING;
14800 }
14801
14802 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14803                                 struct bpf_verifier_env *env,
14804                                 bool visit_callee)
14805 {
14806         int ret, insn_sz;
14807
14808         insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
14809         ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
14810         if (ret)
14811                 return ret;
14812
14813         mark_prune_point(env, t + insn_sz);
14814         /* when we exit from subprog, we need to record non-linear history */
14815         mark_jmp_point(env, t + insn_sz);
14816
14817         if (visit_callee) {
14818                 mark_prune_point(env, t);
14819                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
14820         }
14821         return ret;
14822 }
14823
14824 /* Visits the instruction at index t and returns one of the following:
14825  *  < 0 - an error occurred
14826  *  DONE_EXPLORING - the instruction was fully explored
14827  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14828  */
14829 static int visit_insn(int t, struct bpf_verifier_env *env)
14830 {
14831         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14832         int ret, off, insn_sz;
14833
14834         if (bpf_pseudo_func(insn))
14835                 return visit_func_call_insn(t, insns, env, true);
14836
14837         /* All non-branch instructions have a single fall-through edge. */
14838         if (BPF_CLASS(insn->code) != BPF_JMP &&
14839             BPF_CLASS(insn->code) != BPF_JMP32) {
14840                 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
14841                 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
14842         }
14843
14844         switch (BPF_OP(insn->code)) {
14845         case BPF_EXIT:
14846                 return DONE_EXPLORING;
14847
14848         case BPF_CALL:
14849                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14850                         /* Mark this call insn as a prune point to trigger
14851                          * is_state_visited() check before call itself is
14852                          * processed by __check_func_call(). Otherwise new
14853                          * async state will be pushed for further exploration.
14854                          */
14855                         mark_prune_point(env, t);
14856                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14857                         struct bpf_kfunc_call_arg_meta meta;
14858
14859                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14860                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
14861                                 mark_prune_point(env, t);
14862                                 /* Checking and saving state checkpoints at iter_next() call
14863                                  * is crucial for fast convergence of open-coded iterator loop
14864                                  * logic, so we need to force it. If we don't do that,
14865                                  * is_state_visited() might skip saving a checkpoint, causing
14866                                  * unnecessarily long sequence of not checkpointed
14867                                  * instructions and jumps, leading to exhaustion of jump
14868                                  * history buffer, and potentially other undesired outcomes.
14869                                  * It is expected that with correct open-coded iterators
14870                                  * convergence will happen quickly, so we don't run a risk of
14871                                  * exhausting memory.
14872                                  */
14873                                 mark_force_checkpoint(env, t);
14874                         }
14875                 }
14876                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14877
14878         case BPF_JA:
14879                 if (BPF_SRC(insn->code) != BPF_K)
14880                         return -EINVAL;
14881
14882                 if (BPF_CLASS(insn->code) == BPF_JMP)
14883                         off = insn->off;
14884                 else
14885                         off = insn->imm;
14886
14887                 /* unconditional jump with single edge */
14888                 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
14889                 if (ret)
14890                         return ret;
14891
14892                 mark_prune_point(env, t + off + 1);
14893                 mark_jmp_point(env, t + off + 1);
14894
14895                 return ret;
14896
14897         default:
14898                 /* conditional jump with two edges */
14899                 mark_prune_point(env, t);
14900
14901                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
14902                 if (ret)
14903                         return ret;
14904
14905                 return push_insn(t, t + insn->off + 1, BRANCH, env);
14906         }
14907 }
14908
14909 /* non-recursive depth-first-search to detect loops in BPF program
14910  * loop == back-edge in directed graph
14911  */
14912 static int check_cfg(struct bpf_verifier_env *env)
14913 {
14914         int insn_cnt = env->prog->len;
14915         int *insn_stack, *insn_state;
14916         int ret = 0;
14917         int i;
14918
14919         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14920         if (!insn_state)
14921                 return -ENOMEM;
14922
14923         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14924         if (!insn_stack) {
14925                 kvfree(insn_state);
14926                 return -ENOMEM;
14927         }
14928
14929         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14930         insn_stack[0] = 0; /* 0 is the first instruction */
14931         env->cfg.cur_stack = 1;
14932
14933         while (env->cfg.cur_stack > 0) {
14934                 int t = insn_stack[env->cfg.cur_stack - 1];
14935
14936                 ret = visit_insn(t, env);
14937                 switch (ret) {
14938                 case DONE_EXPLORING:
14939                         insn_state[t] = EXPLORED;
14940                         env->cfg.cur_stack--;
14941                         break;
14942                 case KEEP_EXPLORING:
14943                         break;
14944                 default:
14945                         if (ret > 0) {
14946                                 verbose(env, "visit_insn internal bug\n");
14947                                 ret = -EFAULT;
14948                         }
14949                         goto err_free;
14950                 }
14951         }
14952
14953         if (env->cfg.cur_stack < 0) {
14954                 verbose(env, "pop stack internal bug\n");
14955                 ret = -EFAULT;
14956                 goto err_free;
14957         }
14958
14959         for (i = 0; i < insn_cnt; i++) {
14960                 struct bpf_insn *insn = &env->prog->insnsi[i];
14961
14962                 if (insn_state[i] != EXPLORED) {
14963                         verbose(env, "unreachable insn %d\n", i);
14964                         ret = -EINVAL;
14965                         goto err_free;
14966                 }
14967                 if (bpf_is_ldimm64(insn)) {
14968                         if (insn_state[i + 1] != 0) {
14969                                 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
14970                                 ret = -EINVAL;
14971                                 goto err_free;
14972                         }
14973                         i++; /* skip second half of ldimm64 */
14974                 }
14975         }
14976         ret = 0; /* cfg looks good */
14977
14978 err_free:
14979         kvfree(insn_state);
14980         kvfree(insn_stack);
14981         env->cfg.insn_state = env->cfg.insn_stack = NULL;
14982         return ret;
14983 }
14984
14985 static int check_abnormal_return(struct bpf_verifier_env *env)
14986 {
14987         int i;
14988
14989         for (i = 1; i < env->subprog_cnt; i++) {
14990                 if (env->subprog_info[i].has_ld_abs) {
14991                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14992                         return -EINVAL;
14993                 }
14994                 if (env->subprog_info[i].has_tail_call) {
14995                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14996                         return -EINVAL;
14997                 }
14998         }
14999         return 0;
15000 }
15001
15002 /* The minimum supported BTF func info size */
15003 #define MIN_BPF_FUNCINFO_SIZE   8
15004 #define MAX_FUNCINFO_REC_SIZE   252
15005
15006 static int check_btf_func(struct bpf_verifier_env *env,
15007                           const union bpf_attr *attr,
15008                           bpfptr_t uattr)
15009 {
15010         const struct btf_type *type, *func_proto, *ret_type;
15011         u32 i, nfuncs, urec_size, min_size;
15012         u32 krec_size = sizeof(struct bpf_func_info);
15013         struct bpf_func_info *krecord;
15014         struct bpf_func_info_aux *info_aux = NULL;
15015         struct bpf_prog *prog;
15016         const struct btf *btf;
15017         bpfptr_t urecord;
15018         u32 prev_offset = 0;
15019         bool scalar_return;
15020         int ret = -ENOMEM;
15021
15022         nfuncs = attr->func_info_cnt;
15023         if (!nfuncs) {
15024                 if (check_abnormal_return(env))
15025                         return -EINVAL;
15026                 return 0;
15027         }
15028
15029         if (nfuncs != env->subprog_cnt) {
15030                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15031                 return -EINVAL;
15032         }
15033
15034         urec_size = attr->func_info_rec_size;
15035         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15036             urec_size > MAX_FUNCINFO_REC_SIZE ||
15037             urec_size % sizeof(u32)) {
15038                 verbose(env, "invalid func info rec size %u\n", urec_size);
15039                 return -EINVAL;
15040         }
15041
15042         prog = env->prog;
15043         btf = prog->aux->btf;
15044
15045         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15046         min_size = min_t(u32, krec_size, urec_size);
15047
15048         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15049         if (!krecord)
15050                 return -ENOMEM;
15051         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15052         if (!info_aux)
15053                 goto err_free;
15054
15055         for (i = 0; i < nfuncs; i++) {
15056                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15057                 if (ret) {
15058                         if (ret == -E2BIG) {
15059                                 verbose(env, "nonzero tailing record in func info");
15060                                 /* set the size kernel expects so loader can zero
15061                                  * out the rest of the record.
15062                                  */
15063                                 if (copy_to_bpfptr_offset(uattr,
15064                                                           offsetof(union bpf_attr, func_info_rec_size),
15065                                                           &min_size, sizeof(min_size)))
15066                                         ret = -EFAULT;
15067                         }
15068                         goto err_free;
15069                 }
15070
15071                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15072                         ret = -EFAULT;
15073                         goto err_free;
15074                 }
15075
15076                 /* check insn_off */
15077                 ret = -EINVAL;
15078                 if (i == 0) {
15079                         if (krecord[i].insn_off) {
15080                                 verbose(env,
15081                                         "nonzero insn_off %u for the first func info record",
15082                                         krecord[i].insn_off);
15083                                 goto err_free;
15084                         }
15085                 } else if (krecord[i].insn_off <= prev_offset) {
15086                         verbose(env,
15087                                 "same or smaller insn offset (%u) than previous func info record (%u)",
15088                                 krecord[i].insn_off, prev_offset);
15089                         goto err_free;
15090                 }
15091
15092                 if (env->subprog_info[i].start != krecord[i].insn_off) {
15093                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15094                         goto err_free;
15095                 }
15096
15097                 /* check type_id */
15098                 type = btf_type_by_id(btf, krecord[i].type_id);
15099                 if (!type || !btf_type_is_func(type)) {
15100                         verbose(env, "invalid type id %d in func info",
15101                                 krecord[i].type_id);
15102                         goto err_free;
15103                 }
15104                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15105
15106                 func_proto = btf_type_by_id(btf, type->type);
15107                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15108                         /* btf_func_check() already verified it during BTF load */
15109                         goto err_free;
15110                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15111                 scalar_return =
15112                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15113                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15114                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15115                         goto err_free;
15116                 }
15117                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15118                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15119                         goto err_free;
15120                 }
15121
15122                 prev_offset = krecord[i].insn_off;
15123                 bpfptr_add(&urecord, urec_size);
15124         }
15125
15126         prog->aux->func_info = krecord;
15127         prog->aux->func_info_cnt = nfuncs;
15128         prog->aux->func_info_aux = info_aux;
15129         return 0;
15130
15131 err_free:
15132         kvfree(krecord);
15133         kfree(info_aux);
15134         return ret;
15135 }
15136
15137 static void adjust_btf_func(struct bpf_verifier_env *env)
15138 {
15139         struct bpf_prog_aux *aux = env->prog->aux;
15140         int i;
15141
15142         if (!aux->func_info)
15143                 return;
15144
15145         for (i = 0; i < env->subprog_cnt; i++)
15146                 aux->func_info[i].insn_off = env->subprog_info[i].start;
15147 }
15148
15149 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
15150 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
15151
15152 static int check_btf_line(struct bpf_verifier_env *env,
15153                           const union bpf_attr *attr,
15154                           bpfptr_t uattr)
15155 {
15156         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15157         struct bpf_subprog_info *sub;
15158         struct bpf_line_info *linfo;
15159         struct bpf_prog *prog;
15160         const struct btf *btf;
15161         bpfptr_t ulinfo;
15162         int err;
15163
15164         nr_linfo = attr->line_info_cnt;
15165         if (!nr_linfo)
15166                 return 0;
15167         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15168                 return -EINVAL;
15169
15170         rec_size = attr->line_info_rec_size;
15171         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15172             rec_size > MAX_LINEINFO_REC_SIZE ||
15173             rec_size & (sizeof(u32) - 1))
15174                 return -EINVAL;
15175
15176         /* Need to zero it in case the userspace may
15177          * pass in a smaller bpf_line_info object.
15178          */
15179         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15180                          GFP_KERNEL | __GFP_NOWARN);
15181         if (!linfo)
15182                 return -ENOMEM;
15183
15184         prog = env->prog;
15185         btf = prog->aux->btf;
15186
15187         s = 0;
15188         sub = env->subprog_info;
15189         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15190         expected_size = sizeof(struct bpf_line_info);
15191         ncopy = min_t(u32, expected_size, rec_size);
15192         for (i = 0; i < nr_linfo; i++) {
15193                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15194                 if (err) {
15195                         if (err == -E2BIG) {
15196                                 verbose(env, "nonzero tailing record in line_info");
15197                                 if (copy_to_bpfptr_offset(uattr,
15198                                                           offsetof(union bpf_attr, line_info_rec_size),
15199                                                           &expected_size, sizeof(expected_size)))
15200                                         err = -EFAULT;
15201                         }
15202                         goto err_free;
15203                 }
15204
15205                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15206                         err = -EFAULT;
15207                         goto err_free;
15208                 }
15209
15210                 /*
15211                  * Check insn_off to ensure
15212                  * 1) strictly increasing AND
15213                  * 2) bounded by prog->len
15214                  *
15215                  * The linfo[0].insn_off == 0 check logically falls into
15216                  * the later "missing bpf_line_info for func..." case
15217                  * because the first linfo[0].insn_off must be the
15218                  * first sub also and the first sub must have
15219                  * subprog_info[0].start == 0.
15220                  */
15221                 if ((i && linfo[i].insn_off <= prev_offset) ||
15222                     linfo[i].insn_off >= prog->len) {
15223                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15224                                 i, linfo[i].insn_off, prev_offset,
15225                                 prog->len);
15226                         err = -EINVAL;
15227                         goto err_free;
15228                 }
15229
15230                 if (!prog->insnsi[linfo[i].insn_off].code) {
15231                         verbose(env,
15232                                 "Invalid insn code at line_info[%u].insn_off\n",
15233                                 i);
15234                         err = -EINVAL;
15235                         goto err_free;
15236                 }
15237
15238                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15239                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15240                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15241                         err = -EINVAL;
15242                         goto err_free;
15243                 }
15244
15245                 if (s != env->subprog_cnt) {
15246                         if (linfo[i].insn_off == sub[s].start) {
15247                                 sub[s].linfo_idx = i;
15248                                 s++;
15249                         } else if (sub[s].start < linfo[i].insn_off) {
15250                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
15251                                 err = -EINVAL;
15252                                 goto err_free;
15253                         }
15254                 }
15255
15256                 prev_offset = linfo[i].insn_off;
15257                 bpfptr_add(&ulinfo, rec_size);
15258         }
15259
15260         if (s != env->subprog_cnt) {
15261                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15262                         env->subprog_cnt - s, s);
15263                 err = -EINVAL;
15264                 goto err_free;
15265         }
15266
15267         prog->aux->linfo = linfo;
15268         prog->aux->nr_linfo = nr_linfo;
15269
15270         return 0;
15271
15272 err_free:
15273         kvfree(linfo);
15274         return err;
15275 }
15276
15277 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
15278 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
15279
15280 static int check_core_relo(struct bpf_verifier_env *env,
15281                            const union bpf_attr *attr,
15282                            bpfptr_t uattr)
15283 {
15284         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15285         struct bpf_core_relo core_relo = {};
15286         struct bpf_prog *prog = env->prog;
15287         const struct btf *btf = prog->aux->btf;
15288         struct bpf_core_ctx ctx = {
15289                 .log = &env->log,
15290                 .btf = btf,
15291         };
15292         bpfptr_t u_core_relo;
15293         int err;
15294
15295         nr_core_relo = attr->core_relo_cnt;
15296         if (!nr_core_relo)
15297                 return 0;
15298         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15299                 return -EINVAL;
15300
15301         rec_size = attr->core_relo_rec_size;
15302         if (rec_size < MIN_CORE_RELO_SIZE ||
15303             rec_size > MAX_CORE_RELO_SIZE ||
15304             rec_size % sizeof(u32))
15305                 return -EINVAL;
15306
15307         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15308         expected_size = sizeof(struct bpf_core_relo);
15309         ncopy = min_t(u32, expected_size, rec_size);
15310
15311         /* Unlike func_info and line_info, copy and apply each CO-RE
15312          * relocation record one at a time.
15313          */
15314         for (i = 0; i < nr_core_relo; i++) {
15315                 /* future proofing when sizeof(bpf_core_relo) changes */
15316                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15317                 if (err) {
15318                         if (err == -E2BIG) {
15319                                 verbose(env, "nonzero tailing record in core_relo");
15320                                 if (copy_to_bpfptr_offset(uattr,
15321                                                           offsetof(union bpf_attr, core_relo_rec_size),
15322                                                           &expected_size, sizeof(expected_size)))
15323                                         err = -EFAULT;
15324                         }
15325                         break;
15326                 }
15327
15328                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15329                         err = -EFAULT;
15330                         break;
15331                 }
15332
15333                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15334                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15335                                 i, core_relo.insn_off, prog->len);
15336                         err = -EINVAL;
15337                         break;
15338                 }
15339
15340                 err = bpf_core_apply(&ctx, &core_relo, i,
15341                                      &prog->insnsi[core_relo.insn_off / 8]);
15342                 if (err)
15343                         break;
15344                 bpfptr_add(&u_core_relo, rec_size);
15345         }
15346         return err;
15347 }
15348
15349 static int check_btf_info(struct bpf_verifier_env *env,
15350                           const union bpf_attr *attr,
15351                           bpfptr_t uattr)
15352 {
15353         struct btf *btf;
15354         int err;
15355
15356         if (!attr->func_info_cnt && !attr->line_info_cnt) {
15357                 if (check_abnormal_return(env))
15358                         return -EINVAL;
15359                 return 0;
15360         }
15361
15362         btf = btf_get_by_fd(attr->prog_btf_fd);
15363         if (IS_ERR(btf))
15364                 return PTR_ERR(btf);
15365         if (btf_is_kernel(btf)) {
15366                 btf_put(btf);
15367                 return -EACCES;
15368         }
15369         env->prog->aux->btf = btf;
15370
15371         err = check_btf_func(env, attr, uattr);
15372         if (err)
15373                 return err;
15374
15375         err = check_btf_line(env, attr, uattr);
15376         if (err)
15377                 return err;
15378
15379         err = check_core_relo(env, attr, uattr);
15380         if (err)
15381                 return err;
15382
15383         return 0;
15384 }
15385
15386 /* check %cur's range satisfies %old's */
15387 static bool range_within(struct bpf_reg_state *old,
15388                          struct bpf_reg_state *cur)
15389 {
15390         return old->umin_value <= cur->umin_value &&
15391                old->umax_value >= cur->umax_value &&
15392                old->smin_value <= cur->smin_value &&
15393                old->smax_value >= cur->smax_value &&
15394                old->u32_min_value <= cur->u32_min_value &&
15395                old->u32_max_value >= cur->u32_max_value &&
15396                old->s32_min_value <= cur->s32_min_value &&
15397                old->s32_max_value >= cur->s32_max_value;
15398 }
15399
15400 /* If in the old state two registers had the same id, then they need to have
15401  * the same id in the new state as well.  But that id could be different from
15402  * the old state, so we need to track the mapping from old to new ids.
15403  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15404  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15405  * regs with a different old id could still have new id 9, we don't care about
15406  * that.
15407  * So we look through our idmap to see if this old id has been seen before.  If
15408  * so, we require the new id to match; otherwise, we add the id pair to the map.
15409  */
15410 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15411 {
15412         struct bpf_id_pair *map = idmap->map;
15413         unsigned int i;
15414
15415         /* either both IDs should be set or both should be zero */
15416         if (!!old_id != !!cur_id)
15417                 return false;
15418
15419         if (old_id == 0) /* cur_id == 0 as well */
15420                 return true;
15421
15422         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15423                 if (!map[i].old) {
15424                         /* Reached an empty slot; haven't seen this id before */
15425                         map[i].old = old_id;
15426                         map[i].cur = cur_id;
15427                         return true;
15428                 }
15429                 if (map[i].old == old_id)
15430                         return map[i].cur == cur_id;
15431                 if (map[i].cur == cur_id)
15432                         return false;
15433         }
15434         /* We ran out of idmap slots, which should be impossible */
15435         WARN_ON_ONCE(1);
15436         return false;
15437 }
15438
15439 /* Similar to check_ids(), but allocate a unique temporary ID
15440  * for 'old_id' or 'cur_id' of zero.
15441  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15442  */
15443 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15444 {
15445         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15446         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15447
15448         return check_ids(old_id, cur_id, idmap);
15449 }
15450
15451 static void clean_func_state(struct bpf_verifier_env *env,
15452                              struct bpf_func_state *st)
15453 {
15454         enum bpf_reg_liveness live;
15455         int i, j;
15456
15457         for (i = 0; i < BPF_REG_FP; i++) {
15458                 live = st->regs[i].live;
15459                 /* liveness must not touch this register anymore */
15460                 st->regs[i].live |= REG_LIVE_DONE;
15461                 if (!(live & REG_LIVE_READ))
15462                         /* since the register is unused, clear its state
15463                          * to make further comparison simpler
15464                          */
15465                         __mark_reg_not_init(env, &st->regs[i]);
15466         }
15467
15468         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15469                 live = st->stack[i].spilled_ptr.live;
15470                 /* liveness must not touch this stack slot anymore */
15471                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15472                 if (!(live & REG_LIVE_READ)) {
15473                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15474                         for (j = 0; j < BPF_REG_SIZE; j++)
15475                                 st->stack[i].slot_type[j] = STACK_INVALID;
15476                 }
15477         }
15478 }
15479
15480 static void clean_verifier_state(struct bpf_verifier_env *env,
15481                                  struct bpf_verifier_state *st)
15482 {
15483         int i;
15484
15485         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15486                 /* all regs in this state in all frames were already marked */
15487                 return;
15488
15489         for (i = 0; i <= st->curframe; i++)
15490                 clean_func_state(env, st->frame[i]);
15491 }
15492
15493 /* the parentage chains form a tree.
15494  * the verifier states are added to state lists at given insn and
15495  * pushed into state stack for future exploration.
15496  * when the verifier reaches bpf_exit insn some of the verifer states
15497  * stored in the state lists have their final liveness state already,
15498  * but a lot of states will get revised from liveness point of view when
15499  * the verifier explores other branches.
15500  * Example:
15501  * 1: r0 = 1
15502  * 2: if r1 == 100 goto pc+1
15503  * 3: r0 = 2
15504  * 4: exit
15505  * when the verifier reaches exit insn the register r0 in the state list of
15506  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15507  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15508  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15509  *
15510  * Since the verifier pushes the branch states as it sees them while exploring
15511  * the program the condition of walking the branch instruction for the second
15512  * time means that all states below this branch were already explored and
15513  * their final liveness marks are already propagated.
15514  * Hence when the verifier completes the search of state list in is_state_visited()
15515  * we can call this clean_live_states() function to mark all liveness states
15516  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15517  * will not be used.
15518  * This function also clears the registers and stack for states that !READ
15519  * to simplify state merging.
15520  *
15521  * Important note here that walking the same branch instruction in the callee
15522  * doesn't meant that the states are DONE. The verifier has to compare
15523  * the callsites
15524  */
15525 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15526                               struct bpf_verifier_state *cur)
15527 {
15528         struct bpf_verifier_state_list *sl;
15529         int i;
15530
15531         sl = *explored_state(env, insn);
15532         while (sl) {
15533                 if (sl->state.branches)
15534                         goto next;
15535                 if (sl->state.insn_idx != insn ||
15536                     sl->state.curframe != cur->curframe)
15537                         goto next;
15538                 for (i = 0; i <= cur->curframe; i++)
15539                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15540                                 goto next;
15541                 clean_verifier_state(env, &sl->state);
15542 next:
15543                 sl = sl->next;
15544         }
15545 }
15546
15547 static bool regs_exact(const struct bpf_reg_state *rold,
15548                        const struct bpf_reg_state *rcur,
15549                        struct bpf_idmap *idmap)
15550 {
15551         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15552                check_ids(rold->id, rcur->id, idmap) &&
15553                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15554 }
15555
15556 /* Returns true if (rold safe implies rcur safe) */
15557 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15558                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15559 {
15560         if (!(rold->live & REG_LIVE_READ))
15561                 /* explored state didn't use this */
15562                 return true;
15563         if (rold->type == NOT_INIT)
15564                 /* explored state can't have used this */
15565                 return true;
15566         if (rcur->type == NOT_INIT)
15567                 return false;
15568
15569         /* Enforce that register types have to match exactly, including their
15570          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15571          * rule.
15572          *
15573          * One can make a point that using a pointer register as unbounded
15574          * SCALAR would be technically acceptable, but this could lead to
15575          * pointer leaks because scalars are allowed to leak while pointers
15576          * are not. We could make this safe in special cases if root is
15577          * calling us, but it's probably not worth the hassle.
15578          *
15579          * Also, register types that are *not* MAYBE_NULL could technically be
15580          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15581          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15582          * to the same map).
15583          * However, if the old MAYBE_NULL register then got NULL checked,
15584          * doing so could have affected others with the same id, and we can't
15585          * check for that because we lost the id when we converted to
15586          * a non-MAYBE_NULL variant.
15587          * So, as a general rule we don't allow mixing MAYBE_NULL and
15588          * non-MAYBE_NULL registers as well.
15589          */
15590         if (rold->type != rcur->type)
15591                 return false;
15592
15593         switch (base_type(rold->type)) {
15594         case SCALAR_VALUE:
15595                 if (env->explore_alu_limits) {
15596                         /* explore_alu_limits disables tnum_in() and range_within()
15597                          * logic and requires everything to be strict
15598                          */
15599                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15600                                check_scalar_ids(rold->id, rcur->id, idmap);
15601                 }
15602                 if (!rold->precise)
15603                         return true;
15604                 /* Why check_ids() for scalar registers?
15605                  *
15606                  * Consider the following BPF code:
15607                  *   1: r6 = ... unbound scalar, ID=a ...
15608                  *   2: r7 = ... unbound scalar, ID=b ...
15609                  *   3: if (r6 > r7) goto +1
15610                  *   4: r6 = r7
15611                  *   5: if (r6 > X) goto ...
15612                  *   6: ... memory operation using r7 ...
15613                  *
15614                  * First verification path is [1-6]:
15615                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15616                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15617                  *   r7 <= X, because r6 and r7 share same id.
15618                  * Next verification path is [1-4, 6].
15619                  *
15620                  * Instruction (6) would be reached in two states:
15621                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15622                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15623                  *
15624                  * Use check_ids() to distinguish these states.
15625                  * ---
15626                  * Also verify that new value satisfies old value range knowledge.
15627                  */
15628                 return range_within(rold, rcur) &&
15629                        tnum_in(rold->var_off, rcur->var_off) &&
15630                        check_scalar_ids(rold->id, rcur->id, idmap);
15631         case PTR_TO_MAP_KEY:
15632         case PTR_TO_MAP_VALUE:
15633         case PTR_TO_MEM:
15634         case PTR_TO_BUF:
15635         case PTR_TO_TP_BUFFER:
15636                 /* If the new min/max/var_off satisfy the old ones and
15637                  * everything else matches, we are OK.
15638                  */
15639                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15640                        range_within(rold, rcur) &&
15641                        tnum_in(rold->var_off, rcur->var_off) &&
15642                        check_ids(rold->id, rcur->id, idmap) &&
15643                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15644         case PTR_TO_PACKET_META:
15645         case PTR_TO_PACKET:
15646                 /* We must have at least as much range as the old ptr
15647                  * did, so that any accesses which were safe before are
15648                  * still safe.  This is true even if old range < old off,
15649                  * since someone could have accessed through (ptr - k), or
15650                  * even done ptr -= k in a register, to get a safe access.
15651                  */
15652                 if (rold->range > rcur->range)
15653                         return false;
15654                 /* If the offsets don't match, we can't trust our alignment;
15655                  * nor can we be sure that we won't fall out of range.
15656                  */
15657                 if (rold->off != rcur->off)
15658                         return false;
15659                 /* id relations must be preserved */
15660                 if (!check_ids(rold->id, rcur->id, idmap))
15661                         return false;
15662                 /* new val must satisfy old val knowledge */
15663                 return range_within(rold, rcur) &&
15664                        tnum_in(rold->var_off, rcur->var_off);
15665         case PTR_TO_STACK:
15666                 /* two stack pointers are equal only if they're pointing to
15667                  * the same stack frame, since fp-8 in foo != fp-8 in bar
15668                  */
15669                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15670         default:
15671                 return regs_exact(rold, rcur, idmap);
15672         }
15673 }
15674
15675 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15676                       struct bpf_func_state *cur, struct bpf_idmap *idmap)
15677 {
15678         int i, spi;
15679
15680         /* walk slots of the explored stack and ignore any additional
15681          * slots in the current stack, since explored(safe) state
15682          * didn't use them
15683          */
15684         for (i = 0; i < old->allocated_stack; i++) {
15685                 struct bpf_reg_state *old_reg, *cur_reg;
15686
15687                 spi = i / BPF_REG_SIZE;
15688
15689                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15690                         i += BPF_REG_SIZE - 1;
15691                         /* explored state didn't use this */
15692                         continue;
15693                 }
15694
15695                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15696                         continue;
15697
15698                 if (env->allow_uninit_stack &&
15699                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15700                         continue;
15701
15702                 /* explored stack has more populated slots than current stack
15703                  * and these slots were used
15704                  */
15705                 if (i >= cur->allocated_stack)
15706                         return false;
15707
15708                 /* if old state was safe with misc data in the stack
15709                  * it will be safe with zero-initialized stack.
15710                  * The opposite is not true
15711                  */
15712                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15713                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15714                         continue;
15715                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15716                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15717                         /* Ex: old explored (safe) state has STACK_SPILL in
15718                          * this stack slot, but current has STACK_MISC ->
15719                          * this verifier states are not equivalent,
15720                          * return false to continue verification of this path
15721                          */
15722                         return false;
15723                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15724                         continue;
15725                 /* Both old and cur are having same slot_type */
15726                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15727                 case STACK_SPILL:
15728                         /* when explored and current stack slot are both storing
15729                          * spilled registers, check that stored pointers types
15730                          * are the same as well.
15731                          * Ex: explored safe path could have stored
15732                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15733                          * but current path has stored:
15734                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15735                          * such verifier states are not equivalent.
15736                          * return false to continue verification of this path
15737                          */
15738                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
15739                                      &cur->stack[spi].spilled_ptr, idmap))
15740                                 return false;
15741                         break;
15742                 case STACK_DYNPTR:
15743                         old_reg = &old->stack[spi].spilled_ptr;
15744                         cur_reg = &cur->stack[spi].spilled_ptr;
15745                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15746                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15747                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15748                                 return false;
15749                         break;
15750                 case STACK_ITER:
15751                         old_reg = &old->stack[spi].spilled_ptr;
15752                         cur_reg = &cur->stack[spi].spilled_ptr;
15753                         /* iter.depth is not compared between states as it
15754                          * doesn't matter for correctness and would otherwise
15755                          * prevent convergence; we maintain it only to prevent
15756                          * infinite loop check triggering, see
15757                          * iter_active_depths_differ()
15758                          */
15759                         if (old_reg->iter.btf != cur_reg->iter.btf ||
15760                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15761                             old_reg->iter.state != cur_reg->iter.state ||
15762                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
15763                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15764                                 return false;
15765                         break;
15766                 case STACK_MISC:
15767                 case STACK_ZERO:
15768                 case STACK_INVALID:
15769                         continue;
15770                 /* Ensure that new unhandled slot types return false by default */
15771                 default:
15772                         return false;
15773                 }
15774         }
15775         return true;
15776 }
15777
15778 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15779                     struct bpf_idmap *idmap)
15780 {
15781         int i;
15782
15783         if (old->acquired_refs != cur->acquired_refs)
15784                 return false;
15785
15786         for (i = 0; i < old->acquired_refs; i++) {
15787                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15788                         return false;
15789         }
15790
15791         return true;
15792 }
15793
15794 /* compare two verifier states
15795  *
15796  * all states stored in state_list are known to be valid, since
15797  * verifier reached 'bpf_exit' instruction through them
15798  *
15799  * this function is called when verifier exploring different branches of
15800  * execution popped from the state stack. If it sees an old state that has
15801  * more strict register state and more strict stack state then this execution
15802  * branch doesn't need to be explored further, since verifier already
15803  * concluded that more strict state leads to valid finish.
15804  *
15805  * Therefore two states are equivalent if register state is more conservative
15806  * and explored stack state is more conservative than the current one.
15807  * Example:
15808  *       explored                   current
15809  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15810  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15811  *
15812  * In other words if current stack state (one being explored) has more
15813  * valid slots than old one that already passed validation, it means
15814  * the verifier can stop exploring and conclude that current state is valid too
15815  *
15816  * Similarly with registers. If explored state has register type as invalid
15817  * whereas register type in current state is meaningful, it means that
15818  * the current state will reach 'bpf_exit' instruction safely
15819  */
15820 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15821                               struct bpf_func_state *cur)
15822 {
15823         int i;
15824
15825         for (i = 0; i < MAX_BPF_REG; i++)
15826                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15827                              &env->idmap_scratch))
15828                         return false;
15829
15830         if (!stacksafe(env, old, cur, &env->idmap_scratch))
15831                 return false;
15832
15833         if (!refsafe(old, cur, &env->idmap_scratch))
15834                 return false;
15835
15836         return true;
15837 }
15838
15839 static bool states_equal(struct bpf_verifier_env *env,
15840                          struct bpf_verifier_state *old,
15841                          struct bpf_verifier_state *cur)
15842 {
15843         int i;
15844
15845         if (old->curframe != cur->curframe)
15846                 return false;
15847
15848         env->idmap_scratch.tmp_id_gen = env->id_gen;
15849         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15850
15851         /* Verification state from speculative execution simulation
15852          * must never prune a non-speculative execution one.
15853          */
15854         if (old->speculative && !cur->speculative)
15855                 return false;
15856
15857         if (old->active_lock.ptr != cur->active_lock.ptr)
15858                 return false;
15859
15860         /* Old and cur active_lock's have to be either both present
15861          * or both absent.
15862          */
15863         if (!!old->active_lock.id != !!cur->active_lock.id)
15864                 return false;
15865
15866         if (old->active_lock.id &&
15867             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15868                 return false;
15869
15870         if (old->active_rcu_lock != cur->active_rcu_lock)
15871                 return false;
15872
15873         /* for states to be equal callsites have to be the same
15874          * and all frame states need to be equivalent
15875          */
15876         for (i = 0; i <= old->curframe; i++) {
15877                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15878                         return false;
15879                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15880                         return false;
15881         }
15882         return true;
15883 }
15884
15885 /* Return 0 if no propagation happened. Return negative error code if error
15886  * happened. Otherwise, return the propagated bit.
15887  */
15888 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15889                                   struct bpf_reg_state *reg,
15890                                   struct bpf_reg_state *parent_reg)
15891 {
15892         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15893         u8 flag = reg->live & REG_LIVE_READ;
15894         int err;
15895
15896         /* When comes here, read flags of PARENT_REG or REG could be any of
15897          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15898          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15899          */
15900         if (parent_flag == REG_LIVE_READ64 ||
15901             /* Or if there is no read flag from REG. */
15902             !flag ||
15903             /* Or if the read flag from REG is the same as PARENT_REG. */
15904             parent_flag == flag)
15905                 return 0;
15906
15907         err = mark_reg_read(env, reg, parent_reg, flag);
15908         if (err)
15909                 return err;
15910
15911         return flag;
15912 }
15913
15914 /* A write screens off any subsequent reads; but write marks come from the
15915  * straight-line code between a state and its parent.  When we arrive at an
15916  * equivalent state (jump target or such) we didn't arrive by the straight-line
15917  * code, so read marks in the state must propagate to the parent regardless
15918  * of the state's write marks. That's what 'parent == state->parent' comparison
15919  * in mark_reg_read() is for.
15920  */
15921 static int propagate_liveness(struct bpf_verifier_env *env,
15922                               const struct bpf_verifier_state *vstate,
15923                               struct bpf_verifier_state *vparent)
15924 {
15925         struct bpf_reg_state *state_reg, *parent_reg;
15926         struct bpf_func_state *state, *parent;
15927         int i, frame, err = 0;
15928
15929         if (vparent->curframe != vstate->curframe) {
15930                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15931                      vparent->curframe, vstate->curframe);
15932                 return -EFAULT;
15933         }
15934         /* Propagate read liveness of registers... */
15935         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15936         for (frame = 0; frame <= vstate->curframe; frame++) {
15937                 parent = vparent->frame[frame];
15938                 state = vstate->frame[frame];
15939                 parent_reg = parent->regs;
15940                 state_reg = state->regs;
15941                 /* We don't need to worry about FP liveness, it's read-only */
15942                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15943                         err = propagate_liveness_reg(env, &state_reg[i],
15944                                                      &parent_reg[i]);
15945                         if (err < 0)
15946                                 return err;
15947                         if (err == REG_LIVE_READ64)
15948                                 mark_insn_zext(env, &parent_reg[i]);
15949                 }
15950
15951                 /* Propagate stack slots. */
15952                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15953                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15954                         parent_reg = &parent->stack[i].spilled_ptr;
15955                         state_reg = &state->stack[i].spilled_ptr;
15956                         err = propagate_liveness_reg(env, state_reg,
15957                                                      parent_reg);
15958                         if (err < 0)
15959                                 return err;
15960                 }
15961         }
15962         return 0;
15963 }
15964
15965 /* find precise scalars in the previous equivalent state and
15966  * propagate them into the current state
15967  */
15968 static int propagate_precision(struct bpf_verifier_env *env,
15969                                const struct bpf_verifier_state *old)
15970 {
15971         struct bpf_reg_state *state_reg;
15972         struct bpf_func_state *state;
15973         int i, err = 0, fr;
15974         bool first;
15975
15976         for (fr = old->curframe; fr >= 0; fr--) {
15977                 state = old->frame[fr];
15978                 state_reg = state->regs;
15979                 first = true;
15980                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15981                         if (state_reg->type != SCALAR_VALUE ||
15982                             !state_reg->precise ||
15983                             !(state_reg->live & REG_LIVE_READ))
15984                                 continue;
15985                         if (env->log.level & BPF_LOG_LEVEL2) {
15986                                 if (first)
15987                                         verbose(env, "frame %d: propagating r%d", fr, i);
15988                                 else
15989                                         verbose(env, ",r%d", i);
15990                         }
15991                         bt_set_frame_reg(&env->bt, fr, i);
15992                         first = false;
15993                 }
15994
15995                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15996                         if (!is_spilled_reg(&state->stack[i]))
15997                                 continue;
15998                         state_reg = &state->stack[i].spilled_ptr;
15999                         if (state_reg->type != SCALAR_VALUE ||
16000                             !state_reg->precise ||
16001                             !(state_reg->live & REG_LIVE_READ))
16002                                 continue;
16003                         if (env->log.level & BPF_LOG_LEVEL2) {
16004                                 if (first)
16005                                         verbose(env, "frame %d: propagating fp%d",
16006                                                 fr, (-i - 1) * BPF_REG_SIZE);
16007                                 else
16008                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16009                         }
16010                         bt_set_frame_slot(&env->bt, fr, i);
16011                         first = false;
16012                 }
16013                 if (!first)
16014                         verbose(env, "\n");
16015         }
16016
16017         err = mark_chain_precision_batch(env);
16018         if (err < 0)
16019                 return err;
16020
16021         return 0;
16022 }
16023
16024 static bool states_maybe_looping(struct bpf_verifier_state *old,
16025                                  struct bpf_verifier_state *cur)
16026 {
16027         struct bpf_func_state *fold, *fcur;
16028         int i, fr = cur->curframe;
16029
16030         if (old->curframe != fr)
16031                 return false;
16032
16033         fold = old->frame[fr];
16034         fcur = cur->frame[fr];
16035         for (i = 0; i < MAX_BPF_REG; i++)
16036                 if (memcmp(&fold->regs[i], &fcur->regs[i],
16037                            offsetof(struct bpf_reg_state, parent)))
16038                         return false;
16039         return true;
16040 }
16041
16042 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16043 {
16044         return env->insn_aux_data[insn_idx].is_iter_next;
16045 }
16046
16047 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16048  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16049  * states to match, which otherwise would look like an infinite loop. So while
16050  * iter_next() calls are taken care of, we still need to be careful and
16051  * prevent erroneous and too eager declaration of "ininite loop", when
16052  * iterators are involved.
16053  *
16054  * Here's a situation in pseudo-BPF assembly form:
16055  *
16056  *   0: again:                          ; set up iter_next() call args
16057  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16058  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16059  *   3:   if r0 == 0 goto done
16060  *   4:   ... something useful here ...
16061  *   5:   goto again                    ; another iteration
16062  *   6: done:
16063  *   7:   r1 = &it
16064  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16065  *   9:   exit
16066  *
16067  * This is a typical loop. Let's assume that we have a prune point at 1:,
16068  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16069  * again`, assuming other heuristics don't get in a way).
16070  *
16071  * When we first time come to 1:, let's say we have some state X. We proceed
16072  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16073  * Now we come back to validate that forked ACTIVE state. We proceed through
16074  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16075  * are converging. But the problem is that we don't know that yet, as this
16076  * convergence has to happen at iter_next() call site only. So if nothing is
16077  * done, at 1: verifier will use bounded loop logic and declare infinite
16078  * looping (and would be *technically* correct, if not for iterator's
16079  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16080  * don't want that. So what we do in process_iter_next_call() when we go on
16081  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16082  * a different iteration. So when we suspect an infinite loop, we additionally
16083  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16084  * pretend we are not looping and wait for next iter_next() call.
16085  *
16086  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16087  * loop, because that would actually mean infinite loop, as DRAINED state is
16088  * "sticky", and so we'll keep returning into the same instruction with the
16089  * same state (at least in one of possible code paths).
16090  *
16091  * This approach allows to keep infinite loop heuristic even in the face of
16092  * active iterator. E.g., C snippet below is and will be detected as
16093  * inifintely looping:
16094  *
16095  *   struct bpf_iter_num it;
16096  *   int *p, x;
16097  *
16098  *   bpf_iter_num_new(&it, 0, 10);
16099  *   while ((p = bpf_iter_num_next(&t))) {
16100  *       x = p;
16101  *       while (x--) {} // <<-- infinite loop here
16102  *   }
16103  *
16104  */
16105 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16106 {
16107         struct bpf_reg_state *slot, *cur_slot;
16108         struct bpf_func_state *state;
16109         int i, fr;
16110
16111         for (fr = old->curframe; fr >= 0; fr--) {
16112                 state = old->frame[fr];
16113                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16114                         if (state->stack[i].slot_type[0] != STACK_ITER)
16115                                 continue;
16116
16117                         slot = &state->stack[i].spilled_ptr;
16118                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16119                                 continue;
16120
16121                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16122                         if (cur_slot->iter.depth != slot->iter.depth)
16123                                 return true;
16124                 }
16125         }
16126         return false;
16127 }
16128
16129 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16130 {
16131         struct bpf_verifier_state_list *new_sl;
16132         struct bpf_verifier_state_list *sl, **pprev;
16133         struct bpf_verifier_state *cur = env->cur_state, *new;
16134         int i, j, err, states_cnt = 0;
16135         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16136         bool add_new_state = force_new_state;
16137
16138         /* bpf progs typically have pruning point every 4 instructions
16139          * http://vger.kernel.org/bpfconf2019.html#session-1
16140          * Do not add new state for future pruning if the verifier hasn't seen
16141          * at least 2 jumps and at least 8 instructions.
16142          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16143          * In tests that amounts to up to 50% reduction into total verifier
16144          * memory consumption and 20% verifier time speedup.
16145          */
16146         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16147             env->insn_processed - env->prev_insn_processed >= 8)
16148                 add_new_state = true;
16149
16150         pprev = explored_state(env, insn_idx);
16151         sl = *pprev;
16152
16153         clean_live_states(env, insn_idx, cur);
16154
16155         while (sl) {
16156                 states_cnt++;
16157                 if (sl->state.insn_idx != insn_idx)
16158                         goto next;
16159
16160                 if (sl->state.branches) {
16161                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16162
16163                         if (frame->in_async_callback_fn &&
16164                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16165                                 /* Different async_entry_cnt means that the verifier is
16166                                  * processing another entry into async callback.
16167                                  * Seeing the same state is not an indication of infinite
16168                                  * loop or infinite recursion.
16169                                  * But finding the same state doesn't mean that it's safe
16170                                  * to stop processing the current state. The previous state
16171                                  * hasn't yet reached bpf_exit, since state.branches > 0.
16172                                  * Checking in_async_callback_fn alone is not enough either.
16173                                  * Since the verifier still needs to catch infinite loops
16174                                  * inside async callbacks.
16175                                  */
16176                                 goto skip_inf_loop_check;
16177                         }
16178                         /* BPF open-coded iterators loop detection is special.
16179                          * states_maybe_looping() logic is too simplistic in detecting
16180                          * states that *might* be equivalent, because it doesn't know
16181                          * about ID remapping, so don't even perform it.
16182                          * See process_iter_next_call() and iter_active_depths_differ()
16183                          * for overview of the logic. When current and one of parent
16184                          * states are detected as equivalent, it's a good thing: we prove
16185                          * convergence and can stop simulating further iterations.
16186                          * It's safe to assume that iterator loop will finish, taking into
16187                          * account iter_next() contract of eventually returning
16188                          * sticky NULL result.
16189                          */
16190                         if (is_iter_next_insn(env, insn_idx)) {
16191                                 if (states_equal(env, &sl->state, cur)) {
16192                                         struct bpf_func_state *cur_frame;
16193                                         struct bpf_reg_state *iter_state, *iter_reg;
16194                                         int spi;
16195
16196                                         cur_frame = cur->frame[cur->curframe];
16197                                         /* btf_check_iter_kfuncs() enforces that
16198                                          * iter state pointer is always the first arg
16199                                          */
16200                                         iter_reg = &cur_frame->regs[BPF_REG_1];
16201                                         /* current state is valid due to states_equal(),
16202                                          * so we can assume valid iter and reg state,
16203                                          * no need for extra (re-)validations
16204                                          */
16205                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16206                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16207                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16208                                                 goto hit;
16209                                 }
16210                                 goto skip_inf_loop_check;
16211                         }
16212                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
16213                         if (states_maybe_looping(&sl->state, cur) &&
16214                             states_equal(env, &sl->state, cur) &&
16215                             !iter_active_depths_differ(&sl->state, cur)) {
16216                                 verbose_linfo(env, insn_idx, "; ");
16217                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16218                                 return -EINVAL;
16219                         }
16220                         /* if the verifier is processing a loop, avoid adding new state
16221                          * too often, since different loop iterations have distinct
16222                          * states and may not help future pruning.
16223                          * This threshold shouldn't be too low to make sure that
16224                          * a loop with large bound will be rejected quickly.
16225                          * The most abusive loop will be:
16226                          * r1 += 1
16227                          * if r1 < 1000000 goto pc-2
16228                          * 1M insn_procssed limit / 100 == 10k peak states.
16229                          * This threshold shouldn't be too high either, since states
16230                          * at the end of the loop are likely to be useful in pruning.
16231                          */
16232 skip_inf_loop_check:
16233                         if (!force_new_state &&
16234                             env->jmps_processed - env->prev_jmps_processed < 20 &&
16235                             env->insn_processed - env->prev_insn_processed < 100)
16236                                 add_new_state = false;
16237                         goto miss;
16238                 }
16239                 if (states_equal(env, &sl->state, cur)) {
16240 hit:
16241                         sl->hit_cnt++;
16242                         /* reached equivalent register/stack state,
16243                          * prune the search.
16244                          * Registers read by the continuation are read by us.
16245                          * If we have any write marks in env->cur_state, they
16246                          * will prevent corresponding reads in the continuation
16247                          * from reaching our parent (an explored_state).  Our
16248                          * own state will get the read marks recorded, but
16249                          * they'll be immediately forgotten as we're pruning
16250                          * this state and will pop a new one.
16251                          */
16252                         err = propagate_liveness(env, &sl->state, cur);
16253
16254                         /* if previous state reached the exit with precision and
16255                          * current state is equivalent to it (except precsion marks)
16256                          * the precision needs to be propagated back in
16257                          * the current state.
16258                          */
16259                         err = err ? : push_jmp_history(env, cur);
16260                         err = err ? : propagate_precision(env, &sl->state);
16261                         if (err)
16262                                 return err;
16263                         return 1;
16264                 }
16265 miss:
16266                 /* when new state is not going to be added do not increase miss count.
16267                  * Otherwise several loop iterations will remove the state
16268                  * recorded earlier. The goal of these heuristics is to have
16269                  * states from some iterations of the loop (some in the beginning
16270                  * and some at the end) to help pruning.
16271                  */
16272                 if (add_new_state)
16273                         sl->miss_cnt++;
16274                 /* heuristic to determine whether this state is beneficial
16275                  * to keep checking from state equivalence point of view.
16276                  * Higher numbers increase max_states_per_insn and verification time,
16277                  * but do not meaningfully decrease insn_processed.
16278                  */
16279                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16280                         /* the state is unlikely to be useful. Remove it to
16281                          * speed up verification
16282                          */
16283                         *pprev = sl->next;
16284                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16285                                 u32 br = sl->state.branches;
16286
16287                                 WARN_ONCE(br,
16288                                           "BUG live_done but branches_to_explore %d\n",
16289                                           br);
16290                                 free_verifier_state(&sl->state, false);
16291                                 kfree(sl);
16292                                 env->peak_states--;
16293                         } else {
16294                                 /* cannot free this state, since parentage chain may
16295                                  * walk it later. Add it for free_list instead to
16296                                  * be freed at the end of verification
16297                                  */
16298                                 sl->next = env->free_list;
16299                                 env->free_list = sl;
16300                         }
16301                         sl = *pprev;
16302                         continue;
16303                 }
16304 next:
16305                 pprev = &sl->next;
16306                 sl = *pprev;
16307         }
16308
16309         if (env->max_states_per_insn < states_cnt)
16310                 env->max_states_per_insn = states_cnt;
16311
16312         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16313                 return 0;
16314
16315         if (!add_new_state)
16316                 return 0;
16317
16318         /* There were no equivalent states, remember the current one.
16319          * Technically the current state is not proven to be safe yet,
16320          * but it will either reach outer most bpf_exit (which means it's safe)
16321          * or it will be rejected. When there are no loops the verifier won't be
16322          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16323          * again on the way to bpf_exit.
16324          * When looping the sl->state.branches will be > 0 and this state
16325          * will not be considered for equivalence until branches == 0.
16326          */
16327         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16328         if (!new_sl)
16329                 return -ENOMEM;
16330         env->total_states++;
16331         env->peak_states++;
16332         env->prev_jmps_processed = env->jmps_processed;
16333         env->prev_insn_processed = env->insn_processed;
16334
16335         /* forget precise markings we inherited, see __mark_chain_precision */
16336         if (env->bpf_capable)
16337                 mark_all_scalars_imprecise(env, cur);
16338
16339         /* add new state to the head of linked list */
16340         new = &new_sl->state;
16341         err = copy_verifier_state(new, cur);
16342         if (err) {
16343                 free_verifier_state(new, false);
16344                 kfree(new_sl);
16345                 return err;
16346         }
16347         new->insn_idx = insn_idx;
16348         WARN_ONCE(new->branches != 1,
16349                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16350
16351         cur->parent = new;
16352         cur->first_insn_idx = insn_idx;
16353         clear_jmp_history(cur);
16354         new_sl->next = *explored_state(env, insn_idx);
16355         *explored_state(env, insn_idx) = new_sl;
16356         /* connect new state to parentage chain. Current frame needs all
16357          * registers connected. Only r6 - r9 of the callers are alive (pushed
16358          * to the stack implicitly by JITs) so in callers' frames connect just
16359          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16360          * the state of the call instruction (with WRITTEN set), and r0 comes
16361          * from callee with its full parentage chain, anyway.
16362          */
16363         /* clear write marks in current state: the writes we did are not writes
16364          * our child did, so they don't screen off its reads from us.
16365          * (There are no read marks in current state, because reads always mark
16366          * their parent and current state never has children yet.  Only
16367          * explored_states can get read marks.)
16368          */
16369         for (j = 0; j <= cur->curframe; j++) {
16370                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16371                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16372                 for (i = 0; i < BPF_REG_FP; i++)
16373                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16374         }
16375
16376         /* all stack frames are accessible from callee, clear them all */
16377         for (j = 0; j <= cur->curframe; j++) {
16378                 struct bpf_func_state *frame = cur->frame[j];
16379                 struct bpf_func_state *newframe = new->frame[j];
16380
16381                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16382                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16383                         frame->stack[i].spilled_ptr.parent =
16384                                                 &newframe->stack[i].spilled_ptr;
16385                 }
16386         }
16387         return 0;
16388 }
16389
16390 /* Return true if it's OK to have the same insn return a different type. */
16391 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16392 {
16393         switch (base_type(type)) {
16394         case PTR_TO_CTX:
16395         case PTR_TO_SOCKET:
16396         case PTR_TO_SOCK_COMMON:
16397         case PTR_TO_TCP_SOCK:
16398         case PTR_TO_XDP_SOCK:
16399         case PTR_TO_BTF_ID:
16400                 return false;
16401         default:
16402                 return true;
16403         }
16404 }
16405
16406 /* If an instruction was previously used with particular pointer types, then we
16407  * need to be careful to avoid cases such as the below, where it may be ok
16408  * for one branch accessing the pointer, but not ok for the other branch:
16409  *
16410  * R1 = sock_ptr
16411  * goto X;
16412  * ...
16413  * R1 = some_other_valid_ptr;
16414  * goto X;
16415  * ...
16416  * R2 = *(u32 *)(R1 + 0);
16417  */
16418 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16419 {
16420         return src != prev && (!reg_type_mismatch_ok(src) ||
16421                                !reg_type_mismatch_ok(prev));
16422 }
16423
16424 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16425                              bool allow_trust_missmatch)
16426 {
16427         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16428
16429         if (*prev_type == NOT_INIT) {
16430                 /* Saw a valid insn
16431                  * dst_reg = *(u32 *)(src_reg + off)
16432                  * save type to validate intersecting paths
16433                  */
16434                 *prev_type = type;
16435         } else if (reg_type_mismatch(type, *prev_type)) {
16436                 /* Abuser program is trying to use the same insn
16437                  * dst_reg = *(u32*) (src_reg + off)
16438                  * with different pointer types:
16439                  * src_reg == ctx in one branch and
16440                  * src_reg == stack|map in some other branch.
16441                  * Reject it.
16442                  */
16443                 if (allow_trust_missmatch &&
16444                     base_type(type) == PTR_TO_BTF_ID &&
16445                     base_type(*prev_type) == PTR_TO_BTF_ID) {
16446                         /*
16447                          * Have to support a use case when one path through
16448                          * the program yields TRUSTED pointer while another
16449                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
16450                          * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16451                          */
16452                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16453                 } else {
16454                         verbose(env, "same insn cannot be used with different pointers\n");
16455                         return -EINVAL;
16456                 }
16457         }
16458
16459         return 0;
16460 }
16461
16462 static int do_check(struct bpf_verifier_env *env)
16463 {
16464         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16465         struct bpf_verifier_state *state = env->cur_state;
16466         struct bpf_insn *insns = env->prog->insnsi;
16467         struct bpf_reg_state *regs;
16468         int insn_cnt = env->prog->len;
16469         bool do_print_state = false;
16470         int prev_insn_idx = -1;
16471
16472         for (;;) {
16473                 struct bpf_insn *insn;
16474                 u8 class;
16475                 int err;
16476
16477                 env->prev_insn_idx = prev_insn_idx;
16478                 if (env->insn_idx >= insn_cnt) {
16479                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
16480                                 env->insn_idx, insn_cnt);
16481                         return -EFAULT;
16482                 }
16483
16484                 insn = &insns[env->insn_idx];
16485                 class = BPF_CLASS(insn->code);
16486
16487                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16488                         verbose(env,
16489                                 "BPF program is too large. Processed %d insn\n",
16490                                 env->insn_processed);
16491                         return -E2BIG;
16492                 }
16493
16494                 state->last_insn_idx = env->prev_insn_idx;
16495
16496                 if (is_prune_point(env, env->insn_idx)) {
16497                         err = is_state_visited(env, env->insn_idx);
16498                         if (err < 0)
16499                                 return err;
16500                         if (err == 1) {
16501                                 /* found equivalent state, can prune the search */
16502                                 if (env->log.level & BPF_LOG_LEVEL) {
16503                                         if (do_print_state)
16504                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
16505                                                         env->prev_insn_idx, env->insn_idx,
16506                                                         env->cur_state->speculative ?
16507                                                         " (speculative execution)" : "");
16508                                         else
16509                                                 verbose(env, "%d: safe\n", env->insn_idx);
16510                                 }
16511                                 goto process_bpf_exit;
16512                         }
16513                 }
16514
16515                 if (is_jmp_point(env, env->insn_idx)) {
16516                         err = push_jmp_history(env, state);
16517                         if (err)
16518                                 return err;
16519                 }
16520
16521                 if (signal_pending(current))
16522                         return -EAGAIN;
16523
16524                 if (need_resched())
16525                         cond_resched();
16526
16527                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16528                         verbose(env, "\nfrom %d to %d%s:",
16529                                 env->prev_insn_idx, env->insn_idx,
16530                                 env->cur_state->speculative ?
16531                                 " (speculative execution)" : "");
16532                         print_verifier_state(env, state->frame[state->curframe], true);
16533                         do_print_state = false;
16534                 }
16535
16536                 if (env->log.level & BPF_LOG_LEVEL) {
16537                         const struct bpf_insn_cbs cbs = {
16538                                 .cb_call        = disasm_kfunc_name,
16539                                 .cb_print       = verbose,
16540                                 .private_data   = env,
16541                         };
16542
16543                         if (verifier_state_scratched(env))
16544                                 print_insn_state(env, state->frame[state->curframe]);
16545
16546                         verbose_linfo(env, env->insn_idx, "; ");
16547                         env->prev_log_pos = env->log.end_pos;
16548                         verbose(env, "%d: ", env->insn_idx);
16549                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16550                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16551                         env->prev_log_pos = env->log.end_pos;
16552                 }
16553
16554                 if (bpf_prog_is_offloaded(env->prog->aux)) {
16555                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16556                                                            env->prev_insn_idx);
16557                         if (err)
16558                                 return err;
16559                 }
16560
16561                 regs = cur_regs(env);
16562                 sanitize_mark_insn_seen(env);
16563                 prev_insn_idx = env->insn_idx;
16564
16565                 if (class == BPF_ALU || class == BPF_ALU64) {
16566                         err = check_alu_op(env, insn);
16567                         if (err)
16568                                 return err;
16569
16570                 } else if (class == BPF_LDX) {
16571                         enum bpf_reg_type src_reg_type;
16572
16573                         /* check for reserved fields is already done */
16574
16575                         /* check src operand */
16576                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16577                         if (err)
16578                                 return err;
16579
16580                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16581                         if (err)
16582                                 return err;
16583
16584                         src_reg_type = regs[insn->src_reg].type;
16585
16586                         /* check that memory (src_reg + off) is readable,
16587                          * the state of dst_reg will be updated by this func
16588                          */
16589                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
16590                                                insn->off, BPF_SIZE(insn->code),
16591                                                BPF_READ, insn->dst_reg, false,
16592                                                BPF_MODE(insn->code) == BPF_MEMSX);
16593                         if (err)
16594                                 return err;
16595
16596                         err = save_aux_ptr_type(env, src_reg_type, true);
16597                         if (err)
16598                                 return err;
16599                 } else if (class == BPF_STX) {
16600                         enum bpf_reg_type dst_reg_type;
16601
16602                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16603                                 err = check_atomic(env, env->insn_idx, insn);
16604                                 if (err)
16605                                         return err;
16606                                 env->insn_idx++;
16607                                 continue;
16608                         }
16609
16610                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16611                                 verbose(env, "BPF_STX uses reserved fields\n");
16612                                 return -EINVAL;
16613                         }
16614
16615                         /* check src1 operand */
16616                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16617                         if (err)
16618                                 return err;
16619                         /* check src2 operand */
16620                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16621                         if (err)
16622                                 return err;
16623
16624                         dst_reg_type = regs[insn->dst_reg].type;
16625
16626                         /* check that memory (dst_reg + off) is writeable */
16627                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16628                                                insn->off, BPF_SIZE(insn->code),
16629                                                BPF_WRITE, insn->src_reg, false, false);
16630                         if (err)
16631                                 return err;
16632
16633                         err = save_aux_ptr_type(env, dst_reg_type, false);
16634                         if (err)
16635                                 return err;
16636                 } else if (class == BPF_ST) {
16637                         enum bpf_reg_type dst_reg_type;
16638
16639                         if (BPF_MODE(insn->code) != BPF_MEM ||
16640                             insn->src_reg != BPF_REG_0) {
16641                                 verbose(env, "BPF_ST uses reserved fields\n");
16642                                 return -EINVAL;
16643                         }
16644                         /* check src operand */
16645                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16646                         if (err)
16647                                 return err;
16648
16649                         dst_reg_type = regs[insn->dst_reg].type;
16650
16651                         /* check that memory (dst_reg + off) is writeable */
16652                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16653                                                insn->off, BPF_SIZE(insn->code),
16654                                                BPF_WRITE, -1, false, false);
16655                         if (err)
16656                                 return err;
16657
16658                         err = save_aux_ptr_type(env, dst_reg_type, false);
16659                         if (err)
16660                                 return err;
16661                 } else if (class == BPF_JMP || class == BPF_JMP32) {
16662                         u8 opcode = BPF_OP(insn->code);
16663
16664                         env->jmps_processed++;
16665                         if (opcode == BPF_CALL) {
16666                                 if (BPF_SRC(insn->code) != BPF_K ||
16667                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16668                                      && insn->off != 0) ||
16669                                     (insn->src_reg != BPF_REG_0 &&
16670                                      insn->src_reg != BPF_PSEUDO_CALL &&
16671                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16672                                     insn->dst_reg != BPF_REG_0 ||
16673                                     class == BPF_JMP32) {
16674                                         verbose(env, "BPF_CALL uses reserved fields\n");
16675                                         return -EINVAL;
16676                                 }
16677
16678                                 if (env->cur_state->active_lock.ptr) {
16679                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16680                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
16681                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16682                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16683                                                 verbose(env, "function calls are not allowed while holding a lock\n");
16684                                                 return -EINVAL;
16685                                         }
16686                                 }
16687                                 if (insn->src_reg == BPF_PSEUDO_CALL)
16688                                         err = check_func_call(env, insn, &env->insn_idx);
16689                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16690                                         err = check_kfunc_call(env, insn, &env->insn_idx);
16691                                 else
16692                                         err = check_helper_call(env, insn, &env->insn_idx);
16693                                 if (err)
16694                                         return err;
16695
16696                                 mark_reg_scratched(env, BPF_REG_0);
16697                         } else if (opcode == BPF_JA) {
16698                                 if (BPF_SRC(insn->code) != BPF_K ||
16699                                     insn->src_reg != BPF_REG_0 ||
16700                                     insn->dst_reg != BPF_REG_0 ||
16701                                     (class == BPF_JMP && insn->imm != 0) ||
16702                                     (class == BPF_JMP32 && insn->off != 0)) {
16703                                         verbose(env, "BPF_JA uses reserved fields\n");
16704                                         return -EINVAL;
16705                                 }
16706
16707                                 if (class == BPF_JMP)
16708                                         env->insn_idx += insn->off + 1;
16709                                 else
16710                                         env->insn_idx += insn->imm + 1;
16711                                 continue;
16712
16713                         } else if (opcode == BPF_EXIT) {
16714                                 if (BPF_SRC(insn->code) != BPF_K ||
16715                                     insn->imm != 0 ||
16716                                     insn->src_reg != BPF_REG_0 ||
16717                                     insn->dst_reg != BPF_REG_0 ||
16718                                     class == BPF_JMP32) {
16719                                         verbose(env, "BPF_EXIT uses reserved fields\n");
16720                                         return -EINVAL;
16721                                 }
16722
16723                                 if (env->cur_state->active_lock.ptr &&
16724                                     !in_rbtree_lock_required_cb(env)) {
16725                                         verbose(env, "bpf_spin_unlock is missing\n");
16726                                         return -EINVAL;
16727                                 }
16728
16729                                 if (env->cur_state->active_rcu_lock &&
16730                                     !in_rbtree_lock_required_cb(env)) {
16731                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
16732                                         return -EINVAL;
16733                                 }
16734
16735                                 /* We must do check_reference_leak here before
16736                                  * prepare_func_exit to handle the case when
16737                                  * state->curframe > 0, it may be a callback
16738                                  * function, for which reference_state must
16739                                  * match caller reference state when it exits.
16740                                  */
16741                                 err = check_reference_leak(env);
16742                                 if (err)
16743                                         return err;
16744
16745                                 if (state->curframe) {
16746                                         /* exit from nested function */
16747                                         err = prepare_func_exit(env, &env->insn_idx);
16748                                         if (err)
16749                                                 return err;
16750                                         do_print_state = true;
16751                                         continue;
16752                                 }
16753
16754                                 err = check_return_code(env);
16755                                 if (err)
16756                                         return err;
16757 process_bpf_exit:
16758                                 mark_verifier_state_scratched(env);
16759                                 update_branch_counts(env, env->cur_state);
16760                                 err = pop_stack(env, &prev_insn_idx,
16761                                                 &env->insn_idx, pop_log);
16762                                 if (err < 0) {
16763                                         if (err != -ENOENT)
16764                                                 return err;
16765                                         break;
16766                                 } else {
16767                                         do_print_state = true;
16768                                         continue;
16769                                 }
16770                         } else {
16771                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16772                                 if (err)
16773                                         return err;
16774                         }
16775                 } else if (class == BPF_LD) {
16776                         u8 mode = BPF_MODE(insn->code);
16777
16778                         if (mode == BPF_ABS || mode == BPF_IND) {
16779                                 err = check_ld_abs(env, insn);
16780                                 if (err)
16781                                         return err;
16782
16783                         } else if (mode == BPF_IMM) {
16784                                 err = check_ld_imm(env, insn);
16785                                 if (err)
16786                                         return err;
16787
16788                                 env->insn_idx++;
16789                                 sanitize_mark_insn_seen(env);
16790                         } else {
16791                                 verbose(env, "invalid BPF_LD mode\n");
16792                                 return -EINVAL;
16793                         }
16794                 } else {
16795                         verbose(env, "unknown insn class %d\n", class);
16796                         return -EINVAL;
16797                 }
16798
16799                 env->insn_idx++;
16800         }
16801
16802         return 0;
16803 }
16804
16805 static int find_btf_percpu_datasec(struct btf *btf)
16806 {
16807         const struct btf_type *t;
16808         const char *tname;
16809         int i, n;
16810
16811         /*
16812          * Both vmlinux and module each have their own ".data..percpu"
16813          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16814          * types to look at only module's own BTF types.
16815          */
16816         n = btf_nr_types(btf);
16817         if (btf_is_module(btf))
16818                 i = btf_nr_types(btf_vmlinux);
16819         else
16820                 i = 1;
16821
16822         for(; i < n; i++) {
16823                 t = btf_type_by_id(btf, i);
16824                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16825                         continue;
16826
16827                 tname = btf_name_by_offset(btf, t->name_off);
16828                 if (!strcmp(tname, ".data..percpu"))
16829                         return i;
16830         }
16831
16832         return -ENOENT;
16833 }
16834
16835 /* replace pseudo btf_id with kernel symbol address */
16836 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16837                                struct bpf_insn *insn,
16838                                struct bpf_insn_aux_data *aux)
16839 {
16840         const struct btf_var_secinfo *vsi;
16841         const struct btf_type *datasec;
16842         struct btf_mod_pair *btf_mod;
16843         const struct btf_type *t;
16844         const char *sym_name;
16845         bool percpu = false;
16846         u32 type, id = insn->imm;
16847         struct btf *btf;
16848         s32 datasec_id;
16849         u64 addr;
16850         int i, btf_fd, err;
16851
16852         btf_fd = insn[1].imm;
16853         if (btf_fd) {
16854                 btf = btf_get_by_fd(btf_fd);
16855                 if (IS_ERR(btf)) {
16856                         verbose(env, "invalid module BTF object FD specified.\n");
16857                         return -EINVAL;
16858                 }
16859         } else {
16860                 if (!btf_vmlinux) {
16861                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16862                         return -EINVAL;
16863                 }
16864                 btf = btf_vmlinux;
16865                 btf_get(btf);
16866         }
16867
16868         t = btf_type_by_id(btf, id);
16869         if (!t) {
16870                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16871                 err = -ENOENT;
16872                 goto err_put;
16873         }
16874
16875         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16876                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16877                 err = -EINVAL;
16878                 goto err_put;
16879         }
16880
16881         sym_name = btf_name_by_offset(btf, t->name_off);
16882         addr = kallsyms_lookup_name(sym_name);
16883         if (!addr) {
16884                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16885                         sym_name);
16886                 err = -ENOENT;
16887                 goto err_put;
16888         }
16889         insn[0].imm = (u32)addr;
16890         insn[1].imm = addr >> 32;
16891
16892         if (btf_type_is_func(t)) {
16893                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16894                 aux->btf_var.mem_size = 0;
16895                 goto check_btf;
16896         }
16897
16898         datasec_id = find_btf_percpu_datasec(btf);
16899         if (datasec_id > 0) {
16900                 datasec = btf_type_by_id(btf, datasec_id);
16901                 for_each_vsi(i, datasec, vsi) {
16902                         if (vsi->type == id) {
16903                                 percpu = true;
16904                                 break;
16905                         }
16906                 }
16907         }
16908
16909         type = t->type;
16910         t = btf_type_skip_modifiers(btf, type, NULL);
16911         if (percpu) {
16912                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16913                 aux->btf_var.btf = btf;
16914                 aux->btf_var.btf_id = type;
16915         } else if (!btf_type_is_struct(t)) {
16916                 const struct btf_type *ret;
16917                 const char *tname;
16918                 u32 tsize;
16919
16920                 /* resolve the type size of ksym. */
16921                 ret = btf_resolve_size(btf, t, &tsize);
16922                 if (IS_ERR(ret)) {
16923                         tname = btf_name_by_offset(btf, t->name_off);
16924                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16925                                 tname, PTR_ERR(ret));
16926                         err = -EINVAL;
16927                         goto err_put;
16928                 }
16929                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16930                 aux->btf_var.mem_size = tsize;
16931         } else {
16932                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16933                 aux->btf_var.btf = btf;
16934                 aux->btf_var.btf_id = type;
16935         }
16936 check_btf:
16937         /* check whether we recorded this BTF (and maybe module) already */
16938         for (i = 0; i < env->used_btf_cnt; i++) {
16939                 if (env->used_btfs[i].btf == btf) {
16940                         btf_put(btf);
16941                         return 0;
16942                 }
16943         }
16944
16945         if (env->used_btf_cnt >= MAX_USED_BTFS) {
16946                 err = -E2BIG;
16947                 goto err_put;
16948         }
16949
16950         btf_mod = &env->used_btfs[env->used_btf_cnt];
16951         btf_mod->btf = btf;
16952         btf_mod->module = NULL;
16953
16954         /* if we reference variables from kernel module, bump its refcount */
16955         if (btf_is_module(btf)) {
16956                 btf_mod->module = btf_try_get_module(btf);
16957                 if (!btf_mod->module) {
16958                         err = -ENXIO;
16959                         goto err_put;
16960                 }
16961         }
16962
16963         env->used_btf_cnt++;
16964
16965         return 0;
16966 err_put:
16967         btf_put(btf);
16968         return err;
16969 }
16970
16971 static bool is_tracing_prog_type(enum bpf_prog_type type)
16972 {
16973         switch (type) {
16974         case BPF_PROG_TYPE_KPROBE:
16975         case BPF_PROG_TYPE_TRACEPOINT:
16976         case BPF_PROG_TYPE_PERF_EVENT:
16977         case BPF_PROG_TYPE_RAW_TRACEPOINT:
16978         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16979                 return true;
16980         default:
16981                 return false;
16982         }
16983 }
16984
16985 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16986                                         struct bpf_map *map,
16987                                         struct bpf_prog *prog)
16988
16989 {
16990         enum bpf_prog_type prog_type = resolve_prog_type(prog);
16991
16992         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16993             btf_record_has_field(map->record, BPF_RB_ROOT)) {
16994                 if (is_tracing_prog_type(prog_type)) {
16995                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16996                         return -EINVAL;
16997                 }
16998         }
16999
17000         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17001                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17002                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17003                         return -EINVAL;
17004                 }
17005
17006                 if (is_tracing_prog_type(prog_type)) {
17007                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17008                         return -EINVAL;
17009                 }
17010         }
17011
17012         if (btf_record_has_field(map->record, BPF_TIMER)) {
17013                 if (is_tracing_prog_type(prog_type)) {
17014                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
17015                         return -EINVAL;
17016                 }
17017         }
17018
17019         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17020             !bpf_offload_prog_map_match(prog, map)) {
17021                 verbose(env, "offload device mismatch between prog and map\n");
17022                 return -EINVAL;
17023         }
17024
17025         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17026                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17027                 return -EINVAL;
17028         }
17029
17030         if (prog->aux->sleepable)
17031                 switch (map->map_type) {
17032                 case BPF_MAP_TYPE_HASH:
17033                 case BPF_MAP_TYPE_LRU_HASH:
17034                 case BPF_MAP_TYPE_ARRAY:
17035                 case BPF_MAP_TYPE_PERCPU_HASH:
17036                 case BPF_MAP_TYPE_PERCPU_ARRAY:
17037                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17038                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17039                 case BPF_MAP_TYPE_HASH_OF_MAPS:
17040                 case BPF_MAP_TYPE_RINGBUF:
17041                 case BPF_MAP_TYPE_USER_RINGBUF:
17042                 case BPF_MAP_TYPE_INODE_STORAGE:
17043                 case BPF_MAP_TYPE_SK_STORAGE:
17044                 case BPF_MAP_TYPE_TASK_STORAGE:
17045                 case BPF_MAP_TYPE_CGRP_STORAGE:
17046                         break;
17047                 default:
17048                         verbose(env,
17049                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17050                         return -EINVAL;
17051                 }
17052
17053         return 0;
17054 }
17055
17056 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17057 {
17058         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17059                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17060 }
17061
17062 /* find and rewrite pseudo imm in ld_imm64 instructions:
17063  *
17064  * 1. if it accesses map FD, replace it with actual map pointer.
17065  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17066  *
17067  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17068  */
17069 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17070 {
17071         struct bpf_insn *insn = env->prog->insnsi;
17072         int insn_cnt = env->prog->len;
17073         int i, j, err;
17074
17075         err = bpf_prog_calc_tag(env->prog);
17076         if (err)
17077                 return err;
17078
17079         for (i = 0; i < insn_cnt; i++, insn++) {
17080                 if (BPF_CLASS(insn->code) == BPF_LDX &&
17081                     ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17082                     insn->imm != 0)) {
17083                         verbose(env, "BPF_LDX uses reserved fields\n");
17084                         return -EINVAL;
17085                 }
17086
17087                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17088                         struct bpf_insn_aux_data *aux;
17089                         struct bpf_map *map;
17090                         struct fd f;
17091                         u64 addr;
17092                         u32 fd;
17093
17094                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
17095                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17096                             insn[1].off != 0) {
17097                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
17098                                 return -EINVAL;
17099                         }
17100
17101                         if (insn[0].src_reg == 0)
17102                                 /* valid generic load 64-bit imm */
17103                                 goto next_insn;
17104
17105                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17106                                 aux = &env->insn_aux_data[i];
17107                                 err = check_pseudo_btf_id(env, insn, aux);
17108                                 if (err)
17109                                         return err;
17110                                 goto next_insn;
17111                         }
17112
17113                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17114                                 aux = &env->insn_aux_data[i];
17115                                 aux->ptr_type = PTR_TO_FUNC;
17116                                 goto next_insn;
17117                         }
17118
17119                         /* In final convert_pseudo_ld_imm64() step, this is
17120                          * converted into regular 64-bit imm load insn.
17121                          */
17122                         switch (insn[0].src_reg) {
17123                         case BPF_PSEUDO_MAP_VALUE:
17124                         case BPF_PSEUDO_MAP_IDX_VALUE:
17125                                 break;
17126                         case BPF_PSEUDO_MAP_FD:
17127                         case BPF_PSEUDO_MAP_IDX:
17128                                 if (insn[1].imm == 0)
17129                                         break;
17130                                 fallthrough;
17131                         default:
17132                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17133                                 return -EINVAL;
17134                         }
17135
17136                         switch (insn[0].src_reg) {
17137                         case BPF_PSEUDO_MAP_IDX_VALUE:
17138                         case BPF_PSEUDO_MAP_IDX:
17139                                 if (bpfptr_is_null(env->fd_array)) {
17140                                         verbose(env, "fd_idx without fd_array is invalid\n");
17141                                         return -EPROTO;
17142                                 }
17143                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17144                                                             insn[0].imm * sizeof(fd),
17145                                                             sizeof(fd)))
17146                                         return -EFAULT;
17147                                 break;
17148                         default:
17149                                 fd = insn[0].imm;
17150                                 break;
17151                         }
17152
17153                         f = fdget(fd);
17154                         map = __bpf_map_get(f);
17155                         if (IS_ERR(map)) {
17156                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17157                                         insn[0].imm);
17158                                 return PTR_ERR(map);
17159                         }
17160
17161                         err = check_map_prog_compatibility(env, map, env->prog);
17162                         if (err) {
17163                                 fdput(f);
17164                                 return err;
17165                         }
17166
17167                         aux = &env->insn_aux_data[i];
17168                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17169                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17170                                 addr = (unsigned long)map;
17171                         } else {
17172                                 u32 off = insn[1].imm;
17173
17174                                 if (off >= BPF_MAX_VAR_OFF) {
17175                                         verbose(env, "direct value offset of %u is not allowed\n", off);
17176                                         fdput(f);
17177                                         return -EINVAL;
17178                                 }
17179
17180                                 if (!map->ops->map_direct_value_addr) {
17181                                         verbose(env, "no direct value access support for this map type\n");
17182                                         fdput(f);
17183                                         return -EINVAL;
17184                                 }
17185
17186                                 err = map->ops->map_direct_value_addr(map, &addr, off);
17187                                 if (err) {
17188                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17189                                                 map->value_size, off);
17190                                         fdput(f);
17191                                         return err;
17192                                 }
17193
17194                                 aux->map_off = off;
17195                                 addr += off;
17196                         }
17197
17198                         insn[0].imm = (u32)addr;
17199                         insn[1].imm = addr >> 32;
17200
17201                         /* check whether we recorded this map already */
17202                         for (j = 0; j < env->used_map_cnt; j++) {
17203                                 if (env->used_maps[j] == map) {
17204                                         aux->map_index = j;
17205                                         fdput(f);
17206                                         goto next_insn;
17207                                 }
17208                         }
17209
17210                         if (env->used_map_cnt >= MAX_USED_MAPS) {
17211                                 fdput(f);
17212                                 return -E2BIG;
17213                         }
17214
17215                         /* hold the map. If the program is rejected by verifier,
17216                          * the map will be released by release_maps() or it
17217                          * will be used by the valid program until it's unloaded
17218                          * and all maps are released in free_used_maps()
17219                          */
17220                         bpf_map_inc(map);
17221
17222                         aux->map_index = env->used_map_cnt;
17223                         env->used_maps[env->used_map_cnt++] = map;
17224
17225                         if (bpf_map_is_cgroup_storage(map) &&
17226                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
17227                                 verbose(env, "only one cgroup storage of each type is allowed\n");
17228                                 fdput(f);
17229                                 return -EBUSY;
17230                         }
17231
17232                         fdput(f);
17233 next_insn:
17234                         insn++;
17235                         i++;
17236                         continue;
17237                 }
17238
17239                 /* Basic sanity check before we invest more work here. */
17240                 if (!bpf_opcode_in_insntable(insn->code)) {
17241                         verbose(env, "unknown opcode %02x\n", insn->code);
17242                         return -EINVAL;
17243                 }
17244         }
17245
17246         /* now all pseudo BPF_LD_IMM64 instructions load valid
17247          * 'struct bpf_map *' into a register instead of user map_fd.
17248          * These pointers will be used later by verifier to validate map access.
17249          */
17250         return 0;
17251 }
17252
17253 /* drop refcnt of maps used by the rejected program */
17254 static void release_maps(struct bpf_verifier_env *env)
17255 {
17256         __bpf_free_used_maps(env->prog->aux, env->used_maps,
17257                              env->used_map_cnt);
17258 }
17259
17260 /* drop refcnt of maps used by the rejected program */
17261 static void release_btfs(struct bpf_verifier_env *env)
17262 {
17263         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17264                              env->used_btf_cnt);
17265 }
17266
17267 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17268 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17269 {
17270         struct bpf_insn *insn = env->prog->insnsi;
17271         int insn_cnt = env->prog->len;
17272         int i;
17273
17274         for (i = 0; i < insn_cnt; i++, insn++) {
17275                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17276                         continue;
17277                 if (insn->src_reg == BPF_PSEUDO_FUNC)
17278                         continue;
17279                 insn->src_reg = 0;
17280         }
17281 }
17282
17283 /* single env->prog->insni[off] instruction was replaced with the range
17284  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17285  * [0, off) and [off, end) to new locations, so the patched range stays zero
17286  */
17287 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17288                                  struct bpf_insn_aux_data *new_data,
17289                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
17290 {
17291         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17292         struct bpf_insn *insn = new_prog->insnsi;
17293         u32 old_seen = old_data[off].seen;
17294         u32 prog_len;
17295         int i;
17296
17297         /* aux info at OFF always needs adjustment, no matter fast path
17298          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17299          * original insn at old prog.
17300          */
17301         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17302
17303         if (cnt == 1)
17304                 return;
17305         prog_len = new_prog->len;
17306
17307         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17308         memcpy(new_data + off + cnt - 1, old_data + off,
17309                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17310         for (i = off; i < off + cnt - 1; i++) {
17311                 /* Expand insni[off]'s seen count to the patched range. */
17312                 new_data[i].seen = old_seen;
17313                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17314         }
17315         env->insn_aux_data = new_data;
17316         vfree(old_data);
17317 }
17318
17319 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17320 {
17321         int i;
17322
17323         if (len == 1)
17324                 return;
17325         /* NOTE: fake 'exit' subprog should be updated as well. */
17326         for (i = 0; i <= env->subprog_cnt; i++) {
17327                 if (env->subprog_info[i].start <= off)
17328                         continue;
17329                 env->subprog_info[i].start += len - 1;
17330         }
17331 }
17332
17333 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17334 {
17335         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17336         int i, sz = prog->aux->size_poke_tab;
17337         struct bpf_jit_poke_descriptor *desc;
17338
17339         for (i = 0; i < sz; i++) {
17340                 desc = &tab[i];
17341                 if (desc->insn_idx <= off)
17342                         continue;
17343                 desc->insn_idx += len - 1;
17344         }
17345 }
17346
17347 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17348                                             const struct bpf_insn *patch, u32 len)
17349 {
17350         struct bpf_prog *new_prog;
17351         struct bpf_insn_aux_data *new_data = NULL;
17352
17353         if (len > 1) {
17354                 new_data = vzalloc(array_size(env->prog->len + len - 1,
17355                                               sizeof(struct bpf_insn_aux_data)));
17356                 if (!new_data)
17357                         return NULL;
17358         }
17359
17360         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17361         if (IS_ERR(new_prog)) {
17362                 if (PTR_ERR(new_prog) == -ERANGE)
17363                         verbose(env,
17364                                 "insn %d cannot be patched due to 16-bit range\n",
17365                                 env->insn_aux_data[off].orig_idx);
17366                 vfree(new_data);
17367                 return NULL;
17368         }
17369         adjust_insn_aux_data(env, new_data, new_prog, off, len);
17370         adjust_subprog_starts(env, off, len);
17371         adjust_poke_descs(new_prog, off, len);
17372         return new_prog;
17373 }
17374
17375 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17376                                               u32 off, u32 cnt)
17377 {
17378         int i, j;
17379
17380         /* find first prog starting at or after off (first to remove) */
17381         for (i = 0; i < env->subprog_cnt; i++)
17382                 if (env->subprog_info[i].start >= off)
17383                         break;
17384         /* find first prog starting at or after off + cnt (first to stay) */
17385         for (j = i; j < env->subprog_cnt; j++)
17386                 if (env->subprog_info[j].start >= off + cnt)
17387                         break;
17388         /* if j doesn't start exactly at off + cnt, we are just removing
17389          * the front of previous prog
17390          */
17391         if (env->subprog_info[j].start != off + cnt)
17392                 j--;
17393
17394         if (j > i) {
17395                 struct bpf_prog_aux *aux = env->prog->aux;
17396                 int move;
17397
17398                 /* move fake 'exit' subprog as well */
17399                 move = env->subprog_cnt + 1 - j;
17400
17401                 memmove(env->subprog_info + i,
17402                         env->subprog_info + j,
17403                         sizeof(*env->subprog_info) * move);
17404                 env->subprog_cnt -= j - i;
17405
17406                 /* remove func_info */
17407                 if (aux->func_info) {
17408                         move = aux->func_info_cnt - j;
17409
17410                         memmove(aux->func_info + i,
17411                                 aux->func_info + j,
17412                                 sizeof(*aux->func_info) * move);
17413                         aux->func_info_cnt -= j - i;
17414                         /* func_info->insn_off is set after all code rewrites,
17415                          * in adjust_btf_func() - no need to adjust
17416                          */
17417                 }
17418         } else {
17419                 /* convert i from "first prog to remove" to "first to adjust" */
17420                 if (env->subprog_info[i].start == off)
17421                         i++;
17422         }
17423
17424         /* update fake 'exit' subprog as well */
17425         for (; i <= env->subprog_cnt; i++)
17426                 env->subprog_info[i].start -= cnt;
17427
17428         return 0;
17429 }
17430
17431 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17432                                       u32 cnt)
17433 {
17434         struct bpf_prog *prog = env->prog;
17435         u32 i, l_off, l_cnt, nr_linfo;
17436         struct bpf_line_info *linfo;
17437
17438         nr_linfo = prog->aux->nr_linfo;
17439         if (!nr_linfo)
17440                 return 0;
17441
17442         linfo = prog->aux->linfo;
17443
17444         /* find first line info to remove, count lines to be removed */
17445         for (i = 0; i < nr_linfo; i++)
17446                 if (linfo[i].insn_off >= off)
17447                         break;
17448
17449         l_off = i;
17450         l_cnt = 0;
17451         for (; i < nr_linfo; i++)
17452                 if (linfo[i].insn_off < off + cnt)
17453                         l_cnt++;
17454                 else
17455                         break;
17456
17457         /* First live insn doesn't match first live linfo, it needs to "inherit"
17458          * last removed linfo.  prog is already modified, so prog->len == off
17459          * means no live instructions after (tail of the program was removed).
17460          */
17461         if (prog->len != off && l_cnt &&
17462             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17463                 l_cnt--;
17464                 linfo[--i].insn_off = off + cnt;
17465         }
17466
17467         /* remove the line info which refer to the removed instructions */
17468         if (l_cnt) {
17469                 memmove(linfo + l_off, linfo + i,
17470                         sizeof(*linfo) * (nr_linfo - i));
17471
17472                 prog->aux->nr_linfo -= l_cnt;
17473                 nr_linfo = prog->aux->nr_linfo;
17474         }
17475
17476         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17477         for (i = l_off; i < nr_linfo; i++)
17478                 linfo[i].insn_off -= cnt;
17479
17480         /* fix up all subprogs (incl. 'exit') which start >= off */
17481         for (i = 0; i <= env->subprog_cnt; i++)
17482                 if (env->subprog_info[i].linfo_idx > l_off) {
17483                         /* program may have started in the removed region but
17484                          * may not be fully removed
17485                          */
17486                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17487                                 env->subprog_info[i].linfo_idx -= l_cnt;
17488                         else
17489                                 env->subprog_info[i].linfo_idx = l_off;
17490                 }
17491
17492         return 0;
17493 }
17494
17495 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17496 {
17497         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17498         unsigned int orig_prog_len = env->prog->len;
17499         int err;
17500
17501         if (bpf_prog_is_offloaded(env->prog->aux))
17502                 bpf_prog_offload_remove_insns(env, off, cnt);
17503
17504         err = bpf_remove_insns(env->prog, off, cnt);
17505         if (err)
17506                 return err;
17507
17508         err = adjust_subprog_starts_after_remove(env, off, cnt);
17509         if (err)
17510                 return err;
17511
17512         err = bpf_adj_linfo_after_remove(env, off, cnt);
17513         if (err)
17514                 return err;
17515
17516         memmove(aux_data + off, aux_data + off + cnt,
17517                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17518
17519         return 0;
17520 }
17521
17522 /* The verifier does more data flow analysis than llvm and will not
17523  * explore branches that are dead at run time. Malicious programs can
17524  * have dead code too. Therefore replace all dead at-run-time code
17525  * with 'ja -1'.
17526  *
17527  * Just nops are not optimal, e.g. if they would sit at the end of the
17528  * program and through another bug we would manage to jump there, then
17529  * we'd execute beyond program memory otherwise. Returning exception
17530  * code also wouldn't work since we can have subprogs where the dead
17531  * code could be located.
17532  */
17533 static void sanitize_dead_code(struct bpf_verifier_env *env)
17534 {
17535         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17536         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17537         struct bpf_insn *insn = env->prog->insnsi;
17538         const int insn_cnt = env->prog->len;
17539         int i;
17540
17541         for (i = 0; i < insn_cnt; i++) {
17542                 if (aux_data[i].seen)
17543                         continue;
17544                 memcpy(insn + i, &trap, sizeof(trap));
17545                 aux_data[i].zext_dst = false;
17546         }
17547 }
17548
17549 static bool insn_is_cond_jump(u8 code)
17550 {
17551         u8 op;
17552
17553         op = BPF_OP(code);
17554         if (BPF_CLASS(code) == BPF_JMP32)
17555                 return op != BPF_JA;
17556
17557         if (BPF_CLASS(code) != BPF_JMP)
17558                 return false;
17559
17560         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17561 }
17562
17563 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17564 {
17565         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17566         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17567         struct bpf_insn *insn = env->prog->insnsi;
17568         const int insn_cnt = env->prog->len;
17569         int i;
17570
17571         for (i = 0; i < insn_cnt; i++, insn++) {
17572                 if (!insn_is_cond_jump(insn->code))
17573                         continue;
17574
17575                 if (!aux_data[i + 1].seen)
17576                         ja.off = insn->off;
17577                 else if (!aux_data[i + 1 + insn->off].seen)
17578                         ja.off = 0;
17579                 else
17580                         continue;
17581
17582                 if (bpf_prog_is_offloaded(env->prog->aux))
17583                         bpf_prog_offload_replace_insn(env, i, &ja);
17584
17585                 memcpy(insn, &ja, sizeof(ja));
17586         }
17587 }
17588
17589 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17590 {
17591         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17592         int insn_cnt = env->prog->len;
17593         int i, err;
17594
17595         for (i = 0; i < insn_cnt; i++) {
17596                 int j;
17597
17598                 j = 0;
17599                 while (i + j < insn_cnt && !aux_data[i + j].seen)
17600                         j++;
17601                 if (!j)
17602                         continue;
17603
17604                 err = verifier_remove_insns(env, i, j);
17605                 if (err)
17606                         return err;
17607                 insn_cnt = env->prog->len;
17608         }
17609
17610         return 0;
17611 }
17612
17613 static int opt_remove_nops(struct bpf_verifier_env *env)
17614 {
17615         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17616         struct bpf_insn *insn = env->prog->insnsi;
17617         int insn_cnt = env->prog->len;
17618         int i, err;
17619
17620         for (i = 0; i < insn_cnt; i++) {
17621                 if (memcmp(&insn[i], &ja, sizeof(ja)))
17622                         continue;
17623
17624                 err = verifier_remove_insns(env, i, 1);
17625                 if (err)
17626                         return err;
17627                 insn_cnt--;
17628                 i--;
17629         }
17630
17631         return 0;
17632 }
17633
17634 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17635                                          const union bpf_attr *attr)
17636 {
17637         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17638         struct bpf_insn_aux_data *aux = env->insn_aux_data;
17639         int i, patch_len, delta = 0, len = env->prog->len;
17640         struct bpf_insn *insns = env->prog->insnsi;
17641         struct bpf_prog *new_prog;
17642         bool rnd_hi32;
17643
17644         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17645         zext_patch[1] = BPF_ZEXT_REG(0);
17646         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17647         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17648         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17649         for (i = 0; i < len; i++) {
17650                 int adj_idx = i + delta;
17651                 struct bpf_insn insn;
17652                 int load_reg;
17653
17654                 insn = insns[adj_idx];
17655                 load_reg = insn_def_regno(&insn);
17656                 if (!aux[adj_idx].zext_dst) {
17657                         u8 code, class;
17658                         u32 imm_rnd;
17659
17660                         if (!rnd_hi32)
17661                                 continue;
17662
17663                         code = insn.code;
17664                         class = BPF_CLASS(code);
17665                         if (load_reg == -1)
17666                                 continue;
17667
17668                         /* NOTE: arg "reg" (the fourth one) is only used for
17669                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
17670                          *       here.
17671                          */
17672                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17673                                 if (class == BPF_LD &&
17674                                     BPF_MODE(code) == BPF_IMM)
17675                                         i++;
17676                                 continue;
17677                         }
17678
17679                         /* ctx load could be transformed into wider load. */
17680                         if (class == BPF_LDX &&
17681                             aux[adj_idx].ptr_type == PTR_TO_CTX)
17682                                 continue;
17683
17684                         imm_rnd = get_random_u32();
17685                         rnd_hi32_patch[0] = insn;
17686                         rnd_hi32_patch[1].imm = imm_rnd;
17687                         rnd_hi32_patch[3].dst_reg = load_reg;
17688                         patch = rnd_hi32_patch;
17689                         patch_len = 4;
17690                         goto apply_patch_buffer;
17691                 }
17692
17693                 /* Add in an zero-extend instruction if a) the JIT has requested
17694                  * it or b) it's a CMPXCHG.
17695                  *
17696                  * The latter is because: BPF_CMPXCHG always loads a value into
17697                  * R0, therefore always zero-extends. However some archs'
17698                  * equivalent instruction only does this load when the
17699                  * comparison is successful. This detail of CMPXCHG is
17700                  * orthogonal to the general zero-extension behaviour of the
17701                  * CPU, so it's treated independently of bpf_jit_needs_zext.
17702                  */
17703                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17704                         continue;
17705
17706                 /* Zero-extension is done by the caller. */
17707                 if (bpf_pseudo_kfunc_call(&insn))
17708                         continue;
17709
17710                 if (WARN_ON(load_reg == -1)) {
17711                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17712                         return -EFAULT;
17713                 }
17714
17715                 zext_patch[0] = insn;
17716                 zext_patch[1].dst_reg = load_reg;
17717                 zext_patch[1].src_reg = load_reg;
17718                 patch = zext_patch;
17719                 patch_len = 2;
17720 apply_patch_buffer:
17721                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17722                 if (!new_prog)
17723                         return -ENOMEM;
17724                 env->prog = new_prog;
17725                 insns = new_prog->insnsi;
17726                 aux = env->insn_aux_data;
17727                 delta += patch_len - 1;
17728         }
17729
17730         return 0;
17731 }
17732
17733 /* convert load instructions that access fields of a context type into a
17734  * sequence of instructions that access fields of the underlying structure:
17735  *     struct __sk_buff    -> struct sk_buff
17736  *     struct bpf_sock_ops -> struct sock
17737  */
17738 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17739 {
17740         const struct bpf_verifier_ops *ops = env->ops;
17741         int i, cnt, size, ctx_field_size, delta = 0;
17742         const int insn_cnt = env->prog->len;
17743         struct bpf_insn insn_buf[16], *insn;
17744         u32 target_size, size_default, off;
17745         struct bpf_prog *new_prog;
17746         enum bpf_access_type type;
17747         bool is_narrower_load;
17748
17749         if (ops->gen_prologue || env->seen_direct_write) {
17750                 if (!ops->gen_prologue) {
17751                         verbose(env, "bpf verifier is misconfigured\n");
17752                         return -EINVAL;
17753                 }
17754                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17755                                         env->prog);
17756                 if (cnt >= ARRAY_SIZE(insn_buf)) {
17757                         verbose(env, "bpf verifier is misconfigured\n");
17758                         return -EINVAL;
17759                 } else if (cnt) {
17760                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17761                         if (!new_prog)
17762                                 return -ENOMEM;
17763
17764                         env->prog = new_prog;
17765                         delta += cnt - 1;
17766                 }
17767         }
17768
17769         if (bpf_prog_is_offloaded(env->prog->aux))
17770                 return 0;
17771
17772         insn = env->prog->insnsi + delta;
17773
17774         for (i = 0; i < insn_cnt; i++, insn++) {
17775                 bpf_convert_ctx_access_t convert_ctx_access;
17776                 u8 mode;
17777
17778                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17779                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17780                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17781                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17782                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17783                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17784                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17785                         type = BPF_READ;
17786                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17787                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17788                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17789                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17790                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17791                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17792                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17793                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17794                         type = BPF_WRITE;
17795                 } else {
17796                         continue;
17797                 }
17798
17799                 if (type == BPF_WRITE &&
17800                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
17801                         struct bpf_insn patch[] = {
17802                                 *insn,
17803                                 BPF_ST_NOSPEC(),
17804                         };
17805
17806                         cnt = ARRAY_SIZE(patch);
17807                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17808                         if (!new_prog)
17809                                 return -ENOMEM;
17810
17811                         delta    += cnt - 1;
17812                         env->prog = new_prog;
17813                         insn      = new_prog->insnsi + i + delta;
17814                         continue;
17815                 }
17816
17817                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17818                 case PTR_TO_CTX:
17819                         if (!ops->convert_ctx_access)
17820                                 continue;
17821                         convert_ctx_access = ops->convert_ctx_access;
17822                         break;
17823                 case PTR_TO_SOCKET:
17824                 case PTR_TO_SOCK_COMMON:
17825                         convert_ctx_access = bpf_sock_convert_ctx_access;
17826                         break;
17827                 case PTR_TO_TCP_SOCK:
17828                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17829                         break;
17830                 case PTR_TO_XDP_SOCK:
17831                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17832                         break;
17833                 case PTR_TO_BTF_ID:
17834                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17835                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17836                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17837                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
17838                  * any faults for loads into such types. BPF_WRITE is disallowed
17839                  * for this case.
17840                  */
17841                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17842                         if (type == BPF_READ) {
17843                                 if (BPF_MODE(insn->code) == BPF_MEM)
17844                                         insn->code = BPF_LDX | BPF_PROBE_MEM |
17845                                                      BPF_SIZE((insn)->code);
17846                                 else
17847                                         insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17848                                                      BPF_SIZE((insn)->code);
17849                                 env->prog->aux->num_exentries++;
17850                         }
17851                         continue;
17852                 default:
17853                         continue;
17854                 }
17855
17856                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17857                 size = BPF_LDST_BYTES(insn);
17858                 mode = BPF_MODE(insn->code);
17859
17860                 /* If the read access is a narrower load of the field,
17861                  * convert to a 4/8-byte load, to minimum program type specific
17862                  * convert_ctx_access changes. If conversion is successful,
17863                  * we will apply proper mask to the result.
17864                  */
17865                 is_narrower_load = size < ctx_field_size;
17866                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17867                 off = insn->off;
17868                 if (is_narrower_load) {
17869                         u8 size_code;
17870
17871                         if (type == BPF_WRITE) {
17872                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17873                                 return -EINVAL;
17874                         }
17875
17876                         size_code = BPF_H;
17877                         if (ctx_field_size == 4)
17878                                 size_code = BPF_W;
17879                         else if (ctx_field_size == 8)
17880                                 size_code = BPF_DW;
17881
17882                         insn->off = off & ~(size_default - 1);
17883                         insn->code = BPF_LDX | BPF_MEM | size_code;
17884                 }
17885
17886                 target_size = 0;
17887                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17888                                          &target_size);
17889                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17890                     (ctx_field_size && !target_size)) {
17891                         verbose(env, "bpf verifier is misconfigured\n");
17892                         return -EINVAL;
17893                 }
17894
17895                 if (is_narrower_load && size < target_size) {
17896                         u8 shift = bpf_ctx_narrow_access_offset(
17897                                 off, size, size_default) * 8;
17898                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17899                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17900                                 return -EINVAL;
17901                         }
17902                         if (ctx_field_size <= 4) {
17903                                 if (shift)
17904                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17905                                                                         insn->dst_reg,
17906                                                                         shift);
17907                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17908                                                                 (1 << size * 8) - 1);
17909                         } else {
17910                                 if (shift)
17911                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17912                                                                         insn->dst_reg,
17913                                                                         shift);
17914                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17915                                                                 (1ULL << size * 8) - 1);
17916                         }
17917                 }
17918                 if (mode == BPF_MEMSX)
17919                         insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17920                                                        insn->dst_reg, insn->dst_reg,
17921                                                        size * 8, 0);
17922
17923                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17924                 if (!new_prog)
17925                         return -ENOMEM;
17926
17927                 delta += cnt - 1;
17928
17929                 /* keep walking new program and skip insns we just inserted */
17930                 env->prog = new_prog;
17931                 insn      = new_prog->insnsi + i + delta;
17932         }
17933
17934         return 0;
17935 }
17936
17937 static int jit_subprogs(struct bpf_verifier_env *env)
17938 {
17939         struct bpf_prog *prog = env->prog, **func, *tmp;
17940         int i, j, subprog_start, subprog_end = 0, len, subprog;
17941         struct bpf_map *map_ptr;
17942         struct bpf_insn *insn;
17943         void *old_bpf_func;
17944         int err, num_exentries;
17945
17946         if (env->subprog_cnt <= 1)
17947                 return 0;
17948
17949         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17950                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17951                         continue;
17952
17953                 /* Upon error here we cannot fall back to interpreter but
17954                  * need a hard reject of the program. Thus -EFAULT is
17955                  * propagated in any case.
17956                  */
17957                 subprog = find_subprog(env, i + insn->imm + 1);
17958                 if (subprog < 0) {
17959                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17960                                   i + insn->imm + 1);
17961                         return -EFAULT;
17962                 }
17963                 /* temporarily remember subprog id inside insn instead of
17964                  * aux_data, since next loop will split up all insns into funcs
17965                  */
17966                 insn->off = subprog;
17967                 /* remember original imm in case JIT fails and fallback
17968                  * to interpreter will be needed
17969                  */
17970                 env->insn_aux_data[i].call_imm = insn->imm;
17971                 /* point imm to __bpf_call_base+1 from JITs point of view */
17972                 insn->imm = 1;
17973                 if (bpf_pseudo_func(insn))
17974                         /* jit (e.g. x86_64) may emit fewer instructions
17975                          * if it learns a u32 imm is the same as a u64 imm.
17976                          * Force a non zero here.
17977                          */
17978                         insn[1].imm = 1;
17979         }
17980
17981         err = bpf_prog_alloc_jited_linfo(prog);
17982         if (err)
17983                 goto out_undo_insn;
17984
17985         err = -ENOMEM;
17986         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17987         if (!func)
17988                 goto out_undo_insn;
17989
17990         for (i = 0; i < env->subprog_cnt; i++) {
17991                 subprog_start = subprog_end;
17992                 subprog_end = env->subprog_info[i + 1].start;
17993
17994                 len = subprog_end - subprog_start;
17995                 /* bpf_prog_run() doesn't call subprogs directly,
17996                  * hence main prog stats include the runtime of subprogs.
17997                  * subprogs don't have IDs and not reachable via prog_get_next_id
17998                  * func[i]->stats will never be accessed and stays NULL
17999                  */
18000                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18001                 if (!func[i])
18002                         goto out_free;
18003                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18004                        len * sizeof(struct bpf_insn));
18005                 func[i]->type = prog->type;
18006                 func[i]->len = len;
18007                 if (bpf_prog_calc_tag(func[i]))
18008                         goto out_free;
18009                 func[i]->is_func = 1;
18010                 func[i]->aux->func_idx = i;
18011                 /* Below members will be freed only at prog->aux */
18012                 func[i]->aux->btf = prog->aux->btf;
18013                 func[i]->aux->func_info = prog->aux->func_info;
18014                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18015                 func[i]->aux->poke_tab = prog->aux->poke_tab;
18016                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18017
18018                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18019                         struct bpf_jit_poke_descriptor *poke;
18020
18021                         poke = &prog->aux->poke_tab[j];
18022                         if (poke->insn_idx < subprog_end &&
18023                             poke->insn_idx >= subprog_start)
18024                                 poke->aux = func[i]->aux;
18025                 }
18026
18027                 func[i]->aux->name[0] = 'F';
18028                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18029                 func[i]->jit_requested = 1;
18030                 func[i]->blinding_requested = prog->blinding_requested;
18031                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18032                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18033                 func[i]->aux->linfo = prog->aux->linfo;
18034                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18035                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18036                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18037                 num_exentries = 0;
18038                 insn = func[i]->insnsi;
18039                 for (j = 0; j < func[i]->len; j++, insn++) {
18040                         if (BPF_CLASS(insn->code) == BPF_LDX &&
18041                             (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18042                              BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18043                                 num_exentries++;
18044                 }
18045                 func[i]->aux->num_exentries = num_exentries;
18046                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18047                 func[i] = bpf_int_jit_compile(func[i]);
18048                 if (!func[i]->jited) {
18049                         err = -ENOTSUPP;
18050                         goto out_free;
18051                 }
18052                 cond_resched();
18053         }
18054
18055         /* at this point all bpf functions were successfully JITed
18056          * now populate all bpf_calls with correct addresses and
18057          * run last pass of JIT
18058          */
18059         for (i = 0; i < env->subprog_cnt; i++) {
18060                 insn = func[i]->insnsi;
18061                 for (j = 0; j < func[i]->len; j++, insn++) {
18062                         if (bpf_pseudo_func(insn)) {
18063                                 subprog = insn->off;
18064                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18065                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18066                                 continue;
18067                         }
18068                         if (!bpf_pseudo_call(insn))
18069                                 continue;
18070                         subprog = insn->off;
18071                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18072                 }
18073
18074                 /* we use the aux data to keep a list of the start addresses
18075                  * of the JITed images for each function in the program
18076                  *
18077                  * for some architectures, such as powerpc64, the imm field
18078                  * might not be large enough to hold the offset of the start
18079                  * address of the callee's JITed image from __bpf_call_base
18080                  *
18081                  * in such cases, we can lookup the start address of a callee
18082                  * by using its subprog id, available from the off field of
18083                  * the call instruction, as an index for this list
18084                  */
18085                 func[i]->aux->func = func;
18086                 func[i]->aux->func_cnt = env->subprog_cnt;
18087         }
18088         for (i = 0; i < env->subprog_cnt; i++) {
18089                 old_bpf_func = func[i]->bpf_func;
18090                 tmp = bpf_int_jit_compile(func[i]);
18091                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18092                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18093                         err = -ENOTSUPP;
18094                         goto out_free;
18095                 }
18096                 cond_resched();
18097         }
18098
18099         /* finally lock prog and jit images for all functions and
18100          * populate kallsysm. Begin at the first subprogram, since
18101          * bpf_prog_load will add the kallsyms for the main program.
18102          */
18103         for (i = 1; i < env->subprog_cnt; i++) {
18104                 bpf_prog_lock_ro(func[i]);
18105                 bpf_prog_kallsyms_add(func[i]);
18106         }
18107
18108         /* Last step: make now unused interpreter insns from main
18109          * prog consistent for later dump requests, so they can
18110          * later look the same as if they were interpreted only.
18111          */
18112         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18113                 if (bpf_pseudo_func(insn)) {
18114                         insn[0].imm = env->insn_aux_data[i].call_imm;
18115                         insn[1].imm = insn->off;
18116                         insn->off = 0;
18117                         continue;
18118                 }
18119                 if (!bpf_pseudo_call(insn))
18120                         continue;
18121                 insn->off = env->insn_aux_data[i].call_imm;
18122                 subprog = find_subprog(env, i + insn->off + 1);
18123                 insn->imm = subprog;
18124         }
18125
18126         prog->jited = 1;
18127         prog->bpf_func = func[0]->bpf_func;
18128         prog->jited_len = func[0]->jited_len;
18129         prog->aux->extable = func[0]->aux->extable;
18130         prog->aux->num_exentries = func[0]->aux->num_exentries;
18131         prog->aux->func = func;
18132         prog->aux->func_cnt = env->subprog_cnt;
18133         bpf_prog_jit_attempt_done(prog);
18134         return 0;
18135 out_free:
18136         /* We failed JIT'ing, so at this point we need to unregister poke
18137          * descriptors from subprogs, so that kernel is not attempting to
18138          * patch it anymore as we're freeing the subprog JIT memory.
18139          */
18140         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18141                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18142                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18143         }
18144         /* At this point we're guaranteed that poke descriptors are not
18145          * live anymore. We can just unlink its descriptor table as it's
18146          * released with the main prog.
18147          */
18148         for (i = 0; i < env->subprog_cnt; i++) {
18149                 if (!func[i])
18150                         continue;
18151                 func[i]->aux->poke_tab = NULL;
18152                 bpf_jit_free(func[i]);
18153         }
18154         kfree(func);
18155 out_undo_insn:
18156         /* cleanup main prog to be interpreted */
18157         prog->jit_requested = 0;
18158         prog->blinding_requested = 0;
18159         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18160                 if (!bpf_pseudo_call(insn))
18161                         continue;
18162                 insn->off = 0;
18163                 insn->imm = env->insn_aux_data[i].call_imm;
18164         }
18165         bpf_prog_jit_attempt_done(prog);
18166         return err;
18167 }
18168
18169 static int fixup_call_args(struct bpf_verifier_env *env)
18170 {
18171 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18172         struct bpf_prog *prog = env->prog;
18173         struct bpf_insn *insn = prog->insnsi;
18174         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18175         int i, depth;
18176 #endif
18177         int err = 0;
18178
18179         if (env->prog->jit_requested &&
18180             !bpf_prog_is_offloaded(env->prog->aux)) {
18181                 err = jit_subprogs(env);
18182                 if (err == 0)
18183                         return 0;
18184                 if (err == -EFAULT)
18185                         return err;
18186         }
18187 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18188         if (has_kfunc_call) {
18189                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18190                 return -EINVAL;
18191         }
18192         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18193                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18194                  * have to be rejected, since interpreter doesn't support them yet.
18195                  */
18196                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18197                 return -EINVAL;
18198         }
18199         for (i = 0; i < prog->len; i++, insn++) {
18200                 if (bpf_pseudo_func(insn)) {
18201                         /* When JIT fails the progs with callback calls
18202                          * have to be rejected, since interpreter doesn't support them yet.
18203                          */
18204                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
18205                         return -EINVAL;
18206                 }
18207
18208                 if (!bpf_pseudo_call(insn))
18209                         continue;
18210                 depth = get_callee_stack_depth(env, insn, i);
18211                 if (depth < 0)
18212                         return depth;
18213                 bpf_patch_call_args(insn, depth);
18214         }
18215         err = 0;
18216 #endif
18217         return err;
18218 }
18219
18220 /* replace a generic kfunc with a specialized version if necessary */
18221 static void specialize_kfunc(struct bpf_verifier_env *env,
18222                              u32 func_id, u16 offset, unsigned long *addr)
18223 {
18224         struct bpf_prog *prog = env->prog;
18225         bool seen_direct_write;
18226         void *xdp_kfunc;
18227         bool is_rdonly;
18228
18229         if (bpf_dev_bound_kfunc_id(func_id)) {
18230                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18231                 if (xdp_kfunc) {
18232                         *addr = (unsigned long)xdp_kfunc;
18233                         return;
18234                 }
18235                 /* fallback to default kfunc when not supported by netdev */
18236         }
18237
18238         if (offset)
18239                 return;
18240
18241         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18242                 seen_direct_write = env->seen_direct_write;
18243                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18244
18245                 if (is_rdonly)
18246                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18247
18248                 /* restore env->seen_direct_write to its original value, since
18249                  * may_access_direct_pkt_data mutates it
18250                  */
18251                 env->seen_direct_write = seen_direct_write;
18252         }
18253 }
18254
18255 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18256                                             u16 struct_meta_reg,
18257                                             u16 node_offset_reg,
18258                                             struct bpf_insn *insn,
18259                                             struct bpf_insn *insn_buf,
18260                                             int *cnt)
18261 {
18262         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18263         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18264
18265         insn_buf[0] = addr[0];
18266         insn_buf[1] = addr[1];
18267         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18268         insn_buf[3] = *insn;
18269         *cnt = 4;
18270 }
18271
18272 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18273                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18274 {
18275         const struct bpf_kfunc_desc *desc;
18276
18277         if (!insn->imm) {
18278                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18279                 return -EINVAL;
18280         }
18281
18282         *cnt = 0;
18283
18284         /* insn->imm has the btf func_id. Replace it with an offset relative to
18285          * __bpf_call_base, unless the JIT needs to call functions that are
18286          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18287          */
18288         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18289         if (!desc) {
18290                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18291                         insn->imm);
18292                 return -EFAULT;
18293         }
18294
18295         if (!bpf_jit_supports_far_kfunc_call())
18296                 insn->imm = BPF_CALL_IMM(desc->addr);
18297         if (insn->off)
18298                 return 0;
18299         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18300                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18301                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18302                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18303
18304                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18305                 insn_buf[1] = addr[0];
18306                 insn_buf[2] = addr[1];
18307                 insn_buf[3] = *insn;
18308                 *cnt = 4;
18309         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18310                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18311                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18312                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18313
18314                 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18315                     !kptr_struct_meta) {
18316                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18317                                 insn_idx);
18318                         return -EFAULT;
18319                 }
18320
18321                 insn_buf[0] = addr[0];
18322                 insn_buf[1] = addr[1];
18323                 insn_buf[2] = *insn;
18324                 *cnt = 3;
18325         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18326                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18327                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18328                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18329                 int struct_meta_reg = BPF_REG_3;
18330                 int node_offset_reg = BPF_REG_4;
18331
18332                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18333                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18334                         struct_meta_reg = BPF_REG_4;
18335                         node_offset_reg = BPF_REG_5;
18336                 }
18337
18338                 if (!kptr_struct_meta) {
18339                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18340                                 insn_idx);
18341                         return -EFAULT;
18342                 }
18343
18344                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18345                                                 node_offset_reg, insn, insn_buf, cnt);
18346         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18347                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18348                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18349                 *cnt = 1;
18350         }
18351         return 0;
18352 }
18353
18354 /* Do various post-verification rewrites in a single program pass.
18355  * These rewrites simplify JIT and interpreter implementations.
18356  */
18357 static int do_misc_fixups(struct bpf_verifier_env *env)
18358 {
18359         struct bpf_prog *prog = env->prog;
18360         enum bpf_attach_type eatype = prog->expected_attach_type;
18361         enum bpf_prog_type prog_type = resolve_prog_type(prog);
18362         struct bpf_insn *insn = prog->insnsi;
18363         const struct bpf_func_proto *fn;
18364         const int insn_cnt = prog->len;
18365         const struct bpf_map_ops *ops;
18366         struct bpf_insn_aux_data *aux;
18367         struct bpf_insn insn_buf[16];
18368         struct bpf_prog *new_prog;
18369         struct bpf_map *map_ptr;
18370         int i, ret, cnt, delta = 0;
18371
18372         for (i = 0; i < insn_cnt; i++, insn++) {
18373                 /* Make divide-by-zero exceptions impossible. */
18374                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18375                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18376                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18377                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18378                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18379                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18380                         struct bpf_insn *patchlet;
18381                         struct bpf_insn chk_and_div[] = {
18382                                 /* [R,W]x div 0 -> 0 */
18383                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18384                                              BPF_JNE | BPF_K, insn->src_reg,
18385                                              0, 2, 0),
18386                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18387                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18388                                 *insn,
18389                         };
18390                         struct bpf_insn chk_and_mod[] = {
18391                                 /* [R,W]x mod 0 -> [R,W]x */
18392                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18393                                              BPF_JEQ | BPF_K, insn->src_reg,
18394                                              0, 1 + (is64 ? 0 : 1), 0),
18395                                 *insn,
18396                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18397                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18398                         };
18399
18400                         patchlet = isdiv ? chk_and_div : chk_and_mod;
18401                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18402                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18403
18404                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18405                         if (!new_prog)
18406                                 return -ENOMEM;
18407
18408                         delta    += cnt - 1;
18409                         env->prog = prog = new_prog;
18410                         insn      = new_prog->insnsi + i + delta;
18411                         continue;
18412                 }
18413
18414                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18415                 if (BPF_CLASS(insn->code) == BPF_LD &&
18416                     (BPF_MODE(insn->code) == BPF_ABS ||
18417                      BPF_MODE(insn->code) == BPF_IND)) {
18418                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
18419                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18420                                 verbose(env, "bpf verifier is misconfigured\n");
18421                                 return -EINVAL;
18422                         }
18423
18424                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18425                         if (!new_prog)
18426                                 return -ENOMEM;
18427
18428                         delta    += cnt - 1;
18429                         env->prog = prog = new_prog;
18430                         insn      = new_prog->insnsi + i + delta;
18431                         continue;
18432                 }
18433
18434                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18435                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18436                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18437                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18438                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18439                         struct bpf_insn *patch = &insn_buf[0];
18440                         bool issrc, isneg, isimm;
18441                         u32 off_reg;
18442
18443                         aux = &env->insn_aux_data[i + delta];
18444                         if (!aux->alu_state ||
18445                             aux->alu_state == BPF_ALU_NON_POINTER)
18446                                 continue;
18447
18448                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18449                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18450                                 BPF_ALU_SANITIZE_SRC;
18451                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18452
18453                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
18454                         if (isimm) {
18455                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18456                         } else {
18457                                 if (isneg)
18458                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18459                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18460                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18461                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18462                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18463                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18464                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18465                         }
18466                         if (!issrc)
18467                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18468                         insn->src_reg = BPF_REG_AX;
18469                         if (isneg)
18470                                 insn->code = insn->code == code_add ?
18471                                              code_sub : code_add;
18472                         *patch++ = *insn;
18473                         if (issrc && isneg && !isimm)
18474                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18475                         cnt = patch - insn_buf;
18476
18477                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18478                         if (!new_prog)
18479                                 return -ENOMEM;
18480
18481                         delta    += cnt - 1;
18482                         env->prog = prog = new_prog;
18483                         insn      = new_prog->insnsi + i + delta;
18484                         continue;
18485                 }
18486
18487                 if (insn->code != (BPF_JMP | BPF_CALL))
18488                         continue;
18489                 if (insn->src_reg == BPF_PSEUDO_CALL)
18490                         continue;
18491                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18492                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18493                         if (ret)
18494                                 return ret;
18495                         if (cnt == 0)
18496                                 continue;
18497
18498                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18499                         if (!new_prog)
18500                                 return -ENOMEM;
18501
18502                         delta    += cnt - 1;
18503                         env->prog = prog = new_prog;
18504                         insn      = new_prog->insnsi + i + delta;
18505                         continue;
18506                 }
18507
18508                 if (insn->imm == BPF_FUNC_get_route_realm)
18509                         prog->dst_needed = 1;
18510                 if (insn->imm == BPF_FUNC_get_prandom_u32)
18511                         bpf_user_rnd_init_once();
18512                 if (insn->imm == BPF_FUNC_override_return)
18513                         prog->kprobe_override = 1;
18514                 if (insn->imm == BPF_FUNC_tail_call) {
18515                         /* If we tail call into other programs, we
18516                          * cannot make any assumptions since they can
18517                          * be replaced dynamically during runtime in
18518                          * the program array.
18519                          */
18520                         prog->cb_access = 1;
18521                         if (!allow_tail_call_in_subprogs(env))
18522                                 prog->aux->stack_depth = MAX_BPF_STACK;
18523                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18524
18525                         /* mark bpf_tail_call as different opcode to avoid
18526                          * conditional branch in the interpreter for every normal
18527                          * call and to prevent accidental JITing by JIT compiler
18528                          * that doesn't support bpf_tail_call yet
18529                          */
18530                         insn->imm = 0;
18531                         insn->code = BPF_JMP | BPF_TAIL_CALL;
18532
18533                         aux = &env->insn_aux_data[i + delta];
18534                         if (env->bpf_capable && !prog->blinding_requested &&
18535                             prog->jit_requested &&
18536                             !bpf_map_key_poisoned(aux) &&
18537                             !bpf_map_ptr_poisoned(aux) &&
18538                             !bpf_map_ptr_unpriv(aux)) {
18539                                 struct bpf_jit_poke_descriptor desc = {
18540                                         .reason = BPF_POKE_REASON_TAIL_CALL,
18541                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18542                                         .tail_call.key = bpf_map_key_immediate(aux),
18543                                         .insn_idx = i + delta,
18544                                 };
18545
18546                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18547                                 if (ret < 0) {
18548                                         verbose(env, "adding tail call poke descriptor failed\n");
18549                                         return ret;
18550                                 }
18551
18552                                 insn->imm = ret + 1;
18553                                 continue;
18554                         }
18555
18556                         if (!bpf_map_ptr_unpriv(aux))
18557                                 continue;
18558
18559                         /* instead of changing every JIT dealing with tail_call
18560                          * emit two extra insns:
18561                          * if (index >= max_entries) goto out;
18562                          * index &= array->index_mask;
18563                          * to avoid out-of-bounds cpu speculation
18564                          */
18565                         if (bpf_map_ptr_poisoned(aux)) {
18566                                 verbose(env, "tail_call abusing map_ptr\n");
18567                                 return -EINVAL;
18568                         }
18569
18570                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18571                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18572                                                   map_ptr->max_entries, 2);
18573                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18574                                                     container_of(map_ptr,
18575                                                                  struct bpf_array,
18576                                                                  map)->index_mask);
18577                         insn_buf[2] = *insn;
18578                         cnt = 3;
18579                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18580                         if (!new_prog)
18581                                 return -ENOMEM;
18582
18583                         delta    += cnt - 1;
18584                         env->prog = prog = new_prog;
18585                         insn      = new_prog->insnsi + i + delta;
18586                         continue;
18587                 }
18588
18589                 if (insn->imm == BPF_FUNC_timer_set_callback) {
18590                         /* The verifier will process callback_fn as many times as necessary
18591                          * with different maps and the register states prepared by
18592                          * set_timer_callback_state will be accurate.
18593                          *
18594                          * The following use case is valid:
18595                          *   map1 is shared by prog1, prog2, prog3.
18596                          *   prog1 calls bpf_timer_init for some map1 elements
18597                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
18598                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
18599                          *   prog3 calls bpf_timer_start for some map1 elements.
18600                          *     Those that were not both bpf_timer_init-ed and
18601                          *     bpf_timer_set_callback-ed will return -EINVAL.
18602                          */
18603                         struct bpf_insn ld_addrs[2] = {
18604                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18605                         };
18606
18607                         insn_buf[0] = ld_addrs[0];
18608                         insn_buf[1] = ld_addrs[1];
18609                         insn_buf[2] = *insn;
18610                         cnt = 3;
18611
18612                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18613                         if (!new_prog)
18614                                 return -ENOMEM;
18615
18616                         delta    += cnt - 1;
18617                         env->prog = prog = new_prog;
18618                         insn      = new_prog->insnsi + i + delta;
18619                         goto patch_call_imm;
18620                 }
18621
18622                 if (is_storage_get_function(insn->imm)) {
18623                         if (!env->prog->aux->sleepable ||
18624                             env->insn_aux_data[i + delta].storage_get_func_atomic)
18625                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18626                         else
18627                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18628                         insn_buf[1] = *insn;
18629                         cnt = 2;
18630
18631                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18632                         if (!new_prog)
18633                                 return -ENOMEM;
18634
18635                         delta += cnt - 1;
18636                         env->prog = prog = new_prog;
18637                         insn = new_prog->insnsi + i + delta;
18638                         goto patch_call_imm;
18639                 }
18640
18641                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18642                  * and other inlining handlers are currently limited to 64 bit
18643                  * only.
18644                  */
18645                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18646                     (insn->imm == BPF_FUNC_map_lookup_elem ||
18647                      insn->imm == BPF_FUNC_map_update_elem ||
18648                      insn->imm == BPF_FUNC_map_delete_elem ||
18649                      insn->imm == BPF_FUNC_map_push_elem   ||
18650                      insn->imm == BPF_FUNC_map_pop_elem    ||
18651                      insn->imm == BPF_FUNC_map_peek_elem   ||
18652                      insn->imm == BPF_FUNC_redirect_map    ||
18653                      insn->imm == BPF_FUNC_for_each_map_elem ||
18654                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18655                         aux = &env->insn_aux_data[i + delta];
18656                         if (bpf_map_ptr_poisoned(aux))
18657                                 goto patch_call_imm;
18658
18659                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18660                         ops = map_ptr->ops;
18661                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
18662                             ops->map_gen_lookup) {
18663                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18664                                 if (cnt == -EOPNOTSUPP)
18665                                         goto patch_map_ops_generic;
18666                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18667                                         verbose(env, "bpf verifier is misconfigured\n");
18668                                         return -EINVAL;
18669                                 }
18670
18671                                 new_prog = bpf_patch_insn_data(env, i + delta,
18672                                                                insn_buf, cnt);
18673                                 if (!new_prog)
18674                                         return -ENOMEM;
18675
18676                                 delta    += cnt - 1;
18677                                 env->prog = prog = new_prog;
18678                                 insn      = new_prog->insnsi + i + delta;
18679                                 continue;
18680                         }
18681
18682                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18683                                      (void *(*)(struct bpf_map *map, void *key))NULL));
18684                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18685                                      (long (*)(struct bpf_map *map, void *key))NULL));
18686                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18687                                      (long (*)(struct bpf_map *map, void *key, void *value,
18688                                               u64 flags))NULL));
18689                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18690                                      (long (*)(struct bpf_map *map, void *value,
18691                                               u64 flags))NULL));
18692                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18693                                      (long (*)(struct bpf_map *map, void *value))NULL));
18694                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18695                                      (long (*)(struct bpf_map *map, void *value))NULL));
18696                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
18697                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18698                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18699                                      (long (*)(struct bpf_map *map,
18700                                               bpf_callback_t callback_fn,
18701                                               void *callback_ctx,
18702                                               u64 flags))NULL));
18703                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18704                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18705
18706 patch_map_ops_generic:
18707                         switch (insn->imm) {
18708                         case BPF_FUNC_map_lookup_elem:
18709                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18710                                 continue;
18711                         case BPF_FUNC_map_update_elem:
18712                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18713                                 continue;
18714                         case BPF_FUNC_map_delete_elem:
18715                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18716                                 continue;
18717                         case BPF_FUNC_map_push_elem:
18718                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18719                                 continue;
18720                         case BPF_FUNC_map_pop_elem:
18721                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18722                                 continue;
18723                         case BPF_FUNC_map_peek_elem:
18724                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18725                                 continue;
18726                         case BPF_FUNC_redirect_map:
18727                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18728                                 continue;
18729                         case BPF_FUNC_for_each_map_elem:
18730                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18731                                 continue;
18732                         case BPF_FUNC_map_lookup_percpu_elem:
18733                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18734                                 continue;
18735                         }
18736
18737                         goto patch_call_imm;
18738                 }
18739
18740                 /* Implement bpf_jiffies64 inline. */
18741                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18742                     insn->imm == BPF_FUNC_jiffies64) {
18743                         struct bpf_insn ld_jiffies_addr[2] = {
18744                                 BPF_LD_IMM64(BPF_REG_0,
18745                                              (unsigned long)&jiffies),
18746                         };
18747
18748                         insn_buf[0] = ld_jiffies_addr[0];
18749                         insn_buf[1] = ld_jiffies_addr[1];
18750                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18751                                                   BPF_REG_0, 0);
18752                         cnt = 3;
18753
18754                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18755                                                        cnt);
18756                         if (!new_prog)
18757                                 return -ENOMEM;
18758
18759                         delta    += cnt - 1;
18760                         env->prog = prog = new_prog;
18761                         insn      = new_prog->insnsi + i + delta;
18762                         continue;
18763                 }
18764
18765                 /* Implement bpf_get_func_arg inline. */
18766                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18767                     insn->imm == BPF_FUNC_get_func_arg) {
18768                         /* Load nr_args from ctx - 8 */
18769                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18770                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18771                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18772                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18773                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18774                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18775                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18776                         insn_buf[7] = BPF_JMP_A(1);
18777                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18778                         cnt = 9;
18779
18780                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18781                         if (!new_prog)
18782                                 return -ENOMEM;
18783
18784                         delta    += cnt - 1;
18785                         env->prog = prog = new_prog;
18786                         insn      = new_prog->insnsi + i + delta;
18787                         continue;
18788                 }
18789
18790                 /* Implement bpf_get_func_ret inline. */
18791                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18792                     insn->imm == BPF_FUNC_get_func_ret) {
18793                         if (eatype == BPF_TRACE_FEXIT ||
18794                             eatype == BPF_MODIFY_RETURN) {
18795                                 /* Load nr_args from ctx - 8 */
18796                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18797                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18798                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18799                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18800                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18801                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18802                                 cnt = 6;
18803                         } else {
18804                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18805                                 cnt = 1;
18806                         }
18807
18808                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18809                         if (!new_prog)
18810                                 return -ENOMEM;
18811
18812                         delta    += cnt - 1;
18813                         env->prog = prog = new_prog;
18814                         insn      = new_prog->insnsi + i + delta;
18815                         continue;
18816                 }
18817
18818                 /* Implement get_func_arg_cnt inline. */
18819                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18820                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
18821                         /* Load nr_args from ctx - 8 */
18822                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18823
18824                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18825                         if (!new_prog)
18826                                 return -ENOMEM;
18827
18828                         env->prog = prog = new_prog;
18829                         insn      = new_prog->insnsi + i + delta;
18830                         continue;
18831                 }
18832
18833                 /* Implement bpf_get_func_ip inline. */
18834                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18835                     insn->imm == BPF_FUNC_get_func_ip) {
18836                         /* Load IP address from ctx - 16 */
18837                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18838
18839                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18840                         if (!new_prog)
18841                                 return -ENOMEM;
18842
18843                         env->prog = prog = new_prog;
18844                         insn      = new_prog->insnsi + i + delta;
18845                         continue;
18846                 }
18847
18848 patch_call_imm:
18849                 fn = env->ops->get_func_proto(insn->imm, env->prog);
18850                 /* all functions that have prototype and verifier allowed
18851                  * programs to call them, must be real in-kernel functions
18852                  */
18853                 if (!fn->func) {
18854                         verbose(env,
18855                                 "kernel subsystem misconfigured func %s#%d\n",
18856                                 func_id_name(insn->imm), insn->imm);
18857                         return -EFAULT;
18858                 }
18859                 insn->imm = fn->func - __bpf_call_base;
18860         }
18861
18862         /* Since poke tab is now finalized, publish aux to tracker. */
18863         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18864                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18865                 if (!map_ptr->ops->map_poke_track ||
18866                     !map_ptr->ops->map_poke_untrack ||
18867                     !map_ptr->ops->map_poke_run) {
18868                         verbose(env, "bpf verifier is misconfigured\n");
18869                         return -EINVAL;
18870                 }
18871
18872                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18873                 if (ret < 0) {
18874                         verbose(env, "tracking tail call prog failed\n");
18875                         return ret;
18876                 }
18877         }
18878
18879         sort_kfunc_descs_by_imm_off(env->prog);
18880
18881         return 0;
18882 }
18883
18884 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18885                                         int position,
18886                                         s32 stack_base,
18887                                         u32 callback_subprogno,
18888                                         u32 *cnt)
18889 {
18890         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18891         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18892         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18893         int reg_loop_max = BPF_REG_6;
18894         int reg_loop_cnt = BPF_REG_7;
18895         int reg_loop_ctx = BPF_REG_8;
18896
18897         struct bpf_prog *new_prog;
18898         u32 callback_start;
18899         u32 call_insn_offset;
18900         s32 callback_offset;
18901
18902         /* This represents an inlined version of bpf_iter.c:bpf_loop,
18903          * be careful to modify this code in sync.
18904          */
18905         struct bpf_insn insn_buf[] = {
18906                 /* Return error and jump to the end of the patch if
18907                  * expected number of iterations is too big.
18908                  */
18909                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18910                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18911                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18912                 /* spill R6, R7, R8 to use these as loop vars */
18913                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18914                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18915                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18916                 /* initialize loop vars */
18917                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18918                 BPF_MOV32_IMM(reg_loop_cnt, 0),
18919                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18920                 /* loop header,
18921                  * if reg_loop_cnt >= reg_loop_max skip the loop body
18922                  */
18923                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18924                 /* callback call,
18925                  * correct callback offset would be set after patching
18926                  */
18927                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18928                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18929                 BPF_CALL_REL(0),
18930                 /* increment loop counter */
18931                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18932                 /* jump to loop header if callback returned 0 */
18933                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18934                 /* return value of bpf_loop,
18935                  * set R0 to the number of iterations
18936                  */
18937                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18938                 /* restore original values of R6, R7, R8 */
18939                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18940                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18941                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18942         };
18943
18944         *cnt = ARRAY_SIZE(insn_buf);
18945         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18946         if (!new_prog)
18947                 return new_prog;
18948
18949         /* callback start is known only after patching */
18950         callback_start = env->subprog_info[callback_subprogno].start;
18951         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18952         call_insn_offset = position + 12;
18953         callback_offset = callback_start - call_insn_offset - 1;
18954         new_prog->insnsi[call_insn_offset].imm = callback_offset;
18955
18956         return new_prog;
18957 }
18958
18959 static bool is_bpf_loop_call(struct bpf_insn *insn)
18960 {
18961         return insn->code == (BPF_JMP | BPF_CALL) &&
18962                 insn->src_reg == 0 &&
18963                 insn->imm == BPF_FUNC_loop;
18964 }
18965
18966 /* For all sub-programs in the program (including main) check
18967  * insn_aux_data to see if there are bpf_loop calls that require
18968  * inlining. If such calls are found the calls are replaced with a
18969  * sequence of instructions produced by `inline_bpf_loop` function and
18970  * subprog stack_depth is increased by the size of 3 registers.
18971  * This stack space is used to spill values of the R6, R7, R8.  These
18972  * registers are used to store the loop bound, counter and context
18973  * variables.
18974  */
18975 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18976 {
18977         struct bpf_subprog_info *subprogs = env->subprog_info;
18978         int i, cur_subprog = 0, cnt, delta = 0;
18979         struct bpf_insn *insn = env->prog->insnsi;
18980         int insn_cnt = env->prog->len;
18981         u16 stack_depth = subprogs[cur_subprog].stack_depth;
18982         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18983         u16 stack_depth_extra = 0;
18984
18985         for (i = 0; i < insn_cnt; i++, insn++) {
18986                 struct bpf_loop_inline_state *inline_state =
18987                         &env->insn_aux_data[i + delta].loop_inline_state;
18988
18989                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18990                         struct bpf_prog *new_prog;
18991
18992                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18993                         new_prog = inline_bpf_loop(env,
18994                                                    i + delta,
18995                                                    -(stack_depth + stack_depth_extra),
18996                                                    inline_state->callback_subprogno,
18997                                                    &cnt);
18998                         if (!new_prog)
18999                                 return -ENOMEM;
19000
19001                         delta     += cnt - 1;
19002                         env->prog  = new_prog;
19003                         insn       = new_prog->insnsi + i + delta;
19004                 }
19005
19006                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19007                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
19008                         cur_subprog++;
19009                         stack_depth = subprogs[cur_subprog].stack_depth;
19010                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19011                         stack_depth_extra = 0;
19012                 }
19013         }
19014
19015         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19016
19017         return 0;
19018 }
19019
19020 static void free_states(struct bpf_verifier_env *env)
19021 {
19022         struct bpf_verifier_state_list *sl, *sln;
19023         int i;
19024
19025         sl = env->free_list;
19026         while (sl) {
19027                 sln = sl->next;
19028                 free_verifier_state(&sl->state, false);
19029                 kfree(sl);
19030                 sl = sln;
19031         }
19032         env->free_list = NULL;
19033
19034         if (!env->explored_states)
19035                 return;
19036
19037         for (i = 0; i < state_htab_size(env); i++) {
19038                 sl = env->explored_states[i];
19039
19040                 while (sl) {
19041                         sln = sl->next;
19042                         free_verifier_state(&sl->state, false);
19043                         kfree(sl);
19044                         sl = sln;
19045                 }
19046                 env->explored_states[i] = NULL;
19047         }
19048 }
19049
19050 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19051 {
19052         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19053         struct bpf_verifier_state *state;
19054         struct bpf_reg_state *regs;
19055         int ret, i;
19056
19057         env->prev_linfo = NULL;
19058         env->pass_cnt++;
19059
19060         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19061         if (!state)
19062                 return -ENOMEM;
19063         state->curframe = 0;
19064         state->speculative = false;
19065         state->branches = 1;
19066         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19067         if (!state->frame[0]) {
19068                 kfree(state);
19069                 return -ENOMEM;
19070         }
19071         env->cur_state = state;
19072         init_func_state(env, state->frame[0],
19073                         BPF_MAIN_FUNC /* callsite */,
19074                         0 /* frameno */,
19075                         subprog);
19076         state->first_insn_idx = env->subprog_info[subprog].start;
19077         state->last_insn_idx = -1;
19078
19079         regs = state->frame[state->curframe]->regs;
19080         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19081                 ret = btf_prepare_func_args(env, subprog, regs);
19082                 if (ret)
19083                         goto out;
19084                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19085                         if (regs[i].type == PTR_TO_CTX)
19086                                 mark_reg_known_zero(env, regs, i);
19087                         else if (regs[i].type == SCALAR_VALUE)
19088                                 mark_reg_unknown(env, regs, i);
19089                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
19090                                 const u32 mem_size = regs[i].mem_size;
19091
19092                                 mark_reg_known_zero(env, regs, i);
19093                                 regs[i].mem_size = mem_size;
19094                                 regs[i].id = ++env->id_gen;
19095                         }
19096                 }
19097         } else {
19098                 /* 1st arg to a function */
19099                 regs[BPF_REG_1].type = PTR_TO_CTX;
19100                 mark_reg_known_zero(env, regs, BPF_REG_1);
19101                 ret = btf_check_subprog_arg_match(env, subprog, regs);
19102                 if (ret == -EFAULT)
19103                         /* unlikely verifier bug. abort.
19104                          * ret == 0 and ret < 0 are sadly acceptable for
19105                          * main() function due to backward compatibility.
19106                          * Like socket filter program may be written as:
19107                          * int bpf_prog(struct pt_regs *ctx)
19108                          * and never dereference that ctx in the program.
19109                          * 'struct pt_regs' is a type mismatch for socket
19110                          * filter that should be using 'struct __sk_buff'.
19111                          */
19112                         goto out;
19113         }
19114
19115         ret = do_check(env);
19116 out:
19117         /* check for NULL is necessary, since cur_state can be freed inside
19118          * do_check() under memory pressure.
19119          */
19120         if (env->cur_state) {
19121                 free_verifier_state(env->cur_state, true);
19122                 env->cur_state = NULL;
19123         }
19124         while (!pop_stack(env, NULL, NULL, false));
19125         if (!ret && pop_log)
19126                 bpf_vlog_reset(&env->log, 0);
19127         free_states(env);
19128         return ret;
19129 }
19130
19131 /* Verify all global functions in a BPF program one by one based on their BTF.
19132  * All global functions must pass verification. Otherwise the whole program is rejected.
19133  * Consider:
19134  * int bar(int);
19135  * int foo(int f)
19136  * {
19137  *    return bar(f);
19138  * }
19139  * int bar(int b)
19140  * {
19141  *    ...
19142  * }
19143  * foo() will be verified first for R1=any_scalar_value. During verification it
19144  * will be assumed that bar() already verified successfully and call to bar()
19145  * from foo() will be checked for type match only. Later bar() will be verified
19146  * independently to check that it's safe for R1=any_scalar_value.
19147  */
19148 static int do_check_subprogs(struct bpf_verifier_env *env)
19149 {
19150         struct bpf_prog_aux *aux = env->prog->aux;
19151         int i, ret;
19152
19153         if (!aux->func_info)
19154                 return 0;
19155
19156         for (i = 1; i < env->subprog_cnt; i++) {
19157                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19158                         continue;
19159                 env->insn_idx = env->subprog_info[i].start;
19160                 WARN_ON_ONCE(env->insn_idx == 0);
19161                 ret = do_check_common(env, i);
19162                 if (ret) {
19163                         return ret;
19164                 } else if (env->log.level & BPF_LOG_LEVEL) {
19165                         verbose(env,
19166                                 "Func#%d is safe for any args that match its prototype\n",
19167                                 i);
19168                 }
19169         }
19170         return 0;
19171 }
19172
19173 static int do_check_main(struct bpf_verifier_env *env)
19174 {
19175         int ret;
19176
19177         env->insn_idx = 0;
19178         ret = do_check_common(env, 0);
19179         if (!ret)
19180                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19181         return ret;
19182 }
19183
19184
19185 static void print_verification_stats(struct bpf_verifier_env *env)
19186 {
19187         int i;
19188
19189         if (env->log.level & BPF_LOG_STATS) {
19190                 verbose(env, "verification time %lld usec\n",
19191                         div_u64(env->verification_time, 1000));
19192                 verbose(env, "stack depth ");
19193                 for (i = 0; i < env->subprog_cnt; i++) {
19194                         u32 depth = env->subprog_info[i].stack_depth;
19195
19196                         verbose(env, "%d", depth);
19197                         if (i + 1 < env->subprog_cnt)
19198                                 verbose(env, "+");
19199                 }
19200                 verbose(env, "\n");
19201         }
19202         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19203                 "total_states %d peak_states %d mark_read %d\n",
19204                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19205                 env->max_states_per_insn, env->total_states,
19206                 env->peak_states, env->longest_mark_read_walk);
19207 }
19208
19209 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19210 {
19211         const struct btf_type *t, *func_proto;
19212         const struct bpf_struct_ops *st_ops;
19213         const struct btf_member *member;
19214         struct bpf_prog *prog = env->prog;
19215         u32 btf_id, member_idx;
19216         const char *mname;
19217
19218         if (!prog->gpl_compatible) {
19219                 verbose(env, "struct ops programs must have a GPL compatible license\n");
19220                 return -EINVAL;
19221         }
19222
19223         btf_id = prog->aux->attach_btf_id;
19224         st_ops = bpf_struct_ops_find(btf_id);
19225         if (!st_ops) {
19226                 verbose(env, "attach_btf_id %u is not a supported struct\n",
19227                         btf_id);
19228                 return -ENOTSUPP;
19229         }
19230
19231         t = st_ops->type;
19232         member_idx = prog->expected_attach_type;
19233         if (member_idx >= btf_type_vlen(t)) {
19234                 verbose(env, "attach to invalid member idx %u of struct %s\n",
19235                         member_idx, st_ops->name);
19236                 return -EINVAL;
19237         }
19238
19239         member = &btf_type_member(t)[member_idx];
19240         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19241         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19242                                                NULL);
19243         if (!func_proto) {
19244                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19245                         mname, member_idx, st_ops->name);
19246                 return -EINVAL;
19247         }
19248
19249         if (st_ops->check_member) {
19250                 int err = st_ops->check_member(t, member, prog);
19251
19252                 if (err) {
19253                         verbose(env, "attach to unsupported member %s of struct %s\n",
19254                                 mname, st_ops->name);
19255                         return err;
19256                 }
19257         }
19258
19259         prog->aux->attach_func_proto = func_proto;
19260         prog->aux->attach_func_name = mname;
19261         env->ops = st_ops->verifier_ops;
19262
19263         return 0;
19264 }
19265 #define SECURITY_PREFIX "security_"
19266
19267 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19268 {
19269         if (within_error_injection_list(addr) ||
19270             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19271                 return 0;
19272
19273         return -EINVAL;
19274 }
19275
19276 /* list of non-sleepable functions that are otherwise on
19277  * ALLOW_ERROR_INJECTION list
19278  */
19279 BTF_SET_START(btf_non_sleepable_error_inject)
19280 /* Three functions below can be called from sleepable and non-sleepable context.
19281  * Assume non-sleepable from bpf safety point of view.
19282  */
19283 BTF_ID(func, __filemap_add_folio)
19284 BTF_ID(func, should_fail_alloc_page)
19285 BTF_ID(func, should_failslab)
19286 BTF_SET_END(btf_non_sleepable_error_inject)
19287
19288 static int check_non_sleepable_error_inject(u32 btf_id)
19289 {
19290         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19291 }
19292
19293 int bpf_check_attach_target(struct bpf_verifier_log *log,
19294                             const struct bpf_prog *prog,
19295                             const struct bpf_prog *tgt_prog,
19296                             u32 btf_id,
19297                             struct bpf_attach_target_info *tgt_info)
19298 {
19299         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19300         const char prefix[] = "btf_trace_";
19301         int ret = 0, subprog = -1, i;
19302         const struct btf_type *t;
19303         bool conservative = true;
19304         const char *tname;
19305         struct btf *btf;
19306         long addr = 0;
19307         struct module *mod = NULL;
19308
19309         if (!btf_id) {
19310                 bpf_log(log, "Tracing programs must provide btf_id\n");
19311                 return -EINVAL;
19312         }
19313         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19314         if (!btf) {
19315                 bpf_log(log,
19316                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19317                 return -EINVAL;
19318         }
19319         t = btf_type_by_id(btf, btf_id);
19320         if (!t) {
19321                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19322                 return -EINVAL;
19323         }
19324         tname = btf_name_by_offset(btf, t->name_off);
19325         if (!tname) {
19326                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19327                 return -EINVAL;
19328         }
19329         if (tgt_prog) {
19330                 struct bpf_prog_aux *aux = tgt_prog->aux;
19331
19332                 if (bpf_prog_is_dev_bound(prog->aux) &&
19333                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19334                         bpf_log(log, "Target program bound device mismatch");
19335                         return -EINVAL;
19336                 }
19337
19338                 for (i = 0; i < aux->func_info_cnt; i++)
19339                         if (aux->func_info[i].type_id == btf_id) {
19340                                 subprog = i;
19341                                 break;
19342                         }
19343                 if (subprog == -1) {
19344                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
19345                         return -EINVAL;
19346                 }
19347                 conservative = aux->func_info_aux[subprog].unreliable;
19348                 if (prog_extension) {
19349                         if (conservative) {
19350                                 bpf_log(log,
19351                                         "Cannot replace static functions\n");
19352                                 return -EINVAL;
19353                         }
19354                         if (!prog->jit_requested) {
19355                                 bpf_log(log,
19356                                         "Extension programs should be JITed\n");
19357                                 return -EINVAL;
19358                         }
19359                 }
19360                 if (!tgt_prog->jited) {
19361                         bpf_log(log, "Can attach to only JITed progs\n");
19362                         return -EINVAL;
19363                 }
19364                 if (tgt_prog->type == prog->type) {
19365                         /* Cannot fentry/fexit another fentry/fexit program.
19366                          * Cannot attach program extension to another extension.
19367                          * It's ok to attach fentry/fexit to extension program.
19368                          */
19369                         bpf_log(log, "Cannot recursively attach\n");
19370                         return -EINVAL;
19371                 }
19372                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19373                     prog_extension &&
19374                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19375                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19376                         /* Program extensions can extend all program types
19377                          * except fentry/fexit. The reason is the following.
19378                          * The fentry/fexit programs are used for performance
19379                          * analysis, stats and can be attached to any program
19380                          * type except themselves. When extension program is
19381                          * replacing XDP function it is necessary to allow
19382                          * performance analysis of all functions. Both original
19383                          * XDP program and its program extension. Hence
19384                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19385                          * allowed. If extending of fentry/fexit was allowed it
19386                          * would be possible to create long call chain
19387                          * fentry->extension->fentry->extension beyond
19388                          * reasonable stack size. Hence extending fentry is not
19389                          * allowed.
19390                          */
19391                         bpf_log(log, "Cannot extend fentry/fexit\n");
19392                         return -EINVAL;
19393                 }
19394         } else {
19395                 if (prog_extension) {
19396                         bpf_log(log, "Cannot replace kernel functions\n");
19397                         return -EINVAL;
19398                 }
19399         }
19400
19401         switch (prog->expected_attach_type) {
19402         case BPF_TRACE_RAW_TP:
19403                 if (tgt_prog) {
19404                         bpf_log(log,
19405                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19406                         return -EINVAL;
19407                 }
19408                 if (!btf_type_is_typedef(t)) {
19409                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
19410                                 btf_id);
19411                         return -EINVAL;
19412                 }
19413                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19414                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19415                                 btf_id, tname);
19416                         return -EINVAL;
19417                 }
19418                 tname += sizeof(prefix) - 1;
19419                 t = btf_type_by_id(btf, t->type);
19420                 if (!btf_type_is_ptr(t))
19421                         /* should never happen in valid vmlinux build */
19422                         return -EINVAL;
19423                 t = btf_type_by_id(btf, t->type);
19424                 if (!btf_type_is_func_proto(t))
19425                         /* should never happen in valid vmlinux build */
19426                         return -EINVAL;
19427
19428                 break;
19429         case BPF_TRACE_ITER:
19430                 if (!btf_type_is_func(t)) {
19431                         bpf_log(log, "attach_btf_id %u is not a function\n",
19432                                 btf_id);
19433                         return -EINVAL;
19434                 }
19435                 t = btf_type_by_id(btf, t->type);
19436                 if (!btf_type_is_func_proto(t))
19437                         return -EINVAL;
19438                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19439                 if (ret)
19440                         return ret;
19441                 break;
19442         default:
19443                 if (!prog_extension)
19444                         return -EINVAL;
19445                 fallthrough;
19446         case BPF_MODIFY_RETURN:
19447         case BPF_LSM_MAC:
19448         case BPF_LSM_CGROUP:
19449         case BPF_TRACE_FENTRY:
19450         case BPF_TRACE_FEXIT:
19451                 if (!btf_type_is_func(t)) {
19452                         bpf_log(log, "attach_btf_id %u is not a function\n",
19453                                 btf_id);
19454                         return -EINVAL;
19455                 }
19456                 if (prog_extension &&
19457                     btf_check_type_match(log, prog, btf, t))
19458                         return -EINVAL;
19459                 t = btf_type_by_id(btf, t->type);
19460                 if (!btf_type_is_func_proto(t))
19461                         return -EINVAL;
19462
19463                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19464                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19465                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19466                         return -EINVAL;
19467
19468                 if (tgt_prog && conservative)
19469                         t = NULL;
19470
19471                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19472                 if (ret < 0)
19473                         return ret;
19474
19475                 if (tgt_prog) {
19476                         if (subprog == 0)
19477                                 addr = (long) tgt_prog->bpf_func;
19478                         else
19479                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19480                 } else {
19481                         if (btf_is_module(btf)) {
19482                                 mod = btf_try_get_module(btf);
19483                                 if (mod)
19484                                         addr = find_kallsyms_symbol_value(mod, tname);
19485                                 else
19486                                         addr = 0;
19487                         } else {
19488                                 addr = kallsyms_lookup_name(tname);
19489                         }
19490                         if (!addr) {
19491                                 module_put(mod);
19492                                 bpf_log(log,
19493                                         "The address of function %s cannot be found\n",
19494                                         tname);
19495                                 return -ENOENT;
19496                         }
19497                 }
19498
19499                 if (prog->aux->sleepable) {
19500                         ret = -EINVAL;
19501                         switch (prog->type) {
19502                         case BPF_PROG_TYPE_TRACING:
19503
19504                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19505                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19506                                  */
19507                                 if (!check_non_sleepable_error_inject(btf_id) &&
19508                                     within_error_injection_list(addr))
19509                                         ret = 0;
19510                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19511                                  * in the fmodret id set with the KF_SLEEPABLE flag.
19512                                  */
19513                                 else {
19514                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19515                                                                                 prog);
19516
19517                                         if (flags && (*flags & KF_SLEEPABLE))
19518                                                 ret = 0;
19519                                 }
19520                                 break;
19521                         case BPF_PROG_TYPE_LSM:
19522                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19523                                  * Only some of them are sleepable.
19524                                  */
19525                                 if (bpf_lsm_is_sleepable_hook(btf_id))
19526                                         ret = 0;
19527                                 break;
19528                         default:
19529                                 break;
19530                         }
19531                         if (ret) {
19532                                 module_put(mod);
19533                                 bpf_log(log, "%s is not sleepable\n", tname);
19534                                 return ret;
19535                         }
19536                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19537                         if (tgt_prog) {
19538                                 module_put(mod);
19539                                 bpf_log(log, "can't modify return codes of BPF programs\n");
19540                                 return -EINVAL;
19541                         }
19542                         ret = -EINVAL;
19543                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19544                             !check_attach_modify_return(addr, tname))
19545                                 ret = 0;
19546                         if (ret) {
19547                                 module_put(mod);
19548                                 bpf_log(log, "%s() is not modifiable\n", tname);
19549                                 return ret;
19550                         }
19551                 }
19552
19553                 break;
19554         }
19555         tgt_info->tgt_addr = addr;
19556         tgt_info->tgt_name = tname;
19557         tgt_info->tgt_type = t;
19558         tgt_info->tgt_mod = mod;
19559         return 0;
19560 }
19561
19562 BTF_SET_START(btf_id_deny)
19563 BTF_ID_UNUSED
19564 #ifdef CONFIG_SMP
19565 BTF_ID(func, migrate_disable)
19566 BTF_ID(func, migrate_enable)
19567 #endif
19568 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19569 BTF_ID(func, rcu_read_unlock_strict)
19570 #endif
19571 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19572 BTF_ID(func, preempt_count_add)
19573 BTF_ID(func, preempt_count_sub)
19574 #endif
19575 #ifdef CONFIG_PREEMPT_RCU
19576 BTF_ID(func, __rcu_read_lock)
19577 BTF_ID(func, __rcu_read_unlock)
19578 #endif
19579 BTF_SET_END(btf_id_deny)
19580
19581 static bool can_be_sleepable(struct bpf_prog *prog)
19582 {
19583         if (prog->type == BPF_PROG_TYPE_TRACING) {
19584                 switch (prog->expected_attach_type) {
19585                 case BPF_TRACE_FENTRY:
19586                 case BPF_TRACE_FEXIT:
19587                 case BPF_MODIFY_RETURN:
19588                 case BPF_TRACE_ITER:
19589                         return true;
19590                 default:
19591                         return false;
19592                 }
19593         }
19594         return prog->type == BPF_PROG_TYPE_LSM ||
19595                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19596                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19597 }
19598
19599 static int check_attach_btf_id(struct bpf_verifier_env *env)
19600 {
19601         struct bpf_prog *prog = env->prog;
19602         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19603         struct bpf_attach_target_info tgt_info = {};
19604         u32 btf_id = prog->aux->attach_btf_id;
19605         struct bpf_trampoline *tr;
19606         int ret;
19607         u64 key;
19608
19609         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19610                 if (prog->aux->sleepable)
19611                         /* attach_btf_id checked to be zero already */
19612                         return 0;
19613                 verbose(env, "Syscall programs can only be sleepable\n");
19614                 return -EINVAL;
19615         }
19616
19617         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19618                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19619                 return -EINVAL;
19620         }
19621
19622         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19623                 return check_struct_ops_btf_id(env);
19624
19625         if (prog->type != BPF_PROG_TYPE_TRACING &&
19626             prog->type != BPF_PROG_TYPE_LSM &&
19627             prog->type != BPF_PROG_TYPE_EXT)
19628                 return 0;
19629
19630         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19631         if (ret)
19632                 return ret;
19633
19634         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19635                 /* to make freplace equivalent to their targets, they need to
19636                  * inherit env->ops and expected_attach_type for the rest of the
19637                  * verification
19638                  */
19639                 env->ops = bpf_verifier_ops[tgt_prog->type];
19640                 prog->expected_attach_type = tgt_prog->expected_attach_type;
19641         }
19642
19643         /* store info about the attachment target that will be used later */
19644         prog->aux->attach_func_proto = tgt_info.tgt_type;
19645         prog->aux->attach_func_name = tgt_info.tgt_name;
19646         prog->aux->mod = tgt_info.tgt_mod;
19647
19648         if (tgt_prog) {
19649                 prog->aux->saved_dst_prog_type = tgt_prog->type;
19650                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19651         }
19652
19653         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19654                 prog->aux->attach_btf_trace = true;
19655                 return 0;
19656         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19657                 if (!bpf_iter_prog_supported(prog))
19658                         return -EINVAL;
19659                 return 0;
19660         }
19661
19662         if (prog->type == BPF_PROG_TYPE_LSM) {
19663                 ret = bpf_lsm_verify_prog(&env->log, prog);
19664                 if (ret < 0)
19665                         return ret;
19666         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19667                    btf_id_set_contains(&btf_id_deny, btf_id)) {
19668                 return -EINVAL;
19669         }
19670
19671         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19672         tr = bpf_trampoline_get(key, &tgt_info);
19673         if (!tr)
19674                 return -ENOMEM;
19675
19676         if (tgt_prog && tgt_prog->aux->tail_call_reachable)
19677                 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
19678
19679         prog->aux->dst_trampoline = tr;
19680         return 0;
19681 }
19682
19683 struct btf *bpf_get_btf_vmlinux(void)
19684 {
19685         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19686                 mutex_lock(&bpf_verifier_lock);
19687                 if (!btf_vmlinux)
19688                         btf_vmlinux = btf_parse_vmlinux();
19689                 mutex_unlock(&bpf_verifier_lock);
19690         }
19691         return btf_vmlinux;
19692 }
19693
19694 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19695 {
19696         u64 start_time = ktime_get_ns();
19697         struct bpf_verifier_env *env;
19698         int i, len, ret = -EINVAL, err;
19699         u32 log_true_size;
19700         bool is_priv;
19701
19702         /* no program is valid */
19703         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19704                 return -EINVAL;
19705
19706         /* 'struct bpf_verifier_env' can be global, but since it's not small,
19707          * allocate/free it every time bpf_check() is called
19708          */
19709         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19710         if (!env)
19711                 return -ENOMEM;
19712
19713         env->bt.env = env;
19714
19715         len = (*prog)->len;
19716         env->insn_aux_data =
19717                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19718         ret = -ENOMEM;
19719         if (!env->insn_aux_data)
19720                 goto err_free_env;
19721         for (i = 0; i < len; i++)
19722                 env->insn_aux_data[i].orig_idx = i;
19723         env->prog = *prog;
19724         env->ops = bpf_verifier_ops[env->prog->type];
19725         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19726         is_priv = bpf_capable();
19727
19728         bpf_get_btf_vmlinux();
19729
19730         /* grab the mutex to protect few globals used by verifier */
19731         if (!is_priv)
19732                 mutex_lock(&bpf_verifier_lock);
19733
19734         /* user could have requested verbose verifier output
19735          * and supplied buffer to store the verification trace
19736          */
19737         ret = bpf_vlog_init(&env->log, attr->log_level,
19738                             (char __user *) (unsigned long) attr->log_buf,
19739                             attr->log_size);
19740         if (ret)
19741                 goto err_unlock;
19742
19743         mark_verifier_state_clean(env);
19744
19745         if (IS_ERR(btf_vmlinux)) {
19746                 /* Either gcc or pahole or kernel are broken. */
19747                 verbose(env, "in-kernel BTF is malformed\n");
19748                 ret = PTR_ERR(btf_vmlinux);
19749                 goto skip_full_check;
19750         }
19751
19752         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19753         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19754                 env->strict_alignment = true;
19755         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19756                 env->strict_alignment = false;
19757
19758         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19759         env->allow_uninit_stack = bpf_allow_uninit_stack();
19760         env->bypass_spec_v1 = bpf_bypass_spec_v1();
19761         env->bypass_spec_v4 = bpf_bypass_spec_v4();
19762         env->bpf_capable = bpf_capable();
19763
19764         if (is_priv)
19765                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19766
19767         env->explored_states = kvcalloc(state_htab_size(env),
19768                                        sizeof(struct bpf_verifier_state_list *),
19769                                        GFP_USER);
19770         ret = -ENOMEM;
19771         if (!env->explored_states)
19772                 goto skip_full_check;
19773
19774         ret = add_subprog_and_kfunc(env);
19775         if (ret < 0)
19776                 goto skip_full_check;
19777
19778         ret = check_subprogs(env);
19779         if (ret < 0)
19780                 goto skip_full_check;
19781
19782         ret = check_btf_info(env, attr, uattr);
19783         if (ret < 0)
19784                 goto skip_full_check;
19785
19786         ret = check_attach_btf_id(env);
19787         if (ret)
19788                 goto skip_full_check;
19789
19790         ret = resolve_pseudo_ldimm64(env);
19791         if (ret < 0)
19792                 goto skip_full_check;
19793
19794         if (bpf_prog_is_offloaded(env->prog->aux)) {
19795                 ret = bpf_prog_offload_verifier_prep(env->prog);
19796                 if (ret)
19797                         goto skip_full_check;
19798         }
19799
19800         ret = check_cfg(env);
19801         if (ret < 0)
19802                 goto skip_full_check;
19803
19804         ret = do_check_subprogs(env);
19805         ret = ret ?: do_check_main(env);
19806
19807         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19808                 ret = bpf_prog_offload_finalize(env);
19809
19810 skip_full_check:
19811         kvfree(env->explored_states);
19812
19813         if (ret == 0)
19814                 ret = check_max_stack_depth(env);
19815
19816         /* instruction rewrites happen after this point */
19817         if (ret == 0)
19818                 ret = optimize_bpf_loop(env);
19819
19820         if (is_priv) {
19821                 if (ret == 0)
19822                         opt_hard_wire_dead_code_branches(env);
19823                 if (ret == 0)
19824                         ret = opt_remove_dead_code(env);
19825                 if (ret == 0)
19826                         ret = opt_remove_nops(env);
19827         } else {
19828                 if (ret == 0)
19829                         sanitize_dead_code(env);
19830         }
19831
19832         if (ret == 0)
19833                 /* program is valid, convert *(u32*)(ctx + off) accesses */
19834                 ret = convert_ctx_accesses(env);
19835
19836         if (ret == 0)
19837                 ret = do_misc_fixups(env);
19838
19839         /* do 32-bit optimization after insn patching has done so those patched
19840          * insns could be handled correctly.
19841          */
19842         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19843                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19844                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19845                                                                      : false;
19846         }
19847
19848         if (ret == 0)
19849                 ret = fixup_call_args(env);
19850
19851         env->verification_time = ktime_get_ns() - start_time;
19852         print_verification_stats(env);
19853         env->prog->aux->verified_insns = env->insn_processed;
19854
19855         /* preserve original error even if log finalization is successful */
19856         err = bpf_vlog_finalize(&env->log, &log_true_size);
19857         if (err)
19858                 ret = err;
19859
19860         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19861             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19862                                   &log_true_size, sizeof(log_true_size))) {
19863                 ret = -EFAULT;
19864                 goto err_release_maps;
19865         }
19866
19867         if (ret)
19868                 goto err_release_maps;
19869
19870         if (env->used_map_cnt) {
19871                 /* if program passed verifier, update used_maps in bpf_prog_info */
19872                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19873                                                           sizeof(env->used_maps[0]),
19874                                                           GFP_KERNEL);
19875
19876                 if (!env->prog->aux->used_maps) {
19877                         ret = -ENOMEM;
19878                         goto err_release_maps;
19879                 }
19880
19881                 memcpy(env->prog->aux->used_maps, env->used_maps,
19882                        sizeof(env->used_maps[0]) * env->used_map_cnt);
19883                 env->prog->aux->used_map_cnt = env->used_map_cnt;
19884         }
19885         if (env->used_btf_cnt) {
19886                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19887                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19888                                                           sizeof(env->used_btfs[0]),
19889                                                           GFP_KERNEL);
19890                 if (!env->prog->aux->used_btfs) {
19891                         ret = -ENOMEM;
19892                         goto err_release_maps;
19893                 }
19894
19895                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19896                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19897                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19898         }
19899         if (env->used_map_cnt || env->used_btf_cnt) {
19900                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19901                  * bpf_ld_imm64 instructions
19902                  */
19903                 convert_pseudo_ld_imm64(env);
19904         }
19905
19906         adjust_btf_func(env);
19907
19908 err_release_maps:
19909         if (!env->prog->aux->used_maps)
19910                 /* if we didn't copy map pointers into bpf_prog_info, release
19911                  * them now. Otherwise free_used_maps() will release them.
19912                  */
19913                 release_maps(env);
19914         if (!env->prog->aux->used_btfs)
19915                 release_btfs(env);
19916
19917         /* extension progs temporarily inherit the attach_type of their targets
19918            for verification purposes, so set it back to zero before returning
19919          */
19920         if (env->prog->type == BPF_PROG_TYPE_EXT)
19921                 env->prog->expected_attach_type = 0;
19922
19923         *prog = env->prog;
19924 err_unlock:
19925         if (!is_priv)
19926                 mutex_unlock(&bpf_verifier_lock);
19927         vfree(env->insn_aux_data);
19928 err_free_env:
19929         kfree(env);
19930         return ret;
19931 }