bpf: move kfunc_call_arg_meta higher in the file
[linux-block.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27
28 #include "disasm.h"
29
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32         [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168         /* verifer state is 'st'
169          * before processing instruction 'insn_idx'
170          * and after processing instruction 'prev_insn_idx'
171          */
172         struct bpf_verifier_state st;
173         int insn_idx;
174         int prev_insn_idx;
175         struct bpf_verifier_stack_elem *next;
176         /* length of verifier log at the time this state was pushed on stack */
177         u32 log_pos;
178 };
179
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
181 #define BPF_COMPLEXITY_LIMIT_STATES     64
182
183 #define BPF_MAP_KEY_POISON      (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
185
186 #define BPF_MAP_PTR_UNPRIV      1UL
187 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
188                                           POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
194 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
195 static int ref_set_non_owning(struct bpf_verifier_env *env,
196                               struct bpf_reg_state *reg);
197
198 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
199 {
200         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
201 }
202
203 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
204 {
205         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
206 }
207
208 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
209                               const struct bpf_map *map, bool unpriv)
210 {
211         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
212         unpriv |= bpf_map_ptr_unpriv(aux);
213         aux->map_ptr_state = (unsigned long)map |
214                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
215 }
216
217 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
218 {
219         return aux->map_key_state & BPF_MAP_KEY_POISON;
220 }
221
222 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
223 {
224         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
225 }
226
227 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
228 {
229         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
230 }
231
232 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
233 {
234         bool poisoned = bpf_map_key_poisoned(aux);
235
236         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
237                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
238 }
239
240 static bool bpf_pseudo_call(const struct bpf_insn *insn)
241 {
242         return insn->code == (BPF_JMP | BPF_CALL) &&
243                insn->src_reg == BPF_PSEUDO_CALL;
244 }
245
246 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
247 {
248         return insn->code == (BPF_JMP | BPF_CALL) &&
249                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
250 }
251
252 struct bpf_call_arg_meta {
253         struct bpf_map *map_ptr;
254         bool raw_mode;
255         bool pkt_access;
256         u8 release_regno;
257         int regno;
258         int access_size;
259         int mem_size;
260         u64 msize_max_value;
261         int ref_obj_id;
262         int dynptr_id;
263         int map_uid;
264         int func_id;
265         struct btf *btf;
266         u32 btf_id;
267         struct btf *ret_btf;
268         u32 ret_btf_id;
269         u32 subprogno;
270         struct btf_field *kptr_field;
271 };
272
273 struct bpf_kfunc_call_arg_meta {
274         /* In parameters */
275         struct btf *btf;
276         u32 func_id;
277         u32 kfunc_flags;
278         const struct btf_type *func_proto;
279         const char *func_name;
280         /* Out parameters */
281         u32 ref_obj_id;
282         u8 release_regno;
283         bool r0_rdonly;
284         u32 ret_btf_id;
285         u64 r0_size;
286         u32 subprogno;
287         struct {
288                 u64 value;
289                 bool found;
290         } arg_constant;
291         struct {
292                 struct btf *btf;
293                 u32 btf_id;
294         } arg_obj_drop;
295         struct {
296                 struct btf_field *field;
297         } arg_list_head;
298         struct {
299                 struct btf_field *field;
300         } arg_rbtree_root;
301         struct {
302                 enum bpf_dynptr_type type;
303                 u32 id;
304         } initialized_dynptr;
305         u64 mem_size;
306 };
307
308 struct btf *btf_vmlinux;
309
310 static DEFINE_MUTEX(bpf_verifier_lock);
311
312 static const struct bpf_line_info *
313 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
314 {
315         const struct bpf_line_info *linfo;
316         const struct bpf_prog *prog;
317         u32 i, nr_linfo;
318
319         prog = env->prog;
320         nr_linfo = prog->aux->nr_linfo;
321
322         if (!nr_linfo || insn_off >= prog->len)
323                 return NULL;
324
325         linfo = prog->aux->linfo;
326         for (i = 1; i < nr_linfo; i++)
327                 if (insn_off < linfo[i].insn_off)
328                         break;
329
330         return &linfo[i - 1];
331 }
332
333 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
334                        va_list args)
335 {
336         unsigned int n;
337
338         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
339
340         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
341                   "verifier log line truncated - local buffer too short\n");
342
343         if (log->level == BPF_LOG_KERNEL) {
344                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
345
346                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
347                 return;
348         }
349
350         n = min(log->len_total - log->len_used - 1, n);
351         log->kbuf[n] = '\0';
352         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
353                 log->len_used += n;
354         else
355                 log->ubuf = NULL;
356 }
357
358 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
359 {
360         char zero = 0;
361
362         if (!bpf_verifier_log_needed(log))
363                 return;
364
365         log->len_used = new_pos;
366         if (put_user(zero, log->ubuf + new_pos))
367                 log->ubuf = NULL;
368 }
369
370 /* log_level controls verbosity level of eBPF verifier.
371  * bpf_verifier_log_write() is used to dump the verification trace to the log,
372  * so the user can figure out what's wrong with the program
373  */
374 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
375                                            const char *fmt, ...)
376 {
377         va_list args;
378
379         if (!bpf_verifier_log_needed(&env->log))
380                 return;
381
382         va_start(args, fmt);
383         bpf_verifier_vlog(&env->log, fmt, args);
384         va_end(args);
385 }
386 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
387
388 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
389 {
390         struct bpf_verifier_env *env = private_data;
391         va_list args;
392
393         if (!bpf_verifier_log_needed(&env->log))
394                 return;
395
396         va_start(args, fmt);
397         bpf_verifier_vlog(&env->log, fmt, args);
398         va_end(args);
399 }
400
401 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
402                             const char *fmt, ...)
403 {
404         va_list args;
405
406         if (!bpf_verifier_log_needed(log))
407                 return;
408
409         va_start(args, fmt);
410         bpf_verifier_vlog(log, fmt, args);
411         va_end(args);
412 }
413 EXPORT_SYMBOL_GPL(bpf_log);
414
415 static const char *ltrim(const char *s)
416 {
417         while (isspace(*s))
418                 s++;
419
420         return s;
421 }
422
423 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
424                                          u32 insn_off,
425                                          const char *prefix_fmt, ...)
426 {
427         const struct bpf_line_info *linfo;
428
429         if (!bpf_verifier_log_needed(&env->log))
430                 return;
431
432         linfo = find_linfo(env, insn_off);
433         if (!linfo || linfo == env->prev_linfo)
434                 return;
435
436         if (prefix_fmt) {
437                 va_list args;
438
439                 va_start(args, prefix_fmt);
440                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
441                 va_end(args);
442         }
443
444         verbose(env, "%s\n",
445                 ltrim(btf_name_by_offset(env->prog->aux->btf,
446                                          linfo->line_off)));
447
448         env->prev_linfo = linfo;
449 }
450
451 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
452                                    struct bpf_reg_state *reg,
453                                    struct tnum *range, const char *ctx,
454                                    const char *reg_name)
455 {
456         char tn_buf[48];
457
458         verbose(env, "At %s the register %s ", ctx, reg_name);
459         if (!tnum_is_unknown(reg->var_off)) {
460                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
461                 verbose(env, "has value %s", tn_buf);
462         } else {
463                 verbose(env, "has unknown scalar value");
464         }
465         tnum_strn(tn_buf, sizeof(tn_buf), *range);
466         verbose(env, " should have been in %s\n", tn_buf);
467 }
468
469 static bool type_is_pkt_pointer(enum bpf_reg_type type)
470 {
471         type = base_type(type);
472         return type == PTR_TO_PACKET ||
473                type == PTR_TO_PACKET_META;
474 }
475
476 static bool type_is_sk_pointer(enum bpf_reg_type type)
477 {
478         return type == PTR_TO_SOCKET ||
479                 type == PTR_TO_SOCK_COMMON ||
480                 type == PTR_TO_TCP_SOCK ||
481                 type == PTR_TO_XDP_SOCK;
482 }
483
484 static bool reg_type_not_null(enum bpf_reg_type type)
485 {
486         return type == PTR_TO_SOCKET ||
487                 type == PTR_TO_TCP_SOCK ||
488                 type == PTR_TO_MAP_VALUE ||
489                 type == PTR_TO_MAP_KEY ||
490                 type == PTR_TO_SOCK_COMMON;
491 }
492
493 static bool type_is_ptr_alloc_obj(u32 type)
494 {
495         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
496 }
497
498 static bool type_is_non_owning_ref(u32 type)
499 {
500         return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
501 }
502
503 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
504 {
505         struct btf_record *rec = NULL;
506         struct btf_struct_meta *meta;
507
508         if (reg->type == PTR_TO_MAP_VALUE) {
509                 rec = reg->map_ptr->record;
510         } else if (type_is_ptr_alloc_obj(reg->type)) {
511                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
512                 if (meta)
513                         rec = meta->record;
514         }
515         return rec;
516 }
517
518 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
519 {
520         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
521 }
522
523 static bool type_is_rdonly_mem(u32 type)
524 {
525         return type & MEM_RDONLY;
526 }
527
528 static bool type_may_be_null(u32 type)
529 {
530         return type & PTR_MAYBE_NULL;
531 }
532
533 static bool is_acquire_function(enum bpf_func_id func_id,
534                                 const struct bpf_map *map)
535 {
536         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
537
538         if (func_id == BPF_FUNC_sk_lookup_tcp ||
539             func_id == BPF_FUNC_sk_lookup_udp ||
540             func_id == BPF_FUNC_skc_lookup_tcp ||
541             func_id == BPF_FUNC_ringbuf_reserve ||
542             func_id == BPF_FUNC_kptr_xchg)
543                 return true;
544
545         if (func_id == BPF_FUNC_map_lookup_elem &&
546             (map_type == BPF_MAP_TYPE_SOCKMAP ||
547              map_type == BPF_MAP_TYPE_SOCKHASH))
548                 return true;
549
550         return false;
551 }
552
553 static bool is_ptr_cast_function(enum bpf_func_id func_id)
554 {
555         return func_id == BPF_FUNC_tcp_sock ||
556                 func_id == BPF_FUNC_sk_fullsock ||
557                 func_id == BPF_FUNC_skc_to_tcp_sock ||
558                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
559                 func_id == BPF_FUNC_skc_to_udp6_sock ||
560                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
561                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
562                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
563 }
564
565 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
566 {
567         return func_id == BPF_FUNC_dynptr_data;
568 }
569
570 static bool is_callback_calling_function(enum bpf_func_id func_id)
571 {
572         return func_id == BPF_FUNC_for_each_map_elem ||
573                func_id == BPF_FUNC_timer_set_callback ||
574                func_id == BPF_FUNC_find_vma ||
575                func_id == BPF_FUNC_loop ||
576                func_id == BPF_FUNC_user_ringbuf_drain;
577 }
578
579 static bool is_storage_get_function(enum bpf_func_id func_id)
580 {
581         return func_id == BPF_FUNC_sk_storage_get ||
582                func_id == BPF_FUNC_inode_storage_get ||
583                func_id == BPF_FUNC_task_storage_get ||
584                func_id == BPF_FUNC_cgrp_storage_get;
585 }
586
587 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
588                                         const struct bpf_map *map)
589 {
590         int ref_obj_uses = 0;
591
592         if (is_ptr_cast_function(func_id))
593                 ref_obj_uses++;
594         if (is_acquire_function(func_id, map))
595                 ref_obj_uses++;
596         if (is_dynptr_ref_function(func_id))
597                 ref_obj_uses++;
598
599         return ref_obj_uses > 1;
600 }
601
602 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
603 {
604         return BPF_CLASS(insn->code) == BPF_STX &&
605                BPF_MODE(insn->code) == BPF_ATOMIC &&
606                insn->imm == BPF_CMPXCHG;
607 }
608
609 /* string representation of 'enum bpf_reg_type'
610  *
611  * Note that reg_type_str() can not appear more than once in a single verbose()
612  * statement.
613  */
614 static const char *reg_type_str(struct bpf_verifier_env *env,
615                                 enum bpf_reg_type type)
616 {
617         char postfix[16] = {0}, prefix[64] = {0};
618         static const char * const str[] = {
619                 [NOT_INIT]              = "?",
620                 [SCALAR_VALUE]          = "scalar",
621                 [PTR_TO_CTX]            = "ctx",
622                 [CONST_PTR_TO_MAP]      = "map_ptr",
623                 [PTR_TO_MAP_VALUE]      = "map_value",
624                 [PTR_TO_STACK]          = "fp",
625                 [PTR_TO_PACKET]         = "pkt",
626                 [PTR_TO_PACKET_META]    = "pkt_meta",
627                 [PTR_TO_PACKET_END]     = "pkt_end",
628                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
629                 [PTR_TO_SOCKET]         = "sock",
630                 [PTR_TO_SOCK_COMMON]    = "sock_common",
631                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
632                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
633                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
634                 [PTR_TO_BTF_ID]         = "ptr_",
635                 [PTR_TO_MEM]            = "mem",
636                 [PTR_TO_BUF]            = "buf",
637                 [PTR_TO_FUNC]           = "func",
638                 [PTR_TO_MAP_KEY]        = "map_key",
639                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
640         };
641
642         if (type & PTR_MAYBE_NULL) {
643                 if (base_type(type) == PTR_TO_BTF_ID)
644                         strncpy(postfix, "or_null_", 16);
645                 else
646                         strncpy(postfix, "_or_null", 16);
647         }
648
649         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
650                  type & MEM_RDONLY ? "rdonly_" : "",
651                  type & MEM_RINGBUF ? "ringbuf_" : "",
652                  type & MEM_USER ? "user_" : "",
653                  type & MEM_PERCPU ? "percpu_" : "",
654                  type & MEM_RCU ? "rcu_" : "",
655                  type & PTR_UNTRUSTED ? "untrusted_" : "",
656                  type & PTR_TRUSTED ? "trusted_" : ""
657         );
658
659         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
660                  prefix, str[base_type(type)], postfix);
661         return env->type_str_buf;
662 }
663
664 static char slot_type_char[] = {
665         [STACK_INVALID] = '?',
666         [STACK_SPILL]   = 'r',
667         [STACK_MISC]    = 'm',
668         [STACK_ZERO]    = '0',
669         [STACK_DYNPTR]  = 'd',
670 };
671
672 static void print_liveness(struct bpf_verifier_env *env,
673                            enum bpf_reg_liveness live)
674 {
675         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
676             verbose(env, "_");
677         if (live & REG_LIVE_READ)
678                 verbose(env, "r");
679         if (live & REG_LIVE_WRITTEN)
680                 verbose(env, "w");
681         if (live & REG_LIVE_DONE)
682                 verbose(env, "D");
683 }
684
685 static int __get_spi(s32 off)
686 {
687         return (-off - 1) / BPF_REG_SIZE;
688 }
689
690 static struct bpf_func_state *func(struct bpf_verifier_env *env,
691                                    const struct bpf_reg_state *reg)
692 {
693         struct bpf_verifier_state *cur = env->cur_state;
694
695         return cur->frame[reg->frameno];
696 }
697
698 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
699 {
700        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
701
702        /* We need to check that slots between [spi - nr_slots + 1, spi] are
703         * within [0, allocated_stack).
704         *
705         * Please note that the spi grows downwards. For example, a dynptr
706         * takes the size of two stack slots; the first slot will be at
707         * spi and the second slot will be at spi - 1.
708         */
709        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
710 }
711
712 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
713 {
714         int off, spi;
715
716         if (!tnum_is_const(reg->var_off)) {
717                 verbose(env, "dynptr has to be at a constant offset\n");
718                 return -EINVAL;
719         }
720
721         off = reg->off + reg->var_off.value;
722         if (off % BPF_REG_SIZE) {
723                 verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
724                 return -EINVAL;
725         }
726
727         spi = __get_spi(off);
728         if (spi < 1) {
729                 verbose(env, "cannot pass in dynptr at an offset=%d\n", off);
730                 return -EINVAL;
731         }
732
733         if (!is_spi_bounds_valid(func(env, reg), spi, BPF_DYNPTR_NR_SLOTS))
734                 return -ERANGE;
735         return spi;
736 }
737
738 static const char *kernel_type_name(const struct btf* btf, u32 id)
739 {
740         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
741 }
742
743 static const char *dynptr_type_str(enum bpf_dynptr_type type)
744 {
745         switch (type) {
746         case BPF_DYNPTR_TYPE_LOCAL:
747                 return "local";
748         case BPF_DYNPTR_TYPE_RINGBUF:
749                 return "ringbuf";
750         case BPF_DYNPTR_TYPE_SKB:
751                 return "skb";
752         case BPF_DYNPTR_TYPE_XDP:
753                 return "xdp";
754         case BPF_DYNPTR_TYPE_INVALID:
755                 return "<invalid>";
756         default:
757                 WARN_ONCE(1, "unknown dynptr type %d\n", type);
758                 return "<unknown>";
759         }
760 }
761
762 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
763 {
764         env->scratched_regs |= 1U << regno;
765 }
766
767 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
768 {
769         env->scratched_stack_slots |= 1ULL << spi;
770 }
771
772 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
773 {
774         return (env->scratched_regs >> regno) & 1;
775 }
776
777 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
778 {
779         return (env->scratched_stack_slots >> regno) & 1;
780 }
781
782 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
783 {
784         return env->scratched_regs || env->scratched_stack_slots;
785 }
786
787 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
788 {
789         env->scratched_regs = 0U;
790         env->scratched_stack_slots = 0ULL;
791 }
792
793 /* Used for printing the entire verifier state. */
794 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
795 {
796         env->scratched_regs = ~0U;
797         env->scratched_stack_slots = ~0ULL;
798 }
799
800 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
801 {
802         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
803         case DYNPTR_TYPE_LOCAL:
804                 return BPF_DYNPTR_TYPE_LOCAL;
805         case DYNPTR_TYPE_RINGBUF:
806                 return BPF_DYNPTR_TYPE_RINGBUF;
807         case DYNPTR_TYPE_SKB:
808                 return BPF_DYNPTR_TYPE_SKB;
809         case DYNPTR_TYPE_XDP:
810                 return BPF_DYNPTR_TYPE_XDP;
811         default:
812                 return BPF_DYNPTR_TYPE_INVALID;
813         }
814 }
815
816 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
817 {
818         switch (type) {
819         case BPF_DYNPTR_TYPE_LOCAL:
820                 return DYNPTR_TYPE_LOCAL;
821         case BPF_DYNPTR_TYPE_RINGBUF:
822                 return DYNPTR_TYPE_RINGBUF;
823         case BPF_DYNPTR_TYPE_SKB:
824                 return DYNPTR_TYPE_SKB;
825         case BPF_DYNPTR_TYPE_XDP:
826                 return DYNPTR_TYPE_XDP;
827         default:
828                 return 0;
829         }
830 }
831
832 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
833 {
834         return type == BPF_DYNPTR_TYPE_RINGBUF;
835 }
836
837 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
838                               enum bpf_dynptr_type type,
839                               bool first_slot, int dynptr_id);
840
841 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
842                                 struct bpf_reg_state *reg);
843
844 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
845                                    struct bpf_reg_state *sreg1,
846                                    struct bpf_reg_state *sreg2,
847                                    enum bpf_dynptr_type type)
848 {
849         int id = ++env->id_gen;
850
851         __mark_dynptr_reg(sreg1, type, true, id);
852         __mark_dynptr_reg(sreg2, type, false, id);
853 }
854
855 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
856                                struct bpf_reg_state *reg,
857                                enum bpf_dynptr_type type)
858 {
859         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
860 }
861
862 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
863                                         struct bpf_func_state *state, int spi);
864
865 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
866                                    enum bpf_arg_type arg_type, int insn_idx)
867 {
868         struct bpf_func_state *state = func(env, reg);
869         enum bpf_dynptr_type type;
870         int spi, i, id, err;
871
872         spi = dynptr_get_spi(env, reg);
873         if (spi < 0)
874                 return spi;
875
876         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
877          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
878          * to ensure that for the following example:
879          *      [d1][d1][d2][d2]
880          * spi    3   2   1   0
881          * So marking spi = 2 should lead to destruction of both d1 and d2. In
882          * case they do belong to same dynptr, second call won't see slot_type
883          * as STACK_DYNPTR and will simply skip destruction.
884          */
885         err = destroy_if_dynptr_stack_slot(env, state, spi);
886         if (err)
887                 return err;
888         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
889         if (err)
890                 return err;
891
892         for (i = 0; i < BPF_REG_SIZE; i++) {
893                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
894                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
895         }
896
897         type = arg_to_dynptr_type(arg_type);
898         if (type == BPF_DYNPTR_TYPE_INVALID)
899                 return -EINVAL;
900
901         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
902                                &state->stack[spi - 1].spilled_ptr, type);
903
904         if (dynptr_type_refcounted(type)) {
905                 /* The id is used to track proper releasing */
906                 id = acquire_reference_state(env, insn_idx);
907                 if (id < 0)
908                         return id;
909
910                 state->stack[spi].spilled_ptr.ref_obj_id = id;
911                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
912         }
913
914         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
915         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
916
917         return 0;
918 }
919
920 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
921 {
922         struct bpf_func_state *state = func(env, reg);
923         int spi, i;
924
925         spi = dynptr_get_spi(env, reg);
926         if (spi < 0)
927                 return spi;
928
929         for (i = 0; i < BPF_REG_SIZE; i++) {
930                 state->stack[spi].slot_type[i] = STACK_INVALID;
931                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
932         }
933
934         /* Invalidate any slices associated with this dynptr */
935         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
936                 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
937
938         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
939         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
940
941         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
942          *
943          * While we don't allow reading STACK_INVALID, it is still possible to
944          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
945          * helpers or insns can do partial read of that part without failing,
946          * but check_stack_range_initialized, check_stack_read_var_off, and
947          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
948          * the slot conservatively. Hence we need to prevent those liveness
949          * marking walks.
950          *
951          * This was not a problem before because STACK_INVALID is only set by
952          * default (where the default reg state has its reg->parent as NULL), or
953          * in clean_live_states after REG_LIVE_DONE (at which point
954          * mark_reg_read won't walk reg->parent chain), but not randomly during
955          * verifier state exploration (like we did above). Hence, for our case
956          * parentage chain will still be live (i.e. reg->parent may be
957          * non-NULL), while earlier reg->parent was NULL, so we need
958          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
959          * done later on reads or by mark_dynptr_read as well to unnecessary
960          * mark registers in verifier state.
961          */
962         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
963         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
964
965         return 0;
966 }
967
968 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
969                                struct bpf_reg_state *reg);
970
971 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
972 {
973         if (!env->allow_ptr_leaks)
974                 __mark_reg_not_init(env, reg);
975         else
976                 __mark_reg_unknown(env, reg);
977 }
978
979 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
980                                         struct bpf_func_state *state, int spi)
981 {
982         struct bpf_func_state *fstate;
983         struct bpf_reg_state *dreg;
984         int i, dynptr_id;
985
986         /* We always ensure that STACK_DYNPTR is never set partially,
987          * hence just checking for slot_type[0] is enough. This is
988          * different for STACK_SPILL, where it may be only set for
989          * 1 byte, so code has to use is_spilled_reg.
990          */
991         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
992                 return 0;
993
994         /* Reposition spi to first slot */
995         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
996                 spi = spi + 1;
997
998         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
999                 verbose(env, "cannot overwrite referenced dynptr\n");
1000                 return -EINVAL;
1001         }
1002
1003         mark_stack_slot_scratched(env, spi);
1004         mark_stack_slot_scratched(env, spi - 1);
1005
1006         /* Writing partially to one dynptr stack slot destroys both. */
1007         for (i = 0; i < BPF_REG_SIZE; i++) {
1008                 state->stack[spi].slot_type[i] = STACK_INVALID;
1009                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1010         }
1011
1012         dynptr_id = state->stack[spi].spilled_ptr.id;
1013         /* Invalidate any slices associated with this dynptr */
1014         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1015                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1016                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1017                         continue;
1018                 if (dreg->dynptr_id == dynptr_id)
1019                         mark_reg_invalid(env, dreg);
1020         }));
1021
1022         /* Do not release reference state, we are destroying dynptr on stack,
1023          * not using some helper to release it. Just reset register.
1024          */
1025         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1026         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1027
1028         /* Same reason as unmark_stack_slots_dynptr above */
1029         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1030         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1031
1032         return 0;
1033 }
1034
1035 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1036 {
1037         int spi;
1038
1039         if (reg->type == CONST_PTR_TO_DYNPTR)
1040                 return false;
1041
1042         spi = dynptr_get_spi(env, reg);
1043
1044         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1045          * error because this just means the stack state hasn't been updated yet.
1046          * We will do check_mem_access to check and update stack bounds later.
1047          */
1048         if (spi < 0 && spi != -ERANGE)
1049                 return false;
1050
1051         /* We don't need to check if the stack slots are marked by previous
1052          * dynptr initializations because we allow overwriting existing unreferenced
1053          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1054          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1055          * touching are completely destructed before we reinitialize them for a new
1056          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1057          * instead of delaying it until the end where the user will get "Unreleased
1058          * reference" error.
1059          */
1060         return true;
1061 }
1062
1063 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1064 {
1065         struct bpf_func_state *state = func(env, reg);
1066         int i, spi;
1067
1068         /* This already represents first slot of initialized bpf_dynptr.
1069          *
1070          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1071          * check_func_arg_reg_off's logic, so we don't need to check its
1072          * offset and alignment.
1073          */
1074         if (reg->type == CONST_PTR_TO_DYNPTR)
1075                 return true;
1076
1077         spi = dynptr_get_spi(env, reg);
1078         if (spi < 0)
1079                 return false;
1080         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1081                 return false;
1082
1083         for (i = 0; i < BPF_REG_SIZE; i++) {
1084                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1085                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1086                         return false;
1087         }
1088
1089         return true;
1090 }
1091
1092 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1093                                     enum bpf_arg_type arg_type)
1094 {
1095         struct bpf_func_state *state = func(env, reg);
1096         enum bpf_dynptr_type dynptr_type;
1097         int spi;
1098
1099         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1100         if (arg_type == ARG_PTR_TO_DYNPTR)
1101                 return true;
1102
1103         dynptr_type = arg_to_dynptr_type(arg_type);
1104         if (reg->type == CONST_PTR_TO_DYNPTR) {
1105                 return reg->dynptr.type == dynptr_type;
1106         } else {
1107                 spi = dynptr_get_spi(env, reg);
1108                 if (spi < 0)
1109                         return false;
1110                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1111         }
1112 }
1113
1114 /* The reg state of a pointer or a bounded scalar was saved when
1115  * it was spilled to the stack.
1116  */
1117 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1118 {
1119         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1120 }
1121
1122 static void scrub_spilled_slot(u8 *stype)
1123 {
1124         if (*stype != STACK_INVALID)
1125                 *stype = STACK_MISC;
1126 }
1127
1128 static void print_verifier_state(struct bpf_verifier_env *env,
1129                                  const struct bpf_func_state *state,
1130                                  bool print_all)
1131 {
1132         const struct bpf_reg_state *reg;
1133         enum bpf_reg_type t;
1134         int i;
1135
1136         if (state->frameno)
1137                 verbose(env, " frame%d:", state->frameno);
1138         for (i = 0; i < MAX_BPF_REG; i++) {
1139                 reg = &state->regs[i];
1140                 t = reg->type;
1141                 if (t == NOT_INIT)
1142                         continue;
1143                 if (!print_all && !reg_scratched(env, i))
1144                         continue;
1145                 verbose(env, " R%d", i);
1146                 print_liveness(env, reg->live);
1147                 verbose(env, "=");
1148                 if (t == SCALAR_VALUE && reg->precise)
1149                         verbose(env, "P");
1150                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1151                     tnum_is_const(reg->var_off)) {
1152                         /* reg->off should be 0 for SCALAR_VALUE */
1153                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1154                         verbose(env, "%lld", reg->var_off.value + reg->off);
1155                 } else {
1156                         const char *sep = "";
1157
1158                         verbose(env, "%s", reg_type_str(env, t));
1159                         if (base_type(t) == PTR_TO_BTF_ID)
1160                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
1161                         verbose(env, "(");
1162 /*
1163  * _a stands for append, was shortened to avoid multiline statements below.
1164  * This macro is used to output a comma separated list of attributes.
1165  */
1166 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1167
1168                         if (reg->id)
1169                                 verbose_a("id=%d", reg->id);
1170                         if (reg->ref_obj_id)
1171                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1172                         if (type_is_non_owning_ref(reg->type))
1173                                 verbose_a("%s", "non_own_ref");
1174                         if (t != SCALAR_VALUE)
1175                                 verbose_a("off=%d", reg->off);
1176                         if (type_is_pkt_pointer(t))
1177                                 verbose_a("r=%d", reg->range);
1178                         else if (base_type(t) == CONST_PTR_TO_MAP ||
1179                                  base_type(t) == PTR_TO_MAP_KEY ||
1180                                  base_type(t) == PTR_TO_MAP_VALUE)
1181                                 verbose_a("ks=%d,vs=%d",
1182                                           reg->map_ptr->key_size,
1183                                           reg->map_ptr->value_size);
1184                         if (tnum_is_const(reg->var_off)) {
1185                                 /* Typically an immediate SCALAR_VALUE, but
1186                                  * could be a pointer whose offset is too big
1187                                  * for reg->off
1188                                  */
1189                                 verbose_a("imm=%llx", reg->var_off.value);
1190                         } else {
1191                                 if (reg->smin_value != reg->umin_value &&
1192                                     reg->smin_value != S64_MIN)
1193                                         verbose_a("smin=%lld", (long long)reg->smin_value);
1194                                 if (reg->smax_value != reg->umax_value &&
1195                                     reg->smax_value != S64_MAX)
1196                                         verbose_a("smax=%lld", (long long)reg->smax_value);
1197                                 if (reg->umin_value != 0)
1198                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1199                                 if (reg->umax_value != U64_MAX)
1200                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1201                                 if (!tnum_is_unknown(reg->var_off)) {
1202                                         char tn_buf[48];
1203
1204                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1205                                         verbose_a("var_off=%s", tn_buf);
1206                                 }
1207                                 if (reg->s32_min_value != reg->smin_value &&
1208                                     reg->s32_min_value != S32_MIN)
1209                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1210                                 if (reg->s32_max_value != reg->smax_value &&
1211                                     reg->s32_max_value != S32_MAX)
1212                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1213                                 if (reg->u32_min_value != reg->umin_value &&
1214                                     reg->u32_min_value != U32_MIN)
1215                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1216                                 if (reg->u32_max_value != reg->umax_value &&
1217                                     reg->u32_max_value != U32_MAX)
1218                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1219                         }
1220 #undef verbose_a
1221
1222                         verbose(env, ")");
1223                 }
1224         }
1225         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1226                 char types_buf[BPF_REG_SIZE + 1];
1227                 bool valid = false;
1228                 int j;
1229
1230                 for (j = 0; j < BPF_REG_SIZE; j++) {
1231                         if (state->stack[i].slot_type[j] != STACK_INVALID)
1232                                 valid = true;
1233                         types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1234                 }
1235                 types_buf[BPF_REG_SIZE] = 0;
1236                 if (!valid)
1237                         continue;
1238                 if (!print_all && !stack_slot_scratched(env, i))
1239                         continue;
1240                 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1241                 case STACK_SPILL:
1242                         reg = &state->stack[i].spilled_ptr;
1243                         t = reg->type;
1244
1245                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1246                         print_liveness(env, reg->live);
1247                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1248                         if (t == SCALAR_VALUE && reg->precise)
1249                                 verbose(env, "P");
1250                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1251                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1252                         break;
1253                 case STACK_DYNPTR:
1254                         i += BPF_DYNPTR_NR_SLOTS - 1;
1255                         reg = &state->stack[i].spilled_ptr;
1256
1257                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1258                         print_liveness(env, reg->live);
1259                         verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1260                         if (reg->ref_obj_id)
1261                                 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1262                         break;
1263                 case STACK_MISC:
1264                 case STACK_ZERO:
1265                 default:
1266                         reg = &state->stack[i].spilled_ptr;
1267
1268                         for (j = 0; j < BPF_REG_SIZE; j++)
1269                                 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1270                         types_buf[BPF_REG_SIZE] = 0;
1271
1272                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1273                         print_liveness(env, reg->live);
1274                         verbose(env, "=%s", types_buf);
1275                         break;
1276                 }
1277         }
1278         if (state->acquired_refs && state->refs[0].id) {
1279                 verbose(env, " refs=%d", state->refs[0].id);
1280                 for (i = 1; i < state->acquired_refs; i++)
1281                         if (state->refs[i].id)
1282                                 verbose(env, ",%d", state->refs[i].id);
1283         }
1284         if (state->in_callback_fn)
1285                 verbose(env, " cb");
1286         if (state->in_async_callback_fn)
1287                 verbose(env, " async_cb");
1288         verbose(env, "\n");
1289         mark_verifier_state_clean(env);
1290 }
1291
1292 static inline u32 vlog_alignment(u32 pos)
1293 {
1294         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1295                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1296 }
1297
1298 static void print_insn_state(struct bpf_verifier_env *env,
1299                              const struct bpf_func_state *state)
1300 {
1301         if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1302                 /* remove new line character */
1303                 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1304                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1305         } else {
1306                 verbose(env, "%d:", env->insn_idx);
1307         }
1308         print_verifier_state(env, state, false);
1309 }
1310
1311 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1312  * small to hold src. This is different from krealloc since we don't want to preserve
1313  * the contents of dst.
1314  *
1315  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1316  * not be allocated.
1317  */
1318 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1319 {
1320         size_t alloc_bytes;
1321         void *orig = dst;
1322         size_t bytes;
1323
1324         if (ZERO_OR_NULL_PTR(src))
1325                 goto out;
1326
1327         if (unlikely(check_mul_overflow(n, size, &bytes)))
1328                 return NULL;
1329
1330         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1331         dst = krealloc(orig, alloc_bytes, flags);
1332         if (!dst) {
1333                 kfree(orig);
1334                 return NULL;
1335         }
1336
1337         memcpy(dst, src, bytes);
1338 out:
1339         return dst ? dst : ZERO_SIZE_PTR;
1340 }
1341
1342 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1343  * small to hold new_n items. new items are zeroed out if the array grows.
1344  *
1345  * Contrary to krealloc_array, does not free arr if new_n is zero.
1346  */
1347 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1348 {
1349         size_t alloc_size;
1350         void *new_arr;
1351
1352         if (!new_n || old_n == new_n)
1353                 goto out;
1354
1355         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1356         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1357         if (!new_arr) {
1358                 kfree(arr);
1359                 return NULL;
1360         }
1361         arr = new_arr;
1362
1363         if (new_n > old_n)
1364                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1365
1366 out:
1367         return arr ? arr : ZERO_SIZE_PTR;
1368 }
1369
1370 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1371 {
1372         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1373                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1374         if (!dst->refs)
1375                 return -ENOMEM;
1376
1377         dst->acquired_refs = src->acquired_refs;
1378         return 0;
1379 }
1380
1381 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1382 {
1383         size_t n = src->allocated_stack / BPF_REG_SIZE;
1384
1385         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1386                                 GFP_KERNEL);
1387         if (!dst->stack)
1388                 return -ENOMEM;
1389
1390         dst->allocated_stack = src->allocated_stack;
1391         return 0;
1392 }
1393
1394 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1395 {
1396         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1397                                     sizeof(struct bpf_reference_state));
1398         if (!state->refs)
1399                 return -ENOMEM;
1400
1401         state->acquired_refs = n;
1402         return 0;
1403 }
1404
1405 static int grow_stack_state(struct bpf_func_state *state, int size)
1406 {
1407         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1408
1409         if (old_n >= n)
1410                 return 0;
1411
1412         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1413         if (!state->stack)
1414                 return -ENOMEM;
1415
1416         state->allocated_stack = size;
1417         return 0;
1418 }
1419
1420 /* Acquire a pointer id from the env and update the state->refs to include
1421  * this new pointer reference.
1422  * On success, returns a valid pointer id to associate with the register
1423  * On failure, returns a negative errno.
1424  */
1425 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1426 {
1427         struct bpf_func_state *state = cur_func(env);
1428         int new_ofs = state->acquired_refs;
1429         int id, err;
1430
1431         err = resize_reference_state(state, state->acquired_refs + 1);
1432         if (err)
1433                 return err;
1434         id = ++env->id_gen;
1435         state->refs[new_ofs].id = id;
1436         state->refs[new_ofs].insn_idx = insn_idx;
1437         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1438
1439         return id;
1440 }
1441
1442 /* release function corresponding to acquire_reference_state(). Idempotent. */
1443 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1444 {
1445         int i, last_idx;
1446
1447         last_idx = state->acquired_refs - 1;
1448         for (i = 0; i < state->acquired_refs; i++) {
1449                 if (state->refs[i].id == ptr_id) {
1450                         /* Cannot release caller references in callbacks */
1451                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1452                                 return -EINVAL;
1453                         if (last_idx && i != last_idx)
1454                                 memcpy(&state->refs[i], &state->refs[last_idx],
1455                                        sizeof(*state->refs));
1456                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1457                         state->acquired_refs--;
1458                         return 0;
1459                 }
1460         }
1461         return -EINVAL;
1462 }
1463
1464 static void free_func_state(struct bpf_func_state *state)
1465 {
1466         if (!state)
1467                 return;
1468         kfree(state->refs);
1469         kfree(state->stack);
1470         kfree(state);
1471 }
1472
1473 static void clear_jmp_history(struct bpf_verifier_state *state)
1474 {
1475         kfree(state->jmp_history);
1476         state->jmp_history = NULL;
1477         state->jmp_history_cnt = 0;
1478 }
1479
1480 static void free_verifier_state(struct bpf_verifier_state *state,
1481                                 bool free_self)
1482 {
1483         int i;
1484
1485         for (i = 0; i <= state->curframe; i++) {
1486                 free_func_state(state->frame[i]);
1487                 state->frame[i] = NULL;
1488         }
1489         clear_jmp_history(state);
1490         if (free_self)
1491                 kfree(state);
1492 }
1493
1494 /* copy verifier state from src to dst growing dst stack space
1495  * when necessary to accommodate larger src stack
1496  */
1497 static int copy_func_state(struct bpf_func_state *dst,
1498                            const struct bpf_func_state *src)
1499 {
1500         int err;
1501
1502         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1503         err = copy_reference_state(dst, src);
1504         if (err)
1505                 return err;
1506         return copy_stack_state(dst, src);
1507 }
1508
1509 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1510                                const struct bpf_verifier_state *src)
1511 {
1512         struct bpf_func_state *dst;
1513         int i, err;
1514
1515         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1516                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1517                                             GFP_USER);
1518         if (!dst_state->jmp_history)
1519                 return -ENOMEM;
1520         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1521
1522         /* if dst has more stack frames then src frame, free them */
1523         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1524                 free_func_state(dst_state->frame[i]);
1525                 dst_state->frame[i] = NULL;
1526         }
1527         dst_state->speculative = src->speculative;
1528         dst_state->active_rcu_lock = src->active_rcu_lock;
1529         dst_state->curframe = src->curframe;
1530         dst_state->active_lock.ptr = src->active_lock.ptr;
1531         dst_state->active_lock.id = src->active_lock.id;
1532         dst_state->branches = src->branches;
1533         dst_state->parent = src->parent;
1534         dst_state->first_insn_idx = src->first_insn_idx;
1535         dst_state->last_insn_idx = src->last_insn_idx;
1536         for (i = 0; i <= src->curframe; i++) {
1537                 dst = dst_state->frame[i];
1538                 if (!dst) {
1539                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1540                         if (!dst)
1541                                 return -ENOMEM;
1542                         dst_state->frame[i] = dst;
1543                 }
1544                 err = copy_func_state(dst, src->frame[i]);
1545                 if (err)
1546                         return err;
1547         }
1548         return 0;
1549 }
1550
1551 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1552 {
1553         while (st) {
1554                 u32 br = --st->branches;
1555
1556                 /* WARN_ON(br > 1) technically makes sense here,
1557                  * but see comment in push_stack(), hence:
1558                  */
1559                 WARN_ONCE((int)br < 0,
1560                           "BUG update_branch_counts:branches_to_explore=%d\n",
1561                           br);
1562                 if (br)
1563                         break;
1564                 st = st->parent;
1565         }
1566 }
1567
1568 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1569                      int *insn_idx, bool pop_log)
1570 {
1571         struct bpf_verifier_state *cur = env->cur_state;
1572         struct bpf_verifier_stack_elem *elem, *head = env->head;
1573         int err;
1574
1575         if (env->head == NULL)
1576                 return -ENOENT;
1577
1578         if (cur) {
1579                 err = copy_verifier_state(cur, &head->st);
1580                 if (err)
1581                         return err;
1582         }
1583         if (pop_log)
1584                 bpf_vlog_reset(&env->log, head->log_pos);
1585         if (insn_idx)
1586                 *insn_idx = head->insn_idx;
1587         if (prev_insn_idx)
1588                 *prev_insn_idx = head->prev_insn_idx;
1589         elem = head->next;
1590         free_verifier_state(&head->st, false);
1591         kfree(head);
1592         env->head = elem;
1593         env->stack_size--;
1594         return 0;
1595 }
1596
1597 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1598                                              int insn_idx, int prev_insn_idx,
1599                                              bool speculative)
1600 {
1601         struct bpf_verifier_state *cur = env->cur_state;
1602         struct bpf_verifier_stack_elem *elem;
1603         int err;
1604
1605         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1606         if (!elem)
1607                 goto err;
1608
1609         elem->insn_idx = insn_idx;
1610         elem->prev_insn_idx = prev_insn_idx;
1611         elem->next = env->head;
1612         elem->log_pos = env->log.len_used;
1613         env->head = elem;
1614         env->stack_size++;
1615         err = copy_verifier_state(&elem->st, cur);
1616         if (err)
1617                 goto err;
1618         elem->st.speculative |= speculative;
1619         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1620                 verbose(env, "The sequence of %d jumps is too complex.\n",
1621                         env->stack_size);
1622                 goto err;
1623         }
1624         if (elem->st.parent) {
1625                 ++elem->st.parent->branches;
1626                 /* WARN_ON(branches > 2) technically makes sense here,
1627                  * but
1628                  * 1. speculative states will bump 'branches' for non-branch
1629                  * instructions
1630                  * 2. is_state_visited() heuristics may decide not to create
1631                  * a new state for a sequence of branches and all such current
1632                  * and cloned states will be pointing to a single parent state
1633                  * which might have large 'branches' count.
1634                  */
1635         }
1636         return &elem->st;
1637 err:
1638         free_verifier_state(env->cur_state, true);
1639         env->cur_state = NULL;
1640         /* pop all elements and return */
1641         while (!pop_stack(env, NULL, NULL, false));
1642         return NULL;
1643 }
1644
1645 #define CALLER_SAVED_REGS 6
1646 static const int caller_saved[CALLER_SAVED_REGS] = {
1647         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1648 };
1649
1650 /* This helper doesn't clear reg->id */
1651 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1652 {
1653         reg->var_off = tnum_const(imm);
1654         reg->smin_value = (s64)imm;
1655         reg->smax_value = (s64)imm;
1656         reg->umin_value = imm;
1657         reg->umax_value = imm;
1658
1659         reg->s32_min_value = (s32)imm;
1660         reg->s32_max_value = (s32)imm;
1661         reg->u32_min_value = (u32)imm;
1662         reg->u32_max_value = (u32)imm;
1663 }
1664
1665 /* Mark the unknown part of a register (variable offset or scalar value) as
1666  * known to have the value @imm.
1667  */
1668 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1669 {
1670         /* Clear off and union(map_ptr, range) */
1671         memset(((u8 *)reg) + sizeof(reg->type), 0,
1672                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1673         reg->id = 0;
1674         reg->ref_obj_id = 0;
1675         ___mark_reg_known(reg, imm);
1676 }
1677
1678 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1679 {
1680         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1681         reg->s32_min_value = (s32)imm;
1682         reg->s32_max_value = (s32)imm;
1683         reg->u32_min_value = (u32)imm;
1684         reg->u32_max_value = (u32)imm;
1685 }
1686
1687 /* Mark the 'variable offset' part of a register as zero.  This should be
1688  * used only on registers holding a pointer type.
1689  */
1690 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1691 {
1692         __mark_reg_known(reg, 0);
1693 }
1694
1695 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1696 {
1697         __mark_reg_known(reg, 0);
1698         reg->type = SCALAR_VALUE;
1699 }
1700
1701 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1702                                 struct bpf_reg_state *regs, u32 regno)
1703 {
1704         if (WARN_ON(regno >= MAX_BPF_REG)) {
1705                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1706                 /* Something bad happened, let's kill all regs */
1707                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1708                         __mark_reg_not_init(env, regs + regno);
1709                 return;
1710         }
1711         __mark_reg_known_zero(regs + regno);
1712 }
1713
1714 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1715                               bool first_slot, int dynptr_id)
1716 {
1717         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1718          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1719          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1720          */
1721         __mark_reg_known_zero(reg);
1722         reg->type = CONST_PTR_TO_DYNPTR;
1723         /* Give each dynptr a unique id to uniquely associate slices to it. */
1724         reg->id = dynptr_id;
1725         reg->dynptr.type = type;
1726         reg->dynptr.first_slot = first_slot;
1727 }
1728
1729 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1730 {
1731         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1732                 const struct bpf_map *map = reg->map_ptr;
1733
1734                 if (map->inner_map_meta) {
1735                         reg->type = CONST_PTR_TO_MAP;
1736                         reg->map_ptr = map->inner_map_meta;
1737                         /* transfer reg's id which is unique for every map_lookup_elem
1738                          * as UID of the inner map.
1739                          */
1740                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1741                                 reg->map_uid = reg->id;
1742                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1743                         reg->type = PTR_TO_XDP_SOCK;
1744                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1745                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1746                         reg->type = PTR_TO_SOCKET;
1747                 } else {
1748                         reg->type = PTR_TO_MAP_VALUE;
1749                 }
1750                 return;
1751         }
1752
1753         reg->type &= ~PTR_MAYBE_NULL;
1754 }
1755
1756 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1757                                 struct btf_field_graph_root *ds_head)
1758 {
1759         __mark_reg_known_zero(&regs[regno]);
1760         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1761         regs[regno].btf = ds_head->btf;
1762         regs[regno].btf_id = ds_head->value_btf_id;
1763         regs[regno].off = ds_head->node_offset;
1764 }
1765
1766 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1767 {
1768         return type_is_pkt_pointer(reg->type);
1769 }
1770
1771 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1772 {
1773         return reg_is_pkt_pointer(reg) ||
1774                reg->type == PTR_TO_PACKET_END;
1775 }
1776
1777 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1778 {
1779         return base_type(reg->type) == PTR_TO_MEM &&
1780                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1781 }
1782
1783 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1784 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1785                                     enum bpf_reg_type which)
1786 {
1787         /* The register can already have a range from prior markings.
1788          * This is fine as long as it hasn't been advanced from its
1789          * origin.
1790          */
1791         return reg->type == which &&
1792                reg->id == 0 &&
1793                reg->off == 0 &&
1794                tnum_equals_const(reg->var_off, 0);
1795 }
1796
1797 /* Reset the min/max bounds of a register */
1798 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1799 {
1800         reg->smin_value = S64_MIN;
1801         reg->smax_value = S64_MAX;
1802         reg->umin_value = 0;
1803         reg->umax_value = U64_MAX;
1804
1805         reg->s32_min_value = S32_MIN;
1806         reg->s32_max_value = S32_MAX;
1807         reg->u32_min_value = 0;
1808         reg->u32_max_value = U32_MAX;
1809 }
1810
1811 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1812 {
1813         reg->smin_value = S64_MIN;
1814         reg->smax_value = S64_MAX;
1815         reg->umin_value = 0;
1816         reg->umax_value = U64_MAX;
1817 }
1818
1819 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1820 {
1821         reg->s32_min_value = S32_MIN;
1822         reg->s32_max_value = S32_MAX;
1823         reg->u32_min_value = 0;
1824         reg->u32_max_value = U32_MAX;
1825 }
1826
1827 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1828 {
1829         struct tnum var32_off = tnum_subreg(reg->var_off);
1830
1831         /* min signed is max(sign bit) | min(other bits) */
1832         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1833                         var32_off.value | (var32_off.mask & S32_MIN));
1834         /* max signed is min(sign bit) | max(other bits) */
1835         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1836                         var32_off.value | (var32_off.mask & S32_MAX));
1837         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1838         reg->u32_max_value = min(reg->u32_max_value,
1839                                  (u32)(var32_off.value | var32_off.mask));
1840 }
1841
1842 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1843 {
1844         /* min signed is max(sign bit) | min(other bits) */
1845         reg->smin_value = max_t(s64, reg->smin_value,
1846                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1847         /* max signed is min(sign bit) | max(other bits) */
1848         reg->smax_value = min_t(s64, reg->smax_value,
1849                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1850         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1851         reg->umax_value = min(reg->umax_value,
1852                               reg->var_off.value | reg->var_off.mask);
1853 }
1854
1855 static void __update_reg_bounds(struct bpf_reg_state *reg)
1856 {
1857         __update_reg32_bounds(reg);
1858         __update_reg64_bounds(reg);
1859 }
1860
1861 /* Uses signed min/max values to inform unsigned, and vice-versa */
1862 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1863 {
1864         /* Learn sign from signed bounds.
1865          * If we cannot cross the sign boundary, then signed and unsigned bounds
1866          * are the same, so combine.  This works even in the negative case, e.g.
1867          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1868          */
1869         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1870                 reg->s32_min_value = reg->u32_min_value =
1871                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1872                 reg->s32_max_value = reg->u32_max_value =
1873                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1874                 return;
1875         }
1876         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1877          * boundary, so we must be careful.
1878          */
1879         if ((s32)reg->u32_max_value >= 0) {
1880                 /* Positive.  We can't learn anything from the smin, but smax
1881                  * is positive, hence safe.
1882                  */
1883                 reg->s32_min_value = reg->u32_min_value;
1884                 reg->s32_max_value = reg->u32_max_value =
1885                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1886         } else if ((s32)reg->u32_min_value < 0) {
1887                 /* Negative.  We can't learn anything from the smax, but smin
1888                  * is negative, hence safe.
1889                  */
1890                 reg->s32_min_value = reg->u32_min_value =
1891                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1892                 reg->s32_max_value = reg->u32_max_value;
1893         }
1894 }
1895
1896 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1897 {
1898         /* Learn sign from signed bounds.
1899          * If we cannot cross the sign boundary, then signed and unsigned bounds
1900          * are the same, so combine.  This works even in the negative case, e.g.
1901          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1902          */
1903         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1904                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1905                                                           reg->umin_value);
1906                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1907                                                           reg->umax_value);
1908                 return;
1909         }
1910         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1911          * boundary, so we must be careful.
1912          */
1913         if ((s64)reg->umax_value >= 0) {
1914                 /* Positive.  We can't learn anything from the smin, but smax
1915                  * is positive, hence safe.
1916                  */
1917                 reg->smin_value = reg->umin_value;
1918                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1919                                                           reg->umax_value);
1920         } else if ((s64)reg->umin_value < 0) {
1921                 /* Negative.  We can't learn anything from the smax, but smin
1922                  * is negative, hence safe.
1923                  */
1924                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1925                                                           reg->umin_value);
1926                 reg->smax_value = reg->umax_value;
1927         }
1928 }
1929
1930 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1931 {
1932         __reg32_deduce_bounds(reg);
1933         __reg64_deduce_bounds(reg);
1934 }
1935
1936 /* Attempts to improve var_off based on unsigned min/max information */
1937 static void __reg_bound_offset(struct bpf_reg_state *reg)
1938 {
1939         struct tnum var64_off = tnum_intersect(reg->var_off,
1940                                                tnum_range(reg->umin_value,
1941                                                           reg->umax_value));
1942         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1943                                                 tnum_range(reg->u32_min_value,
1944                                                            reg->u32_max_value));
1945
1946         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1947 }
1948
1949 static void reg_bounds_sync(struct bpf_reg_state *reg)
1950 {
1951         /* We might have learned new bounds from the var_off. */
1952         __update_reg_bounds(reg);
1953         /* We might have learned something about the sign bit. */
1954         __reg_deduce_bounds(reg);
1955         /* We might have learned some bits from the bounds. */
1956         __reg_bound_offset(reg);
1957         /* Intersecting with the old var_off might have improved our bounds
1958          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1959          * then new var_off is (0; 0x7f...fc) which improves our umax.
1960          */
1961         __update_reg_bounds(reg);
1962 }
1963
1964 static bool __reg32_bound_s64(s32 a)
1965 {
1966         return a >= 0 && a <= S32_MAX;
1967 }
1968
1969 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1970 {
1971         reg->umin_value = reg->u32_min_value;
1972         reg->umax_value = reg->u32_max_value;
1973
1974         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1975          * be positive otherwise set to worse case bounds and refine later
1976          * from tnum.
1977          */
1978         if (__reg32_bound_s64(reg->s32_min_value) &&
1979             __reg32_bound_s64(reg->s32_max_value)) {
1980                 reg->smin_value = reg->s32_min_value;
1981                 reg->smax_value = reg->s32_max_value;
1982         } else {
1983                 reg->smin_value = 0;
1984                 reg->smax_value = U32_MAX;
1985         }
1986 }
1987
1988 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1989 {
1990         /* special case when 64-bit register has upper 32-bit register
1991          * zeroed. Typically happens after zext or <<32, >>32 sequence
1992          * allowing us to use 32-bit bounds directly,
1993          */
1994         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1995                 __reg_assign_32_into_64(reg);
1996         } else {
1997                 /* Otherwise the best we can do is push lower 32bit known and
1998                  * unknown bits into register (var_off set from jmp logic)
1999                  * then learn as much as possible from the 64-bit tnum
2000                  * known and unknown bits. The previous smin/smax bounds are
2001                  * invalid here because of jmp32 compare so mark them unknown
2002                  * so they do not impact tnum bounds calculation.
2003                  */
2004                 __mark_reg64_unbounded(reg);
2005         }
2006         reg_bounds_sync(reg);
2007 }
2008
2009 static bool __reg64_bound_s32(s64 a)
2010 {
2011         return a >= S32_MIN && a <= S32_MAX;
2012 }
2013
2014 static bool __reg64_bound_u32(u64 a)
2015 {
2016         return a >= U32_MIN && a <= U32_MAX;
2017 }
2018
2019 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2020 {
2021         __mark_reg32_unbounded(reg);
2022         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2023                 reg->s32_min_value = (s32)reg->smin_value;
2024                 reg->s32_max_value = (s32)reg->smax_value;
2025         }
2026         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2027                 reg->u32_min_value = (u32)reg->umin_value;
2028                 reg->u32_max_value = (u32)reg->umax_value;
2029         }
2030         reg_bounds_sync(reg);
2031 }
2032
2033 /* Mark a register as having a completely unknown (scalar) value. */
2034 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2035                                struct bpf_reg_state *reg)
2036 {
2037         /*
2038          * Clear type, off, and union(map_ptr, range) and
2039          * padding between 'type' and union
2040          */
2041         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2042         reg->type = SCALAR_VALUE;
2043         reg->id = 0;
2044         reg->ref_obj_id = 0;
2045         reg->var_off = tnum_unknown;
2046         reg->frameno = 0;
2047         reg->precise = !env->bpf_capable;
2048         __mark_reg_unbounded(reg);
2049 }
2050
2051 static void mark_reg_unknown(struct bpf_verifier_env *env,
2052                              struct bpf_reg_state *regs, u32 regno)
2053 {
2054         if (WARN_ON(regno >= MAX_BPF_REG)) {
2055                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2056                 /* Something bad happened, let's kill all regs except FP */
2057                 for (regno = 0; regno < BPF_REG_FP; regno++)
2058                         __mark_reg_not_init(env, regs + regno);
2059                 return;
2060         }
2061         __mark_reg_unknown(env, regs + regno);
2062 }
2063
2064 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2065                                 struct bpf_reg_state *reg)
2066 {
2067         __mark_reg_unknown(env, reg);
2068         reg->type = NOT_INIT;
2069 }
2070
2071 static void mark_reg_not_init(struct bpf_verifier_env *env,
2072                               struct bpf_reg_state *regs, u32 regno)
2073 {
2074         if (WARN_ON(regno >= MAX_BPF_REG)) {
2075                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2076                 /* Something bad happened, let's kill all regs except FP */
2077                 for (regno = 0; regno < BPF_REG_FP; regno++)
2078                         __mark_reg_not_init(env, regs + regno);
2079                 return;
2080         }
2081         __mark_reg_not_init(env, regs + regno);
2082 }
2083
2084 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2085                             struct bpf_reg_state *regs, u32 regno,
2086                             enum bpf_reg_type reg_type,
2087                             struct btf *btf, u32 btf_id,
2088                             enum bpf_type_flag flag)
2089 {
2090         if (reg_type == SCALAR_VALUE) {
2091                 mark_reg_unknown(env, regs, regno);
2092                 return;
2093         }
2094         mark_reg_known_zero(env, regs, regno);
2095         regs[regno].type = PTR_TO_BTF_ID | flag;
2096         regs[regno].btf = btf;
2097         regs[regno].btf_id = btf_id;
2098 }
2099
2100 #define DEF_NOT_SUBREG  (0)
2101 static void init_reg_state(struct bpf_verifier_env *env,
2102                            struct bpf_func_state *state)
2103 {
2104         struct bpf_reg_state *regs = state->regs;
2105         int i;
2106
2107         for (i = 0; i < MAX_BPF_REG; i++) {
2108                 mark_reg_not_init(env, regs, i);
2109                 regs[i].live = REG_LIVE_NONE;
2110                 regs[i].parent = NULL;
2111                 regs[i].subreg_def = DEF_NOT_SUBREG;
2112         }
2113
2114         /* frame pointer */
2115         regs[BPF_REG_FP].type = PTR_TO_STACK;
2116         mark_reg_known_zero(env, regs, BPF_REG_FP);
2117         regs[BPF_REG_FP].frameno = state->frameno;
2118 }
2119
2120 #define BPF_MAIN_FUNC (-1)
2121 static void init_func_state(struct bpf_verifier_env *env,
2122                             struct bpf_func_state *state,
2123                             int callsite, int frameno, int subprogno)
2124 {
2125         state->callsite = callsite;
2126         state->frameno = frameno;
2127         state->subprogno = subprogno;
2128         state->callback_ret_range = tnum_range(0, 0);
2129         init_reg_state(env, state);
2130         mark_verifier_state_scratched(env);
2131 }
2132
2133 /* Similar to push_stack(), but for async callbacks */
2134 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2135                                                 int insn_idx, int prev_insn_idx,
2136                                                 int subprog)
2137 {
2138         struct bpf_verifier_stack_elem *elem;
2139         struct bpf_func_state *frame;
2140
2141         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2142         if (!elem)
2143                 goto err;
2144
2145         elem->insn_idx = insn_idx;
2146         elem->prev_insn_idx = prev_insn_idx;
2147         elem->next = env->head;
2148         elem->log_pos = env->log.len_used;
2149         env->head = elem;
2150         env->stack_size++;
2151         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2152                 verbose(env,
2153                         "The sequence of %d jumps is too complex for async cb.\n",
2154                         env->stack_size);
2155                 goto err;
2156         }
2157         /* Unlike push_stack() do not copy_verifier_state().
2158          * The caller state doesn't matter.
2159          * This is async callback. It starts in a fresh stack.
2160          * Initialize it similar to do_check_common().
2161          */
2162         elem->st.branches = 1;
2163         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2164         if (!frame)
2165                 goto err;
2166         init_func_state(env, frame,
2167                         BPF_MAIN_FUNC /* callsite */,
2168                         0 /* frameno within this callchain */,
2169                         subprog /* subprog number within this prog */);
2170         elem->st.frame[0] = frame;
2171         return &elem->st;
2172 err:
2173         free_verifier_state(env->cur_state, true);
2174         env->cur_state = NULL;
2175         /* pop all elements and return */
2176         while (!pop_stack(env, NULL, NULL, false));
2177         return NULL;
2178 }
2179
2180
2181 enum reg_arg_type {
2182         SRC_OP,         /* register is used as source operand */
2183         DST_OP,         /* register is used as destination operand */
2184         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2185 };
2186
2187 static int cmp_subprogs(const void *a, const void *b)
2188 {
2189         return ((struct bpf_subprog_info *)a)->start -
2190                ((struct bpf_subprog_info *)b)->start;
2191 }
2192
2193 static int find_subprog(struct bpf_verifier_env *env, int off)
2194 {
2195         struct bpf_subprog_info *p;
2196
2197         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2198                     sizeof(env->subprog_info[0]), cmp_subprogs);
2199         if (!p)
2200                 return -ENOENT;
2201         return p - env->subprog_info;
2202
2203 }
2204
2205 static int add_subprog(struct bpf_verifier_env *env, int off)
2206 {
2207         int insn_cnt = env->prog->len;
2208         int ret;
2209
2210         if (off >= insn_cnt || off < 0) {
2211                 verbose(env, "call to invalid destination\n");
2212                 return -EINVAL;
2213         }
2214         ret = find_subprog(env, off);
2215         if (ret >= 0)
2216                 return ret;
2217         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2218                 verbose(env, "too many subprograms\n");
2219                 return -E2BIG;
2220         }
2221         /* determine subprog starts. The end is one before the next starts */
2222         env->subprog_info[env->subprog_cnt++].start = off;
2223         sort(env->subprog_info, env->subprog_cnt,
2224              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2225         return env->subprog_cnt - 1;
2226 }
2227
2228 #define MAX_KFUNC_DESCS 256
2229 #define MAX_KFUNC_BTFS  256
2230
2231 struct bpf_kfunc_desc {
2232         struct btf_func_model func_model;
2233         u32 func_id;
2234         s32 imm;
2235         u16 offset;
2236 };
2237
2238 struct bpf_kfunc_btf {
2239         struct btf *btf;
2240         struct module *module;
2241         u16 offset;
2242 };
2243
2244 struct bpf_kfunc_desc_tab {
2245         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2246         u32 nr_descs;
2247 };
2248
2249 struct bpf_kfunc_btf_tab {
2250         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2251         u32 nr_descs;
2252 };
2253
2254 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2255 {
2256         const struct bpf_kfunc_desc *d0 = a;
2257         const struct bpf_kfunc_desc *d1 = b;
2258
2259         /* func_id is not greater than BTF_MAX_TYPE */
2260         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2261 }
2262
2263 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2264 {
2265         const struct bpf_kfunc_btf *d0 = a;
2266         const struct bpf_kfunc_btf *d1 = b;
2267
2268         return d0->offset - d1->offset;
2269 }
2270
2271 static const struct bpf_kfunc_desc *
2272 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2273 {
2274         struct bpf_kfunc_desc desc = {
2275                 .func_id = func_id,
2276                 .offset = offset,
2277         };
2278         struct bpf_kfunc_desc_tab *tab;
2279
2280         tab = prog->aux->kfunc_tab;
2281         return bsearch(&desc, tab->descs, tab->nr_descs,
2282                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2283 }
2284
2285 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2286                                          s16 offset)
2287 {
2288         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2289         struct bpf_kfunc_btf_tab *tab;
2290         struct bpf_kfunc_btf *b;
2291         struct module *mod;
2292         struct btf *btf;
2293         int btf_fd;
2294
2295         tab = env->prog->aux->kfunc_btf_tab;
2296         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2297                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2298         if (!b) {
2299                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2300                         verbose(env, "too many different module BTFs\n");
2301                         return ERR_PTR(-E2BIG);
2302                 }
2303
2304                 if (bpfptr_is_null(env->fd_array)) {
2305                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2306                         return ERR_PTR(-EPROTO);
2307                 }
2308
2309                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2310                                             offset * sizeof(btf_fd),
2311                                             sizeof(btf_fd)))
2312                         return ERR_PTR(-EFAULT);
2313
2314                 btf = btf_get_by_fd(btf_fd);
2315                 if (IS_ERR(btf)) {
2316                         verbose(env, "invalid module BTF fd specified\n");
2317                         return btf;
2318                 }
2319
2320                 if (!btf_is_module(btf)) {
2321                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2322                         btf_put(btf);
2323                         return ERR_PTR(-EINVAL);
2324                 }
2325
2326                 mod = btf_try_get_module(btf);
2327                 if (!mod) {
2328                         btf_put(btf);
2329                         return ERR_PTR(-ENXIO);
2330                 }
2331
2332                 b = &tab->descs[tab->nr_descs++];
2333                 b->btf = btf;
2334                 b->module = mod;
2335                 b->offset = offset;
2336
2337                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2338                      kfunc_btf_cmp_by_off, NULL);
2339         }
2340         return b->btf;
2341 }
2342
2343 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2344 {
2345         if (!tab)
2346                 return;
2347
2348         while (tab->nr_descs--) {
2349                 module_put(tab->descs[tab->nr_descs].module);
2350                 btf_put(tab->descs[tab->nr_descs].btf);
2351         }
2352         kfree(tab);
2353 }
2354
2355 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2356 {
2357         if (offset) {
2358                 if (offset < 0) {
2359                         /* In the future, this can be allowed to increase limit
2360                          * of fd index into fd_array, interpreted as u16.
2361                          */
2362                         verbose(env, "negative offset disallowed for kernel module function call\n");
2363                         return ERR_PTR(-EINVAL);
2364                 }
2365
2366                 return __find_kfunc_desc_btf(env, offset);
2367         }
2368         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2369 }
2370
2371 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2372 {
2373         const struct btf_type *func, *func_proto;
2374         struct bpf_kfunc_btf_tab *btf_tab;
2375         struct bpf_kfunc_desc_tab *tab;
2376         struct bpf_prog_aux *prog_aux;
2377         struct bpf_kfunc_desc *desc;
2378         const char *func_name;
2379         struct btf *desc_btf;
2380         unsigned long call_imm;
2381         unsigned long addr;
2382         int err;
2383
2384         prog_aux = env->prog->aux;
2385         tab = prog_aux->kfunc_tab;
2386         btf_tab = prog_aux->kfunc_btf_tab;
2387         if (!tab) {
2388                 if (!btf_vmlinux) {
2389                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2390                         return -ENOTSUPP;
2391                 }
2392
2393                 if (!env->prog->jit_requested) {
2394                         verbose(env, "JIT is required for calling kernel function\n");
2395                         return -ENOTSUPP;
2396                 }
2397
2398                 if (!bpf_jit_supports_kfunc_call()) {
2399                         verbose(env, "JIT does not support calling kernel function\n");
2400                         return -ENOTSUPP;
2401                 }
2402
2403                 if (!env->prog->gpl_compatible) {
2404                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2405                         return -EINVAL;
2406                 }
2407
2408                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2409                 if (!tab)
2410                         return -ENOMEM;
2411                 prog_aux->kfunc_tab = tab;
2412         }
2413
2414         /* func_id == 0 is always invalid, but instead of returning an error, be
2415          * conservative and wait until the code elimination pass before returning
2416          * error, so that invalid calls that get pruned out can be in BPF programs
2417          * loaded from userspace.  It is also required that offset be untouched
2418          * for such calls.
2419          */
2420         if (!func_id && !offset)
2421                 return 0;
2422
2423         if (!btf_tab && offset) {
2424                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2425                 if (!btf_tab)
2426                         return -ENOMEM;
2427                 prog_aux->kfunc_btf_tab = btf_tab;
2428         }
2429
2430         desc_btf = find_kfunc_desc_btf(env, offset);
2431         if (IS_ERR(desc_btf)) {
2432                 verbose(env, "failed to find BTF for kernel function\n");
2433                 return PTR_ERR(desc_btf);
2434         }
2435
2436         if (find_kfunc_desc(env->prog, func_id, offset))
2437                 return 0;
2438
2439         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2440                 verbose(env, "too many different kernel function calls\n");
2441                 return -E2BIG;
2442         }
2443
2444         func = btf_type_by_id(desc_btf, func_id);
2445         if (!func || !btf_type_is_func(func)) {
2446                 verbose(env, "kernel btf_id %u is not a function\n",
2447                         func_id);
2448                 return -EINVAL;
2449         }
2450         func_proto = btf_type_by_id(desc_btf, func->type);
2451         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2452                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2453                         func_id);
2454                 return -EINVAL;
2455         }
2456
2457         func_name = btf_name_by_offset(desc_btf, func->name_off);
2458         addr = kallsyms_lookup_name(func_name);
2459         if (!addr) {
2460                 verbose(env, "cannot find address for kernel function %s\n",
2461                         func_name);
2462                 return -EINVAL;
2463         }
2464
2465         call_imm = BPF_CALL_IMM(addr);
2466         /* Check whether or not the relative offset overflows desc->imm */
2467         if ((unsigned long)(s32)call_imm != call_imm) {
2468                 verbose(env, "address of kernel function %s is out of range\n",
2469                         func_name);
2470                 return -EINVAL;
2471         }
2472
2473         if (bpf_dev_bound_kfunc_id(func_id)) {
2474                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2475                 if (err)
2476                         return err;
2477         }
2478
2479         desc = &tab->descs[tab->nr_descs++];
2480         desc->func_id = func_id;
2481         desc->imm = call_imm;
2482         desc->offset = offset;
2483         err = btf_distill_func_proto(&env->log, desc_btf,
2484                                      func_proto, func_name,
2485                                      &desc->func_model);
2486         if (!err)
2487                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2488                      kfunc_desc_cmp_by_id_off, NULL);
2489         return err;
2490 }
2491
2492 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2493 {
2494         const struct bpf_kfunc_desc *d0 = a;
2495         const struct bpf_kfunc_desc *d1 = b;
2496
2497         if (d0->imm > d1->imm)
2498                 return 1;
2499         else if (d0->imm < d1->imm)
2500                 return -1;
2501         return 0;
2502 }
2503
2504 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2505 {
2506         struct bpf_kfunc_desc_tab *tab;
2507
2508         tab = prog->aux->kfunc_tab;
2509         if (!tab)
2510                 return;
2511
2512         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2513              kfunc_desc_cmp_by_imm, NULL);
2514 }
2515
2516 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2517 {
2518         return !!prog->aux->kfunc_tab;
2519 }
2520
2521 const struct btf_func_model *
2522 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2523                          const struct bpf_insn *insn)
2524 {
2525         const struct bpf_kfunc_desc desc = {
2526                 .imm = insn->imm,
2527         };
2528         const struct bpf_kfunc_desc *res;
2529         struct bpf_kfunc_desc_tab *tab;
2530
2531         tab = prog->aux->kfunc_tab;
2532         res = bsearch(&desc, tab->descs, tab->nr_descs,
2533                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2534
2535         return res ? &res->func_model : NULL;
2536 }
2537
2538 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2539 {
2540         struct bpf_subprog_info *subprog = env->subprog_info;
2541         struct bpf_insn *insn = env->prog->insnsi;
2542         int i, ret, insn_cnt = env->prog->len;
2543
2544         /* Add entry function. */
2545         ret = add_subprog(env, 0);
2546         if (ret)
2547                 return ret;
2548
2549         for (i = 0; i < insn_cnt; i++, insn++) {
2550                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2551                     !bpf_pseudo_kfunc_call(insn))
2552                         continue;
2553
2554                 if (!env->bpf_capable) {
2555                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2556                         return -EPERM;
2557                 }
2558
2559                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2560                         ret = add_subprog(env, i + insn->imm + 1);
2561                 else
2562                         ret = add_kfunc_call(env, insn->imm, insn->off);
2563
2564                 if (ret < 0)
2565                         return ret;
2566         }
2567
2568         /* Add a fake 'exit' subprog which could simplify subprog iteration
2569          * logic. 'subprog_cnt' should not be increased.
2570          */
2571         subprog[env->subprog_cnt].start = insn_cnt;
2572
2573         if (env->log.level & BPF_LOG_LEVEL2)
2574                 for (i = 0; i < env->subprog_cnt; i++)
2575                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2576
2577         return 0;
2578 }
2579
2580 static int check_subprogs(struct bpf_verifier_env *env)
2581 {
2582         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2583         struct bpf_subprog_info *subprog = env->subprog_info;
2584         struct bpf_insn *insn = env->prog->insnsi;
2585         int insn_cnt = env->prog->len;
2586
2587         /* now check that all jumps are within the same subprog */
2588         subprog_start = subprog[cur_subprog].start;
2589         subprog_end = subprog[cur_subprog + 1].start;
2590         for (i = 0; i < insn_cnt; i++) {
2591                 u8 code = insn[i].code;
2592
2593                 if (code == (BPF_JMP | BPF_CALL) &&
2594                     insn[i].src_reg == 0 &&
2595                     insn[i].imm == BPF_FUNC_tail_call)
2596                         subprog[cur_subprog].has_tail_call = true;
2597                 if (BPF_CLASS(code) == BPF_LD &&
2598                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2599                         subprog[cur_subprog].has_ld_abs = true;
2600                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2601                         goto next;
2602                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2603                         goto next;
2604                 off = i + insn[i].off + 1;
2605                 if (off < subprog_start || off >= subprog_end) {
2606                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2607                         return -EINVAL;
2608                 }
2609 next:
2610                 if (i == subprog_end - 1) {
2611                         /* to avoid fall-through from one subprog into another
2612                          * the last insn of the subprog should be either exit
2613                          * or unconditional jump back
2614                          */
2615                         if (code != (BPF_JMP | BPF_EXIT) &&
2616                             code != (BPF_JMP | BPF_JA)) {
2617                                 verbose(env, "last insn is not an exit or jmp\n");
2618                                 return -EINVAL;
2619                         }
2620                         subprog_start = subprog_end;
2621                         cur_subprog++;
2622                         if (cur_subprog < env->subprog_cnt)
2623                                 subprog_end = subprog[cur_subprog + 1].start;
2624                 }
2625         }
2626         return 0;
2627 }
2628
2629 /* Parentage chain of this register (or stack slot) should take care of all
2630  * issues like callee-saved registers, stack slot allocation time, etc.
2631  */
2632 static int mark_reg_read(struct bpf_verifier_env *env,
2633                          const struct bpf_reg_state *state,
2634                          struct bpf_reg_state *parent, u8 flag)
2635 {
2636         bool writes = parent == state->parent; /* Observe write marks */
2637         int cnt = 0;
2638
2639         while (parent) {
2640                 /* if read wasn't screened by an earlier write ... */
2641                 if (writes && state->live & REG_LIVE_WRITTEN)
2642                         break;
2643                 if (parent->live & REG_LIVE_DONE) {
2644                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2645                                 reg_type_str(env, parent->type),
2646                                 parent->var_off.value, parent->off);
2647                         return -EFAULT;
2648                 }
2649                 /* The first condition is more likely to be true than the
2650                  * second, checked it first.
2651                  */
2652                 if ((parent->live & REG_LIVE_READ) == flag ||
2653                     parent->live & REG_LIVE_READ64)
2654                         /* The parentage chain never changes and
2655                          * this parent was already marked as LIVE_READ.
2656                          * There is no need to keep walking the chain again and
2657                          * keep re-marking all parents as LIVE_READ.
2658                          * This case happens when the same register is read
2659                          * multiple times without writes into it in-between.
2660                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2661                          * then no need to set the weak REG_LIVE_READ32.
2662                          */
2663                         break;
2664                 /* ... then we depend on parent's value */
2665                 parent->live |= flag;
2666                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2667                 if (flag == REG_LIVE_READ64)
2668                         parent->live &= ~REG_LIVE_READ32;
2669                 state = parent;
2670                 parent = state->parent;
2671                 writes = true;
2672                 cnt++;
2673         }
2674
2675         if (env->longest_mark_read_walk < cnt)
2676                 env->longest_mark_read_walk = cnt;
2677         return 0;
2678 }
2679
2680 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2681 {
2682         struct bpf_func_state *state = func(env, reg);
2683         int spi, ret;
2684
2685         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2686          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2687          * check_kfunc_call.
2688          */
2689         if (reg->type == CONST_PTR_TO_DYNPTR)
2690                 return 0;
2691         spi = dynptr_get_spi(env, reg);
2692         if (spi < 0)
2693                 return spi;
2694         /* Caller ensures dynptr is valid and initialized, which means spi is in
2695          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2696          * read.
2697          */
2698         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2699                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2700         if (ret)
2701                 return ret;
2702         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2703                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2704 }
2705
2706 /* This function is supposed to be used by the following 32-bit optimization
2707  * code only. It returns TRUE if the source or destination register operates
2708  * on 64-bit, otherwise return FALSE.
2709  */
2710 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2711                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2712 {
2713         u8 code, class, op;
2714
2715         code = insn->code;
2716         class = BPF_CLASS(code);
2717         op = BPF_OP(code);
2718         if (class == BPF_JMP) {
2719                 /* BPF_EXIT for "main" will reach here. Return TRUE
2720                  * conservatively.
2721                  */
2722                 if (op == BPF_EXIT)
2723                         return true;
2724                 if (op == BPF_CALL) {
2725                         /* BPF to BPF call will reach here because of marking
2726                          * caller saved clobber with DST_OP_NO_MARK for which we
2727                          * don't care the register def because they are anyway
2728                          * marked as NOT_INIT already.
2729                          */
2730                         if (insn->src_reg == BPF_PSEUDO_CALL)
2731                                 return false;
2732                         /* Helper call will reach here because of arg type
2733                          * check, conservatively return TRUE.
2734                          */
2735                         if (t == SRC_OP)
2736                                 return true;
2737
2738                         return false;
2739                 }
2740         }
2741
2742         if (class == BPF_ALU64 || class == BPF_JMP ||
2743             /* BPF_END always use BPF_ALU class. */
2744             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2745                 return true;
2746
2747         if (class == BPF_ALU || class == BPF_JMP32)
2748                 return false;
2749
2750         if (class == BPF_LDX) {
2751                 if (t != SRC_OP)
2752                         return BPF_SIZE(code) == BPF_DW;
2753                 /* LDX source must be ptr. */
2754                 return true;
2755         }
2756
2757         if (class == BPF_STX) {
2758                 /* BPF_STX (including atomic variants) has multiple source
2759                  * operands, one of which is a ptr. Check whether the caller is
2760                  * asking about it.
2761                  */
2762                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2763                         return true;
2764                 return BPF_SIZE(code) == BPF_DW;
2765         }
2766
2767         if (class == BPF_LD) {
2768                 u8 mode = BPF_MODE(code);
2769
2770                 /* LD_IMM64 */
2771                 if (mode == BPF_IMM)
2772                         return true;
2773
2774                 /* Both LD_IND and LD_ABS return 32-bit data. */
2775                 if (t != SRC_OP)
2776                         return  false;
2777
2778                 /* Implicit ctx ptr. */
2779                 if (regno == BPF_REG_6)
2780                         return true;
2781
2782                 /* Explicit source could be any width. */
2783                 return true;
2784         }
2785
2786         if (class == BPF_ST)
2787                 /* The only source register for BPF_ST is a ptr. */
2788                 return true;
2789
2790         /* Conservatively return true at default. */
2791         return true;
2792 }
2793
2794 /* Return the regno defined by the insn, or -1. */
2795 static int insn_def_regno(const struct bpf_insn *insn)
2796 {
2797         switch (BPF_CLASS(insn->code)) {
2798         case BPF_JMP:
2799         case BPF_JMP32:
2800         case BPF_ST:
2801                 return -1;
2802         case BPF_STX:
2803                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2804                     (insn->imm & BPF_FETCH)) {
2805                         if (insn->imm == BPF_CMPXCHG)
2806                                 return BPF_REG_0;
2807                         else
2808                                 return insn->src_reg;
2809                 } else {
2810                         return -1;
2811                 }
2812         default:
2813                 return insn->dst_reg;
2814         }
2815 }
2816
2817 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2818 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2819 {
2820         int dst_reg = insn_def_regno(insn);
2821
2822         if (dst_reg == -1)
2823                 return false;
2824
2825         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2826 }
2827
2828 static void mark_insn_zext(struct bpf_verifier_env *env,
2829                            struct bpf_reg_state *reg)
2830 {
2831         s32 def_idx = reg->subreg_def;
2832
2833         if (def_idx == DEF_NOT_SUBREG)
2834                 return;
2835
2836         env->insn_aux_data[def_idx - 1].zext_dst = true;
2837         /* The dst will be zero extended, so won't be sub-register anymore. */
2838         reg->subreg_def = DEF_NOT_SUBREG;
2839 }
2840
2841 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2842                          enum reg_arg_type t)
2843 {
2844         struct bpf_verifier_state *vstate = env->cur_state;
2845         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2846         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2847         struct bpf_reg_state *reg, *regs = state->regs;
2848         bool rw64;
2849
2850         if (regno >= MAX_BPF_REG) {
2851                 verbose(env, "R%d is invalid\n", regno);
2852                 return -EINVAL;
2853         }
2854
2855         mark_reg_scratched(env, regno);
2856
2857         reg = &regs[regno];
2858         rw64 = is_reg64(env, insn, regno, reg, t);
2859         if (t == SRC_OP) {
2860                 /* check whether register used as source operand can be read */
2861                 if (reg->type == NOT_INIT) {
2862                         verbose(env, "R%d !read_ok\n", regno);
2863                         return -EACCES;
2864                 }
2865                 /* We don't need to worry about FP liveness because it's read-only */
2866                 if (regno == BPF_REG_FP)
2867                         return 0;
2868
2869                 if (rw64)
2870                         mark_insn_zext(env, reg);
2871
2872                 return mark_reg_read(env, reg, reg->parent,
2873                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2874         } else {
2875                 /* check whether register used as dest operand can be written to */
2876                 if (regno == BPF_REG_FP) {
2877                         verbose(env, "frame pointer is read only\n");
2878                         return -EACCES;
2879                 }
2880                 reg->live |= REG_LIVE_WRITTEN;
2881                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2882                 if (t == DST_OP)
2883                         mark_reg_unknown(env, regs, regno);
2884         }
2885         return 0;
2886 }
2887
2888 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
2889 {
2890         env->insn_aux_data[idx].jmp_point = true;
2891 }
2892
2893 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
2894 {
2895         return env->insn_aux_data[insn_idx].jmp_point;
2896 }
2897
2898 /* for any branch, call, exit record the history of jmps in the given state */
2899 static int push_jmp_history(struct bpf_verifier_env *env,
2900                             struct bpf_verifier_state *cur)
2901 {
2902         u32 cnt = cur->jmp_history_cnt;
2903         struct bpf_idx_pair *p;
2904         size_t alloc_size;
2905
2906         if (!is_jmp_point(env, env->insn_idx))
2907                 return 0;
2908
2909         cnt++;
2910         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2911         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2912         if (!p)
2913                 return -ENOMEM;
2914         p[cnt - 1].idx = env->insn_idx;
2915         p[cnt - 1].prev_idx = env->prev_insn_idx;
2916         cur->jmp_history = p;
2917         cur->jmp_history_cnt = cnt;
2918         return 0;
2919 }
2920
2921 /* Backtrack one insn at a time. If idx is not at the top of recorded
2922  * history then previous instruction came from straight line execution.
2923  */
2924 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2925                              u32 *history)
2926 {
2927         u32 cnt = *history;
2928
2929         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2930                 i = st->jmp_history[cnt - 1].prev_idx;
2931                 (*history)--;
2932         } else {
2933                 i--;
2934         }
2935         return i;
2936 }
2937
2938 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2939 {
2940         const struct btf_type *func;
2941         struct btf *desc_btf;
2942
2943         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2944                 return NULL;
2945
2946         desc_btf = find_kfunc_desc_btf(data, insn->off);
2947         if (IS_ERR(desc_btf))
2948                 return "<error>";
2949
2950         func = btf_type_by_id(desc_btf, insn->imm);
2951         return btf_name_by_offset(desc_btf, func->name_off);
2952 }
2953
2954 /* For given verifier state backtrack_insn() is called from the last insn to
2955  * the first insn. Its purpose is to compute a bitmask of registers and
2956  * stack slots that needs precision in the parent verifier state.
2957  */
2958 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2959                           u32 *reg_mask, u64 *stack_mask)
2960 {
2961         const struct bpf_insn_cbs cbs = {
2962                 .cb_call        = disasm_kfunc_name,
2963                 .cb_print       = verbose,
2964                 .private_data   = env,
2965         };
2966         struct bpf_insn *insn = env->prog->insnsi + idx;
2967         u8 class = BPF_CLASS(insn->code);
2968         u8 opcode = BPF_OP(insn->code);
2969         u8 mode = BPF_MODE(insn->code);
2970         u32 dreg = 1u << insn->dst_reg;
2971         u32 sreg = 1u << insn->src_reg;
2972         u32 spi;
2973
2974         if (insn->code == 0)
2975                 return 0;
2976         if (env->log.level & BPF_LOG_LEVEL2) {
2977                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2978                 verbose(env, "%d: ", idx);
2979                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2980         }
2981
2982         if (class == BPF_ALU || class == BPF_ALU64) {
2983                 if (!(*reg_mask & dreg))
2984                         return 0;
2985                 if (opcode == BPF_MOV) {
2986                         if (BPF_SRC(insn->code) == BPF_X) {
2987                                 /* dreg = sreg
2988                                  * dreg needs precision after this insn
2989                                  * sreg needs precision before this insn
2990                                  */
2991                                 *reg_mask &= ~dreg;
2992                                 *reg_mask |= sreg;
2993                         } else {
2994                                 /* dreg = K
2995                                  * dreg needs precision after this insn.
2996                                  * Corresponding register is already marked
2997                                  * as precise=true in this verifier state.
2998                                  * No further markings in parent are necessary
2999                                  */
3000                                 *reg_mask &= ~dreg;
3001                         }
3002                 } else {
3003                         if (BPF_SRC(insn->code) == BPF_X) {
3004                                 /* dreg += sreg
3005                                  * both dreg and sreg need precision
3006                                  * before this insn
3007                                  */
3008                                 *reg_mask |= sreg;
3009                         } /* else dreg += K
3010                            * dreg still needs precision before this insn
3011                            */
3012                 }
3013         } else if (class == BPF_LDX) {
3014                 if (!(*reg_mask & dreg))
3015                         return 0;
3016                 *reg_mask &= ~dreg;
3017
3018                 /* scalars can only be spilled into stack w/o losing precision.
3019                  * Load from any other memory can be zero extended.
3020                  * The desire to keep that precision is already indicated
3021                  * by 'precise' mark in corresponding register of this state.
3022                  * No further tracking necessary.
3023                  */
3024                 if (insn->src_reg != BPF_REG_FP)
3025                         return 0;
3026
3027                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3028                  * that [fp - off] slot contains scalar that needs to be
3029                  * tracked with precision
3030                  */
3031                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3032                 if (spi >= 64) {
3033                         verbose(env, "BUG spi %d\n", spi);
3034                         WARN_ONCE(1, "verifier backtracking bug");
3035                         return -EFAULT;
3036                 }
3037                 *stack_mask |= 1ull << spi;
3038         } else if (class == BPF_STX || class == BPF_ST) {
3039                 if (*reg_mask & dreg)
3040                         /* stx & st shouldn't be using _scalar_ dst_reg
3041                          * to access memory. It means backtracking
3042                          * encountered a case of pointer subtraction.
3043                          */
3044                         return -ENOTSUPP;
3045                 /* scalars can only be spilled into stack */
3046                 if (insn->dst_reg != BPF_REG_FP)
3047                         return 0;
3048                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3049                 if (spi >= 64) {
3050                         verbose(env, "BUG spi %d\n", spi);
3051                         WARN_ONCE(1, "verifier backtracking bug");
3052                         return -EFAULT;
3053                 }
3054                 if (!(*stack_mask & (1ull << spi)))
3055                         return 0;
3056                 *stack_mask &= ~(1ull << spi);
3057                 if (class == BPF_STX)
3058                         *reg_mask |= sreg;
3059         } else if (class == BPF_JMP || class == BPF_JMP32) {
3060                 if (opcode == BPF_CALL) {
3061                         if (insn->src_reg == BPF_PSEUDO_CALL)
3062                                 return -ENOTSUPP;
3063                         /* BPF helpers that invoke callback subprogs are
3064                          * equivalent to BPF_PSEUDO_CALL above
3065                          */
3066                         if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3067                                 return -ENOTSUPP;
3068                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3069                          * catch this error later. Make backtracking conservative
3070                          * with ENOTSUPP.
3071                          */
3072                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3073                                 return -ENOTSUPP;
3074                         /* regular helper call sets R0 */
3075                         *reg_mask &= ~1;
3076                         if (*reg_mask & 0x3f) {
3077                                 /* if backtracing was looking for registers R1-R5
3078                                  * they should have been found already.
3079                                  */
3080                                 verbose(env, "BUG regs %x\n", *reg_mask);
3081                                 WARN_ONCE(1, "verifier backtracking bug");
3082                                 return -EFAULT;
3083                         }
3084                 } else if (opcode == BPF_EXIT) {
3085                         return -ENOTSUPP;
3086                 }
3087         } else if (class == BPF_LD) {
3088                 if (!(*reg_mask & dreg))
3089                         return 0;
3090                 *reg_mask &= ~dreg;
3091                 /* It's ld_imm64 or ld_abs or ld_ind.
3092                  * For ld_imm64 no further tracking of precision
3093                  * into parent is necessary
3094                  */
3095                 if (mode == BPF_IND || mode == BPF_ABS)
3096                         /* to be analyzed */
3097                         return -ENOTSUPP;
3098         }
3099         return 0;
3100 }
3101
3102 /* the scalar precision tracking algorithm:
3103  * . at the start all registers have precise=false.
3104  * . scalar ranges are tracked as normal through alu and jmp insns.
3105  * . once precise value of the scalar register is used in:
3106  *   .  ptr + scalar alu
3107  *   . if (scalar cond K|scalar)
3108  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3109  *   backtrack through the verifier states and mark all registers and
3110  *   stack slots with spilled constants that these scalar regisers
3111  *   should be precise.
3112  * . during state pruning two registers (or spilled stack slots)
3113  *   are equivalent if both are not precise.
3114  *
3115  * Note the verifier cannot simply walk register parentage chain,
3116  * since many different registers and stack slots could have been
3117  * used to compute single precise scalar.
3118  *
3119  * The approach of starting with precise=true for all registers and then
3120  * backtrack to mark a register as not precise when the verifier detects
3121  * that program doesn't care about specific value (e.g., when helper
3122  * takes register as ARG_ANYTHING parameter) is not safe.
3123  *
3124  * It's ok to walk single parentage chain of the verifier states.
3125  * It's possible that this backtracking will go all the way till 1st insn.
3126  * All other branches will be explored for needing precision later.
3127  *
3128  * The backtracking needs to deal with cases like:
3129  *   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)
3130  * r9 -= r8
3131  * r5 = r9
3132  * if r5 > 0x79f goto pc+7
3133  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3134  * r5 += 1
3135  * ...
3136  * call bpf_perf_event_output#25
3137  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3138  *
3139  * and this case:
3140  * r6 = 1
3141  * call foo // uses callee's r6 inside to compute r0
3142  * r0 += r6
3143  * if r0 == 0 goto
3144  *
3145  * to track above reg_mask/stack_mask needs to be independent for each frame.
3146  *
3147  * Also if parent's curframe > frame where backtracking started,
3148  * the verifier need to mark registers in both frames, otherwise callees
3149  * may incorrectly prune callers. This is similar to
3150  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3151  *
3152  * For now backtracking falls back into conservative marking.
3153  */
3154 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3155                                      struct bpf_verifier_state *st)
3156 {
3157         struct bpf_func_state *func;
3158         struct bpf_reg_state *reg;
3159         int i, j;
3160
3161         /* big hammer: mark all scalars precise in this path.
3162          * pop_stack may still get !precise scalars.
3163          * We also skip current state and go straight to first parent state,
3164          * because precision markings in current non-checkpointed state are
3165          * not needed. See why in the comment in __mark_chain_precision below.
3166          */
3167         for (st = st->parent; st; st = st->parent) {
3168                 for (i = 0; i <= st->curframe; i++) {
3169                         func = st->frame[i];
3170                         for (j = 0; j < BPF_REG_FP; j++) {
3171                                 reg = &func->regs[j];
3172                                 if (reg->type != SCALAR_VALUE)
3173                                         continue;
3174                                 reg->precise = true;
3175                         }
3176                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3177                                 if (!is_spilled_reg(&func->stack[j]))
3178                                         continue;
3179                                 reg = &func->stack[j].spilled_ptr;
3180                                 if (reg->type != SCALAR_VALUE)
3181                                         continue;
3182                                 reg->precise = true;
3183                         }
3184                 }
3185         }
3186 }
3187
3188 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3189 {
3190         struct bpf_func_state *func;
3191         struct bpf_reg_state *reg;
3192         int i, j;
3193
3194         for (i = 0; i <= st->curframe; i++) {
3195                 func = st->frame[i];
3196                 for (j = 0; j < BPF_REG_FP; j++) {
3197                         reg = &func->regs[j];
3198                         if (reg->type != SCALAR_VALUE)
3199                                 continue;
3200                         reg->precise = false;
3201                 }
3202                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3203                         if (!is_spilled_reg(&func->stack[j]))
3204                                 continue;
3205                         reg = &func->stack[j].spilled_ptr;
3206                         if (reg->type != SCALAR_VALUE)
3207                                 continue;
3208                         reg->precise = false;
3209                 }
3210         }
3211 }
3212
3213 /*
3214  * __mark_chain_precision() backtracks BPF program instruction sequence and
3215  * chain of verifier states making sure that register *regno* (if regno >= 0)
3216  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3217  * SCALARS, as well as any other registers and slots that contribute to
3218  * a tracked state of given registers/stack slots, depending on specific BPF
3219  * assembly instructions (see backtrack_insns() for exact instruction handling
3220  * logic). This backtracking relies on recorded jmp_history and is able to
3221  * traverse entire chain of parent states. This process ends only when all the
3222  * necessary registers/slots and their transitive dependencies are marked as
3223  * precise.
3224  *
3225  * One important and subtle aspect is that precise marks *do not matter* in
3226  * the currently verified state (current state). It is important to understand
3227  * why this is the case.
3228  *
3229  * First, note that current state is the state that is not yet "checkpointed",
3230  * i.e., it is not yet put into env->explored_states, and it has no children
3231  * states as well. It's ephemeral, and can end up either a) being discarded if
3232  * compatible explored state is found at some point or BPF_EXIT instruction is
3233  * reached or b) checkpointed and put into env->explored_states, branching out
3234  * into one or more children states.
3235  *
3236  * In the former case, precise markings in current state are completely
3237  * ignored by state comparison code (see regsafe() for details). Only
3238  * checkpointed ("old") state precise markings are important, and if old
3239  * state's register/slot is precise, regsafe() assumes current state's
3240  * register/slot as precise and checks value ranges exactly and precisely. If
3241  * states turn out to be compatible, current state's necessary precise
3242  * markings and any required parent states' precise markings are enforced
3243  * after the fact with propagate_precision() logic, after the fact. But it's
3244  * important to realize that in this case, even after marking current state
3245  * registers/slots as precise, we immediately discard current state. So what
3246  * actually matters is any of the precise markings propagated into current
3247  * state's parent states, which are always checkpointed (due to b) case above).
3248  * As such, for scenario a) it doesn't matter if current state has precise
3249  * markings set or not.
3250  *
3251  * Now, for the scenario b), checkpointing and forking into child(ren)
3252  * state(s). Note that before current state gets to checkpointing step, any
3253  * processed instruction always assumes precise SCALAR register/slot
3254  * knowledge: if precise value or range is useful to prune jump branch, BPF
3255  * verifier takes this opportunity enthusiastically. Similarly, when
3256  * register's value is used to calculate offset or memory address, exact
3257  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3258  * what we mentioned above about state comparison ignoring precise markings
3259  * during state comparison, BPF verifier ignores and also assumes precise
3260  * markings *at will* during instruction verification process. But as verifier
3261  * assumes precision, it also propagates any precision dependencies across
3262  * parent states, which are not yet finalized, so can be further restricted
3263  * based on new knowledge gained from restrictions enforced by their children
3264  * states. This is so that once those parent states are finalized, i.e., when
3265  * they have no more active children state, state comparison logic in
3266  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3267  * required for correctness.
3268  *
3269  * To build a bit more intuition, note also that once a state is checkpointed,
3270  * the path we took to get to that state is not important. This is crucial
3271  * property for state pruning. When state is checkpointed and finalized at
3272  * some instruction index, it can be correctly and safely used to "short
3273  * circuit" any *compatible* state that reaches exactly the same instruction
3274  * index. I.e., if we jumped to that instruction from a completely different
3275  * code path than original finalized state was derived from, it doesn't
3276  * matter, current state can be discarded because from that instruction
3277  * forward having a compatible state will ensure we will safely reach the
3278  * exit. States describe preconditions for further exploration, but completely
3279  * forget the history of how we got here.
3280  *
3281  * This also means that even if we needed precise SCALAR range to get to
3282  * finalized state, but from that point forward *that same* SCALAR register is
3283  * never used in a precise context (i.e., it's precise value is not needed for
3284  * correctness), it's correct and safe to mark such register as "imprecise"
3285  * (i.e., precise marking set to false). This is what we rely on when we do
3286  * not set precise marking in current state. If no child state requires
3287  * precision for any given SCALAR register, it's safe to dictate that it can
3288  * be imprecise. If any child state does require this register to be precise,
3289  * we'll mark it precise later retroactively during precise markings
3290  * propagation from child state to parent states.
3291  *
3292  * Skipping precise marking setting in current state is a mild version of
3293  * relying on the above observation. But we can utilize this property even
3294  * more aggressively by proactively forgetting any precise marking in the
3295  * current state (which we inherited from the parent state), right before we
3296  * checkpoint it and branch off into new child state. This is done by
3297  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3298  * finalized states which help in short circuiting more future states.
3299  */
3300 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3301                                   int spi)
3302 {
3303         struct bpf_verifier_state *st = env->cur_state;
3304         int first_idx = st->first_insn_idx;
3305         int last_idx = env->insn_idx;
3306         struct bpf_func_state *func;
3307         struct bpf_reg_state *reg;
3308         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3309         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3310         bool skip_first = true;
3311         bool new_marks = false;
3312         int i, err;
3313
3314         if (!env->bpf_capable)
3315                 return 0;
3316
3317         /* Do sanity checks against current state of register and/or stack
3318          * slot, but don't set precise flag in current state, as precision
3319          * tracking in the current state is unnecessary.
3320          */
3321         func = st->frame[frame];
3322         if (regno >= 0) {
3323                 reg = &func->regs[regno];
3324                 if (reg->type != SCALAR_VALUE) {
3325                         WARN_ONCE(1, "backtracing misuse");
3326                         return -EFAULT;
3327                 }
3328                 new_marks = true;
3329         }
3330
3331         while (spi >= 0) {
3332                 if (!is_spilled_reg(&func->stack[spi])) {
3333                         stack_mask = 0;
3334                         break;
3335                 }
3336                 reg = &func->stack[spi].spilled_ptr;
3337                 if (reg->type != SCALAR_VALUE) {
3338                         stack_mask = 0;
3339                         break;
3340                 }
3341                 new_marks = true;
3342                 break;
3343         }
3344
3345         if (!new_marks)
3346                 return 0;
3347         if (!reg_mask && !stack_mask)
3348                 return 0;
3349
3350         for (;;) {
3351                 DECLARE_BITMAP(mask, 64);
3352                 u32 history = st->jmp_history_cnt;
3353
3354                 if (env->log.level & BPF_LOG_LEVEL2)
3355                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3356
3357                 if (last_idx < 0) {
3358                         /* we are at the entry into subprog, which
3359                          * is expected for global funcs, but only if
3360                          * requested precise registers are R1-R5
3361                          * (which are global func's input arguments)
3362                          */
3363                         if (st->curframe == 0 &&
3364                             st->frame[0]->subprogno > 0 &&
3365                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
3366                             stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3367                                 bitmap_from_u64(mask, reg_mask);
3368                                 for_each_set_bit(i, mask, 32) {
3369                                         reg = &st->frame[0]->regs[i];
3370                                         if (reg->type != SCALAR_VALUE) {
3371                                                 reg_mask &= ~(1u << i);
3372                                                 continue;
3373                                         }
3374                                         reg->precise = true;
3375                                 }
3376                                 return 0;
3377                         }
3378
3379                         verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3380                                 st->frame[0]->subprogno, reg_mask, stack_mask);
3381                         WARN_ONCE(1, "verifier backtracking bug");
3382                         return -EFAULT;
3383                 }
3384
3385                 for (i = last_idx;;) {
3386                         if (skip_first) {
3387                                 err = 0;
3388                                 skip_first = false;
3389                         } else {
3390                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3391                         }
3392                         if (err == -ENOTSUPP) {
3393                                 mark_all_scalars_precise(env, st);
3394                                 return 0;
3395                         } else if (err) {
3396                                 return err;
3397                         }
3398                         if (!reg_mask && !stack_mask)
3399                                 /* Found assignment(s) into tracked register in this state.
3400                                  * Since this state is already marked, just return.
3401                                  * Nothing to be tracked further in the parent state.
3402                                  */
3403                                 return 0;
3404                         if (i == first_idx)
3405                                 break;
3406                         i = get_prev_insn_idx(st, i, &history);
3407                         if (i >= env->prog->len) {
3408                                 /* This can happen if backtracking reached insn 0
3409                                  * and there are still reg_mask or stack_mask
3410                                  * to backtrack.
3411                                  * It means the backtracking missed the spot where
3412                                  * particular register was initialized with a constant.
3413                                  */
3414                                 verbose(env, "BUG backtracking idx %d\n", i);
3415                                 WARN_ONCE(1, "verifier backtracking bug");
3416                                 return -EFAULT;
3417                         }
3418                 }
3419                 st = st->parent;
3420                 if (!st)
3421                         break;
3422
3423                 new_marks = false;
3424                 func = st->frame[frame];
3425                 bitmap_from_u64(mask, reg_mask);
3426                 for_each_set_bit(i, mask, 32) {
3427                         reg = &func->regs[i];
3428                         if (reg->type != SCALAR_VALUE) {
3429                                 reg_mask &= ~(1u << i);
3430                                 continue;
3431                         }
3432                         if (!reg->precise)
3433                                 new_marks = true;
3434                         reg->precise = true;
3435                 }
3436
3437                 bitmap_from_u64(mask, stack_mask);
3438                 for_each_set_bit(i, mask, 64) {
3439                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
3440                                 /* the sequence of instructions:
3441                                  * 2: (bf) r3 = r10
3442                                  * 3: (7b) *(u64 *)(r3 -8) = r0
3443                                  * 4: (79) r4 = *(u64 *)(r10 -8)
3444                                  * doesn't contain jmps. It's backtracked
3445                                  * as a single block.
3446                                  * During backtracking insn 3 is not recognized as
3447                                  * stack access, so at the end of backtracking
3448                                  * stack slot fp-8 is still marked in stack_mask.
3449                                  * However the parent state may not have accessed
3450                                  * fp-8 and it's "unallocated" stack space.
3451                                  * In such case fallback to conservative.
3452                                  */
3453                                 mark_all_scalars_precise(env, st);
3454                                 return 0;
3455                         }
3456
3457                         if (!is_spilled_reg(&func->stack[i])) {
3458                                 stack_mask &= ~(1ull << i);
3459                                 continue;
3460                         }
3461                         reg = &func->stack[i].spilled_ptr;
3462                         if (reg->type != SCALAR_VALUE) {
3463                                 stack_mask &= ~(1ull << i);
3464                                 continue;
3465                         }
3466                         if (!reg->precise)
3467                                 new_marks = true;
3468                         reg->precise = true;
3469                 }
3470                 if (env->log.level & BPF_LOG_LEVEL2) {
3471                         verbose(env, "parent %s regs=%x stack=%llx marks:",
3472                                 new_marks ? "didn't have" : "already had",
3473                                 reg_mask, stack_mask);
3474                         print_verifier_state(env, func, true);
3475                 }
3476
3477                 if (!reg_mask && !stack_mask)
3478                         break;
3479                 if (!new_marks)
3480                         break;
3481
3482                 last_idx = st->last_insn_idx;
3483                 first_idx = st->first_insn_idx;
3484         }
3485         return 0;
3486 }
3487
3488 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3489 {
3490         return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3491 }
3492
3493 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3494 {
3495         return __mark_chain_precision(env, frame, regno, -1);
3496 }
3497
3498 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3499 {
3500         return __mark_chain_precision(env, frame, -1, spi);
3501 }
3502
3503 static bool is_spillable_regtype(enum bpf_reg_type type)
3504 {
3505         switch (base_type(type)) {
3506         case PTR_TO_MAP_VALUE:
3507         case PTR_TO_STACK:
3508         case PTR_TO_CTX:
3509         case PTR_TO_PACKET:
3510         case PTR_TO_PACKET_META:
3511         case PTR_TO_PACKET_END:
3512         case PTR_TO_FLOW_KEYS:
3513         case CONST_PTR_TO_MAP:
3514         case PTR_TO_SOCKET:
3515         case PTR_TO_SOCK_COMMON:
3516         case PTR_TO_TCP_SOCK:
3517         case PTR_TO_XDP_SOCK:
3518         case PTR_TO_BTF_ID:
3519         case PTR_TO_BUF:
3520         case PTR_TO_MEM:
3521         case PTR_TO_FUNC:
3522         case PTR_TO_MAP_KEY:
3523                 return true;
3524         default:
3525                 return false;
3526         }
3527 }
3528
3529 /* Does this register contain a constant zero? */
3530 static bool register_is_null(struct bpf_reg_state *reg)
3531 {
3532         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3533 }
3534
3535 static bool register_is_const(struct bpf_reg_state *reg)
3536 {
3537         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3538 }
3539
3540 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3541 {
3542         return tnum_is_unknown(reg->var_off) &&
3543                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3544                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3545                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3546                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3547 }
3548
3549 static bool register_is_bounded(struct bpf_reg_state *reg)
3550 {
3551         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3552 }
3553
3554 static bool __is_pointer_value(bool allow_ptr_leaks,
3555                                const struct bpf_reg_state *reg)
3556 {
3557         if (allow_ptr_leaks)
3558                 return false;
3559
3560         return reg->type != SCALAR_VALUE;
3561 }
3562
3563 /* Copy src state preserving dst->parent and dst->live fields */
3564 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3565 {
3566         struct bpf_reg_state *parent = dst->parent;
3567         enum bpf_reg_liveness live = dst->live;
3568
3569         *dst = *src;
3570         dst->parent = parent;
3571         dst->live = live;
3572 }
3573
3574 static void save_register_state(struct bpf_func_state *state,
3575                                 int spi, struct bpf_reg_state *reg,
3576                                 int size)
3577 {
3578         int i;
3579
3580         copy_register_state(&state->stack[spi].spilled_ptr, reg);
3581         if (size == BPF_REG_SIZE)
3582                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3583
3584         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3585                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3586
3587         /* size < 8 bytes spill */
3588         for (; i; i--)
3589                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3590 }
3591
3592 static bool is_bpf_st_mem(struct bpf_insn *insn)
3593 {
3594         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3595 }
3596
3597 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3598  * stack boundary and alignment are checked in check_mem_access()
3599  */
3600 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3601                                        /* stack frame we're writing to */
3602                                        struct bpf_func_state *state,
3603                                        int off, int size, int value_regno,
3604                                        int insn_idx)
3605 {
3606         struct bpf_func_state *cur; /* state of the current function */
3607         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3608         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3609         struct bpf_reg_state *reg = NULL;
3610         u32 dst_reg = insn->dst_reg;
3611
3612         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3613         if (err)
3614                 return err;
3615         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3616          * so it's aligned access and [off, off + size) are within stack limits
3617          */
3618         if (!env->allow_ptr_leaks &&
3619             state->stack[spi].slot_type[0] == STACK_SPILL &&
3620             size != BPF_REG_SIZE) {
3621                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3622                 return -EACCES;
3623         }
3624
3625         cur = env->cur_state->frame[env->cur_state->curframe];
3626         if (value_regno >= 0)
3627                 reg = &cur->regs[value_regno];
3628         if (!env->bypass_spec_v4) {
3629                 bool sanitize = reg && is_spillable_regtype(reg->type);
3630
3631                 for (i = 0; i < size; i++) {
3632                         u8 type = state->stack[spi].slot_type[i];
3633
3634                         if (type != STACK_MISC && type != STACK_ZERO) {
3635                                 sanitize = true;
3636                                 break;
3637                         }
3638                 }
3639
3640                 if (sanitize)
3641                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3642         }
3643
3644         err = destroy_if_dynptr_stack_slot(env, state, spi);
3645         if (err)
3646                 return err;
3647
3648         mark_stack_slot_scratched(env, spi);
3649         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3650             !register_is_null(reg) && env->bpf_capable) {
3651                 if (dst_reg != BPF_REG_FP) {
3652                         /* The backtracking logic can only recognize explicit
3653                          * stack slot address like [fp - 8]. Other spill of
3654                          * scalar via different register has to be conservative.
3655                          * Backtrack from here and mark all registers as precise
3656                          * that contributed into 'reg' being a constant.
3657                          */
3658                         err = mark_chain_precision(env, value_regno);
3659                         if (err)
3660                                 return err;
3661                 }
3662                 save_register_state(state, spi, reg, size);
3663         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3664                    insn->imm != 0 && env->bpf_capable) {
3665                 struct bpf_reg_state fake_reg = {};
3666
3667                 __mark_reg_known(&fake_reg, (u32)insn->imm);
3668                 fake_reg.type = SCALAR_VALUE;
3669                 save_register_state(state, spi, &fake_reg, size);
3670         } else if (reg && is_spillable_regtype(reg->type)) {
3671                 /* register containing pointer is being spilled into stack */
3672                 if (size != BPF_REG_SIZE) {
3673                         verbose_linfo(env, insn_idx, "; ");
3674                         verbose(env, "invalid size of register spill\n");
3675                         return -EACCES;
3676                 }
3677                 if (state != cur && reg->type == PTR_TO_STACK) {
3678                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3679                         return -EINVAL;
3680                 }
3681                 save_register_state(state, spi, reg, size);
3682         } else {
3683                 u8 type = STACK_MISC;
3684
3685                 /* regular write of data into stack destroys any spilled ptr */
3686                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3687                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3688                 if (is_spilled_reg(&state->stack[spi]))
3689                         for (i = 0; i < BPF_REG_SIZE; i++)
3690                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3691
3692                 /* only mark the slot as written if all 8 bytes were written
3693                  * otherwise read propagation may incorrectly stop too soon
3694                  * when stack slots are partially written.
3695                  * This heuristic means that read propagation will be
3696                  * conservative, since it will add reg_live_read marks
3697                  * to stack slots all the way to first state when programs
3698                  * writes+reads less than 8 bytes
3699                  */
3700                 if (size == BPF_REG_SIZE)
3701                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3702
3703                 /* when we zero initialize stack slots mark them as such */
3704                 if ((reg && register_is_null(reg)) ||
3705                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3706                         /* backtracking doesn't work for STACK_ZERO yet. */
3707                         err = mark_chain_precision(env, value_regno);
3708                         if (err)
3709                                 return err;
3710                         type = STACK_ZERO;
3711                 }
3712
3713                 /* Mark slots affected by this stack write. */
3714                 for (i = 0; i < size; i++)
3715                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3716                                 type;
3717         }
3718         return 0;
3719 }
3720
3721 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3722  * known to contain a variable offset.
3723  * This function checks whether the write is permitted and conservatively
3724  * tracks the effects of the write, considering that each stack slot in the
3725  * dynamic range is potentially written to.
3726  *
3727  * 'off' includes 'regno->off'.
3728  * 'value_regno' can be -1, meaning that an unknown value is being written to
3729  * the stack.
3730  *
3731  * Spilled pointers in range are not marked as written because we don't know
3732  * what's going to be actually written. This means that read propagation for
3733  * future reads cannot be terminated by this write.
3734  *
3735  * For privileged programs, uninitialized stack slots are considered
3736  * initialized by this write (even though we don't know exactly what offsets
3737  * are going to be written to). The idea is that we don't want the verifier to
3738  * reject future reads that access slots written to through variable offsets.
3739  */
3740 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3741                                      /* func where register points to */
3742                                      struct bpf_func_state *state,
3743                                      int ptr_regno, int off, int size,
3744                                      int value_regno, int insn_idx)
3745 {
3746         struct bpf_func_state *cur; /* state of the current function */
3747         int min_off, max_off;
3748         int i, err;
3749         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3750         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3751         bool writing_zero = false;
3752         /* set if the fact that we're writing a zero is used to let any
3753          * stack slots remain STACK_ZERO
3754          */
3755         bool zero_used = false;
3756
3757         cur = env->cur_state->frame[env->cur_state->curframe];
3758         ptr_reg = &cur->regs[ptr_regno];
3759         min_off = ptr_reg->smin_value + off;
3760         max_off = ptr_reg->smax_value + off + size;
3761         if (value_regno >= 0)
3762                 value_reg = &cur->regs[value_regno];
3763         if ((value_reg && register_is_null(value_reg)) ||
3764             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3765                 writing_zero = true;
3766
3767         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3768         if (err)
3769                 return err;
3770
3771         for (i = min_off; i < max_off; i++) {
3772                 int spi;
3773
3774                 spi = __get_spi(i);
3775                 err = destroy_if_dynptr_stack_slot(env, state, spi);
3776                 if (err)
3777                         return err;
3778         }
3779
3780         /* Variable offset writes destroy any spilled pointers in range. */
3781         for (i = min_off; i < max_off; i++) {
3782                 u8 new_type, *stype;
3783                 int slot, spi;
3784
3785                 slot = -i - 1;
3786                 spi = slot / BPF_REG_SIZE;
3787                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3788                 mark_stack_slot_scratched(env, spi);
3789
3790                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3791                         /* Reject the write if range we may write to has not
3792                          * been initialized beforehand. If we didn't reject
3793                          * here, the ptr status would be erased below (even
3794                          * though not all slots are actually overwritten),
3795                          * possibly opening the door to leaks.
3796                          *
3797                          * We do however catch STACK_INVALID case below, and
3798                          * only allow reading possibly uninitialized memory
3799                          * later for CAP_PERFMON, as the write may not happen to
3800                          * that slot.
3801                          */
3802                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3803                                 insn_idx, i);
3804                         return -EINVAL;
3805                 }
3806
3807                 /* Erase all spilled pointers. */
3808                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3809
3810                 /* Update the slot type. */
3811                 new_type = STACK_MISC;
3812                 if (writing_zero && *stype == STACK_ZERO) {
3813                         new_type = STACK_ZERO;
3814                         zero_used = true;
3815                 }
3816                 /* If the slot is STACK_INVALID, we check whether it's OK to
3817                  * pretend that it will be initialized by this write. The slot
3818                  * might not actually be written to, and so if we mark it as
3819                  * initialized future reads might leak uninitialized memory.
3820                  * For privileged programs, we will accept such reads to slots
3821                  * that may or may not be written because, if we're reject
3822                  * them, the error would be too confusing.
3823                  */
3824                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3825                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3826                                         insn_idx, i);
3827                         return -EINVAL;
3828                 }
3829                 *stype = new_type;
3830         }
3831         if (zero_used) {
3832                 /* backtracking doesn't work for STACK_ZERO yet. */
3833                 err = mark_chain_precision(env, value_regno);
3834                 if (err)
3835                         return err;
3836         }
3837         return 0;
3838 }
3839
3840 /* When register 'dst_regno' is assigned some values from stack[min_off,
3841  * max_off), we set the register's type according to the types of the
3842  * respective stack slots. If all the stack values are known to be zeros, then
3843  * so is the destination reg. Otherwise, the register is considered to be
3844  * SCALAR. This function does not deal with register filling; the caller must
3845  * ensure that all spilled registers in the stack range have been marked as
3846  * read.
3847  */
3848 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3849                                 /* func where src register points to */
3850                                 struct bpf_func_state *ptr_state,
3851                                 int min_off, int max_off, int dst_regno)
3852 {
3853         struct bpf_verifier_state *vstate = env->cur_state;
3854         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3855         int i, slot, spi;
3856         u8 *stype;
3857         int zeros = 0;
3858
3859         for (i = min_off; i < max_off; i++) {
3860                 slot = -i - 1;
3861                 spi = slot / BPF_REG_SIZE;
3862                 stype = ptr_state->stack[spi].slot_type;
3863                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3864                         break;
3865                 zeros++;
3866         }
3867         if (zeros == max_off - min_off) {
3868                 /* any access_size read into register is zero extended,
3869                  * so the whole register == const_zero
3870                  */
3871                 __mark_reg_const_zero(&state->regs[dst_regno]);
3872                 /* backtracking doesn't support STACK_ZERO yet,
3873                  * so mark it precise here, so that later
3874                  * backtracking can stop here.
3875                  * Backtracking may not need this if this register
3876                  * doesn't participate in pointer adjustment.
3877                  * Forward propagation of precise flag is not
3878                  * necessary either. This mark is only to stop
3879                  * backtracking. Any register that contributed
3880                  * to const 0 was marked precise before spill.
3881                  */
3882                 state->regs[dst_regno].precise = true;
3883         } else {
3884                 /* have read misc data from the stack */
3885                 mark_reg_unknown(env, state->regs, dst_regno);
3886         }
3887         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3888 }
3889
3890 /* Read the stack at 'off' and put the results into the register indicated by
3891  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3892  * spilled reg.
3893  *
3894  * 'dst_regno' can be -1, meaning that the read value is not going to a
3895  * register.
3896  *
3897  * The access is assumed to be within the current stack bounds.
3898  */
3899 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3900                                       /* func where src register points to */
3901                                       struct bpf_func_state *reg_state,
3902                                       int off, int size, int dst_regno)
3903 {
3904         struct bpf_verifier_state *vstate = env->cur_state;
3905         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3906         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3907         struct bpf_reg_state *reg;
3908         u8 *stype, type;
3909
3910         stype = reg_state->stack[spi].slot_type;
3911         reg = &reg_state->stack[spi].spilled_ptr;
3912
3913         if (is_spilled_reg(&reg_state->stack[spi])) {
3914                 u8 spill_size = 1;
3915
3916                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3917                         spill_size++;
3918
3919                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3920                         if (reg->type != SCALAR_VALUE) {
3921                                 verbose_linfo(env, env->insn_idx, "; ");
3922                                 verbose(env, "invalid size of register fill\n");
3923                                 return -EACCES;
3924                         }
3925
3926                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3927                         if (dst_regno < 0)
3928                                 return 0;
3929
3930                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3931                                 /* The earlier check_reg_arg() has decided the
3932                                  * subreg_def for this insn.  Save it first.
3933                                  */
3934                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3935
3936                                 copy_register_state(&state->regs[dst_regno], reg);
3937                                 state->regs[dst_regno].subreg_def = subreg_def;
3938                         } else {
3939                                 for (i = 0; i < size; i++) {
3940                                         type = stype[(slot - i) % BPF_REG_SIZE];
3941                                         if (type == STACK_SPILL)
3942                                                 continue;
3943                                         if (type == STACK_MISC)
3944                                                 continue;
3945                                         if (type == STACK_INVALID && env->allow_uninit_stack)
3946                                                 continue;
3947                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3948                                                 off, i, size);
3949                                         return -EACCES;
3950                                 }
3951                                 mark_reg_unknown(env, state->regs, dst_regno);
3952                         }
3953                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3954                         return 0;
3955                 }
3956
3957                 if (dst_regno >= 0) {
3958                         /* restore register state from stack */
3959                         copy_register_state(&state->regs[dst_regno], reg);
3960                         /* mark reg as written since spilled pointer state likely
3961                          * has its liveness marks cleared by is_state_visited()
3962                          * which resets stack/reg liveness for state transitions
3963                          */
3964                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3965                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3966                         /* If dst_regno==-1, the caller is asking us whether
3967                          * it is acceptable to use this value as a SCALAR_VALUE
3968                          * (e.g. for XADD).
3969                          * We must not allow unprivileged callers to do that
3970                          * with spilled pointers.
3971                          */
3972                         verbose(env, "leaking pointer from stack off %d\n",
3973                                 off);
3974                         return -EACCES;
3975                 }
3976                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3977         } else {
3978                 for (i = 0; i < size; i++) {
3979                         type = stype[(slot - i) % BPF_REG_SIZE];
3980                         if (type == STACK_MISC)
3981                                 continue;
3982                         if (type == STACK_ZERO)
3983                                 continue;
3984                         if (type == STACK_INVALID && env->allow_uninit_stack)
3985                                 continue;
3986                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3987                                 off, i, size);
3988                         return -EACCES;
3989                 }
3990                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3991                 if (dst_regno >= 0)
3992                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3993         }
3994         return 0;
3995 }
3996
3997 enum bpf_access_src {
3998         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3999         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4000 };
4001
4002 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4003                                          int regno, int off, int access_size,
4004                                          bool zero_size_allowed,
4005                                          enum bpf_access_src type,
4006                                          struct bpf_call_arg_meta *meta);
4007
4008 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4009 {
4010         return cur_regs(env) + regno;
4011 }
4012
4013 /* Read the stack at 'ptr_regno + off' and put the result into the register
4014  * 'dst_regno'.
4015  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4016  * but not its variable offset.
4017  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4018  *
4019  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4020  * filling registers (i.e. reads of spilled register cannot be detected when
4021  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4022  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4023  * offset; for a fixed offset check_stack_read_fixed_off should be used
4024  * instead.
4025  */
4026 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4027                                     int ptr_regno, int off, int size, int dst_regno)
4028 {
4029         /* The state of the source register. */
4030         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4031         struct bpf_func_state *ptr_state = func(env, reg);
4032         int err;
4033         int min_off, max_off;
4034
4035         /* Note that we pass a NULL meta, so raw access will not be permitted.
4036          */
4037         err = check_stack_range_initialized(env, ptr_regno, off, size,
4038                                             false, ACCESS_DIRECT, NULL);
4039         if (err)
4040                 return err;
4041
4042         min_off = reg->smin_value + off;
4043         max_off = reg->smax_value + off;
4044         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4045         return 0;
4046 }
4047
4048 /* check_stack_read dispatches to check_stack_read_fixed_off or
4049  * check_stack_read_var_off.
4050  *
4051  * The caller must ensure that the offset falls within the allocated stack
4052  * bounds.
4053  *
4054  * 'dst_regno' is a register which will receive the value from the stack. It
4055  * can be -1, meaning that the read value is not going to a register.
4056  */
4057 static int check_stack_read(struct bpf_verifier_env *env,
4058                             int ptr_regno, int off, int size,
4059                             int dst_regno)
4060 {
4061         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4062         struct bpf_func_state *state = func(env, reg);
4063         int err;
4064         /* Some accesses are only permitted with a static offset. */
4065         bool var_off = !tnum_is_const(reg->var_off);
4066
4067         /* The offset is required to be static when reads don't go to a
4068          * register, in order to not leak pointers (see
4069          * check_stack_read_fixed_off).
4070          */
4071         if (dst_regno < 0 && var_off) {
4072                 char tn_buf[48];
4073
4074                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4075                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4076                         tn_buf, off, size);
4077                 return -EACCES;
4078         }
4079         /* Variable offset is prohibited for unprivileged mode for simplicity
4080          * since it requires corresponding support in Spectre masking for stack
4081          * ALU. See also retrieve_ptr_limit().
4082          */
4083         if (!env->bypass_spec_v1 && var_off) {
4084                 char tn_buf[48];
4085
4086                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4087                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
4088                                 ptr_regno, tn_buf);
4089                 return -EACCES;
4090         }
4091
4092         if (!var_off) {
4093                 off += reg->var_off.value;
4094                 err = check_stack_read_fixed_off(env, state, off, size,
4095                                                  dst_regno);
4096         } else {
4097                 /* Variable offset stack reads need more conservative handling
4098                  * than fixed offset ones. Note that dst_regno >= 0 on this
4099                  * branch.
4100                  */
4101                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4102                                                dst_regno);
4103         }
4104         return err;
4105 }
4106
4107
4108 /* check_stack_write dispatches to check_stack_write_fixed_off or
4109  * check_stack_write_var_off.
4110  *
4111  * 'ptr_regno' is the register used as a pointer into the stack.
4112  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4113  * 'value_regno' is the register whose value we're writing to the stack. It can
4114  * be -1, meaning that we're not writing from a register.
4115  *
4116  * The caller must ensure that the offset falls within the maximum stack size.
4117  */
4118 static int check_stack_write(struct bpf_verifier_env *env,
4119                              int ptr_regno, int off, int size,
4120                              int value_regno, int insn_idx)
4121 {
4122         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4123         struct bpf_func_state *state = func(env, reg);
4124         int err;
4125
4126         if (tnum_is_const(reg->var_off)) {
4127                 off += reg->var_off.value;
4128                 err = check_stack_write_fixed_off(env, state, off, size,
4129                                                   value_regno, insn_idx);
4130         } else {
4131                 /* Variable offset stack reads need more conservative handling
4132                  * than fixed offset ones.
4133                  */
4134                 err = check_stack_write_var_off(env, state,
4135                                                 ptr_regno, off, size,
4136                                                 value_regno, insn_idx);
4137         }
4138         return err;
4139 }
4140
4141 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4142                                  int off, int size, enum bpf_access_type type)
4143 {
4144         struct bpf_reg_state *regs = cur_regs(env);
4145         struct bpf_map *map = regs[regno].map_ptr;
4146         u32 cap = bpf_map_flags_to_cap(map);
4147
4148         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4149                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4150                         map->value_size, off, size);
4151                 return -EACCES;
4152         }
4153
4154         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4155                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4156                         map->value_size, off, size);
4157                 return -EACCES;
4158         }
4159
4160         return 0;
4161 }
4162
4163 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4164 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4165                               int off, int size, u32 mem_size,
4166                               bool zero_size_allowed)
4167 {
4168         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4169         struct bpf_reg_state *reg;
4170
4171         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4172                 return 0;
4173
4174         reg = &cur_regs(env)[regno];
4175         switch (reg->type) {
4176         case PTR_TO_MAP_KEY:
4177                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4178                         mem_size, off, size);
4179                 break;
4180         case PTR_TO_MAP_VALUE:
4181                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4182                         mem_size, off, size);
4183                 break;
4184         case PTR_TO_PACKET:
4185         case PTR_TO_PACKET_META:
4186         case PTR_TO_PACKET_END:
4187                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4188                         off, size, regno, reg->id, off, mem_size);
4189                 break;
4190         case PTR_TO_MEM:
4191         default:
4192                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4193                         mem_size, off, size);
4194         }
4195
4196         return -EACCES;
4197 }
4198
4199 /* check read/write into a memory region with possible variable offset */
4200 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4201                                    int off, int size, u32 mem_size,
4202                                    bool zero_size_allowed)
4203 {
4204         struct bpf_verifier_state *vstate = env->cur_state;
4205         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4206         struct bpf_reg_state *reg = &state->regs[regno];
4207         int err;
4208
4209         /* We may have adjusted the register pointing to memory region, so we
4210          * need to try adding each of min_value and max_value to off
4211          * to make sure our theoretical access will be safe.
4212          *
4213          * The minimum value is only important with signed
4214          * comparisons where we can't assume the floor of a
4215          * value is 0.  If we are using signed variables for our
4216          * index'es we need to make sure that whatever we use
4217          * will have a set floor within our range.
4218          */
4219         if (reg->smin_value < 0 &&
4220             (reg->smin_value == S64_MIN ||
4221              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4222               reg->smin_value + off < 0)) {
4223                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4224                         regno);
4225                 return -EACCES;
4226         }
4227         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4228                                  mem_size, zero_size_allowed);
4229         if (err) {
4230                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4231                         regno);
4232                 return err;
4233         }
4234
4235         /* If we haven't set a max value then we need to bail since we can't be
4236          * sure we won't do bad things.
4237          * If reg->umax_value + off could overflow, treat that as unbounded too.
4238          */
4239         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4240                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4241                         regno);
4242                 return -EACCES;
4243         }
4244         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4245                                  mem_size, zero_size_allowed);
4246         if (err) {
4247                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4248                         regno);
4249                 return err;
4250         }
4251
4252         return 0;
4253 }
4254
4255 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4256                                const struct bpf_reg_state *reg, int regno,
4257                                bool fixed_off_ok)
4258 {
4259         /* Access to this pointer-typed register or passing it to a helper
4260          * is only allowed in its original, unmodified form.
4261          */
4262
4263         if (reg->off < 0) {
4264                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4265                         reg_type_str(env, reg->type), regno, reg->off);
4266                 return -EACCES;
4267         }
4268
4269         if (!fixed_off_ok && reg->off) {
4270                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4271                         reg_type_str(env, reg->type), regno, reg->off);
4272                 return -EACCES;
4273         }
4274
4275         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4276                 char tn_buf[48];
4277
4278                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4279                 verbose(env, "variable %s access var_off=%s disallowed\n",
4280                         reg_type_str(env, reg->type), tn_buf);
4281                 return -EACCES;
4282         }
4283
4284         return 0;
4285 }
4286
4287 int check_ptr_off_reg(struct bpf_verifier_env *env,
4288                       const struct bpf_reg_state *reg, int regno)
4289 {
4290         return __check_ptr_off_reg(env, reg, regno, false);
4291 }
4292
4293 static int map_kptr_match_type(struct bpf_verifier_env *env,
4294                                struct btf_field *kptr_field,
4295                                struct bpf_reg_state *reg, u32 regno)
4296 {
4297         const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4298         int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4299         const char *reg_name = "";
4300
4301         /* Only unreferenced case accepts untrusted pointers */
4302         if (kptr_field->type == BPF_KPTR_UNREF)
4303                 perm_flags |= PTR_UNTRUSTED;
4304
4305         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4306                 goto bad_type;
4307
4308         if (!btf_is_kernel(reg->btf)) {
4309                 verbose(env, "R%d must point to kernel BTF\n", regno);
4310                 return -EINVAL;
4311         }
4312         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
4313         reg_name = kernel_type_name(reg->btf, reg->btf_id);
4314
4315         /* For ref_ptr case, release function check should ensure we get one
4316          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4317          * normal store of unreferenced kptr, we must ensure var_off is zero.
4318          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4319          * reg->off and reg->ref_obj_id are not needed here.
4320          */
4321         if (__check_ptr_off_reg(env, reg, regno, true))
4322                 return -EACCES;
4323
4324         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
4325          * we also need to take into account the reg->off.
4326          *
4327          * We want to support cases like:
4328          *
4329          * struct foo {
4330          *         struct bar br;
4331          *         struct baz bz;
4332          * };
4333          *
4334          * struct foo *v;
4335          * v = func();        // PTR_TO_BTF_ID
4336          * val->foo = v;      // reg->off is zero, btf and btf_id match type
4337          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4338          *                    // first member type of struct after comparison fails
4339          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4340          *                    // to match type
4341          *
4342          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4343          * is zero. We must also ensure that btf_struct_ids_match does not walk
4344          * the struct to match type against first member of struct, i.e. reject
4345          * second case from above. Hence, when type is BPF_KPTR_REF, we set
4346          * strict mode to true for type match.
4347          */
4348         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4349                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4350                                   kptr_field->type == BPF_KPTR_REF))
4351                 goto bad_type;
4352         return 0;
4353 bad_type:
4354         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4355                 reg_type_str(env, reg->type), reg_name);
4356         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4357         if (kptr_field->type == BPF_KPTR_UNREF)
4358                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4359                         targ_name);
4360         else
4361                 verbose(env, "\n");
4362         return -EINVAL;
4363 }
4364
4365 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4366  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4367  */
4368 static bool in_rcu_cs(struct bpf_verifier_env *env)
4369 {
4370         return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4371 }
4372
4373 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4374 BTF_SET_START(rcu_protected_types)
4375 BTF_ID(struct, prog_test_ref_kfunc)
4376 BTF_ID(struct, cgroup)
4377 BTF_SET_END(rcu_protected_types)
4378
4379 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4380 {
4381         if (!btf_is_kernel(btf))
4382                 return false;
4383         return btf_id_set_contains(&rcu_protected_types, btf_id);
4384 }
4385
4386 static bool rcu_safe_kptr(const struct btf_field *field)
4387 {
4388         const struct btf_field_kptr *kptr = &field->kptr;
4389
4390         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4391 }
4392
4393 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4394                                  int value_regno, int insn_idx,
4395                                  struct btf_field *kptr_field)
4396 {
4397         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4398         int class = BPF_CLASS(insn->code);
4399         struct bpf_reg_state *val_reg;
4400
4401         /* Things we already checked for in check_map_access and caller:
4402          *  - Reject cases where variable offset may touch kptr
4403          *  - size of access (must be BPF_DW)
4404          *  - tnum_is_const(reg->var_off)
4405          *  - kptr_field->offset == off + reg->var_off.value
4406          */
4407         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4408         if (BPF_MODE(insn->code) != BPF_MEM) {
4409                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4410                 return -EACCES;
4411         }
4412
4413         /* We only allow loading referenced kptr, since it will be marked as
4414          * untrusted, similar to unreferenced kptr.
4415          */
4416         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4417                 verbose(env, "store to referenced kptr disallowed\n");
4418                 return -EACCES;
4419         }
4420
4421         if (class == BPF_LDX) {
4422                 val_reg = reg_state(env, value_regno);
4423                 /* We can simply mark the value_regno receiving the pointer
4424                  * value from map as PTR_TO_BTF_ID, with the correct type.
4425                  */
4426                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4427                                 kptr_field->kptr.btf_id,
4428                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4429                                 PTR_MAYBE_NULL | MEM_RCU :
4430                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
4431                 /* For mark_ptr_or_null_reg */
4432                 val_reg->id = ++env->id_gen;
4433         } else if (class == BPF_STX) {
4434                 val_reg = reg_state(env, value_regno);
4435                 if (!register_is_null(val_reg) &&
4436                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4437                         return -EACCES;
4438         } else if (class == BPF_ST) {
4439                 if (insn->imm) {
4440                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4441                                 kptr_field->offset);
4442                         return -EACCES;
4443                 }
4444         } else {
4445                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4446                 return -EACCES;
4447         }
4448         return 0;
4449 }
4450
4451 /* check read/write into a map element with possible variable offset */
4452 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4453                             int off, int size, bool zero_size_allowed,
4454                             enum bpf_access_src src)
4455 {
4456         struct bpf_verifier_state *vstate = env->cur_state;
4457         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4458         struct bpf_reg_state *reg = &state->regs[regno];
4459         struct bpf_map *map = reg->map_ptr;
4460         struct btf_record *rec;
4461         int err, i;
4462
4463         err = check_mem_region_access(env, regno, off, size, map->value_size,
4464                                       zero_size_allowed);
4465         if (err)
4466                 return err;
4467
4468         if (IS_ERR_OR_NULL(map->record))
4469                 return 0;
4470         rec = map->record;
4471         for (i = 0; i < rec->cnt; i++) {
4472                 struct btf_field *field = &rec->fields[i];
4473                 u32 p = field->offset;
4474
4475                 /* If any part of a field  can be touched by load/store, reject
4476                  * this program. To check that [x1, x2) overlaps with [y1, y2),
4477                  * it is sufficient to check x1 < y2 && y1 < x2.
4478                  */
4479                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4480                     p < reg->umax_value + off + size) {
4481                         switch (field->type) {
4482                         case BPF_KPTR_UNREF:
4483                         case BPF_KPTR_REF:
4484                                 if (src != ACCESS_DIRECT) {
4485                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
4486                                         return -EACCES;
4487                                 }
4488                                 if (!tnum_is_const(reg->var_off)) {
4489                                         verbose(env, "kptr access cannot have variable offset\n");
4490                                         return -EACCES;
4491                                 }
4492                                 if (p != off + reg->var_off.value) {
4493                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4494                                                 p, off + reg->var_off.value);
4495                                         return -EACCES;
4496                                 }
4497                                 if (size != bpf_size_to_bytes(BPF_DW)) {
4498                                         verbose(env, "kptr access size must be BPF_DW\n");
4499                                         return -EACCES;
4500                                 }
4501                                 break;
4502                         default:
4503                                 verbose(env, "%s cannot be accessed directly by load/store\n",
4504                                         btf_field_type_name(field->type));
4505                                 return -EACCES;
4506                         }
4507                 }
4508         }
4509         return 0;
4510 }
4511
4512 #define MAX_PACKET_OFF 0xffff
4513
4514 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4515                                        const struct bpf_call_arg_meta *meta,
4516                                        enum bpf_access_type t)
4517 {
4518         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4519
4520         switch (prog_type) {
4521         /* Program types only with direct read access go here! */
4522         case BPF_PROG_TYPE_LWT_IN:
4523         case BPF_PROG_TYPE_LWT_OUT:
4524         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4525         case BPF_PROG_TYPE_SK_REUSEPORT:
4526         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4527         case BPF_PROG_TYPE_CGROUP_SKB:
4528                 if (t == BPF_WRITE)
4529                         return false;
4530                 fallthrough;
4531
4532         /* Program types with direct read + write access go here! */
4533         case BPF_PROG_TYPE_SCHED_CLS:
4534         case BPF_PROG_TYPE_SCHED_ACT:
4535         case BPF_PROG_TYPE_XDP:
4536         case BPF_PROG_TYPE_LWT_XMIT:
4537         case BPF_PROG_TYPE_SK_SKB:
4538         case BPF_PROG_TYPE_SK_MSG:
4539                 if (meta)
4540                         return meta->pkt_access;
4541
4542                 env->seen_direct_write = true;
4543                 return true;
4544
4545         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4546                 if (t == BPF_WRITE)
4547                         env->seen_direct_write = true;
4548
4549                 return true;
4550
4551         default:
4552                 return false;
4553         }
4554 }
4555
4556 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4557                                int size, bool zero_size_allowed)
4558 {
4559         struct bpf_reg_state *regs = cur_regs(env);
4560         struct bpf_reg_state *reg = &regs[regno];
4561         int err;
4562
4563         /* We may have added a variable offset to the packet pointer; but any
4564          * reg->range we have comes after that.  We are only checking the fixed
4565          * offset.
4566          */
4567
4568         /* We don't allow negative numbers, because we aren't tracking enough
4569          * detail to prove they're safe.
4570          */
4571         if (reg->smin_value < 0) {
4572                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4573                         regno);
4574                 return -EACCES;
4575         }
4576
4577         err = reg->range < 0 ? -EINVAL :
4578               __check_mem_access(env, regno, off, size, reg->range,
4579                                  zero_size_allowed);
4580         if (err) {
4581                 verbose(env, "R%d offset is outside of the packet\n", regno);
4582                 return err;
4583         }
4584
4585         /* __check_mem_access has made sure "off + size - 1" is within u16.
4586          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4587          * otherwise find_good_pkt_pointers would have refused to set range info
4588          * that __check_mem_access would have rejected this pkt access.
4589          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4590          */
4591         env->prog->aux->max_pkt_offset =
4592                 max_t(u32, env->prog->aux->max_pkt_offset,
4593                       off + reg->umax_value + size - 1);
4594
4595         return err;
4596 }
4597
4598 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4599 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4600                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4601                             struct btf **btf, u32 *btf_id)
4602 {
4603         struct bpf_insn_access_aux info = {
4604                 .reg_type = *reg_type,
4605                 .log = &env->log,
4606         };
4607
4608         if (env->ops->is_valid_access &&
4609             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4610                 /* A non zero info.ctx_field_size indicates that this field is a
4611                  * candidate for later verifier transformation to load the whole
4612                  * field and then apply a mask when accessed with a narrower
4613                  * access than actual ctx access size. A zero info.ctx_field_size
4614                  * will only allow for whole field access and rejects any other
4615                  * type of narrower access.
4616                  */
4617                 *reg_type = info.reg_type;
4618
4619                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4620                         *btf = info.btf;
4621                         *btf_id = info.btf_id;
4622                 } else {
4623                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4624                 }
4625                 /* remember the offset of last byte accessed in ctx */
4626                 if (env->prog->aux->max_ctx_offset < off + size)
4627                         env->prog->aux->max_ctx_offset = off + size;
4628                 return 0;
4629         }
4630
4631         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4632         return -EACCES;
4633 }
4634
4635 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4636                                   int size)
4637 {
4638         if (size < 0 || off < 0 ||
4639             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4640                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4641                         off, size);
4642                 return -EACCES;
4643         }
4644         return 0;
4645 }
4646
4647 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4648                              u32 regno, int off, int size,
4649                              enum bpf_access_type t)
4650 {
4651         struct bpf_reg_state *regs = cur_regs(env);
4652         struct bpf_reg_state *reg = &regs[regno];
4653         struct bpf_insn_access_aux info = {};
4654         bool valid;
4655
4656         if (reg->smin_value < 0) {
4657                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4658                         regno);
4659                 return -EACCES;
4660         }
4661
4662         switch (reg->type) {
4663         case PTR_TO_SOCK_COMMON:
4664                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4665                 break;
4666         case PTR_TO_SOCKET:
4667                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4668                 break;
4669         case PTR_TO_TCP_SOCK:
4670                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4671                 break;
4672         case PTR_TO_XDP_SOCK:
4673                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4674                 break;
4675         default:
4676                 valid = false;
4677         }
4678
4679
4680         if (valid) {
4681                 env->insn_aux_data[insn_idx].ctx_field_size =
4682                         info.ctx_field_size;
4683                 return 0;
4684         }
4685
4686         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4687                 regno, reg_type_str(env, reg->type), off, size);
4688
4689         return -EACCES;
4690 }
4691
4692 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4693 {
4694         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4695 }
4696
4697 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4698 {
4699         const struct bpf_reg_state *reg = reg_state(env, regno);
4700
4701         return reg->type == PTR_TO_CTX;
4702 }
4703
4704 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4705 {
4706         const struct bpf_reg_state *reg = reg_state(env, regno);
4707
4708         return type_is_sk_pointer(reg->type);
4709 }
4710
4711 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4712 {
4713         const struct bpf_reg_state *reg = reg_state(env, regno);
4714
4715         return type_is_pkt_pointer(reg->type);
4716 }
4717
4718 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4719 {
4720         const struct bpf_reg_state *reg = reg_state(env, regno);
4721
4722         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4723         return reg->type == PTR_TO_FLOW_KEYS;
4724 }
4725
4726 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4727 {
4728         /* A referenced register is always trusted. */
4729         if (reg->ref_obj_id)
4730                 return true;
4731
4732         /* If a register is not referenced, it is trusted if it has the
4733          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4734          * other type modifiers may be safe, but we elect to take an opt-in
4735          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4736          * not.
4737          *
4738          * Eventually, we should make PTR_TRUSTED the single source of truth
4739          * for whether a register is trusted.
4740          */
4741         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4742                !bpf_type_has_unsafe_modifiers(reg->type);
4743 }
4744
4745 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4746 {
4747         return reg->type & MEM_RCU;
4748 }
4749
4750 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4751                                    const struct bpf_reg_state *reg,
4752                                    int off, int size, bool strict)
4753 {
4754         struct tnum reg_off;
4755         int ip_align;
4756
4757         /* Byte size accesses are always allowed. */
4758         if (!strict || size == 1)
4759                 return 0;
4760
4761         /* For platforms that do not have a Kconfig enabling
4762          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4763          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4764          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4765          * to this code only in strict mode where we want to emulate
4766          * the NET_IP_ALIGN==2 checking.  Therefore use an
4767          * unconditional IP align value of '2'.
4768          */
4769         ip_align = 2;
4770
4771         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4772         if (!tnum_is_aligned(reg_off, size)) {
4773                 char tn_buf[48];
4774
4775                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4776                 verbose(env,
4777                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4778                         ip_align, tn_buf, reg->off, off, size);
4779                 return -EACCES;
4780         }
4781
4782         return 0;
4783 }
4784
4785 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4786                                        const struct bpf_reg_state *reg,
4787                                        const char *pointer_desc,
4788                                        int off, int size, bool strict)
4789 {
4790         struct tnum reg_off;
4791
4792         /* Byte size accesses are always allowed. */
4793         if (!strict || size == 1)
4794                 return 0;
4795
4796         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4797         if (!tnum_is_aligned(reg_off, size)) {
4798                 char tn_buf[48];
4799
4800                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4801                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4802                         pointer_desc, tn_buf, reg->off, off, size);
4803                 return -EACCES;
4804         }
4805
4806         return 0;
4807 }
4808
4809 static int check_ptr_alignment(struct bpf_verifier_env *env,
4810                                const struct bpf_reg_state *reg, int off,
4811                                int size, bool strict_alignment_once)
4812 {
4813         bool strict = env->strict_alignment || strict_alignment_once;
4814         const char *pointer_desc = "";
4815
4816         switch (reg->type) {
4817         case PTR_TO_PACKET:
4818         case PTR_TO_PACKET_META:
4819                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4820                  * right in front, treat it the very same way.
4821                  */
4822                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4823         case PTR_TO_FLOW_KEYS:
4824                 pointer_desc = "flow keys ";
4825                 break;
4826         case PTR_TO_MAP_KEY:
4827                 pointer_desc = "key ";
4828                 break;
4829         case PTR_TO_MAP_VALUE:
4830                 pointer_desc = "value ";
4831                 break;
4832         case PTR_TO_CTX:
4833                 pointer_desc = "context ";
4834                 break;
4835         case PTR_TO_STACK:
4836                 pointer_desc = "stack ";
4837                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4838                  * and check_stack_read_fixed_off() relies on stack accesses being
4839                  * aligned.
4840                  */
4841                 strict = true;
4842                 break;
4843         case PTR_TO_SOCKET:
4844                 pointer_desc = "sock ";
4845                 break;
4846         case PTR_TO_SOCK_COMMON:
4847                 pointer_desc = "sock_common ";
4848                 break;
4849         case PTR_TO_TCP_SOCK:
4850                 pointer_desc = "tcp_sock ";
4851                 break;
4852         case PTR_TO_XDP_SOCK:
4853                 pointer_desc = "xdp_sock ";
4854                 break;
4855         default:
4856                 break;
4857         }
4858         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4859                                            strict);
4860 }
4861
4862 static int update_stack_depth(struct bpf_verifier_env *env,
4863                               const struct bpf_func_state *func,
4864                               int off)
4865 {
4866         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4867
4868         if (stack >= -off)
4869                 return 0;
4870
4871         /* update known max for given subprogram */
4872         env->subprog_info[func->subprogno].stack_depth = -off;
4873         return 0;
4874 }
4875
4876 /* starting from main bpf function walk all instructions of the function
4877  * and recursively walk all callees that given function can call.
4878  * Ignore jump and exit insns.
4879  * Since recursion is prevented by check_cfg() this algorithm
4880  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4881  */
4882 static int check_max_stack_depth(struct bpf_verifier_env *env)
4883 {
4884         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4885         struct bpf_subprog_info *subprog = env->subprog_info;
4886         struct bpf_insn *insn = env->prog->insnsi;
4887         bool tail_call_reachable = false;
4888         int ret_insn[MAX_CALL_FRAMES];
4889         int ret_prog[MAX_CALL_FRAMES];
4890         int j;
4891
4892 process_func:
4893         /* protect against potential stack overflow that might happen when
4894          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4895          * depth for such case down to 256 so that the worst case scenario
4896          * would result in 8k stack size (32 which is tailcall limit * 256 =
4897          * 8k).
4898          *
4899          * To get the idea what might happen, see an example:
4900          * func1 -> sub rsp, 128
4901          *  subfunc1 -> sub rsp, 256
4902          *  tailcall1 -> add rsp, 256
4903          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4904          *   subfunc2 -> sub rsp, 64
4905          *   subfunc22 -> sub rsp, 128
4906          *   tailcall2 -> add rsp, 128
4907          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4908          *
4909          * tailcall will unwind the current stack frame but it will not get rid
4910          * of caller's stack as shown on the example above.
4911          */
4912         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4913                 verbose(env,
4914                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4915                         depth);
4916                 return -EACCES;
4917         }
4918         /* round up to 32-bytes, since this is granularity
4919          * of interpreter stack size
4920          */
4921         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4922         if (depth > MAX_BPF_STACK) {
4923                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4924                         frame + 1, depth);
4925                 return -EACCES;
4926         }
4927 continue_func:
4928         subprog_end = subprog[idx + 1].start;
4929         for (; i < subprog_end; i++) {
4930                 int next_insn;
4931
4932                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4933                         continue;
4934                 /* remember insn and function to return to */
4935                 ret_insn[frame] = i + 1;
4936                 ret_prog[frame] = idx;
4937
4938                 /* find the callee */
4939                 next_insn = i + insn[i].imm + 1;
4940                 idx = find_subprog(env, next_insn);
4941                 if (idx < 0) {
4942                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4943                                   next_insn);
4944                         return -EFAULT;
4945                 }
4946                 if (subprog[idx].is_async_cb) {
4947                         if (subprog[idx].has_tail_call) {
4948                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4949                                 return -EFAULT;
4950                         }
4951                          /* async callbacks don't increase bpf prog stack size */
4952                         continue;
4953                 }
4954                 i = next_insn;
4955
4956                 if (subprog[idx].has_tail_call)
4957                         tail_call_reachable = true;
4958
4959                 frame++;
4960                 if (frame >= MAX_CALL_FRAMES) {
4961                         verbose(env, "the call stack of %d frames is too deep !\n",
4962                                 frame);
4963                         return -E2BIG;
4964                 }
4965                 goto process_func;
4966         }
4967         /* if tail call got detected across bpf2bpf calls then mark each of the
4968          * currently present subprog frames as tail call reachable subprogs;
4969          * this info will be utilized by JIT so that we will be preserving the
4970          * tail call counter throughout bpf2bpf calls combined with tailcalls
4971          */
4972         if (tail_call_reachable)
4973                 for (j = 0; j < frame; j++)
4974                         subprog[ret_prog[j]].tail_call_reachable = true;
4975         if (subprog[0].tail_call_reachable)
4976                 env->prog->aux->tail_call_reachable = true;
4977
4978         /* end of for() loop means the last insn of the 'subprog'
4979          * was reached. Doesn't matter whether it was JA or EXIT
4980          */
4981         if (frame == 0)
4982                 return 0;
4983         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4984         frame--;
4985         i = ret_insn[frame];
4986         idx = ret_prog[frame];
4987         goto continue_func;
4988 }
4989
4990 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4991 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4992                                   const struct bpf_insn *insn, int idx)
4993 {
4994         int start = idx + insn->imm + 1, subprog;
4995
4996         subprog = find_subprog(env, start);
4997         if (subprog < 0) {
4998                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4999                           start);
5000                 return -EFAULT;
5001         }
5002         return env->subprog_info[subprog].stack_depth;
5003 }
5004 #endif
5005
5006 static int __check_buffer_access(struct bpf_verifier_env *env,
5007                                  const char *buf_info,
5008                                  const struct bpf_reg_state *reg,
5009                                  int regno, int off, int size)
5010 {
5011         if (off < 0) {
5012                 verbose(env,
5013                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5014                         regno, buf_info, off, size);
5015                 return -EACCES;
5016         }
5017         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5018                 char tn_buf[48];
5019
5020                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5021                 verbose(env,
5022                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5023                         regno, off, tn_buf);
5024                 return -EACCES;
5025         }
5026
5027         return 0;
5028 }
5029
5030 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5031                                   const struct bpf_reg_state *reg,
5032                                   int regno, int off, int size)
5033 {
5034         int err;
5035
5036         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5037         if (err)
5038                 return err;
5039
5040         if (off + size > env->prog->aux->max_tp_access)
5041                 env->prog->aux->max_tp_access = off + size;
5042
5043         return 0;
5044 }
5045
5046 static int check_buffer_access(struct bpf_verifier_env *env,
5047                                const struct bpf_reg_state *reg,
5048                                int regno, int off, int size,
5049                                bool zero_size_allowed,
5050                                u32 *max_access)
5051 {
5052         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5053         int err;
5054
5055         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5056         if (err)
5057                 return err;
5058
5059         if (off + size > *max_access)
5060                 *max_access = off + size;
5061
5062         return 0;
5063 }
5064
5065 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5066 static void zext_32_to_64(struct bpf_reg_state *reg)
5067 {
5068         reg->var_off = tnum_subreg(reg->var_off);
5069         __reg_assign_32_into_64(reg);
5070 }
5071
5072 /* truncate register to smaller size (in bytes)
5073  * must be called with size < BPF_REG_SIZE
5074  */
5075 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5076 {
5077         u64 mask;
5078
5079         /* clear high bits in bit representation */
5080         reg->var_off = tnum_cast(reg->var_off, size);
5081
5082         /* fix arithmetic bounds */
5083         mask = ((u64)1 << (size * 8)) - 1;
5084         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5085                 reg->umin_value &= mask;
5086                 reg->umax_value &= mask;
5087         } else {
5088                 reg->umin_value = 0;
5089                 reg->umax_value = mask;
5090         }
5091         reg->smin_value = reg->umin_value;
5092         reg->smax_value = reg->umax_value;
5093
5094         /* If size is smaller than 32bit register the 32bit register
5095          * values are also truncated so we push 64-bit bounds into
5096          * 32-bit bounds. Above were truncated < 32-bits already.
5097          */
5098         if (size >= 4)
5099                 return;
5100         __reg_combine_64_into_32(reg);
5101 }
5102
5103 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5104 {
5105         /* A map is considered read-only if the following condition are true:
5106          *
5107          * 1) BPF program side cannot change any of the map content. The
5108          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5109          *    and was set at map creation time.
5110          * 2) The map value(s) have been initialized from user space by a
5111          *    loader and then "frozen", such that no new map update/delete
5112          *    operations from syscall side are possible for the rest of
5113          *    the map's lifetime from that point onwards.
5114          * 3) Any parallel/pending map update/delete operations from syscall
5115          *    side have been completed. Only after that point, it's safe to
5116          *    assume that map value(s) are immutable.
5117          */
5118         return (map->map_flags & BPF_F_RDONLY_PROG) &&
5119                READ_ONCE(map->frozen) &&
5120                !bpf_map_write_active(map);
5121 }
5122
5123 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5124 {
5125         void *ptr;
5126         u64 addr;
5127         int err;
5128
5129         err = map->ops->map_direct_value_addr(map, &addr, off);
5130         if (err)
5131                 return err;
5132         ptr = (void *)(long)addr + off;
5133
5134         switch (size) {
5135         case sizeof(u8):
5136                 *val = (u64)*(u8 *)ptr;
5137                 break;
5138         case sizeof(u16):
5139                 *val = (u64)*(u16 *)ptr;
5140                 break;
5141         case sizeof(u32):
5142                 *val = (u64)*(u32 *)ptr;
5143                 break;
5144         case sizeof(u64):
5145                 *val = *(u64 *)ptr;
5146                 break;
5147         default:
5148                 return -EINVAL;
5149         }
5150         return 0;
5151 }
5152
5153 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5154 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5155
5156 /*
5157  * Allow list few fields as RCU trusted or full trusted.
5158  * This logic doesn't allow mix tagging and will be removed once GCC supports
5159  * btf_type_tag.
5160  */
5161
5162 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5163 BTF_TYPE_SAFE_RCU(struct task_struct) {
5164         const cpumask_t *cpus_ptr;
5165         struct css_set __rcu *cgroups;
5166         struct task_struct __rcu *real_parent;
5167         struct task_struct *group_leader;
5168 };
5169
5170 BTF_TYPE_SAFE_RCU(struct css_set) {
5171         struct cgroup *dfl_cgrp;
5172 };
5173
5174 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5175 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5176         __bpf_md_ptr(struct seq_file *, seq);
5177 };
5178
5179 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5180         __bpf_md_ptr(struct bpf_iter_meta *, meta);
5181         __bpf_md_ptr(struct task_struct *, task);
5182 };
5183
5184 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5185         struct file *file;
5186 };
5187
5188 BTF_TYPE_SAFE_TRUSTED(struct file) {
5189         struct inode *f_inode;
5190 };
5191
5192 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5193         /* no negative dentry-s in places where bpf can see it */
5194         struct inode *d_inode;
5195 };
5196
5197 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5198         struct sock *sk;
5199 };
5200
5201 static bool type_is_rcu(struct bpf_verifier_env *env,
5202                         struct bpf_reg_state *reg,
5203                         int off)
5204 {
5205         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5206         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5207
5208         return btf_nested_type_is_trusted(&env->log, reg, off, "__safe_rcu");
5209 }
5210
5211 static bool type_is_trusted(struct bpf_verifier_env *env,
5212                             struct bpf_reg_state *reg,
5213                             int off)
5214 {
5215         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5216         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5217         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5218         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5219         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5220         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5221
5222         return btf_nested_type_is_trusted(&env->log, reg, off, "__safe_trusted");
5223 }
5224
5225 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5226                                    struct bpf_reg_state *regs,
5227                                    int regno, int off, int size,
5228                                    enum bpf_access_type atype,
5229                                    int value_regno)
5230 {
5231         struct bpf_reg_state *reg = regs + regno;
5232         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5233         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5234         enum bpf_type_flag flag = 0;
5235         u32 btf_id;
5236         int ret;
5237
5238         if (!env->allow_ptr_leaks) {
5239                 verbose(env,
5240                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5241                         tname);
5242                 return -EPERM;
5243         }
5244         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5245                 verbose(env,
5246                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5247                         tname);
5248                 return -EINVAL;
5249         }
5250         if (off < 0) {
5251                 verbose(env,
5252                         "R%d is ptr_%s invalid negative access: off=%d\n",
5253                         regno, tname, off);
5254                 return -EACCES;
5255         }
5256         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5257                 char tn_buf[48];
5258
5259                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5260                 verbose(env,
5261                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5262                         regno, tname, off, tn_buf);
5263                 return -EACCES;
5264         }
5265
5266         if (reg->type & MEM_USER) {
5267                 verbose(env,
5268                         "R%d is ptr_%s access user memory: off=%d\n",
5269                         regno, tname, off);
5270                 return -EACCES;
5271         }
5272
5273         if (reg->type & MEM_PERCPU) {
5274                 verbose(env,
5275                         "R%d is ptr_%s access percpu memory: off=%d\n",
5276                         regno, tname, off);
5277                 return -EACCES;
5278         }
5279
5280         if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
5281                 if (!btf_is_kernel(reg->btf)) {
5282                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5283                         return -EFAULT;
5284                 }
5285                 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5286         } else {
5287                 /* Writes are permitted with default btf_struct_access for
5288                  * program allocated objects (which always have ref_obj_id > 0),
5289                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5290                  */
5291                 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5292                         verbose(env, "only read is supported\n");
5293                         return -EACCES;
5294                 }
5295
5296                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5297                     !reg->ref_obj_id) {
5298                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5299                         return -EFAULT;
5300                 }
5301
5302                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
5303         }
5304
5305         if (ret < 0)
5306                 return ret;
5307
5308         if (ret != PTR_TO_BTF_ID) {
5309                 /* just mark; */
5310
5311         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5312                 /* If this is an untrusted pointer, all pointers formed by walking it
5313                  * also inherit the untrusted flag.
5314                  */
5315                 flag = PTR_UNTRUSTED;
5316
5317         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5318                 /* By default any pointer obtained from walking a trusted pointer is no
5319                  * longer trusted, unless the field being accessed has explicitly been
5320                  * marked as inheriting its parent's state of trust (either full or RCU).
5321                  * For example:
5322                  * 'cgroups' pointer is untrusted if task->cgroups dereference
5323                  * happened in a sleepable program outside of bpf_rcu_read_lock()
5324                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5325                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5326                  *
5327                  * A regular RCU-protected pointer with __rcu tag can also be deemed
5328                  * trusted if we are in an RCU CS. Such pointer can be NULL.
5329                  */
5330                 if (type_is_trusted(env, reg, off)) {
5331                         flag |= PTR_TRUSTED;
5332                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5333                         if (type_is_rcu(env, reg, off)) {
5334                                 /* ignore __rcu tag and mark it MEM_RCU */
5335                                 flag |= MEM_RCU;
5336                         } else if (flag & MEM_RCU) {
5337                                 /* __rcu tagged pointers can be NULL */
5338                                 flag |= PTR_MAYBE_NULL;
5339                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
5340                                 /* keep as-is */
5341                         } else {
5342                                 /* walking unknown pointers yields untrusted pointer */
5343                                 flag = PTR_UNTRUSTED;
5344                         }
5345                 } else {
5346                         /*
5347                          * If not in RCU CS or MEM_RCU pointer can be NULL then
5348                          * aggressively mark as untrusted otherwise such
5349                          * pointers will be plain PTR_TO_BTF_ID without flags
5350                          * and will be allowed to be passed into helpers for
5351                          * compat reasons.
5352                          */
5353                         flag = PTR_UNTRUSTED;
5354                 }
5355         } else {
5356                 /* Old compat. Deprecated */
5357                 flag &= ~PTR_TRUSTED;
5358         }
5359
5360         if (atype == BPF_READ && value_regno >= 0)
5361                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5362
5363         return 0;
5364 }
5365
5366 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5367                                    struct bpf_reg_state *regs,
5368                                    int regno, int off, int size,
5369                                    enum bpf_access_type atype,
5370                                    int value_regno)
5371 {
5372         struct bpf_reg_state *reg = regs + regno;
5373         struct bpf_map *map = reg->map_ptr;
5374         struct bpf_reg_state map_reg;
5375         enum bpf_type_flag flag = 0;
5376         const struct btf_type *t;
5377         const char *tname;
5378         u32 btf_id;
5379         int ret;
5380
5381         if (!btf_vmlinux) {
5382                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5383                 return -ENOTSUPP;
5384         }
5385
5386         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5387                 verbose(env, "map_ptr access not supported for map type %d\n",
5388                         map->map_type);
5389                 return -ENOTSUPP;
5390         }
5391
5392         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5393         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5394
5395         if (!env->allow_ptr_leaks) {
5396                 verbose(env,
5397                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5398                         tname);
5399                 return -EPERM;
5400         }
5401
5402         if (off < 0) {
5403                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
5404                         regno, tname, off);
5405                 return -EACCES;
5406         }
5407
5408         if (atype != BPF_READ) {
5409                 verbose(env, "only read from %s is supported\n", tname);
5410                 return -EACCES;
5411         }
5412
5413         /* Simulate access to a PTR_TO_BTF_ID */
5414         memset(&map_reg, 0, sizeof(map_reg));
5415         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5416         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
5417         if (ret < 0)
5418                 return ret;
5419
5420         if (value_regno >= 0)
5421                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5422
5423         return 0;
5424 }
5425
5426 /* Check that the stack access at the given offset is within bounds. The
5427  * maximum valid offset is -1.
5428  *
5429  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5430  * -state->allocated_stack for reads.
5431  */
5432 static int check_stack_slot_within_bounds(int off,
5433                                           struct bpf_func_state *state,
5434                                           enum bpf_access_type t)
5435 {
5436         int min_valid_off;
5437
5438         if (t == BPF_WRITE)
5439                 min_valid_off = -MAX_BPF_STACK;
5440         else
5441                 min_valid_off = -state->allocated_stack;
5442
5443         if (off < min_valid_off || off > -1)
5444                 return -EACCES;
5445         return 0;
5446 }
5447
5448 /* Check that the stack access at 'regno + off' falls within the maximum stack
5449  * bounds.
5450  *
5451  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5452  */
5453 static int check_stack_access_within_bounds(
5454                 struct bpf_verifier_env *env,
5455                 int regno, int off, int access_size,
5456                 enum bpf_access_src src, enum bpf_access_type type)
5457 {
5458         struct bpf_reg_state *regs = cur_regs(env);
5459         struct bpf_reg_state *reg = regs + regno;
5460         struct bpf_func_state *state = func(env, reg);
5461         int min_off, max_off;
5462         int err;
5463         char *err_extra;
5464
5465         if (src == ACCESS_HELPER)
5466                 /* We don't know if helpers are reading or writing (or both). */
5467                 err_extra = " indirect access to";
5468         else if (type == BPF_READ)
5469                 err_extra = " read from";
5470         else
5471                 err_extra = " write to";
5472
5473         if (tnum_is_const(reg->var_off)) {
5474                 min_off = reg->var_off.value + off;
5475                 if (access_size > 0)
5476                         max_off = min_off + access_size - 1;
5477                 else
5478                         max_off = min_off;
5479         } else {
5480                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5481                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
5482                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5483                                 err_extra, regno);
5484                         return -EACCES;
5485                 }
5486                 min_off = reg->smin_value + off;
5487                 if (access_size > 0)
5488                         max_off = reg->smax_value + off + access_size - 1;
5489                 else
5490                         max_off = min_off;
5491         }
5492
5493         err = check_stack_slot_within_bounds(min_off, state, type);
5494         if (!err)
5495                 err = check_stack_slot_within_bounds(max_off, state, type);
5496
5497         if (err) {
5498                 if (tnum_is_const(reg->var_off)) {
5499                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5500                                 err_extra, regno, off, access_size);
5501                 } else {
5502                         char tn_buf[48];
5503
5504                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5505                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5506                                 err_extra, regno, tn_buf, access_size);
5507                 }
5508         }
5509         return err;
5510 }
5511
5512 /* check whether memory at (regno + off) is accessible for t = (read | write)
5513  * if t==write, value_regno is a register which value is stored into memory
5514  * if t==read, value_regno is a register which will receive the value from memory
5515  * if t==write && value_regno==-1, some unknown value is stored into memory
5516  * if t==read && value_regno==-1, don't care what we read from memory
5517  */
5518 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5519                             int off, int bpf_size, enum bpf_access_type t,
5520                             int value_regno, bool strict_alignment_once)
5521 {
5522         struct bpf_reg_state *regs = cur_regs(env);
5523         struct bpf_reg_state *reg = regs + regno;
5524         struct bpf_func_state *state;
5525         int size, err = 0;
5526
5527         size = bpf_size_to_bytes(bpf_size);
5528         if (size < 0)
5529                 return size;
5530
5531         /* alignment checks will add in reg->off themselves */
5532         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5533         if (err)
5534                 return err;
5535
5536         /* for access checks, reg->off is just part of off */
5537         off += reg->off;
5538
5539         if (reg->type == PTR_TO_MAP_KEY) {
5540                 if (t == BPF_WRITE) {
5541                         verbose(env, "write to change key R%d not allowed\n", regno);
5542                         return -EACCES;
5543                 }
5544
5545                 err = check_mem_region_access(env, regno, off, size,
5546                                               reg->map_ptr->key_size, false);
5547                 if (err)
5548                         return err;
5549                 if (value_regno >= 0)
5550                         mark_reg_unknown(env, regs, value_regno);
5551         } else if (reg->type == PTR_TO_MAP_VALUE) {
5552                 struct btf_field *kptr_field = NULL;
5553
5554                 if (t == BPF_WRITE && value_regno >= 0 &&
5555                     is_pointer_value(env, value_regno)) {
5556                         verbose(env, "R%d leaks addr into map\n", value_regno);
5557                         return -EACCES;
5558                 }
5559                 err = check_map_access_type(env, regno, off, size, t);
5560                 if (err)
5561                         return err;
5562                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5563                 if (err)
5564                         return err;
5565                 if (tnum_is_const(reg->var_off))
5566                         kptr_field = btf_record_find(reg->map_ptr->record,
5567                                                      off + reg->var_off.value, BPF_KPTR);
5568                 if (kptr_field) {
5569                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5570                 } else if (t == BPF_READ && value_regno >= 0) {
5571                         struct bpf_map *map = reg->map_ptr;
5572
5573                         /* if map is read-only, track its contents as scalars */
5574                         if (tnum_is_const(reg->var_off) &&
5575                             bpf_map_is_rdonly(map) &&
5576                             map->ops->map_direct_value_addr) {
5577                                 int map_off = off + reg->var_off.value;
5578                                 u64 val = 0;
5579
5580                                 err = bpf_map_direct_read(map, map_off, size,
5581                                                           &val);
5582                                 if (err)
5583                                         return err;
5584
5585                                 regs[value_regno].type = SCALAR_VALUE;
5586                                 __mark_reg_known(&regs[value_regno], val);
5587                         } else {
5588                                 mark_reg_unknown(env, regs, value_regno);
5589                         }
5590                 }
5591         } else if (base_type(reg->type) == PTR_TO_MEM) {
5592                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5593
5594                 if (type_may_be_null(reg->type)) {
5595                         verbose(env, "R%d invalid mem access '%s'\n", regno,
5596                                 reg_type_str(env, reg->type));
5597                         return -EACCES;
5598                 }
5599
5600                 if (t == BPF_WRITE && rdonly_mem) {
5601                         verbose(env, "R%d cannot write into %s\n",
5602                                 regno, reg_type_str(env, reg->type));
5603                         return -EACCES;
5604                 }
5605
5606                 if (t == BPF_WRITE && value_regno >= 0 &&
5607                     is_pointer_value(env, value_regno)) {
5608                         verbose(env, "R%d leaks addr into mem\n", value_regno);
5609                         return -EACCES;
5610                 }
5611
5612                 err = check_mem_region_access(env, regno, off, size,
5613                                               reg->mem_size, false);
5614                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5615                         mark_reg_unknown(env, regs, value_regno);
5616         } else if (reg->type == PTR_TO_CTX) {
5617                 enum bpf_reg_type reg_type = SCALAR_VALUE;
5618                 struct btf *btf = NULL;
5619                 u32 btf_id = 0;
5620
5621                 if (t == BPF_WRITE && value_regno >= 0 &&
5622                     is_pointer_value(env, value_regno)) {
5623                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
5624                         return -EACCES;
5625                 }
5626
5627                 err = check_ptr_off_reg(env, reg, regno);
5628                 if (err < 0)
5629                         return err;
5630
5631                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5632                                        &btf_id);
5633                 if (err)
5634                         verbose_linfo(env, insn_idx, "; ");
5635                 if (!err && t == BPF_READ && value_regno >= 0) {
5636                         /* ctx access returns either a scalar, or a
5637                          * PTR_TO_PACKET[_META,_END]. In the latter
5638                          * case, we know the offset is zero.
5639                          */
5640                         if (reg_type == SCALAR_VALUE) {
5641                                 mark_reg_unknown(env, regs, value_regno);
5642                         } else {
5643                                 mark_reg_known_zero(env, regs,
5644                                                     value_regno);
5645                                 if (type_may_be_null(reg_type))
5646                                         regs[value_regno].id = ++env->id_gen;
5647                                 /* A load of ctx field could have different
5648                                  * actual load size with the one encoded in the
5649                                  * insn. When the dst is PTR, it is for sure not
5650                                  * a sub-register.
5651                                  */
5652                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5653                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5654                                         regs[value_regno].btf = btf;
5655                                         regs[value_regno].btf_id = btf_id;
5656                                 }
5657                         }
5658                         regs[value_regno].type = reg_type;
5659                 }
5660
5661         } else if (reg->type == PTR_TO_STACK) {
5662                 /* Basic bounds checks. */
5663                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5664                 if (err)
5665                         return err;
5666
5667                 state = func(env, reg);
5668                 err = update_stack_depth(env, state, off);
5669                 if (err)
5670                         return err;
5671
5672                 if (t == BPF_READ)
5673                         err = check_stack_read(env, regno, off, size,
5674                                                value_regno);
5675                 else
5676                         err = check_stack_write(env, regno, off, size,
5677                                                 value_regno, insn_idx);
5678         } else if (reg_is_pkt_pointer(reg)) {
5679                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5680                         verbose(env, "cannot write into packet\n");
5681                         return -EACCES;
5682                 }
5683                 if (t == BPF_WRITE && value_regno >= 0 &&
5684                     is_pointer_value(env, value_regno)) {
5685                         verbose(env, "R%d leaks addr into packet\n",
5686                                 value_regno);
5687                         return -EACCES;
5688                 }
5689                 err = check_packet_access(env, regno, off, size, false);
5690                 if (!err && t == BPF_READ && value_regno >= 0)
5691                         mark_reg_unknown(env, regs, value_regno);
5692         } else if (reg->type == PTR_TO_FLOW_KEYS) {
5693                 if (t == BPF_WRITE && value_regno >= 0 &&
5694                     is_pointer_value(env, value_regno)) {
5695                         verbose(env, "R%d leaks addr into flow keys\n",
5696                                 value_regno);
5697                         return -EACCES;
5698                 }
5699
5700                 err = check_flow_keys_access(env, off, size);
5701                 if (!err && t == BPF_READ && value_regno >= 0)
5702                         mark_reg_unknown(env, regs, value_regno);
5703         } else if (type_is_sk_pointer(reg->type)) {
5704                 if (t == BPF_WRITE) {
5705                         verbose(env, "R%d cannot write into %s\n",
5706                                 regno, reg_type_str(env, reg->type));
5707                         return -EACCES;
5708                 }
5709                 err = check_sock_access(env, insn_idx, regno, off, size, t);
5710                 if (!err && value_regno >= 0)
5711                         mark_reg_unknown(env, regs, value_regno);
5712         } else if (reg->type == PTR_TO_TP_BUFFER) {
5713                 err = check_tp_buffer_access(env, reg, regno, off, size);
5714                 if (!err && t == BPF_READ && value_regno >= 0)
5715                         mark_reg_unknown(env, regs, value_regno);
5716         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5717                    !type_may_be_null(reg->type)) {
5718                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5719                                               value_regno);
5720         } else if (reg->type == CONST_PTR_TO_MAP) {
5721                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5722                                               value_regno);
5723         } else if (base_type(reg->type) == PTR_TO_BUF) {
5724                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5725                 u32 *max_access;
5726
5727                 if (rdonly_mem) {
5728                         if (t == BPF_WRITE) {
5729                                 verbose(env, "R%d cannot write into %s\n",
5730                                         regno, reg_type_str(env, reg->type));
5731                                 return -EACCES;
5732                         }
5733                         max_access = &env->prog->aux->max_rdonly_access;
5734                 } else {
5735                         max_access = &env->prog->aux->max_rdwr_access;
5736                 }
5737
5738                 err = check_buffer_access(env, reg, regno, off, size, false,
5739                                           max_access);
5740
5741                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5742                         mark_reg_unknown(env, regs, value_regno);
5743         } else {
5744                 verbose(env, "R%d invalid mem access '%s'\n", regno,
5745                         reg_type_str(env, reg->type));
5746                 return -EACCES;
5747         }
5748
5749         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5750             regs[value_regno].type == SCALAR_VALUE) {
5751                 /* b/h/w load zero-extends, mark upper bits as known 0 */
5752                 coerce_reg_to_size(&regs[value_regno], size);
5753         }
5754         return err;
5755 }
5756
5757 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5758 {
5759         int load_reg;
5760         int err;
5761
5762         switch (insn->imm) {
5763         case BPF_ADD:
5764         case BPF_ADD | BPF_FETCH:
5765         case BPF_AND:
5766         case BPF_AND | BPF_FETCH:
5767         case BPF_OR:
5768         case BPF_OR | BPF_FETCH:
5769         case BPF_XOR:
5770         case BPF_XOR | BPF_FETCH:
5771         case BPF_XCHG:
5772         case BPF_CMPXCHG:
5773                 break;
5774         default:
5775                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5776                 return -EINVAL;
5777         }
5778
5779         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5780                 verbose(env, "invalid atomic operand size\n");
5781                 return -EINVAL;
5782         }
5783
5784         /* check src1 operand */
5785         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5786         if (err)
5787                 return err;
5788
5789         /* check src2 operand */
5790         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5791         if (err)
5792                 return err;
5793
5794         if (insn->imm == BPF_CMPXCHG) {
5795                 /* Check comparison of R0 with memory location */
5796                 const u32 aux_reg = BPF_REG_0;
5797
5798                 err = check_reg_arg(env, aux_reg, SRC_OP);
5799                 if (err)
5800                         return err;
5801
5802                 if (is_pointer_value(env, aux_reg)) {
5803                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5804                         return -EACCES;
5805                 }
5806         }
5807
5808         if (is_pointer_value(env, insn->src_reg)) {
5809                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5810                 return -EACCES;
5811         }
5812
5813         if (is_ctx_reg(env, insn->dst_reg) ||
5814             is_pkt_reg(env, insn->dst_reg) ||
5815             is_flow_key_reg(env, insn->dst_reg) ||
5816             is_sk_reg(env, insn->dst_reg)) {
5817                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5818                         insn->dst_reg,
5819                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5820                 return -EACCES;
5821         }
5822
5823         if (insn->imm & BPF_FETCH) {
5824                 if (insn->imm == BPF_CMPXCHG)
5825                         load_reg = BPF_REG_0;
5826                 else
5827                         load_reg = insn->src_reg;
5828
5829                 /* check and record load of old value */
5830                 err = check_reg_arg(env, load_reg, DST_OP);
5831                 if (err)
5832                         return err;
5833         } else {
5834                 /* This instruction accesses a memory location but doesn't
5835                  * actually load it into a register.
5836                  */
5837                 load_reg = -1;
5838         }
5839
5840         /* Check whether we can read the memory, with second call for fetch
5841          * case to simulate the register fill.
5842          */
5843         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5844                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5845         if (!err && load_reg >= 0)
5846                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5847                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5848                                        true);
5849         if (err)
5850                 return err;
5851
5852         /* Check whether we can write into the same memory. */
5853         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5854                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5855         if (err)
5856                 return err;
5857
5858         return 0;
5859 }
5860
5861 /* When register 'regno' is used to read the stack (either directly or through
5862  * a helper function) make sure that it's within stack boundary and, depending
5863  * on the access type, that all elements of the stack are initialized.
5864  *
5865  * 'off' includes 'regno->off', but not its dynamic part (if any).
5866  *
5867  * All registers that have been spilled on the stack in the slots within the
5868  * read offsets are marked as read.
5869  */
5870 static int check_stack_range_initialized(
5871                 struct bpf_verifier_env *env, int regno, int off,
5872                 int access_size, bool zero_size_allowed,
5873                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5874 {
5875         struct bpf_reg_state *reg = reg_state(env, regno);
5876         struct bpf_func_state *state = func(env, reg);
5877         int err, min_off, max_off, i, j, slot, spi;
5878         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5879         enum bpf_access_type bounds_check_type;
5880         /* Some accesses can write anything into the stack, others are
5881          * read-only.
5882          */
5883         bool clobber = false;
5884
5885         if (access_size == 0 && !zero_size_allowed) {
5886                 verbose(env, "invalid zero-sized read\n");
5887                 return -EACCES;
5888         }
5889
5890         if (type == ACCESS_HELPER) {
5891                 /* The bounds checks for writes are more permissive than for
5892                  * reads. However, if raw_mode is not set, we'll do extra
5893                  * checks below.
5894                  */
5895                 bounds_check_type = BPF_WRITE;
5896                 clobber = true;
5897         } else {
5898                 bounds_check_type = BPF_READ;
5899         }
5900         err = check_stack_access_within_bounds(env, regno, off, access_size,
5901                                                type, bounds_check_type);
5902         if (err)
5903                 return err;
5904
5905
5906         if (tnum_is_const(reg->var_off)) {
5907                 min_off = max_off = reg->var_off.value + off;
5908         } else {
5909                 /* Variable offset is prohibited for unprivileged mode for
5910                  * simplicity since it requires corresponding support in
5911                  * Spectre masking for stack ALU.
5912                  * See also retrieve_ptr_limit().
5913                  */
5914                 if (!env->bypass_spec_v1) {
5915                         char tn_buf[48];
5916
5917                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5918                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5919                                 regno, err_extra, tn_buf);
5920                         return -EACCES;
5921                 }
5922                 /* Only initialized buffer on stack is allowed to be accessed
5923                  * with variable offset. With uninitialized buffer it's hard to
5924                  * guarantee that whole memory is marked as initialized on
5925                  * helper return since specific bounds are unknown what may
5926                  * cause uninitialized stack leaking.
5927                  */
5928                 if (meta && meta->raw_mode)
5929                         meta = NULL;
5930
5931                 min_off = reg->smin_value + off;
5932                 max_off = reg->smax_value + off;
5933         }
5934
5935         if (meta && meta->raw_mode) {
5936                 /* Ensure we won't be overwriting dynptrs when simulating byte
5937                  * by byte access in check_helper_call using meta.access_size.
5938                  * This would be a problem if we have a helper in the future
5939                  * which takes:
5940                  *
5941                  *      helper(uninit_mem, len, dynptr)
5942                  *
5943                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
5944                  * may end up writing to dynptr itself when touching memory from
5945                  * arg 1. This can be relaxed on a case by case basis for known
5946                  * safe cases, but reject due to the possibilitiy of aliasing by
5947                  * default.
5948                  */
5949                 for (i = min_off; i < max_off + access_size; i++) {
5950                         int stack_off = -i - 1;
5951
5952                         spi = __get_spi(i);
5953                         /* raw_mode may write past allocated_stack */
5954                         if (state->allocated_stack <= stack_off)
5955                                 continue;
5956                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
5957                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
5958                                 return -EACCES;
5959                         }
5960                 }
5961                 meta->access_size = access_size;
5962                 meta->regno = regno;
5963                 return 0;
5964         }
5965
5966         for (i = min_off; i < max_off + access_size; i++) {
5967                 u8 *stype;
5968
5969                 slot = -i - 1;
5970                 spi = slot / BPF_REG_SIZE;
5971                 if (state->allocated_stack <= slot)
5972                         goto err;
5973                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5974                 if (*stype == STACK_MISC)
5975                         goto mark;
5976                 if ((*stype == STACK_ZERO) ||
5977                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
5978                         if (clobber) {
5979                                 /* helper can write anything into the stack */
5980                                 *stype = STACK_MISC;
5981                         }
5982                         goto mark;
5983                 }
5984
5985                 if (is_spilled_reg(&state->stack[spi]) &&
5986                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5987                      env->allow_ptr_leaks)) {
5988                         if (clobber) {
5989                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5990                                 for (j = 0; j < BPF_REG_SIZE; j++)
5991                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5992                         }
5993                         goto mark;
5994                 }
5995
5996 err:
5997                 if (tnum_is_const(reg->var_off)) {
5998                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5999                                 err_extra, regno, min_off, i - min_off, access_size);
6000                 } else {
6001                         char tn_buf[48];
6002
6003                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6004                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6005                                 err_extra, regno, tn_buf, i - min_off, access_size);
6006                 }
6007                 return -EACCES;
6008 mark:
6009                 /* reading any byte out of 8-byte 'spill_slot' will cause
6010                  * the whole slot to be marked as 'read'
6011                  */
6012                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6013                               state->stack[spi].spilled_ptr.parent,
6014                               REG_LIVE_READ64);
6015                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6016                  * be sure that whether stack slot is written to or not. Hence,
6017                  * we must still conservatively propagate reads upwards even if
6018                  * helper may write to the entire memory range.
6019                  */
6020         }
6021         return update_stack_depth(env, state, min_off);
6022 }
6023
6024 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6025                                    int access_size, bool zero_size_allowed,
6026                                    struct bpf_call_arg_meta *meta)
6027 {
6028         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6029         u32 *max_access;
6030
6031         switch (base_type(reg->type)) {
6032         case PTR_TO_PACKET:
6033         case PTR_TO_PACKET_META:
6034                 return check_packet_access(env, regno, reg->off, access_size,
6035                                            zero_size_allowed);
6036         case PTR_TO_MAP_KEY:
6037                 if (meta && meta->raw_mode) {
6038                         verbose(env, "R%d cannot write into %s\n", regno,
6039                                 reg_type_str(env, reg->type));
6040                         return -EACCES;
6041                 }
6042                 return check_mem_region_access(env, regno, reg->off, access_size,
6043                                                reg->map_ptr->key_size, false);
6044         case PTR_TO_MAP_VALUE:
6045                 if (check_map_access_type(env, regno, reg->off, access_size,
6046                                           meta && meta->raw_mode ? BPF_WRITE :
6047                                           BPF_READ))
6048                         return -EACCES;
6049                 return check_map_access(env, regno, reg->off, access_size,
6050                                         zero_size_allowed, ACCESS_HELPER);
6051         case PTR_TO_MEM:
6052                 if (type_is_rdonly_mem(reg->type)) {
6053                         if (meta && meta->raw_mode) {
6054                                 verbose(env, "R%d cannot write into %s\n", regno,
6055                                         reg_type_str(env, reg->type));
6056                                 return -EACCES;
6057                         }
6058                 }
6059                 return check_mem_region_access(env, regno, reg->off,
6060                                                access_size, reg->mem_size,
6061                                                zero_size_allowed);
6062         case PTR_TO_BUF:
6063                 if (type_is_rdonly_mem(reg->type)) {
6064                         if (meta && meta->raw_mode) {
6065                                 verbose(env, "R%d cannot write into %s\n", regno,
6066                                         reg_type_str(env, reg->type));
6067                                 return -EACCES;
6068                         }
6069
6070                         max_access = &env->prog->aux->max_rdonly_access;
6071                 } else {
6072                         max_access = &env->prog->aux->max_rdwr_access;
6073                 }
6074                 return check_buffer_access(env, reg, regno, reg->off,
6075                                            access_size, zero_size_allowed,
6076                                            max_access);
6077         case PTR_TO_STACK:
6078                 return check_stack_range_initialized(
6079                                 env,
6080                                 regno, reg->off, access_size,
6081                                 zero_size_allowed, ACCESS_HELPER, meta);
6082         case PTR_TO_CTX:
6083                 /* in case the function doesn't know how to access the context,
6084                  * (because we are in a program of type SYSCALL for example), we
6085                  * can not statically check its size.
6086                  * Dynamically check it now.
6087                  */
6088                 if (!env->ops->convert_ctx_access) {
6089                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6090                         int offset = access_size - 1;
6091
6092                         /* Allow zero-byte read from PTR_TO_CTX */
6093                         if (access_size == 0)
6094                                 return zero_size_allowed ? 0 : -EACCES;
6095
6096                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6097                                                 atype, -1, false);
6098                 }
6099
6100                 fallthrough;
6101         default: /* scalar_value or invalid ptr */
6102                 /* Allow zero-byte read from NULL, regardless of pointer type */
6103                 if (zero_size_allowed && access_size == 0 &&
6104                     register_is_null(reg))
6105                         return 0;
6106
6107                 verbose(env, "R%d type=%s ", regno,
6108                         reg_type_str(env, reg->type));
6109                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6110                 return -EACCES;
6111         }
6112 }
6113
6114 static int check_mem_size_reg(struct bpf_verifier_env *env,
6115                               struct bpf_reg_state *reg, u32 regno,
6116                               bool zero_size_allowed,
6117                               struct bpf_call_arg_meta *meta)
6118 {
6119         int err;
6120
6121         /* This is used to refine r0 return value bounds for helpers
6122          * that enforce this value as an upper bound on return values.
6123          * See do_refine_retval_range() for helpers that can refine
6124          * the return value. C type of helper is u32 so we pull register
6125          * bound from umax_value however, if negative verifier errors
6126          * out. Only upper bounds can be learned because retval is an
6127          * int type and negative retvals are allowed.
6128          */
6129         meta->msize_max_value = reg->umax_value;
6130
6131         /* The register is SCALAR_VALUE; the access check
6132          * happens using its boundaries.
6133          */
6134         if (!tnum_is_const(reg->var_off))
6135                 /* For unprivileged variable accesses, disable raw
6136                  * mode so that the program is required to
6137                  * initialize all the memory that the helper could
6138                  * just partially fill up.
6139                  */
6140                 meta = NULL;
6141
6142         if (reg->smin_value < 0) {
6143                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6144                         regno);
6145                 return -EACCES;
6146         }
6147
6148         if (reg->umin_value == 0) {
6149                 err = check_helper_mem_access(env, regno - 1, 0,
6150                                               zero_size_allowed,
6151                                               meta);
6152                 if (err)
6153                         return err;
6154         }
6155
6156         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6157                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6158                         regno);
6159                 return -EACCES;
6160         }
6161         err = check_helper_mem_access(env, regno - 1,
6162                                       reg->umax_value,
6163                                       zero_size_allowed, meta);
6164         if (!err)
6165                 err = mark_chain_precision(env, regno);
6166         return err;
6167 }
6168
6169 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6170                    u32 regno, u32 mem_size)
6171 {
6172         bool may_be_null = type_may_be_null(reg->type);
6173         struct bpf_reg_state saved_reg;
6174         struct bpf_call_arg_meta meta;
6175         int err;
6176
6177         if (register_is_null(reg))
6178                 return 0;
6179
6180         memset(&meta, 0, sizeof(meta));
6181         /* Assuming that the register contains a value check if the memory
6182          * access is safe. Temporarily save and restore the register's state as
6183          * the conversion shouldn't be visible to a caller.
6184          */
6185         if (may_be_null) {
6186                 saved_reg = *reg;
6187                 mark_ptr_not_null_reg(reg);
6188         }
6189
6190         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6191         /* Check access for BPF_WRITE */
6192         meta.raw_mode = true;
6193         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6194
6195         if (may_be_null)
6196                 *reg = saved_reg;
6197
6198         return err;
6199 }
6200
6201 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6202                                     u32 regno)
6203 {
6204         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6205         bool may_be_null = type_may_be_null(mem_reg->type);
6206         struct bpf_reg_state saved_reg;
6207         struct bpf_call_arg_meta meta;
6208         int err;
6209
6210         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6211
6212         memset(&meta, 0, sizeof(meta));
6213
6214         if (may_be_null) {
6215                 saved_reg = *mem_reg;
6216                 mark_ptr_not_null_reg(mem_reg);
6217         }
6218
6219         err = check_mem_size_reg(env, reg, regno, true, &meta);
6220         /* Check access for BPF_WRITE */
6221         meta.raw_mode = true;
6222         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6223
6224         if (may_be_null)
6225                 *mem_reg = saved_reg;
6226         return err;
6227 }
6228
6229 /* Implementation details:
6230  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6231  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6232  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6233  * Two separate bpf_obj_new will also have different reg->id.
6234  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6235  * clears reg->id after value_or_null->value transition, since the verifier only
6236  * cares about the range of access to valid map value pointer and doesn't care
6237  * about actual address of the map element.
6238  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6239  * reg->id > 0 after value_or_null->value transition. By doing so
6240  * two bpf_map_lookups will be considered two different pointers that
6241  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6242  * returned from bpf_obj_new.
6243  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6244  * dead-locks.
6245  * Since only one bpf_spin_lock is allowed the checks are simpler than
6246  * reg_is_refcounted() logic. The verifier needs to remember only
6247  * one spin_lock instead of array of acquired_refs.
6248  * cur_state->active_lock remembers which map value element or allocated
6249  * object got locked and clears it after bpf_spin_unlock.
6250  */
6251 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6252                              bool is_lock)
6253 {
6254         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6255         struct bpf_verifier_state *cur = env->cur_state;
6256         bool is_const = tnum_is_const(reg->var_off);
6257         u64 val = reg->var_off.value;
6258         struct bpf_map *map = NULL;
6259         struct btf *btf = NULL;
6260         struct btf_record *rec;
6261
6262         if (!is_const) {
6263                 verbose(env,
6264                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6265                         regno);
6266                 return -EINVAL;
6267         }
6268         if (reg->type == PTR_TO_MAP_VALUE) {
6269                 map = reg->map_ptr;
6270                 if (!map->btf) {
6271                         verbose(env,
6272                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
6273                                 map->name);
6274                         return -EINVAL;
6275                 }
6276         } else {
6277                 btf = reg->btf;
6278         }
6279
6280         rec = reg_btf_record(reg);
6281         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6282                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6283                         map ? map->name : "kptr");
6284                 return -EINVAL;
6285         }
6286         if (rec->spin_lock_off != val + reg->off) {
6287                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6288                         val + reg->off, rec->spin_lock_off);
6289                 return -EINVAL;
6290         }
6291         if (is_lock) {
6292                 if (cur->active_lock.ptr) {
6293                         verbose(env,
6294                                 "Locking two bpf_spin_locks are not allowed\n");
6295                         return -EINVAL;
6296                 }
6297                 if (map)
6298                         cur->active_lock.ptr = map;
6299                 else
6300                         cur->active_lock.ptr = btf;
6301                 cur->active_lock.id = reg->id;
6302         } else {
6303                 void *ptr;
6304
6305                 if (map)
6306                         ptr = map;
6307                 else
6308                         ptr = btf;
6309
6310                 if (!cur->active_lock.ptr) {
6311                         verbose(env, "bpf_spin_unlock without taking a lock\n");
6312                         return -EINVAL;
6313                 }
6314                 if (cur->active_lock.ptr != ptr ||
6315                     cur->active_lock.id != reg->id) {
6316                         verbose(env, "bpf_spin_unlock of different lock\n");
6317                         return -EINVAL;
6318                 }
6319
6320                 invalidate_non_owning_refs(env);
6321
6322                 cur->active_lock.ptr = NULL;
6323                 cur->active_lock.id = 0;
6324         }
6325         return 0;
6326 }
6327
6328 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6329                               struct bpf_call_arg_meta *meta)
6330 {
6331         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6332         bool is_const = tnum_is_const(reg->var_off);
6333         struct bpf_map *map = reg->map_ptr;
6334         u64 val = reg->var_off.value;
6335
6336         if (!is_const) {
6337                 verbose(env,
6338                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6339                         regno);
6340                 return -EINVAL;
6341         }
6342         if (!map->btf) {
6343                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6344                         map->name);
6345                 return -EINVAL;
6346         }
6347         if (!btf_record_has_field(map->record, BPF_TIMER)) {
6348                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6349                 return -EINVAL;
6350         }
6351         if (map->record->timer_off != val + reg->off) {
6352                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6353                         val + reg->off, map->record->timer_off);
6354                 return -EINVAL;
6355         }
6356         if (meta->map_ptr) {
6357                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6358                 return -EFAULT;
6359         }
6360         meta->map_uid = reg->map_uid;
6361         meta->map_ptr = map;
6362         return 0;
6363 }
6364
6365 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6366                              struct bpf_call_arg_meta *meta)
6367 {
6368         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6369         struct bpf_map *map_ptr = reg->map_ptr;
6370         struct btf_field *kptr_field;
6371         u32 kptr_off;
6372
6373         if (!tnum_is_const(reg->var_off)) {
6374                 verbose(env,
6375                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6376                         regno);
6377                 return -EINVAL;
6378         }
6379         if (!map_ptr->btf) {
6380                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6381                         map_ptr->name);
6382                 return -EINVAL;
6383         }
6384         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6385                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6386                 return -EINVAL;
6387         }
6388
6389         meta->map_ptr = map_ptr;
6390         kptr_off = reg->off + reg->var_off.value;
6391         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6392         if (!kptr_field) {
6393                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6394                 return -EACCES;
6395         }
6396         if (kptr_field->type != BPF_KPTR_REF) {
6397                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6398                 return -EACCES;
6399         }
6400         meta->kptr_field = kptr_field;
6401         return 0;
6402 }
6403
6404 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6405  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6406  *
6407  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6408  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6409  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6410  *
6411  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6412  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6413  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6414  * mutate the view of the dynptr and also possibly destroy it. In the latter
6415  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6416  * memory that dynptr points to.
6417  *
6418  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6419  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6420  * readonly dynptr view yet, hence only the first case is tracked and checked.
6421  *
6422  * This is consistent with how C applies the const modifier to a struct object,
6423  * where the pointer itself inside bpf_dynptr becomes const but not what it
6424  * points to.
6425  *
6426  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6427  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6428  */
6429 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6430                                enum bpf_arg_type arg_type)
6431 {
6432         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6433         int err;
6434
6435         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6436          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6437          */
6438         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6439                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6440                 return -EFAULT;
6441         }
6442
6443         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6444          *               constructing a mutable bpf_dynptr object.
6445          *
6446          *               Currently, this is only possible with PTR_TO_STACK
6447          *               pointing to a region of at least 16 bytes which doesn't
6448          *               contain an existing bpf_dynptr.
6449          *
6450          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6451          *               mutated or destroyed. However, the memory it points to
6452          *               may be mutated.
6453          *
6454          *  None       - Points to a initialized dynptr that can be mutated and
6455          *               destroyed, including mutation of the memory it points
6456          *               to.
6457          */
6458         if (arg_type & MEM_UNINIT) {
6459                 int i;
6460
6461                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6462                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6463                         return -EINVAL;
6464                 }
6465
6466                 /* we write BPF_DW bits (8 bytes) at a time */
6467                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6468                         err = check_mem_access(env, insn_idx, regno,
6469                                                i, BPF_DW, BPF_WRITE, -1, false);
6470                         if (err)
6471                                 return err;
6472                 }
6473
6474                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6475         } else /* MEM_RDONLY and None case from above */ {
6476                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6477                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6478                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6479                         return -EINVAL;
6480                 }
6481
6482                 if (!is_dynptr_reg_valid_init(env, reg)) {
6483                         verbose(env,
6484                                 "Expected an initialized dynptr as arg #%d\n",
6485                                 regno);
6486                         return -EINVAL;
6487                 }
6488
6489                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6490                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6491                         verbose(env,
6492                                 "Expected a dynptr of type %s as arg #%d\n",
6493                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6494                         return -EINVAL;
6495                 }
6496
6497                 err = mark_dynptr_read(env, reg);
6498         }
6499         return err;
6500 }
6501
6502 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6503 {
6504         return type == ARG_CONST_SIZE ||
6505                type == ARG_CONST_SIZE_OR_ZERO;
6506 }
6507
6508 static bool arg_type_is_release(enum bpf_arg_type type)
6509 {
6510         return type & OBJ_RELEASE;
6511 }
6512
6513 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6514 {
6515         return base_type(type) == ARG_PTR_TO_DYNPTR;
6516 }
6517
6518 static int int_ptr_type_to_size(enum bpf_arg_type type)
6519 {
6520         if (type == ARG_PTR_TO_INT)
6521                 return sizeof(u32);
6522         else if (type == ARG_PTR_TO_LONG)
6523                 return sizeof(u64);
6524
6525         return -EINVAL;
6526 }
6527
6528 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6529                                  const struct bpf_call_arg_meta *meta,
6530                                  enum bpf_arg_type *arg_type)
6531 {
6532         if (!meta->map_ptr) {
6533                 /* kernel subsystem misconfigured verifier */
6534                 verbose(env, "invalid map_ptr to access map->type\n");
6535                 return -EACCES;
6536         }
6537
6538         switch (meta->map_ptr->map_type) {
6539         case BPF_MAP_TYPE_SOCKMAP:
6540         case BPF_MAP_TYPE_SOCKHASH:
6541                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6542                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6543                 } else {
6544                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
6545                         return -EINVAL;
6546                 }
6547                 break;
6548         case BPF_MAP_TYPE_BLOOM_FILTER:
6549                 if (meta->func_id == BPF_FUNC_map_peek_elem)
6550                         *arg_type = ARG_PTR_TO_MAP_VALUE;
6551                 break;
6552         default:
6553                 break;
6554         }
6555         return 0;
6556 }
6557
6558 struct bpf_reg_types {
6559         const enum bpf_reg_type types[10];
6560         u32 *btf_id;
6561 };
6562
6563 static const struct bpf_reg_types sock_types = {
6564         .types = {
6565                 PTR_TO_SOCK_COMMON,
6566                 PTR_TO_SOCKET,
6567                 PTR_TO_TCP_SOCK,
6568                 PTR_TO_XDP_SOCK,
6569         },
6570 };
6571
6572 #ifdef CONFIG_NET
6573 static const struct bpf_reg_types btf_id_sock_common_types = {
6574         .types = {
6575                 PTR_TO_SOCK_COMMON,
6576                 PTR_TO_SOCKET,
6577                 PTR_TO_TCP_SOCK,
6578                 PTR_TO_XDP_SOCK,
6579                 PTR_TO_BTF_ID,
6580                 PTR_TO_BTF_ID | PTR_TRUSTED,
6581         },
6582         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6583 };
6584 #endif
6585
6586 static const struct bpf_reg_types mem_types = {
6587         .types = {
6588                 PTR_TO_STACK,
6589                 PTR_TO_PACKET,
6590                 PTR_TO_PACKET_META,
6591                 PTR_TO_MAP_KEY,
6592                 PTR_TO_MAP_VALUE,
6593                 PTR_TO_MEM,
6594                 PTR_TO_MEM | MEM_RINGBUF,
6595                 PTR_TO_BUF,
6596         },
6597 };
6598
6599 static const struct bpf_reg_types int_ptr_types = {
6600         .types = {
6601                 PTR_TO_STACK,
6602                 PTR_TO_PACKET,
6603                 PTR_TO_PACKET_META,
6604                 PTR_TO_MAP_KEY,
6605                 PTR_TO_MAP_VALUE,
6606         },
6607 };
6608
6609 static const struct bpf_reg_types spin_lock_types = {
6610         .types = {
6611                 PTR_TO_MAP_VALUE,
6612                 PTR_TO_BTF_ID | MEM_ALLOC,
6613         }
6614 };
6615
6616 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
6617 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
6618 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
6619 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
6620 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
6621 static const struct bpf_reg_types btf_ptr_types = {
6622         .types = {
6623                 PTR_TO_BTF_ID,
6624                 PTR_TO_BTF_ID | PTR_TRUSTED,
6625                 PTR_TO_BTF_ID | MEM_RCU,
6626         },
6627 };
6628 static const struct bpf_reg_types percpu_btf_ptr_types = {
6629         .types = {
6630                 PTR_TO_BTF_ID | MEM_PERCPU,
6631                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
6632         }
6633 };
6634 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
6635 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
6636 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
6637 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
6638 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
6639 static const struct bpf_reg_types dynptr_types = {
6640         .types = {
6641                 PTR_TO_STACK,
6642                 CONST_PTR_TO_DYNPTR,
6643         }
6644 };
6645
6646 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
6647         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
6648         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
6649         [ARG_CONST_SIZE]                = &scalar_types,
6650         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
6651         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
6652         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
6653         [ARG_PTR_TO_CTX]                = &context_types,
6654         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
6655 #ifdef CONFIG_NET
6656         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
6657 #endif
6658         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
6659         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
6660         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
6661         [ARG_PTR_TO_MEM]                = &mem_types,
6662         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
6663         [ARG_PTR_TO_INT]                = &int_ptr_types,
6664         [ARG_PTR_TO_LONG]               = &int_ptr_types,
6665         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
6666         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
6667         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
6668         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
6669         [ARG_PTR_TO_TIMER]              = &timer_types,
6670         [ARG_PTR_TO_KPTR]               = &kptr_types,
6671         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
6672 };
6673
6674 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6675                           enum bpf_arg_type arg_type,
6676                           const u32 *arg_btf_id,
6677                           struct bpf_call_arg_meta *meta)
6678 {
6679         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6680         enum bpf_reg_type expected, type = reg->type;
6681         const struct bpf_reg_types *compatible;
6682         int i, j;
6683
6684         compatible = compatible_reg_types[base_type(arg_type)];
6685         if (!compatible) {
6686                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6687                 return -EFAULT;
6688         }
6689
6690         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6691          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6692          *
6693          * Same for MAYBE_NULL:
6694          *
6695          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6696          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6697          *
6698          * Therefore we fold these flags depending on the arg_type before comparison.
6699          */
6700         if (arg_type & MEM_RDONLY)
6701                 type &= ~MEM_RDONLY;
6702         if (arg_type & PTR_MAYBE_NULL)
6703                 type &= ~PTR_MAYBE_NULL;
6704
6705         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6706                 expected = compatible->types[i];
6707                 if (expected == NOT_INIT)
6708                         break;
6709
6710                 if (type == expected)
6711                         goto found;
6712         }
6713
6714         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6715         for (j = 0; j + 1 < i; j++)
6716                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6717         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6718         return -EACCES;
6719
6720 found:
6721         if (base_type(reg->type) != PTR_TO_BTF_ID)
6722                 return 0;
6723
6724         switch ((int)reg->type) {
6725         case PTR_TO_BTF_ID:
6726         case PTR_TO_BTF_ID | PTR_TRUSTED:
6727         case PTR_TO_BTF_ID | MEM_RCU:
6728         {
6729                 /* For bpf_sk_release, it needs to match against first member
6730                  * 'struct sock_common', hence make an exception for it. This
6731                  * allows bpf_sk_release to work for multiple socket types.
6732                  */
6733                 bool strict_type_match = arg_type_is_release(arg_type) &&
6734                                          meta->func_id != BPF_FUNC_sk_release;
6735
6736                 if (!arg_btf_id) {
6737                         if (!compatible->btf_id) {
6738                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6739                                 return -EFAULT;
6740                         }
6741                         arg_btf_id = compatible->btf_id;
6742                 }
6743
6744                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
6745                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6746                                 return -EACCES;
6747                 } else {
6748                         if (arg_btf_id == BPF_PTR_POISON) {
6749                                 verbose(env, "verifier internal error:");
6750                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6751                                         regno);
6752                                 return -EACCES;
6753                         }
6754
6755                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6756                                                   btf_vmlinux, *arg_btf_id,
6757                                                   strict_type_match)) {
6758                                 verbose(env, "R%d is of type %s but %s is expected\n",
6759                                         regno, kernel_type_name(reg->btf, reg->btf_id),
6760                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
6761                                 return -EACCES;
6762                         }
6763                 }
6764                 break;
6765         }
6766         case PTR_TO_BTF_ID | MEM_ALLOC:
6767                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6768                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6769                         return -EFAULT;
6770                 }
6771                 /* Handled by helper specific checks */
6772                 break;
6773         case PTR_TO_BTF_ID | MEM_PERCPU:
6774         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
6775                 /* Handled by helper specific checks */
6776                 break;
6777         default:
6778                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
6779                 return -EFAULT;
6780         }
6781         return 0;
6782 }
6783
6784 static struct btf_field *
6785 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
6786 {
6787         struct btf_field *field;
6788         struct btf_record *rec;
6789
6790         rec = reg_btf_record(reg);
6791         if (!rec)
6792                 return NULL;
6793
6794         field = btf_record_find(rec, off, fields);
6795         if (!field)
6796                 return NULL;
6797
6798         return field;
6799 }
6800
6801 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6802                            const struct bpf_reg_state *reg, int regno,
6803                            enum bpf_arg_type arg_type)
6804 {
6805         u32 type = reg->type;
6806
6807         /* When referenced register is passed to release function, its fixed
6808          * offset must be 0.
6809          *
6810          * We will check arg_type_is_release reg has ref_obj_id when storing
6811          * meta->release_regno.
6812          */
6813         if (arg_type_is_release(arg_type)) {
6814                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
6815                  * may not directly point to the object being released, but to
6816                  * dynptr pointing to such object, which might be at some offset
6817                  * on the stack. In that case, we simply to fallback to the
6818                  * default handling.
6819                  */
6820                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
6821                         return 0;
6822
6823                 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
6824                         if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
6825                                 return __check_ptr_off_reg(env, reg, regno, true);
6826
6827                         verbose(env, "R%d must have zero offset when passed to release func\n",
6828                                 regno);
6829                         verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
6830                                 kernel_type_name(reg->btf, reg->btf_id), reg->off);
6831                         return -EINVAL;
6832                 }
6833
6834                 /* Doing check_ptr_off_reg check for the offset will catch this
6835                  * because fixed_off_ok is false, but checking here allows us
6836                  * to give the user a better error message.
6837                  */
6838                 if (reg->off) {
6839                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
6840                                 regno);
6841                         return -EINVAL;
6842                 }
6843                 return __check_ptr_off_reg(env, reg, regno, false);
6844         }
6845
6846         switch (type) {
6847         /* Pointer types where both fixed and variable offset is explicitly allowed: */
6848         case PTR_TO_STACK:
6849         case PTR_TO_PACKET:
6850         case PTR_TO_PACKET_META:
6851         case PTR_TO_MAP_KEY:
6852         case PTR_TO_MAP_VALUE:
6853         case PTR_TO_MEM:
6854         case PTR_TO_MEM | MEM_RDONLY:
6855         case PTR_TO_MEM | MEM_RINGBUF:
6856         case PTR_TO_BUF:
6857         case PTR_TO_BUF | MEM_RDONLY:
6858         case SCALAR_VALUE:
6859                 return 0;
6860         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6861          * fixed offset.
6862          */
6863         case PTR_TO_BTF_ID:
6864         case PTR_TO_BTF_ID | MEM_ALLOC:
6865         case PTR_TO_BTF_ID | PTR_TRUSTED:
6866         case PTR_TO_BTF_ID | MEM_RCU:
6867         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
6868                 /* When referenced PTR_TO_BTF_ID is passed to release function,
6869                  * its fixed offset must be 0. In the other cases, fixed offset
6870                  * can be non-zero. This was already checked above. So pass
6871                  * fixed_off_ok as true to allow fixed offset for all other
6872                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
6873                  * still need to do checks instead of returning.
6874                  */
6875                 return __check_ptr_off_reg(env, reg, regno, true);
6876         default:
6877                 return __check_ptr_off_reg(env, reg, regno, false);
6878         }
6879 }
6880
6881 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
6882                                                 const struct bpf_func_proto *fn,
6883                                                 struct bpf_reg_state *regs)
6884 {
6885         struct bpf_reg_state *state = NULL;
6886         int i;
6887
6888         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
6889                 if (arg_type_is_dynptr(fn->arg_type[i])) {
6890                         if (state) {
6891                                 verbose(env, "verifier internal error: multiple dynptr args\n");
6892                                 return NULL;
6893                         }
6894                         state = &regs[BPF_REG_1 + i];
6895                 }
6896
6897         if (!state)
6898                 verbose(env, "verifier internal error: no dynptr arg found\n");
6899
6900         return state;
6901 }
6902
6903 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6904 {
6905         struct bpf_func_state *state = func(env, reg);
6906         int spi;
6907
6908         if (reg->type == CONST_PTR_TO_DYNPTR)
6909                 return reg->id;
6910         spi = dynptr_get_spi(env, reg);
6911         if (spi < 0)
6912                 return spi;
6913         return state->stack[spi].spilled_ptr.id;
6914 }
6915
6916 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6917 {
6918         struct bpf_func_state *state = func(env, reg);
6919         int spi;
6920
6921         if (reg->type == CONST_PTR_TO_DYNPTR)
6922                 return reg->ref_obj_id;
6923         spi = dynptr_get_spi(env, reg);
6924         if (spi < 0)
6925                 return spi;
6926         return state->stack[spi].spilled_ptr.ref_obj_id;
6927 }
6928
6929 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
6930                                             struct bpf_reg_state *reg)
6931 {
6932         struct bpf_func_state *state = func(env, reg);
6933         int spi;
6934
6935         if (reg->type == CONST_PTR_TO_DYNPTR)
6936                 return reg->dynptr.type;
6937
6938         spi = __get_spi(reg->off);
6939         if (spi < 0) {
6940                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
6941                 return BPF_DYNPTR_TYPE_INVALID;
6942         }
6943
6944         return state->stack[spi].spilled_ptr.dynptr.type;
6945 }
6946
6947 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6948                           struct bpf_call_arg_meta *meta,
6949                           const struct bpf_func_proto *fn,
6950                           int insn_idx)
6951 {
6952         u32 regno = BPF_REG_1 + arg;
6953         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6954         enum bpf_arg_type arg_type = fn->arg_type[arg];
6955         enum bpf_reg_type type = reg->type;
6956         u32 *arg_btf_id = NULL;
6957         int err = 0;
6958
6959         if (arg_type == ARG_DONTCARE)
6960                 return 0;
6961
6962         err = check_reg_arg(env, regno, SRC_OP);
6963         if (err)
6964                 return err;
6965
6966         if (arg_type == ARG_ANYTHING) {
6967                 if (is_pointer_value(env, regno)) {
6968                         verbose(env, "R%d leaks addr into helper function\n",
6969                                 regno);
6970                         return -EACCES;
6971                 }
6972                 return 0;
6973         }
6974
6975         if (type_is_pkt_pointer(type) &&
6976             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6977                 verbose(env, "helper access to the packet is not allowed\n");
6978                 return -EACCES;
6979         }
6980
6981         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6982                 err = resolve_map_arg_type(env, meta, &arg_type);
6983                 if (err)
6984                         return err;
6985         }
6986
6987         if (register_is_null(reg) && type_may_be_null(arg_type))
6988                 /* A NULL register has a SCALAR_VALUE type, so skip
6989                  * type checking.
6990                  */
6991                 goto skip_type_check;
6992
6993         /* arg_btf_id and arg_size are in a union. */
6994         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6995             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6996                 arg_btf_id = fn->arg_btf_id[arg];
6997
6998         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6999         if (err)
7000                 return err;
7001
7002         err = check_func_arg_reg_off(env, reg, regno, arg_type);
7003         if (err)
7004                 return err;
7005
7006 skip_type_check:
7007         if (arg_type_is_release(arg_type)) {
7008                 if (arg_type_is_dynptr(arg_type)) {
7009                         struct bpf_func_state *state = func(env, reg);
7010                         int spi;
7011
7012                         /* Only dynptr created on stack can be released, thus
7013                          * the get_spi and stack state checks for spilled_ptr
7014                          * should only be done before process_dynptr_func for
7015                          * PTR_TO_STACK.
7016                          */
7017                         if (reg->type == PTR_TO_STACK) {
7018                                 spi = dynptr_get_spi(env, reg);
7019                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7020                                         verbose(env, "arg %d is an unacquired reference\n", regno);
7021                                         return -EINVAL;
7022                                 }
7023                         } else {
7024                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
7025                                 return -EINVAL;
7026                         }
7027                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
7028                         verbose(env, "R%d must be referenced when passed to release function\n",
7029                                 regno);
7030                         return -EINVAL;
7031                 }
7032                 if (meta->release_regno) {
7033                         verbose(env, "verifier internal error: more than one release argument\n");
7034                         return -EFAULT;
7035                 }
7036                 meta->release_regno = regno;
7037         }
7038
7039         if (reg->ref_obj_id) {
7040                 if (meta->ref_obj_id) {
7041                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7042                                 regno, reg->ref_obj_id,
7043                                 meta->ref_obj_id);
7044                         return -EFAULT;
7045                 }
7046                 meta->ref_obj_id = reg->ref_obj_id;
7047         }
7048
7049         switch (base_type(arg_type)) {
7050         case ARG_CONST_MAP_PTR:
7051                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7052                 if (meta->map_ptr) {
7053                         /* Use map_uid (which is unique id of inner map) to reject:
7054                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7055                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7056                          * if (inner_map1 && inner_map2) {
7057                          *     timer = bpf_map_lookup_elem(inner_map1);
7058                          *     if (timer)
7059                          *         // mismatch would have been allowed
7060                          *         bpf_timer_init(timer, inner_map2);
7061                          * }
7062                          *
7063                          * Comparing map_ptr is enough to distinguish normal and outer maps.
7064                          */
7065                         if (meta->map_ptr != reg->map_ptr ||
7066                             meta->map_uid != reg->map_uid) {
7067                                 verbose(env,
7068                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7069                                         meta->map_uid, reg->map_uid);
7070                                 return -EINVAL;
7071                         }
7072                 }
7073                 meta->map_ptr = reg->map_ptr;
7074                 meta->map_uid = reg->map_uid;
7075                 break;
7076         case ARG_PTR_TO_MAP_KEY:
7077                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
7078                  * check that [key, key + map->key_size) are within
7079                  * stack limits and initialized
7080                  */
7081                 if (!meta->map_ptr) {
7082                         /* in function declaration map_ptr must come before
7083                          * map_key, so that it's verified and known before
7084                          * we have to check map_key here. Otherwise it means
7085                          * that kernel subsystem misconfigured verifier
7086                          */
7087                         verbose(env, "invalid map_ptr to access map->key\n");
7088                         return -EACCES;
7089                 }
7090                 err = check_helper_mem_access(env, regno,
7091                                               meta->map_ptr->key_size, false,
7092                                               NULL);
7093                 break;
7094         case ARG_PTR_TO_MAP_VALUE:
7095                 if (type_may_be_null(arg_type) && register_is_null(reg))
7096                         return 0;
7097
7098                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
7099                  * check [value, value + map->value_size) validity
7100                  */
7101                 if (!meta->map_ptr) {
7102                         /* kernel subsystem misconfigured verifier */
7103                         verbose(env, "invalid map_ptr to access map->value\n");
7104                         return -EACCES;
7105                 }
7106                 meta->raw_mode = arg_type & MEM_UNINIT;
7107                 err = check_helper_mem_access(env, regno,
7108                                               meta->map_ptr->value_size, false,
7109                                               meta);
7110                 break;
7111         case ARG_PTR_TO_PERCPU_BTF_ID:
7112                 if (!reg->btf_id) {
7113                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7114                         return -EACCES;
7115                 }
7116                 meta->ret_btf = reg->btf;
7117                 meta->ret_btf_id = reg->btf_id;
7118                 break;
7119         case ARG_PTR_TO_SPIN_LOCK:
7120                 if (in_rbtree_lock_required_cb(env)) {
7121                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7122                         return -EACCES;
7123                 }
7124                 if (meta->func_id == BPF_FUNC_spin_lock) {
7125                         err = process_spin_lock(env, regno, true);
7126                         if (err)
7127                                 return err;
7128                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
7129                         err = process_spin_lock(env, regno, false);
7130                         if (err)
7131                                 return err;
7132                 } else {
7133                         verbose(env, "verifier internal error\n");
7134                         return -EFAULT;
7135                 }
7136                 break;
7137         case ARG_PTR_TO_TIMER:
7138                 err = process_timer_func(env, regno, meta);
7139                 if (err)
7140                         return err;
7141                 break;
7142         case ARG_PTR_TO_FUNC:
7143                 meta->subprogno = reg->subprogno;
7144                 break;
7145         case ARG_PTR_TO_MEM:
7146                 /* The access to this pointer is only checked when we hit the
7147                  * next is_mem_size argument below.
7148                  */
7149                 meta->raw_mode = arg_type & MEM_UNINIT;
7150                 if (arg_type & MEM_FIXED_SIZE) {
7151                         err = check_helper_mem_access(env, regno,
7152                                                       fn->arg_size[arg], false,
7153                                                       meta);
7154                 }
7155                 break;
7156         case ARG_CONST_SIZE:
7157                 err = check_mem_size_reg(env, reg, regno, false, meta);
7158                 break;
7159         case ARG_CONST_SIZE_OR_ZERO:
7160                 err = check_mem_size_reg(env, reg, regno, true, meta);
7161                 break;
7162         case ARG_PTR_TO_DYNPTR:
7163                 err = process_dynptr_func(env, regno, insn_idx, arg_type);
7164                 if (err)
7165                         return err;
7166                 break;
7167         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
7168                 if (!tnum_is_const(reg->var_off)) {
7169                         verbose(env, "R%d is not a known constant'\n",
7170                                 regno);
7171                         return -EACCES;
7172                 }
7173                 meta->mem_size = reg->var_off.value;
7174                 err = mark_chain_precision(env, regno);
7175                 if (err)
7176                         return err;
7177                 break;
7178         case ARG_PTR_TO_INT:
7179         case ARG_PTR_TO_LONG:
7180         {
7181                 int size = int_ptr_type_to_size(arg_type);
7182
7183                 err = check_helper_mem_access(env, regno, size, false, meta);
7184                 if (err)
7185                         return err;
7186                 err = check_ptr_alignment(env, reg, 0, size, true);
7187                 break;
7188         }
7189         case ARG_PTR_TO_CONST_STR:
7190         {
7191                 struct bpf_map *map = reg->map_ptr;
7192                 int map_off;
7193                 u64 map_addr;
7194                 char *str_ptr;
7195
7196                 if (!bpf_map_is_rdonly(map)) {
7197                         verbose(env, "R%d does not point to a readonly map'\n", regno);
7198                         return -EACCES;
7199                 }
7200
7201                 if (!tnum_is_const(reg->var_off)) {
7202                         verbose(env, "R%d is not a constant address'\n", regno);
7203                         return -EACCES;
7204                 }
7205
7206                 if (!map->ops->map_direct_value_addr) {
7207                         verbose(env, "no direct value access support for this map type\n");
7208                         return -EACCES;
7209                 }
7210
7211                 err = check_map_access(env, regno, reg->off,
7212                                        map->value_size - reg->off, false,
7213                                        ACCESS_HELPER);
7214                 if (err)
7215                         return err;
7216
7217                 map_off = reg->off + reg->var_off.value;
7218                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7219                 if (err) {
7220                         verbose(env, "direct value access on string failed\n");
7221                         return err;
7222                 }
7223
7224                 str_ptr = (char *)(long)(map_addr);
7225                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7226                         verbose(env, "string is not zero-terminated\n");
7227                         return -EINVAL;
7228                 }
7229                 break;
7230         }
7231         case ARG_PTR_TO_KPTR:
7232                 err = process_kptr_func(env, regno, meta);
7233                 if (err)
7234                         return err;
7235                 break;
7236         }
7237
7238         return err;
7239 }
7240
7241 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7242 {
7243         enum bpf_attach_type eatype = env->prog->expected_attach_type;
7244         enum bpf_prog_type type = resolve_prog_type(env->prog);
7245
7246         if (func_id != BPF_FUNC_map_update_elem)
7247                 return false;
7248
7249         /* It's not possible to get access to a locked struct sock in these
7250          * contexts, so updating is safe.
7251          */
7252         switch (type) {
7253         case BPF_PROG_TYPE_TRACING:
7254                 if (eatype == BPF_TRACE_ITER)
7255                         return true;
7256                 break;
7257         case BPF_PROG_TYPE_SOCKET_FILTER:
7258         case BPF_PROG_TYPE_SCHED_CLS:
7259         case BPF_PROG_TYPE_SCHED_ACT:
7260         case BPF_PROG_TYPE_XDP:
7261         case BPF_PROG_TYPE_SK_REUSEPORT:
7262         case BPF_PROG_TYPE_FLOW_DISSECTOR:
7263         case BPF_PROG_TYPE_SK_LOOKUP:
7264                 return true;
7265         default:
7266                 break;
7267         }
7268
7269         verbose(env, "cannot update sockmap in this context\n");
7270         return false;
7271 }
7272
7273 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7274 {
7275         return env->prog->jit_requested &&
7276                bpf_jit_supports_subprog_tailcalls();
7277 }
7278
7279 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7280                                         struct bpf_map *map, int func_id)
7281 {
7282         if (!map)
7283                 return 0;
7284
7285         /* We need a two way check, first is from map perspective ... */
7286         switch (map->map_type) {
7287         case BPF_MAP_TYPE_PROG_ARRAY:
7288                 if (func_id != BPF_FUNC_tail_call)
7289                         goto error;
7290                 break;
7291         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7292                 if (func_id != BPF_FUNC_perf_event_read &&
7293                     func_id != BPF_FUNC_perf_event_output &&
7294                     func_id != BPF_FUNC_skb_output &&
7295                     func_id != BPF_FUNC_perf_event_read_value &&
7296                     func_id != BPF_FUNC_xdp_output)
7297                         goto error;
7298                 break;
7299         case BPF_MAP_TYPE_RINGBUF:
7300                 if (func_id != BPF_FUNC_ringbuf_output &&
7301                     func_id != BPF_FUNC_ringbuf_reserve &&
7302                     func_id != BPF_FUNC_ringbuf_query &&
7303                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7304                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7305                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
7306                         goto error;
7307                 break;
7308         case BPF_MAP_TYPE_USER_RINGBUF:
7309                 if (func_id != BPF_FUNC_user_ringbuf_drain)
7310                         goto error;
7311                 break;
7312         case BPF_MAP_TYPE_STACK_TRACE:
7313                 if (func_id != BPF_FUNC_get_stackid)
7314                         goto error;
7315                 break;
7316         case BPF_MAP_TYPE_CGROUP_ARRAY:
7317                 if (func_id != BPF_FUNC_skb_under_cgroup &&
7318                     func_id != BPF_FUNC_current_task_under_cgroup)
7319                         goto error;
7320                 break;
7321         case BPF_MAP_TYPE_CGROUP_STORAGE:
7322         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7323                 if (func_id != BPF_FUNC_get_local_storage)
7324                         goto error;
7325                 break;
7326         case BPF_MAP_TYPE_DEVMAP:
7327         case BPF_MAP_TYPE_DEVMAP_HASH:
7328                 if (func_id != BPF_FUNC_redirect_map &&
7329                     func_id != BPF_FUNC_map_lookup_elem)
7330                         goto error;
7331                 break;
7332         /* Restrict bpf side of cpumap and xskmap, open when use-cases
7333          * appear.
7334          */
7335         case BPF_MAP_TYPE_CPUMAP:
7336                 if (func_id != BPF_FUNC_redirect_map)
7337                         goto error;
7338                 break;
7339         case BPF_MAP_TYPE_XSKMAP:
7340                 if (func_id != BPF_FUNC_redirect_map &&
7341                     func_id != BPF_FUNC_map_lookup_elem)
7342                         goto error;
7343                 break;
7344         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7345         case BPF_MAP_TYPE_HASH_OF_MAPS:
7346                 if (func_id != BPF_FUNC_map_lookup_elem)
7347                         goto error;
7348                 break;
7349         case BPF_MAP_TYPE_SOCKMAP:
7350                 if (func_id != BPF_FUNC_sk_redirect_map &&
7351                     func_id != BPF_FUNC_sock_map_update &&
7352                     func_id != BPF_FUNC_map_delete_elem &&
7353                     func_id != BPF_FUNC_msg_redirect_map &&
7354                     func_id != BPF_FUNC_sk_select_reuseport &&
7355                     func_id != BPF_FUNC_map_lookup_elem &&
7356                     !may_update_sockmap(env, func_id))
7357                         goto error;
7358                 break;
7359         case BPF_MAP_TYPE_SOCKHASH:
7360                 if (func_id != BPF_FUNC_sk_redirect_hash &&
7361                     func_id != BPF_FUNC_sock_hash_update &&
7362                     func_id != BPF_FUNC_map_delete_elem &&
7363                     func_id != BPF_FUNC_msg_redirect_hash &&
7364                     func_id != BPF_FUNC_sk_select_reuseport &&
7365                     func_id != BPF_FUNC_map_lookup_elem &&
7366                     !may_update_sockmap(env, func_id))
7367                         goto error;
7368                 break;
7369         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7370                 if (func_id != BPF_FUNC_sk_select_reuseport)
7371                         goto error;
7372                 break;
7373         case BPF_MAP_TYPE_QUEUE:
7374         case BPF_MAP_TYPE_STACK:
7375                 if (func_id != BPF_FUNC_map_peek_elem &&
7376                     func_id != BPF_FUNC_map_pop_elem &&
7377                     func_id != BPF_FUNC_map_push_elem)
7378                         goto error;
7379                 break;
7380         case BPF_MAP_TYPE_SK_STORAGE:
7381                 if (func_id != BPF_FUNC_sk_storage_get &&
7382                     func_id != BPF_FUNC_sk_storage_delete &&
7383                     func_id != BPF_FUNC_kptr_xchg)
7384                         goto error;
7385                 break;
7386         case BPF_MAP_TYPE_INODE_STORAGE:
7387                 if (func_id != BPF_FUNC_inode_storage_get &&
7388                     func_id != BPF_FUNC_inode_storage_delete &&
7389                     func_id != BPF_FUNC_kptr_xchg)
7390                         goto error;
7391                 break;
7392         case BPF_MAP_TYPE_TASK_STORAGE:
7393                 if (func_id != BPF_FUNC_task_storage_get &&
7394                     func_id != BPF_FUNC_task_storage_delete &&
7395                     func_id != BPF_FUNC_kptr_xchg)
7396                         goto error;
7397                 break;
7398         case BPF_MAP_TYPE_CGRP_STORAGE:
7399                 if (func_id != BPF_FUNC_cgrp_storage_get &&
7400                     func_id != BPF_FUNC_cgrp_storage_delete &&
7401                     func_id != BPF_FUNC_kptr_xchg)
7402                         goto error;
7403                 break;
7404         case BPF_MAP_TYPE_BLOOM_FILTER:
7405                 if (func_id != BPF_FUNC_map_peek_elem &&
7406                     func_id != BPF_FUNC_map_push_elem)
7407                         goto error;
7408                 break;
7409         default:
7410                 break;
7411         }
7412
7413         /* ... and second from the function itself. */
7414         switch (func_id) {
7415         case BPF_FUNC_tail_call:
7416                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7417                         goto error;
7418                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7419                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7420                         return -EINVAL;
7421                 }
7422                 break;
7423         case BPF_FUNC_perf_event_read:
7424         case BPF_FUNC_perf_event_output:
7425         case BPF_FUNC_perf_event_read_value:
7426         case BPF_FUNC_skb_output:
7427         case BPF_FUNC_xdp_output:
7428                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7429                         goto error;
7430                 break;
7431         case BPF_FUNC_ringbuf_output:
7432         case BPF_FUNC_ringbuf_reserve:
7433         case BPF_FUNC_ringbuf_query:
7434         case BPF_FUNC_ringbuf_reserve_dynptr:
7435         case BPF_FUNC_ringbuf_submit_dynptr:
7436         case BPF_FUNC_ringbuf_discard_dynptr:
7437                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7438                         goto error;
7439                 break;
7440         case BPF_FUNC_user_ringbuf_drain:
7441                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7442                         goto error;
7443                 break;
7444         case BPF_FUNC_get_stackid:
7445                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7446                         goto error;
7447                 break;
7448         case BPF_FUNC_current_task_under_cgroup:
7449         case BPF_FUNC_skb_under_cgroup:
7450                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7451                         goto error;
7452                 break;
7453         case BPF_FUNC_redirect_map:
7454                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7455                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7456                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
7457                     map->map_type != BPF_MAP_TYPE_XSKMAP)
7458                         goto error;
7459                 break;
7460         case BPF_FUNC_sk_redirect_map:
7461         case BPF_FUNC_msg_redirect_map:
7462         case BPF_FUNC_sock_map_update:
7463                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7464                         goto error;
7465                 break;
7466         case BPF_FUNC_sk_redirect_hash:
7467         case BPF_FUNC_msg_redirect_hash:
7468         case BPF_FUNC_sock_hash_update:
7469                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7470                         goto error;
7471                 break;
7472         case BPF_FUNC_get_local_storage:
7473                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7474                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7475                         goto error;
7476                 break;
7477         case BPF_FUNC_sk_select_reuseport:
7478                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7479                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7480                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
7481                         goto error;
7482                 break;
7483         case BPF_FUNC_map_pop_elem:
7484                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7485                     map->map_type != BPF_MAP_TYPE_STACK)
7486                         goto error;
7487                 break;
7488         case BPF_FUNC_map_peek_elem:
7489         case BPF_FUNC_map_push_elem:
7490                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7491                     map->map_type != BPF_MAP_TYPE_STACK &&
7492                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7493                         goto error;
7494                 break;
7495         case BPF_FUNC_map_lookup_percpu_elem:
7496                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7497                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7498                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7499                         goto error;
7500                 break;
7501         case BPF_FUNC_sk_storage_get:
7502         case BPF_FUNC_sk_storage_delete:
7503                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7504                         goto error;
7505                 break;
7506         case BPF_FUNC_inode_storage_get:
7507         case BPF_FUNC_inode_storage_delete:
7508                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7509                         goto error;
7510                 break;
7511         case BPF_FUNC_task_storage_get:
7512         case BPF_FUNC_task_storage_delete:
7513                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7514                         goto error;
7515                 break;
7516         case BPF_FUNC_cgrp_storage_get:
7517         case BPF_FUNC_cgrp_storage_delete:
7518                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7519                         goto error;
7520                 break;
7521         default:
7522                 break;
7523         }
7524
7525         return 0;
7526 error:
7527         verbose(env, "cannot pass map_type %d into func %s#%d\n",
7528                 map->map_type, func_id_name(func_id), func_id);
7529         return -EINVAL;
7530 }
7531
7532 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7533 {
7534         int count = 0;
7535
7536         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7537                 count++;
7538         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7539                 count++;
7540         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7541                 count++;
7542         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7543                 count++;
7544         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7545                 count++;
7546
7547         /* We only support one arg being in raw mode at the moment,
7548          * which is sufficient for the helper functions we have
7549          * right now.
7550          */
7551         return count <= 1;
7552 }
7553
7554 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7555 {
7556         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7557         bool has_size = fn->arg_size[arg] != 0;
7558         bool is_next_size = false;
7559
7560         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7561                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
7562
7563         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
7564                 return is_next_size;
7565
7566         return has_size == is_next_size || is_next_size == is_fixed;
7567 }
7568
7569 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
7570 {
7571         /* bpf_xxx(..., buf, len) call will access 'len'
7572          * bytes from memory 'buf'. Both arg types need
7573          * to be paired, so make sure there's no buggy
7574          * helper function specification.
7575          */
7576         if (arg_type_is_mem_size(fn->arg1_type) ||
7577             check_args_pair_invalid(fn, 0) ||
7578             check_args_pair_invalid(fn, 1) ||
7579             check_args_pair_invalid(fn, 2) ||
7580             check_args_pair_invalid(fn, 3) ||
7581             check_args_pair_invalid(fn, 4))
7582                 return false;
7583
7584         return true;
7585 }
7586
7587 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
7588 {
7589         int i;
7590
7591         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
7592                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
7593                         return !!fn->arg_btf_id[i];
7594                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
7595                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
7596                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
7597                     /* arg_btf_id and arg_size are in a union. */
7598                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
7599                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
7600                         return false;
7601         }
7602
7603         return true;
7604 }
7605
7606 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
7607 {
7608         return check_raw_mode_ok(fn) &&
7609                check_arg_pair_ok(fn) &&
7610                check_btf_id_ok(fn) ? 0 : -EINVAL;
7611 }
7612
7613 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
7614  * are now invalid, so turn them into unknown SCALAR_VALUE.
7615  *
7616  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
7617  * since these slices point to packet data.
7618  */
7619 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
7620 {
7621         struct bpf_func_state *state;
7622         struct bpf_reg_state *reg;
7623
7624         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7625                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
7626                         mark_reg_invalid(env, reg);
7627         }));
7628 }
7629
7630 enum {
7631         AT_PKT_END = -1,
7632         BEYOND_PKT_END = -2,
7633 };
7634
7635 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
7636 {
7637         struct bpf_func_state *state = vstate->frame[vstate->curframe];
7638         struct bpf_reg_state *reg = &state->regs[regn];
7639
7640         if (reg->type != PTR_TO_PACKET)
7641                 /* PTR_TO_PACKET_META is not supported yet */
7642                 return;
7643
7644         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
7645          * How far beyond pkt_end it goes is unknown.
7646          * if (!range_open) it's the case of pkt >= pkt_end
7647          * if (range_open) it's the case of pkt > pkt_end
7648          * hence this pointer is at least 1 byte bigger than pkt_end
7649          */
7650         if (range_open)
7651                 reg->range = BEYOND_PKT_END;
7652         else
7653                 reg->range = AT_PKT_END;
7654 }
7655
7656 /* The pointer with the specified id has released its reference to kernel
7657  * resources. Identify all copies of the same pointer and clear the reference.
7658  */
7659 static int release_reference(struct bpf_verifier_env *env,
7660                              int ref_obj_id)
7661 {
7662         struct bpf_func_state *state;
7663         struct bpf_reg_state *reg;
7664         int err;
7665
7666         err = release_reference_state(cur_func(env), ref_obj_id);
7667         if (err)
7668                 return err;
7669
7670         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
7671                 if (reg->ref_obj_id == ref_obj_id)
7672                         mark_reg_invalid(env, reg);
7673         }));
7674
7675         return 0;
7676 }
7677
7678 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
7679 {
7680         struct bpf_func_state *unused;
7681         struct bpf_reg_state *reg;
7682
7683         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
7684                 if (type_is_non_owning_ref(reg->type))
7685                         mark_reg_invalid(env, reg);
7686         }));
7687 }
7688
7689 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
7690                                     struct bpf_reg_state *regs)
7691 {
7692         int i;
7693
7694         /* after the call registers r0 - r5 were scratched */
7695         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7696                 mark_reg_not_init(env, regs, caller_saved[i]);
7697                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7698         }
7699 }
7700
7701 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
7702                                    struct bpf_func_state *caller,
7703                                    struct bpf_func_state *callee,
7704                                    int insn_idx);
7705
7706 static int set_callee_state(struct bpf_verifier_env *env,
7707                             struct bpf_func_state *caller,
7708                             struct bpf_func_state *callee, int insn_idx);
7709
7710 static bool is_callback_calling_kfunc(u32 btf_id);
7711
7712 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7713                              int *insn_idx, int subprog,
7714                              set_callee_state_fn set_callee_state_cb)
7715 {
7716         struct bpf_verifier_state *state = env->cur_state;
7717         struct bpf_func_info_aux *func_info_aux;
7718         struct bpf_func_state *caller, *callee;
7719         int err;
7720         bool is_global = false;
7721
7722         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
7723                 verbose(env, "the call stack of %d frames is too deep\n",
7724                         state->curframe + 2);
7725                 return -E2BIG;
7726         }
7727
7728         caller = state->frame[state->curframe];
7729         if (state->frame[state->curframe + 1]) {
7730                 verbose(env, "verifier bug. Frame %d already allocated\n",
7731                         state->curframe + 1);
7732                 return -EFAULT;
7733         }
7734
7735         func_info_aux = env->prog->aux->func_info_aux;
7736         if (func_info_aux)
7737                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
7738         err = btf_check_subprog_call(env, subprog, caller->regs);
7739         if (err == -EFAULT)
7740                 return err;
7741         if (is_global) {
7742                 if (err) {
7743                         verbose(env, "Caller passes invalid args into func#%d\n",
7744                                 subprog);
7745                         return err;
7746                 } else {
7747                         if (env->log.level & BPF_LOG_LEVEL)
7748                                 verbose(env,
7749                                         "Func#%d is global and valid. Skipping.\n",
7750                                         subprog);
7751                         clear_caller_saved_regs(env, caller->regs);
7752
7753                         /* All global functions return a 64-bit SCALAR_VALUE */
7754                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
7755                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7756
7757                         /* continue with next insn after call */
7758                         return 0;
7759                 }
7760         }
7761
7762         /* set_callee_state is used for direct subprog calls, but we are
7763          * interested in validating only BPF helpers that can call subprogs as
7764          * callbacks
7765          */
7766         if (set_callee_state_cb != set_callee_state) {
7767                 if (bpf_pseudo_kfunc_call(insn) &&
7768                     !is_callback_calling_kfunc(insn->imm)) {
7769                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
7770                                 func_id_name(insn->imm), insn->imm);
7771                         return -EFAULT;
7772                 } else if (!bpf_pseudo_kfunc_call(insn) &&
7773                            !is_callback_calling_function(insn->imm)) { /* helper */
7774                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
7775                                 func_id_name(insn->imm), insn->imm);
7776                         return -EFAULT;
7777                 }
7778         }
7779
7780         if (insn->code == (BPF_JMP | BPF_CALL) &&
7781             insn->src_reg == 0 &&
7782             insn->imm == BPF_FUNC_timer_set_callback) {
7783                 struct bpf_verifier_state *async_cb;
7784
7785                 /* there is no real recursion here. timer callbacks are async */
7786                 env->subprog_info[subprog].is_async_cb = true;
7787                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
7788                                          *insn_idx, subprog);
7789                 if (!async_cb)
7790                         return -EFAULT;
7791                 callee = async_cb->frame[0];
7792                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
7793
7794                 /* Convert bpf_timer_set_callback() args into timer callback args */
7795                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
7796                 if (err)
7797                         return err;
7798
7799                 clear_caller_saved_regs(env, caller->regs);
7800                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
7801                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7802                 /* continue with next insn after call */
7803                 return 0;
7804         }
7805
7806         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
7807         if (!callee)
7808                 return -ENOMEM;
7809         state->frame[state->curframe + 1] = callee;
7810
7811         /* callee cannot access r0, r6 - r9 for reading and has to write
7812          * into its own stack before reading from it.
7813          * callee can read/write into caller's stack
7814          */
7815         init_func_state(env, callee,
7816                         /* remember the callsite, it will be used by bpf_exit */
7817                         *insn_idx /* callsite */,
7818                         state->curframe + 1 /* frameno within this callchain */,
7819                         subprog /* subprog number within this prog */);
7820
7821         /* Transfer references to the callee */
7822         err = copy_reference_state(callee, caller);
7823         if (err)
7824                 goto err_out;
7825
7826         err = set_callee_state_cb(env, caller, callee, *insn_idx);
7827         if (err)
7828                 goto err_out;
7829
7830         clear_caller_saved_regs(env, caller->regs);
7831
7832         /* only increment it after check_reg_arg() finished */
7833         state->curframe++;
7834
7835         /* and go analyze first insn of the callee */
7836         *insn_idx = env->subprog_info[subprog].start - 1;
7837
7838         if (env->log.level & BPF_LOG_LEVEL) {
7839                 verbose(env, "caller:\n");
7840                 print_verifier_state(env, caller, true);
7841                 verbose(env, "callee:\n");
7842                 print_verifier_state(env, callee, true);
7843         }
7844         return 0;
7845
7846 err_out:
7847         free_func_state(callee);
7848         state->frame[state->curframe + 1] = NULL;
7849         return err;
7850 }
7851
7852 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7853                                    struct bpf_func_state *caller,
7854                                    struct bpf_func_state *callee)
7855 {
7856         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7857          *      void *callback_ctx, u64 flags);
7858          * callback_fn(struct bpf_map *map, void *key, void *value,
7859          *      void *callback_ctx);
7860          */
7861         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7862
7863         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7864         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7865         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7866
7867         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7868         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7869         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7870
7871         /* pointer to stack or null */
7872         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7873
7874         /* unused */
7875         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7876         return 0;
7877 }
7878
7879 static int set_callee_state(struct bpf_verifier_env *env,
7880                             struct bpf_func_state *caller,
7881                             struct bpf_func_state *callee, int insn_idx)
7882 {
7883         int i;
7884
7885         /* copy r1 - r5 args that callee can access.  The copy includes parent
7886          * pointers, which connects us up to the liveness chain
7887          */
7888         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7889                 callee->regs[i] = caller->regs[i];
7890         return 0;
7891 }
7892
7893 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7894                            int *insn_idx)
7895 {
7896         int subprog, target_insn;
7897
7898         target_insn = *insn_idx + insn->imm + 1;
7899         subprog = find_subprog(env, target_insn);
7900         if (subprog < 0) {
7901                 verbose(env, "verifier bug. No program starts at insn %d\n",
7902                         target_insn);
7903                 return -EFAULT;
7904         }
7905
7906         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7907 }
7908
7909 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7910                                        struct bpf_func_state *caller,
7911                                        struct bpf_func_state *callee,
7912                                        int insn_idx)
7913 {
7914         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7915         struct bpf_map *map;
7916         int err;
7917
7918         if (bpf_map_ptr_poisoned(insn_aux)) {
7919                 verbose(env, "tail_call abusing map_ptr\n");
7920                 return -EINVAL;
7921         }
7922
7923         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7924         if (!map->ops->map_set_for_each_callback_args ||
7925             !map->ops->map_for_each_callback) {
7926                 verbose(env, "callback function not allowed for map\n");
7927                 return -ENOTSUPP;
7928         }
7929
7930         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7931         if (err)
7932                 return err;
7933
7934         callee->in_callback_fn = true;
7935         callee->callback_ret_range = tnum_range(0, 1);
7936         return 0;
7937 }
7938
7939 static int set_loop_callback_state(struct bpf_verifier_env *env,
7940                                    struct bpf_func_state *caller,
7941                                    struct bpf_func_state *callee,
7942                                    int insn_idx)
7943 {
7944         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7945          *          u64 flags);
7946          * callback_fn(u32 index, void *callback_ctx);
7947          */
7948         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7949         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7950
7951         /* unused */
7952         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7953         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7954         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7955
7956         callee->in_callback_fn = true;
7957         callee->callback_ret_range = tnum_range(0, 1);
7958         return 0;
7959 }
7960
7961 static int set_timer_callback_state(struct bpf_verifier_env *env,
7962                                     struct bpf_func_state *caller,
7963                                     struct bpf_func_state *callee,
7964                                     int insn_idx)
7965 {
7966         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7967
7968         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7969          * callback_fn(struct bpf_map *map, void *key, void *value);
7970          */
7971         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7972         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7973         callee->regs[BPF_REG_1].map_ptr = map_ptr;
7974
7975         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7976         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7977         callee->regs[BPF_REG_2].map_ptr = map_ptr;
7978
7979         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7980         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7981         callee->regs[BPF_REG_3].map_ptr = map_ptr;
7982
7983         /* unused */
7984         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7985         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7986         callee->in_async_callback_fn = true;
7987         callee->callback_ret_range = tnum_range(0, 1);
7988         return 0;
7989 }
7990
7991 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7992                                        struct bpf_func_state *caller,
7993                                        struct bpf_func_state *callee,
7994                                        int insn_idx)
7995 {
7996         /* bpf_find_vma(struct task_struct *task, u64 addr,
7997          *               void *callback_fn, void *callback_ctx, u64 flags)
7998          * (callback_fn)(struct task_struct *task,
7999          *               struct vm_area_struct *vma, void *callback_ctx);
8000          */
8001         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8002
8003         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8004         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8005         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8006         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8007
8008         /* pointer to stack or null */
8009         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8010
8011         /* unused */
8012         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8013         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8014         callee->in_callback_fn = true;
8015         callee->callback_ret_range = tnum_range(0, 1);
8016         return 0;
8017 }
8018
8019 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8020                                            struct bpf_func_state *caller,
8021                                            struct bpf_func_state *callee,
8022                                            int insn_idx)
8023 {
8024         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8025          *                        callback_ctx, u64 flags);
8026          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8027          */
8028         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8029         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8030         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8031
8032         /* unused */
8033         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8034         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8035         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8036
8037         callee->in_callback_fn = true;
8038         callee->callback_ret_range = tnum_range(0, 1);
8039         return 0;
8040 }
8041
8042 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8043                                          struct bpf_func_state *caller,
8044                                          struct bpf_func_state *callee,
8045                                          int insn_idx)
8046 {
8047         /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
8048          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8049          *
8050          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
8051          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8052          * by this point, so look at 'root'
8053          */
8054         struct btf_field *field;
8055
8056         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8057                                       BPF_RB_ROOT);
8058         if (!field || !field->graph_root.value_btf_id)
8059                 return -EFAULT;
8060
8061         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8062         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8063         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8064         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8065
8066         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8067         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8068         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8069         callee->in_callback_fn = true;
8070         callee->callback_ret_range = tnum_range(0, 1);
8071         return 0;
8072 }
8073
8074 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8075
8076 /* Are we currently verifying the callback for a rbtree helper that must
8077  * be called with lock held? If so, no need to complain about unreleased
8078  * lock
8079  */
8080 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8081 {
8082         struct bpf_verifier_state *state = env->cur_state;
8083         struct bpf_insn *insn = env->prog->insnsi;
8084         struct bpf_func_state *callee;
8085         int kfunc_btf_id;
8086
8087         if (!state->curframe)
8088                 return false;
8089
8090         callee = state->frame[state->curframe];
8091
8092         if (!callee->in_callback_fn)
8093                 return false;
8094
8095         kfunc_btf_id = insn[callee->callsite].imm;
8096         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8097 }
8098
8099 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8100 {
8101         struct bpf_verifier_state *state = env->cur_state;
8102         struct bpf_func_state *caller, *callee;
8103         struct bpf_reg_state *r0;
8104         int err;
8105
8106         callee = state->frame[state->curframe];
8107         r0 = &callee->regs[BPF_REG_0];
8108         if (r0->type == PTR_TO_STACK) {
8109                 /* technically it's ok to return caller's stack pointer
8110                  * (or caller's caller's pointer) back to the caller,
8111                  * since these pointers are valid. Only current stack
8112                  * pointer will be invalid as soon as function exits,
8113                  * but let's be conservative
8114                  */
8115                 verbose(env, "cannot return stack pointer to the caller\n");
8116                 return -EINVAL;
8117         }
8118
8119         caller = state->frame[state->curframe - 1];
8120         if (callee->in_callback_fn) {
8121                 /* enforce R0 return value range [0, 1]. */
8122                 struct tnum range = callee->callback_ret_range;
8123
8124                 if (r0->type != SCALAR_VALUE) {
8125                         verbose(env, "R0 not a scalar value\n");
8126                         return -EACCES;
8127                 }
8128                 if (!tnum_in(range, r0->var_off)) {
8129                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8130                         return -EINVAL;
8131                 }
8132         } else {
8133                 /* return to the caller whatever r0 had in the callee */
8134                 caller->regs[BPF_REG_0] = *r0;
8135         }
8136
8137         /* callback_fn frame should have released its own additions to parent's
8138          * reference state at this point, or check_reference_leak would
8139          * complain, hence it must be the same as the caller. There is no need
8140          * to copy it back.
8141          */
8142         if (!callee->in_callback_fn) {
8143                 /* Transfer references to the caller */
8144                 err = copy_reference_state(caller, callee);
8145                 if (err)
8146                         return err;
8147         }
8148
8149         *insn_idx = callee->callsite + 1;
8150         if (env->log.level & BPF_LOG_LEVEL) {
8151                 verbose(env, "returning from callee:\n");
8152                 print_verifier_state(env, callee, true);
8153                 verbose(env, "to caller at %d:\n", *insn_idx);
8154                 print_verifier_state(env, caller, true);
8155         }
8156         /* clear everything in the callee */
8157         free_func_state(callee);
8158         state->frame[state->curframe--] = NULL;
8159         return 0;
8160 }
8161
8162 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8163                                    int func_id,
8164                                    struct bpf_call_arg_meta *meta)
8165 {
8166         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
8167
8168         if (ret_type != RET_INTEGER ||
8169             (func_id != BPF_FUNC_get_stack &&
8170              func_id != BPF_FUNC_get_task_stack &&
8171              func_id != BPF_FUNC_probe_read_str &&
8172              func_id != BPF_FUNC_probe_read_kernel_str &&
8173              func_id != BPF_FUNC_probe_read_user_str))
8174                 return;
8175
8176         ret_reg->smax_value = meta->msize_max_value;
8177         ret_reg->s32_max_value = meta->msize_max_value;
8178         ret_reg->smin_value = -MAX_ERRNO;
8179         ret_reg->s32_min_value = -MAX_ERRNO;
8180         reg_bounds_sync(ret_reg);
8181 }
8182
8183 static int
8184 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8185                 int func_id, int insn_idx)
8186 {
8187         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8188         struct bpf_map *map = meta->map_ptr;
8189
8190         if (func_id != BPF_FUNC_tail_call &&
8191             func_id != BPF_FUNC_map_lookup_elem &&
8192             func_id != BPF_FUNC_map_update_elem &&
8193             func_id != BPF_FUNC_map_delete_elem &&
8194             func_id != BPF_FUNC_map_push_elem &&
8195             func_id != BPF_FUNC_map_pop_elem &&
8196             func_id != BPF_FUNC_map_peek_elem &&
8197             func_id != BPF_FUNC_for_each_map_elem &&
8198             func_id != BPF_FUNC_redirect_map &&
8199             func_id != BPF_FUNC_map_lookup_percpu_elem)
8200                 return 0;
8201
8202         if (map == NULL) {
8203                 verbose(env, "kernel subsystem misconfigured verifier\n");
8204                 return -EINVAL;
8205         }
8206
8207         /* In case of read-only, some additional restrictions
8208          * need to be applied in order to prevent altering the
8209          * state of the map from program side.
8210          */
8211         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8212             (func_id == BPF_FUNC_map_delete_elem ||
8213              func_id == BPF_FUNC_map_update_elem ||
8214              func_id == BPF_FUNC_map_push_elem ||
8215              func_id == BPF_FUNC_map_pop_elem)) {
8216                 verbose(env, "write into map forbidden\n");
8217                 return -EACCES;
8218         }
8219
8220         if (!BPF_MAP_PTR(aux->map_ptr_state))
8221                 bpf_map_ptr_store(aux, meta->map_ptr,
8222                                   !meta->map_ptr->bypass_spec_v1);
8223         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
8224                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
8225                                   !meta->map_ptr->bypass_spec_v1);
8226         return 0;
8227 }
8228
8229 static int
8230 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8231                 int func_id, int insn_idx)
8232 {
8233         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8234         struct bpf_reg_state *regs = cur_regs(env), *reg;
8235         struct bpf_map *map = meta->map_ptr;
8236         u64 val, max;
8237         int err;
8238
8239         if (func_id != BPF_FUNC_tail_call)
8240                 return 0;
8241         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8242                 verbose(env, "kernel subsystem misconfigured verifier\n");
8243                 return -EINVAL;
8244         }
8245
8246         reg = &regs[BPF_REG_3];
8247         val = reg->var_off.value;
8248         max = map->max_entries;
8249
8250         if (!(register_is_const(reg) && val < max)) {
8251                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8252                 return 0;
8253         }
8254
8255         err = mark_chain_precision(env, BPF_REG_3);
8256         if (err)
8257                 return err;
8258         if (bpf_map_key_unseen(aux))
8259                 bpf_map_key_store(aux, val);
8260         else if (!bpf_map_key_poisoned(aux) &&
8261                   bpf_map_key_immediate(aux) != val)
8262                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8263         return 0;
8264 }
8265
8266 static int check_reference_leak(struct bpf_verifier_env *env)
8267 {
8268         struct bpf_func_state *state = cur_func(env);
8269         bool refs_lingering = false;
8270         int i;
8271
8272         if (state->frameno && !state->in_callback_fn)
8273                 return 0;
8274
8275         for (i = 0; i < state->acquired_refs; i++) {
8276                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8277                         continue;
8278                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8279                         state->refs[i].id, state->refs[i].insn_idx);
8280                 refs_lingering = true;
8281         }
8282         return refs_lingering ? -EINVAL : 0;
8283 }
8284
8285 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8286                                    struct bpf_reg_state *regs)
8287 {
8288         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8289         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8290         struct bpf_map *fmt_map = fmt_reg->map_ptr;
8291         struct bpf_bprintf_data data = {};
8292         int err, fmt_map_off, num_args;
8293         u64 fmt_addr;
8294         char *fmt;
8295
8296         /* data must be an array of u64 */
8297         if (data_len_reg->var_off.value % 8)
8298                 return -EINVAL;
8299         num_args = data_len_reg->var_off.value / 8;
8300
8301         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8302          * and map_direct_value_addr is set.
8303          */
8304         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8305         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8306                                                   fmt_map_off);
8307         if (err) {
8308                 verbose(env, "verifier bug\n");
8309                 return -EFAULT;
8310         }
8311         fmt = (char *)(long)fmt_addr + fmt_map_off;
8312
8313         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8314          * can focus on validating the format specifiers.
8315          */
8316         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8317         if (err < 0)
8318                 verbose(env, "Invalid format string\n");
8319
8320         return err;
8321 }
8322
8323 static int check_get_func_ip(struct bpf_verifier_env *env)
8324 {
8325         enum bpf_prog_type type = resolve_prog_type(env->prog);
8326         int func_id = BPF_FUNC_get_func_ip;
8327
8328         if (type == BPF_PROG_TYPE_TRACING) {
8329                 if (!bpf_prog_has_trampoline(env->prog)) {
8330                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8331                                 func_id_name(func_id), func_id);
8332                         return -ENOTSUPP;
8333                 }
8334                 return 0;
8335         } else if (type == BPF_PROG_TYPE_KPROBE) {
8336                 return 0;
8337         }
8338
8339         verbose(env, "func %s#%d not supported for program type %d\n",
8340                 func_id_name(func_id), func_id, type);
8341         return -ENOTSUPP;
8342 }
8343
8344 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8345 {
8346         return &env->insn_aux_data[env->insn_idx];
8347 }
8348
8349 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8350 {
8351         struct bpf_reg_state *regs = cur_regs(env);
8352         struct bpf_reg_state *reg = &regs[BPF_REG_4];
8353         bool reg_is_null = register_is_null(reg);
8354
8355         if (reg_is_null)
8356                 mark_chain_precision(env, BPF_REG_4);
8357
8358         return reg_is_null;
8359 }
8360
8361 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8362 {
8363         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8364
8365         if (!state->initialized) {
8366                 state->initialized = 1;
8367                 state->fit_for_inline = loop_flag_is_zero(env);
8368                 state->callback_subprogno = subprogno;
8369                 return;
8370         }
8371
8372         if (!state->fit_for_inline)
8373                 return;
8374
8375         state->fit_for_inline = (loop_flag_is_zero(env) &&
8376                                  state->callback_subprogno == subprogno);
8377 }
8378
8379 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8380                              int *insn_idx_p)
8381 {
8382         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8383         const struct bpf_func_proto *fn = NULL;
8384         enum bpf_return_type ret_type;
8385         enum bpf_type_flag ret_flag;
8386         struct bpf_reg_state *regs;
8387         struct bpf_call_arg_meta meta;
8388         int insn_idx = *insn_idx_p;
8389         bool changes_data;
8390         int i, err, func_id;
8391
8392         /* find function prototype */
8393         func_id = insn->imm;
8394         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8395                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8396                         func_id);
8397                 return -EINVAL;
8398         }
8399
8400         if (env->ops->get_func_proto)
8401                 fn = env->ops->get_func_proto(func_id, env->prog);
8402         if (!fn) {
8403                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8404                         func_id);
8405                 return -EINVAL;
8406         }
8407
8408         /* eBPF programs must be GPL compatible to use GPL-ed functions */
8409         if (!env->prog->gpl_compatible && fn->gpl_only) {
8410                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8411                 return -EINVAL;
8412         }
8413
8414         if (fn->allowed && !fn->allowed(env->prog)) {
8415                 verbose(env, "helper call is not allowed in probe\n");
8416                 return -EINVAL;
8417         }
8418
8419         if (!env->prog->aux->sleepable && fn->might_sleep) {
8420                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
8421                 return -EINVAL;
8422         }
8423
8424         /* With LD_ABS/IND some JITs save/restore skb from r1. */
8425         changes_data = bpf_helper_changes_pkt_data(fn->func);
8426         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8427                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8428                         func_id_name(func_id), func_id);
8429                 return -EINVAL;
8430         }
8431
8432         memset(&meta, 0, sizeof(meta));
8433         meta.pkt_access = fn->pkt_access;
8434
8435         err = check_func_proto(fn, func_id);
8436         if (err) {
8437                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8438                         func_id_name(func_id), func_id);
8439                 return err;
8440         }
8441
8442         if (env->cur_state->active_rcu_lock) {
8443                 if (fn->might_sleep) {
8444                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8445                                 func_id_name(func_id), func_id);
8446                         return -EINVAL;
8447                 }
8448
8449                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8450                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8451         }
8452
8453         meta.func_id = func_id;
8454         /* check args */
8455         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8456                 err = check_func_arg(env, i, &meta, fn, insn_idx);
8457                 if (err)
8458                         return err;
8459         }
8460
8461         err = record_func_map(env, &meta, func_id, insn_idx);
8462         if (err)
8463                 return err;
8464
8465         err = record_func_key(env, &meta, func_id, insn_idx);
8466         if (err)
8467                 return err;
8468
8469         /* Mark slots with STACK_MISC in case of raw mode, stack offset
8470          * is inferred from register state.
8471          */
8472         for (i = 0; i < meta.access_size; i++) {
8473                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8474                                        BPF_WRITE, -1, false);
8475                 if (err)
8476                         return err;
8477         }
8478
8479         regs = cur_regs(env);
8480
8481         if (meta.release_regno) {
8482                 err = -EINVAL;
8483                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8484                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8485                  * is safe to do directly.
8486                  */
8487                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8488                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8489                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8490                                 return -EFAULT;
8491                         }
8492                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
8493                 } else if (meta.ref_obj_id) {
8494                         err = release_reference(env, meta.ref_obj_id);
8495                 } else if (register_is_null(&regs[meta.release_regno])) {
8496                         /* meta.ref_obj_id can only be 0 if register that is meant to be
8497                          * released is NULL, which must be > R0.
8498                          */
8499                         err = 0;
8500                 }
8501                 if (err) {
8502                         verbose(env, "func %s#%d reference has not been acquired before\n",
8503                                 func_id_name(func_id), func_id);
8504                         return err;
8505                 }
8506         }
8507
8508         switch (func_id) {
8509         case BPF_FUNC_tail_call:
8510                 err = check_reference_leak(env);
8511                 if (err) {
8512                         verbose(env, "tail_call would lead to reference leak\n");
8513                         return err;
8514                 }
8515                 break;
8516         case BPF_FUNC_get_local_storage:
8517                 /* check that flags argument in get_local_storage(map, flags) is 0,
8518                  * this is required because get_local_storage() can't return an error.
8519                  */
8520                 if (!register_is_null(&regs[BPF_REG_2])) {
8521                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8522                         return -EINVAL;
8523                 }
8524                 break;
8525         case BPF_FUNC_for_each_map_elem:
8526                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8527                                         set_map_elem_callback_state);
8528                 break;
8529         case BPF_FUNC_timer_set_callback:
8530                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8531                                         set_timer_callback_state);
8532                 break;
8533         case BPF_FUNC_find_vma:
8534                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8535                                         set_find_vma_callback_state);
8536                 break;
8537         case BPF_FUNC_snprintf:
8538                 err = check_bpf_snprintf_call(env, regs);
8539                 break;
8540         case BPF_FUNC_loop:
8541                 update_loop_inline_state(env, meta.subprogno);
8542                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8543                                         set_loop_callback_state);
8544                 break;
8545         case BPF_FUNC_dynptr_from_mem:
8546                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8547                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8548                                 reg_type_str(env, regs[BPF_REG_1].type));
8549                         return -EACCES;
8550                 }
8551                 break;
8552         case BPF_FUNC_set_retval:
8553                 if (prog_type == BPF_PROG_TYPE_LSM &&
8554                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8555                         if (!env->prog->aux->attach_func_proto->type) {
8556                                 /* Make sure programs that attach to void
8557                                  * hooks don't try to modify return value.
8558                                  */
8559                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8560                                 return -EINVAL;
8561                         }
8562                 }
8563                 break;
8564         case BPF_FUNC_dynptr_data:
8565         {
8566                 struct bpf_reg_state *reg;
8567                 int id, ref_obj_id;
8568
8569                 reg = get_dynptr_arg_reg(env, fn, regs);
8570                 if (!reg)
8571                         return -EFAULT;
8572
8573
8574                 if (meta.dynptr_id) {
8575                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
8576                         return -EFAULT;
8577                 }
8578                 if (meta.ref_obj_id) {
8579                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
8580                         return -EFAULT;
8581                 }
8582
8583                 id = dynptr_id(env, reg);
8584                 if (id < 0) {
8585                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
8586                         return id;
8587                 }
8588
8589                 ref_obj_id = dynptr_ref_obj_id(env, reg);
8590                 if (ref_obj_id < 0) {
8591                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
8592                         return ref_obj_id;
8593                 }
8594
8595                 meta.dynptr_id = id;
8596                 meta.ref_obj_id = ref_obj_id;
8597
8598                 break;
8599         }
8600         case BPF_FUNC_dynptr_write:
8601         {
8602                 enum bpf_dynptr_type dynptr_type;
8603                 struct bpf_reg_state *reg;
8604
8605                 reg = get_dynptr_arg_reg(env, fn, regs);
8606                 if (!reg)
8607                         return -EFAULT;
8608
8609                 dynptr_type = dynptr_get_type(env, reg);
8610                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
8611                         return -EFAULT;
8612
8613                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
8614                         /* this will trigger clear_all_pkt_pointers(), which will
8615                          * invalidate all dynptr slices associated with the skb
8616                          */
8617                         changes_data = true;
8618
8619                 break;
8620         }
8621         case BPF_FUNC_user_ringbuf_drain:
8622                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8623                                         set_user_ringbuf_callback_state);
8624                 break;
8625         }
8626
8627         if (err)
8628                 return err;
8629
8630         /* reset caller saved regs */
8631         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8632                 mark_reg_not_init(env, regs, caller_saved[i]);
8633                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8634         }
8635
8636         /* helper call returns 64-bit value. */
8637         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8638
8639         /* update return register (already marked as written above) */
8640         ret_type = fn->ret_type;
8641         ret_flag = type_flag(ret_type);
8642
8643         switch (base_type(ret_type)) {
8644         case RET_INTEGER:
8645                 /* sets type to SCALAR_VALUE */
8646                 mark_reg_unknown(env, regs, BPF_REG_0);
8647                 break;
8648         case RET_VOID:
8649                 regs[BPF_REG_0].type = NOT_INIT;
8650                 break;
8651         case RET_PTR_TO_MAP_VALUE:
8652                 /* There is no offset yet applied, variable or fixed */
8653                 mark_reg_known_zero(env, regs, BPF_REG_0);
8654                 /* remember map_ptr, so that check_map_access()
8655                  * can check 'value_size' boundary of memory access
8656                  * to map element returned from bpf_map_lookup_elem()
8657                  */
8658                 if (meta.map_ptr == NULL) {
8659                         verbose(env,
8660                                 "kernel subsystem misconfigured verifier\n");
8661                         return -EINVAL;
8662                 }
8663                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
8664                 regs[BPF_REG_0].map_uid = meta.map_uid;
8665                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
8666                 if (!type_may_be_null(ret_type) &&
8667                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
8668                         regs[BPF_REG_0].id = ++env->id_gen;
8669                 }
8670                 break;
8671         case RET_PTR_TO_SOCKET:
8672                 mark_reg_known_zero(env, regs, BPF_REG_0);
8673                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
8674                 break;
8675         case RET_PTR_TO_SOCK_COMMON:
8676                 mark_reg_known_zero(env, regs, BPF_REG_0);
8677                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
8678                 break;
8679         case RET_PTR_TO_TCP_SOCK:
8680                 mark_reg_known_zero(env, regs, BPF_REG_0);
8681                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
8682                 break;
8683         case RET_PTR_TO_MEM:
8684                 mark_reg_known_zero(env, regs, BPF_REG_0);
8685                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8686                 regs[BPF_REG_0].mem_size = meta.mem_size;
8687                 break;
8688         case RET_PTR_TO_MEM_OR_BTF_ID:
8689         {
8690                 const struct btf_type *t;
8691
8692                 mark_reg_known_zero(env, regs, BPF_REG_0);
8693                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
8694                 if (!btf_type_is_struct(t)) {
8695                         u32 tsize;
8696                         const struct btf_type *ret;
8697                         const char *tname;
8698
8699                         /* resolve the type size of ksym. */
8700                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
8701                         if (IS_ERR(ret)) {
8702                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
8703                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
8704                                         tname, PTR_ERR(ret));
8705                                 return -EINVAL;
8706                         }
8707                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
8708                         regs[BPF_REG_0].mem_size = tsize;
8709                 } else {
8710                         /* MEM_RDONLY may be carried from ret_flag, but it
8711                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
8712                          * it will confuse the check of PTR_TO_BTF_ID in
8713                          * check_mem_access().
8714                          */
8715                         ret_flag &= ~MEM_RDONLY;
8716
8717                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8718                         regs[BPF_REG_0].btf = meta.ret_btf;
8719                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8720                 }
8721                 break;
8722         }
8723         case RET_PTR_TO_BTF_ID:
8724         {
8725                 struct btf *ret_btf;
8726                 int ret_btf_id;
8727
8728                 mark_reg_known_zero(env, regs, BPF_REG_0);
8729                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
8730                 if (func_id == BPF_FUNC_kptr_xchg) {
8731                         ret_btf = meta.kptr_field->kptr.btf;
8732                         ret_btf_id = meta.kptr_field->kptr.btf_id;
8733                 } else {
8734                         if (fn->ret_btf_id == BPF_PTR_POISON) {
8735                                 verbose(env, "verifier internal error:");
8736                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
8737                                         func_id_name(func_id));
8738                                 return -EINVAL;
8739                         }
8740                         ret_btf = btf_vmlinux;
8741                         ret_btf_id = *fn->ret_btf_id;
8742                 }
8743                 if (ret_btf_id == 0) {
8744                         verbose(env, "invalid return type %u of func %s#%d\n",
8745                                 base_type(ret_type), func_id_name(func_id),
8746                                 func_id);
8747                         return -EINVAL;
8748                 }
8749                 regs[BPF_REG_0].btf = ret_btf;
8750                 regs[BPF_REG_0].btf_id = ret_btf_id;
8751                 break;
8752         }
8753         default:
8754                 verbose(env, "unknown return type %u of func %s#%d\n",
8755                         base_type(ret_type), func_id_name(func_id), func_id);
8756                 return -EINVAL;
8757         }
8758
8759         if (type_may_be_null(regs[BPF_REG_0].type))
8760                 regs[BPF_REG_0].id = ++env->id_gen;
8761
8762         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
8763                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
8764                         func_id_name(func_id), func_id);
8765                 return -EFAULT;
8766         }
8767
8768         if (is_dynptr_ref_function(func_id))
8769                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
8770
8771         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
8772                 /* For release_reference() */
8773                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8774         } else if (is_acquire_function(func_id, meta.map_ptr)) {
8775                 int id = acquire_reference_state(env, insn_idx);
8776
8777                 if (id < 0)
8778                         return id;
8779                 /* For mark_ptr_or_null_reg() */
8780                 regs[BPF_REG_0].id = id;
8781                 /* For release_reference() */
8782                 regs[BPF_REG_0].ref_obj_id = id;
8783         }
8784
8785         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
8786
8787         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
8788         if (err)
8789                 return err;
8790
8791         if ((func_id == BPF_FUNC_get_stack ||
8792              func_id == BPF_FUNC_get_task_stack) &&
8793             !env->prog->has_callchain_buf) {
8794                 const char *err_str;
8795
8796 #ifdef CONFIG_PERF_EVENTS
8797                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
8798                 err_str = "cannot get callchain buffer for func %s#%d\n";
8799 #else
8800                 err = -ENOTSUPP;
8801                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
8802 #endif
8803                 if (err) {
8804                         verbose(env, err_str, func_id_name(func_id), func_id);
8805                         return err;
8806                 }
8807
8808                 env->prog->has_callchain_buf = true;
8809         }
8810
8811         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
8812                 env->prog->call_get_stack = true;
8813
8814         if (func_id == BPF_FUNC_get_func_ip) {
8815                 if (check_get_func_ip(env))
8816                         return -ENOTSUPP;
8817                 env->prog->call_get_func_ip = true;
8818         }
8819
8820         if (changes_data)
8821                 clear_all_pkt_pointers(env);
8822         return 0;
8823 }
8824
8825 /* mark_btf_func_reg_size() is used when the reg size is determined by
8826  * the BTF func_proto's return value size and argument.
8827  */
8828 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
8829                                    size_t reg_size)
8830 {
8831         struct bpf_reg_state *reg = &cur_regs(env)[regno];
8832
8833         if (regno == BPF_REG_0) {
8834                 /* Function return value */
8835                 reg->live |= REG_LIVE_WRITTEN;
8836                 reg->subreg_def = reg_size == sizeof(u64) ?
8837                         DEF_NOT_SUBREG : env->insn_idx + 1;
8838         } else {
8839                 /* Function argument */
8840                 if (reg_size == sizeof(u64)) {
8841                         mark_insn_zext(env, reg);
8842                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
8843                 } else {
8844                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
8845                 }
8846         }
8847 }
8848
8849 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
8850 {
8851         return meta->kfunc_flags & KF_ACQUIRE;
8852 }
8853
8854 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
8855 {
8856         return meta->kfunc_flags & KF_RET_NULL;
8857 }
8858
8859 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
8860 {
8861         return meta->kfunc_flags & KF_RELEASE;
8862 }
8863
8864 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
8865 {
8866         return meta->kfunc_flags & KF_TRUSTED_ARGS;
8867 }
8868
8869 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
8870 {
8871         return meta->kfunc_flags & KF_SLEEPABLE;
8872 }
8873
8874 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
8875 {
8876         return meta->kfunc_flags & KF_DESTRUCTIVE;
8877 }
8878
8879 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
8880 {
8881         return meta->kfunc_flags & KF_RCU;
8882 }
8883
8884 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
8885 {
8886         return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
8887 }
8888
8889 static bool __kfunc_param_match_suffix(const struct btf *btf,
8890                                        const struct btf_param *arg,
8891                                        const char *suffix)
8892 {
8893         int suffix_len = strlen(suffix), len;
8894         const char *param_name;
8895
8896         /* In the future, this can be ported to use BTF tagging */
8897         param_name = btf_name_by_offset(btf, arg->name_off);
8898         if (str_is_empty(param_name))
8899                 return false;
8900         len = strlen(param_name);
8901         if (len < suffix_len)
8902                 return false;
8903         param_name += len - suffix_len;
8904         return !strncmp(param_name, suffix, suffix_len);
8905 }
8906
8907 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8908                                   const struct btf_param *arg,
8909                                   const struct bpf_reg_state *reg)
8910 {
8911         const struct btf_type *t;
8912
8913         t = btf_type_skip_modifiers(btf, arg->type, NULL);
8914         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8915                 return false;
8916
8917         return __kfunc_param_match_suffix(btf, arg, "__sz");
8918 }
8919
8920 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
8921                                         const struct btf_param *arg,
8922                                         const struct bpf_reg_state *reg)
8923 {
8924         const struct btf_type *t;
8925
8926         t = btf_type_skip_modifiers(btf, arg->type, NULL);
8927         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8928                 return false;
8929
8930         return __kfunc_param_match_suffix(btf, arg, "__szk");
8931 }
8932
8933 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8934 {
8935         return __kfunc_param_match_suffix(btf, arg, "__k");
8936 }
8937
8938 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8939 {
8940         return __kfunc_param_match_suffix(btf, arg, "__ign");
8941 }
8942
8943 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8944 {
8945         return __kfunc_param_match_suffix(btf, arg, "__alloc");
8946 }
8947
8948 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
8949 {
8950         return __kfunc_param_match_suffix(btf, arg, "__uninit");
8951 }
8952
8953 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8954                                           const struct btf_param *arg,
8955                                           const char *name)
8956 {
8957         int len, target_len = strlen(name);
8958         const char *param_name;
8959
8960         param_name = btf_name_by_offset(btf, arg->name_off);
8961         if (str_is_empty(param_name))
8962                 return false;
8963         len = strlen(param_name);
8964         if (len != target_len)
8965                 return false;
8966         if (strcmp(param_name, name))
8967                 return false;
8968
8969         return true;
8970 }
8971
8972 enum {
8973         KF_ARG_DYNPTR_ID,
8974         KF_ARG_LIST_HEAD_ID,
8975         KF_ARG_LIST_NODE_ID,
8976         KF_ARG_RB_ROOT_ID,
8977         KF_ARG_RB_NODE_ID,
8978 };
8979
8980 BTF_ID_LIST(kf_arg_btf_ids)
8981 BTF_ID(struct, bpf_dynptr_kern)
8982 BTF_ID(struct, bpf_list_head)
8983 BTF_ID(struct, bpf_list_node)
8984 BTF_ID(struct, bpf_rb_root)
8985 BTF_ID(struct, bpf_rb_node)
8986
8987 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8988                                     const struct btf_param *arg, int type)
8989 {
8990         const struct btf_type *t;
8991         u32 res_id;
8992
8993         t = btf_type_skip_modifiers(btf, arg->type, NULL);
8994         if (!t)
8995                 return false;
8996         if (!btf_type_is_ptr(t))
8997                 return false;
8998         t = btf_type_skip_modifiers(btf, t->type, &res_id);
8999         if (!t)
9000                 return false;
9001         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9002 }
9003
9004 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9005 {
9006         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9007 }
9008
9009 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9010 {
9011         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9012 }
9013
9014 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9015 {
9016         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9017 }
9018
9019 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9020 {
9021         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9022 }
9023
9024 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9025 {
9026         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9027 }
9028
9029 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9030                                   const struct btf_param *arg)
9031 {
9032         const struct btf_type *t;
9033
9034         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9035         if (!t)
9036                 return false;
9037
9038         return true;
9039 }
9040
9041 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9042 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9043                                         const struct btf *btf,
9044                                         const struct btf_type *t, int rec)
9045 {
9046         const struct btf_type *member_type;
9047         const struct btf_member *member;
9048         u32 i;
9049
9050         if (!btf_type_is_struct(t))
9051                 return false;
9052
9053         for_each_member(i, t, member) {
9054                 const struct btf_array *array;
9055
9056                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9057                 if (btf_type_is_struct(member_type)) {
9058                         if (rec >= 3) {
9059                                 verbose(env, "max struct nesting depth exceeded\n");
9060                                 return false;
9061                         }
9062                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9063                                 return false;
9064                         continue;
9065                 }
9066                 if (btf_type_is_array(member_type)) {
9067                         array = btf_array(member_type);
9068                         if (!array->nelems)
9069                                 return false;
9070                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9071                         if (!btf_type_is_scalar(member_type))
9072                                 return false;
9073                         continue;
9074                 }
9075                 if (!btf_type_is_scalar(member_type))
9076                         return false;
9077         }
9078         return true;
9079 }
9080
9081
9082 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9083 #ifdef CONFIG_NET
9084         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9085         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9086         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9087 #endif
9088 };
9089
9090 enum kfunc_ptr_arg_type {
9091         KF_ARG_PTR_TO_CTX,
9092         KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
9093         KF_ARG_PTR_TO_KPTR,          /* PTR_TO_KPTR but type specific */
9094         KF_ARG_PTR_TO_DYNPTR,
9095         KF_ARG_PTR_TO_LIST_HEAD,
9096         KF_ARG_PTR_TO_LIST_NODE,
9097         KF_ARG_PTR_TO_BTF_ID,        /* Also covers reg2btf_ids conversions */
9098         KF_ARG_PTR_TO_MEM,
9099         KF_ARG_PTR_TO_MEM_SIZE,      /* Size derived from next argument, skip it */
9100         KF_ARG_PTR_TO_CALLBACK,
9101         KF_ARG_PTR_TO_RB_ROOT,
9102         KF_ARG_PTR_TO_RB_NODE,
9103 };
9104
9105 enum special_kfunc_type {
9106         KF_bpf_obj_new_impl,
9107         KF_bpf_obj_drop_impl,
9108         KF_bpf_list_push_front,
9109         KF_bpf_list_push_back,
9110         KF_bpf_list_pop_front,
9111         KF_bpf_list_pop_back,
9112         KF_bpf_cast_to_kern_ctx,
9113         KF_bpf_rdonly_cast,
9114         KF_bpf_rcu_read_lock,
9115         KF_bpf_rcu_read_unlock,
9116         KF_bpf_rbtree_remove,
9117         KF_bpf_rbtree_add,
9118         KF_bpf_rbtree_first,
9119         KF_bpf_dynptr_from_skb,
9120         KF_bpf_dynptr_from_xdp,
9121         KF_bpf_dynptr_slice,
9122         KF_bpf_dynptr_slice_rdwr,
9123 };
9124
9125 BTF_SET_START(special_kfunc_set)
9126 BTF_ID(func, bpf_obj_new_impl)
9127 BTF_ID(func, bpf_obj_drop_impl)
9128 BTF_ID(func, bpf_list_push_front)
9129 BTF_ID(func, bpf_list_push_back)
9130 BTF_ID(func, bpf_list_pop_front)
9131 BTF_ID(func, bpf_list_pop_back)
9132 BTF_ID(func, bpf_cast_to_kern_ctx)
9133 BTF_ID(func, bpf_rdonly_cast)
9134 BTF_ID(func, bpf_rbtree_remove)
9135 BTF_ID(func, bpf_rbtree_add)
9136 BTF_ID(func, bpf_rbtree_first)
9137 BTF_ID(func, bpf_dynptr_from_skb)
9138 BTF_ID(func, bpf_dynptr_from_xdp)
9139 BTF_ID(func, bpf_dynptr_slice)
9140 BTF_ID(func, bpf_dynptr_slice_rdwr)
9141 BTF_SET_END(special_kfunc_set)
9142
9143 BTF_ID_LIST(special_kfunc_list)
9144 BTF_ID(func, bpf_obj_new_impl)
9145 BTF_ID(func, bpf_obj_drop_impl)
9146 BTF_ID(func, bpf_list_push_front)
9147 BTF_ID(func, bpf_list_push_back)
9148 BTF_ID(func, bpf_list_pop_front)
9149 BTF_ID(func, bpf_list_pop_back)
9150 BTF_ID(func, bpf_cast_to_kern_ctx)
9151 BTF_ID(func, bpf_rdonly_cast)
9152 BTF_ID(func, bpf_rcu_read_lock)
9153 BTF_ID(func, bpf_rcu_read_unlock)
9154 BTF_ID(func, bpf_rbtree_remove)
9155 BTF_ID(func, bpf_rbtree_add)
9156 BTF_ID(func, bpf_rbtree_first)
9157 BTF_ID(func, bpf_dynptr_from_skb)
9158 BTF_ID(func, bpf_dynptr_from_xdp)
9159 BTF_ID(func, bpf_dynptr_slice)
9160 BTF_ID(func, bpf_dynptr_slice_rdwr)
9161
9162 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9163 {
9164         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9165 }
9166
9167 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9168 {
9169         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9170 }
9171
9172 static enum kfunc_ptr_arg_type
9173 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9174                        struct bpf_kfunc_call_arg_meta *meta,
9175                        const struct btf_type *t, const struct btf_type *ref_t,
9176                        const char *ref_tname, const struct btf_param *args,
9177                        int argno, int nargs)
9178 {
9179         u32 regno = argno + 1;
9180         struct bpf_reg_state *regs = cur_regs(env);
9181         struct bpf_reg_state *reg = &regs[regno];
9182         bool arg_mem_size = false;
9183
9184         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9185                 return KF_ARG_PTR_TO_CTX;
9186
9187         /* In this function, we verify the kfunc's BTF as per the argument type,
9188          * leaving the rest of the verification with respect to the register
9189          * type to our caller. When a set of conditions hold in the BTF type of
9190          * arguments, we resolve it to a known kfunc_ptr_arg_type.
9191          */
9192         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9193                 return KF_ARG_PTR_TO_CTX;
9194
9195         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9196                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9197
9198         if (is_kfunc_arg_kptr_get(meta, argno)) {
9199                 if (!btf_type_is_ptr(ref_t)) {
9200                         verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
9201                         return -EINVAL;
9202                 }
9203                 ref_t = btf_type_by_id(meta->btf, ref_t->type);
9204                 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
9205                 if (!btf_type_is_struct(ref_t)) {
9206                         verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
9207                                 meta->func_name, btf_type_str(ref_t), ref_tname);
9208                         return -EINVAL;
9209                 }
9210                 return KF_ARG_PTR_TO_KPTR;
9211         }
9212
9213         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9214                 return KF_ARG_PTR_TO_DYNPTR;
9215
9216         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9217                 return KF_ARG_PTR_TO_LIST_HEAD;
9218
9219         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9220                 return KF_ARG_PTR_TO_LIST_NODE;
9221
9222         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9223                 return KF_ARG_PTR_TO_RB_ROOT;
9224
9225         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9226                 return KF_ARG_PTR_TO_RB_NODE;
9227
9228         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9229                 if (!btf_type_is_struct(ref_t)) {
9230                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9231                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9232                         return -EINVAL;
9233                 }
9234                 return KF_ARG_PTR_TO_BTF_ID;
9235         }
9236
9237         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9238                 return KF_ARG_PTR_TO_CALLBACK;
9239
9240
9241         if (argno + 1 < nargs &&
9242             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
9243              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
9244                 arg_mem_size = true;
9245
9246         /* This is the catch all argument type of register types supported by
9247          * check_helper_mem_access. However, we only allow when argument type is
9248          * pointer to scalar, or struct composed (recursively) of scalars. When
9249          * arg_mem_size is true, the pointer can be void *.
9250          */
9251         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9252             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9253                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9254                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9255                 return -EINVAL;
9256         }
9257         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9258 }
9259
9260 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9261                                         struct bpf_reg_state *reg,
9262                                         const struct btf_type *ref_t,
9263                                         const char *ref_tname, u32 ref_id,
9264                                         struct bpf_kfunc_call_arg_meta *meta,
9265                                         int argno)
9266 {
9267         const struct btf_type *reg_ref_t;
9268         bool strict_type_match = false;
9269         const struct btf *reg_btf;
9270         const char *reg_ref_tname;
9271         u32 reg_ref_id;
9272
9273         if (base_type(reg->type) == PTR_TO_BTF_ID) {
9274                 reg_btf = reg->btf;
9275                 reg_ref_id = reg->btf_id;
9276         } else {
9277                 reg_btf = btf_vmlinux;
9278                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9279         }
9280
9281         /* Enforce strict type matching for calls to kfuncs that are acquiring
9282          * or releasing a reference, or are no-cast aliases. We do _not_
9283          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9284          * as we want to enable BPF programs to pass types that are bitwise
9285          * equivalent without forcing them to explicitly cast with something
9286          * like bpf_cast_to_kern_ctx().
9287          *
9288          * For example, say we had a type like the following:
9289          *
9290          * struct bpf_cpumask {
9291          *      cpumask_t cpumask;
9292          *      refcount_t usage;
9293          * };
9294          *
9295          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9296          * to a struct cpumask, so it would be safe to pass a struct
9297          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9298          *
9299          * The philosophy here is similar to how we allow scalars of different
9300          * types to be passed to kfuncs as long as the size is the same. The
9301          * only difference here is that we're simply allowing
9302          * btf_struct_ids_match() to walk the struct at the 0th offset, and
9303          * resolve types.
9304          */
9305         if (is_kfunc_acquire(meta) ||
9306             (is_kfunc_release(meta) && reg->ref_obj_id) ||
9307             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9308                 strict_type_match = true;
9309
9310         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9311
9312         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9313         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9314         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9315                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9316                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9317                         btf_type_str(reg_ref_t), reg_ref_tname);
9318                 return -EINVAL;
9319         }
9320         return 0;
9321 }
9322
9323 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9324                                       struct bpf_reg_state *reg,
9325                                       const struct btf_type *ref_t,
9326                                       const char *ref_tname,
9327                                       struct bpf_kfunc_call_arg_meta *meta,
9328                                       int argno)
9329 {
9330         struct btf_field *kptr_field;
9331
9332         /* check_func_arg_reg_off allows var_off for
9333          * PTR_TO_MAP_VALUE, but we need fixed offset to find
9334          * off_desc.
9335          */
9336         if (!tnum_is_const(reg->var_off)) {
9337                 verbose(env, "arg#0 must have constant offset\n");
9338                 return -EINVAL;
9339         }
9340
9341         kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9342         if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9343                 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9344                         reg->off + reg->var_off.value);
9345                 return -EINVAL;
9346         }
9347
9348         if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9349                                   kptr_field->kptr.btf_id, true)) {
9350                 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9351                         meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9352                 return -EINVAL;
9353         }
9354         return 0;
9355 }
9356
9357 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9358 {
9359         struct bpf_verifier_state *state = env->cur_state;
9360
9361         if (!state->active_lock.ptr) {
9362                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9363                 return -EFAULT;
9364         }
9365
9366         if (type_flag(reg->type) & NON_OWN_REF) {
9367                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9368                 return -EFAULT;
9369         }
9370
9371         reg->type |= NON_OWN_REF;
9372         return 0;
9373 }
9374
9375 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9376 {
9377         struct bpf_func_state *state, *unused;
9378         struct bpf_reg_state *reg;
9379         int i;
9380
9381         state = cur_func(env);
9382
9383         if (!ref_obj_id) {
9384                 verbose(env, "verifier internal error: ref_obj_id is zero for "
9385                              "owning -> non-owning conversion\n");
9386                 return -EFAULT;
9387         }
9388
9389         for (i = 0; i < state->acquired_refs; i++) {
9390                 if (state->refs[i].id != ref_obj_id)
9391                         continue;
9392
9393                 /* Clear ref_obj_id here so release_reference doesn't clobber
9394                  * the whole reg
9395                  */
9396                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9397                         if (reg->ref_obj_id == ref_obj_id) {
9398                                 reg->ref_obj_id = 0;
9399                                 ref_set_non_owning(env, reg);
9400                         }
9401                 }));
9402                 return 0;
9403         }
9404
9405         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9406         return -EFAULT;
9407 }
9408
9409 /* Implementation details:
9410  *
9411  * Each register points to some region of memory, which we define as an
9412  * allocation. Each allocation may embed a bpf_spin_lock which protects any
9413  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9414  * allocation. The lock and the data it protects are colocated in the same
9415  * memory region.
9416  *
9417  * Hence, everytime a register holds a pointer value pointing to such
9418  * allocation, the verifier preserves a unique reg->id for it.
9419  *
9420  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9421  * bpf_spin_lock is called.
9422  *
9423  * To enable this, lock state in the verifier captures two values:
9424  *      active_lock.ptr = Register's type specific pointer
9425  *      active_lock.id  = A unique ID for each register pointer value
9426  *
9427  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9428  * supported register types.
9429  *
9430  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9431  * allocated objects is the reg->btf pointer.
9432  *
9433  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9434  * can establish the provenance of the map value statically for each distinct
9435  * lookup into such maps. They always contain a single map value hence unique
9436  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9437  *
9438  * So, in case of global variables, they use array maps with max_entries = 1,
9439  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9440  * into the same map value as max_entries is 1, as described above).
9441  *
9442  * In case of inner map lookups, the inner map pointer has same map_ptr as the
9443  * outer map pointer (in verifier context), but each lookup into an inner map
9444  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9445  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9446  * will get different reg->id assigned to each lookup, hence different
9447  * active_lock.id.
9448  *
9449  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9450  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9451  * returned from bpf_obj_new. Each allocation receives a new reg->id.
9452  */
9453 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9454 {
9455         void *ptr;
9456         u32 id;
9457
9458         switch ((int)reg->type) {
9459         case PTR_TO_MAP_VALUE:
9460                 ptr = reg->map_ptr;
9461                 break;
9462         case PTR_TO_BTF_ID | MEM_ALLOC:
9463                 ptr = reg->btf;
9464                 break;
9465         default:
9466                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
9467                 return -EFAULT;
9468         }
9469         id = reg->id;
9470
9471         if (!env->cur_state->active_lock.ptr)
9472                 return -EINVAL;
9473         if (env->cur_state->active_lock.ptr != ptr ||
9474             env->cur_state->active_lock.id != id) {
9475                 verbose(env, "held lock and object are not in the same allocation\n");
9476                 return -EINVAL;
9477         }
9478         return 0;
9479 }
9480
9481 static bool is_bpf_list_api_kfunc(u32 btf_id)
9482 {
9483         return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9484                btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9485                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9486                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9487 }
9488
9489 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9490 {
9491         return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9492                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9493                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9494 }
9495
9496 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9497 {
9498         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9499 }
9500
9501 static bool is_callback_calling_kfunc(u32 btf_id)
9502 {
9503         return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9504 }
9505
9506 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9507 {
9508         return is_bpf_rbtree_api_kfunc(btf_id);
9509 }
9510
9511 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9512                                           enum btf_field_type head_field_type,
9513                                           u32 kfunc_btf_id)
9514 {
9515         bool ret;
9516
9517         switch (head_field_type) {
9518         case BPF_LIST_HEAD:
9519                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9520                 break;
9521         case BPF_RB_ROOT:
9522                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9523                 break;
9524         default:
9525                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9526                         btf_field_type_name(head_field_type));
9527                 return false;
9528         }
9529
9530         if (!ret)
9531                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9532                         btf_field_type_name(head_field_type));
9533         return ret;
9534 }
9535
9536 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9537                                           enum btf_field_type node_field_type,
9538                                           u32 kfunc_btf_id)
9539 {
9540         bool ret;
9541
9542         switch (node_field_type) {
9543         case BPF_LIST_NODE:
9544                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9545                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9546                 break;
9547         case BPF_RB_NODE:
9548                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9549                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9550                 break;
9551         default:
9552                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9553                         btf_field_type_name(node_field_type));
9554                 return false;
9555         }
9556
9557         if (!ret)
9558                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
9559                         btf_field_type_name(node_field_type));
9560         return ret;
9561 }
9562
9563 static int
9564 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
9565                                    struct bpf_reg_state *reg, u32 regno,
9566                                    struct bpf_kfunc_call_arg_meta *meta,
9567                                    enum btf_field_type head_field_type,
9568                                    struct btf_field **head_field)
9569 {
9570         const char *head_type_name;
9571         struct btf_field *field;
9572         struct btf_record *rec;
9573         u32 head_off;
9574
9575         if (meta->btf != btf_vmlinux) {
9576                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9577                 return -EFAULT;
9578         }
9579
9580         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
9581                 return -EFAULT;
9582
9583         head_type_name = btf_field_type_name(head_field_type);
9584         if (!tnum_is_const(reg->var_off)) {
9585                 verbose(env,
9586                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
9587                         regno, head_type_name);
9588                 return -EINVAL;
9589         }
9590
9591         rec = reg_btf_record(reg);
9592         head_off = reg->off + reg->var_off.value;
9593         field = btf_record_find(rec, head_off, head_field_type);
9594         if (!field) {
9595                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
9596                 return -EINVAL;
9597         }
9598
9599         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
9600         if (check_reg_allocation_locked(env, reg)) {
9601                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
9602                         rec->spin_lock_off, head_type_name);
9603                 return -EINVAL;
9604         }
9605
9606         if (*head_field) {
9607                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
9608                 return -EFAULT;
9609         }
9610         *head_field = field;
9611         return 0;
9612 }
9613
9614 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9615                                            struct bpf_reg_state *reg, u32 regno,
9616                                            struct bpf_kfunc_call_arg_meta *meta)
9617 {
9618         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
9619                                                           &meta->arg_list_head.field);
9620 }
9621
9622 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9623                                              struct bpf_reg_state *reg, u32 regno,
9624                                              struct bpf_kfunc_call_arg_meta *meta)
9625 {
9626         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
9627                                                           &meta->arg_rbtree_root.field);
9628 }
9629
9630 static int
9631 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
9632                                    struct bpf_reg_state *reg, u32 regno,
9633                                    struct bpf_kfunc_call_arg_meta *meta,
9634                                    enum btf_field_type head_field_type,
9635                                    enum btf_field_type node_field_type,
9636                                    struct btf_field **node_field)
9637 {
9638         const char *node_type_name;
9639         const struct btf_type *et, *t;
9640         struct btf_field *field;
9641         u32 node_off;
9642
9643         if (meta->btf != btf_vmlinux) {
9644                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
9645                 return -EFAULT;
9646         }
9647
9648         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
9649                 return -EFAULT;
9650
9651         node_type_name = btf_field_type_name(node_field_type);
9652         if (!tnum_is_const(reg->var_off)) {
9653                 verbose(env,
9654                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
9655                         regno, node_type_name);
9656                 return -EINVAL;
9657         }
9658
9659         node_off = reg->off + reg->var_off.value;
9660         field = reg_find_field_offset(reg, node_off, node_field_type);
9661         if (!field || field->offset != node_off) {
9662                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
9663                 return -EINVAL;
9664         }
9665
9666         field = *node_field;
9667
9668         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
9669         t = btf_type_by_id(reg->btf, reg->btf_id);
9670         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
9671                                   field->graph_root.value_btf_id, true)) {
9672                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
9673                         "in struct %s, but arg is at offset=%d in struct %s\n",
9674                         btf_field_type_name(head_field_type),
9675                         btf_field_type_name(node_field_type),
9676                         field->graph_root.node_offset,
9677                         btf_name_by_offset(field->graph_root.btf, et->name_off),
9678                         node_off, btf_name_by_offset(reg->btf, t->name_off));
9679                 return -EINVAL;
9680         }
9681
9682         if (node_off != field->graph_root.node_offset) {
9683                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
9684                         node_off, btf_field_type_name(node_field_type),
9685                         field->graph_root.node_offset,
9686                         btf_name_by_offset(field->graph_root.btf, et->name_off));
9687                 return -EINVAL;
9688         }
9689
9690         return 0;
9691 }
9692
9693 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9694                                            struct bpf_reg_state *reg, u32 regno,
9695                                            struct bpf_kfunc_call_arg_meta *meta)
9696 {
9697         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9698                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
9699                                                   &meta->arg_list_head.field);
9700 }
9701
9702 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9703                                              struct bpf_reg_state *reg, u32 regno,
9704                                              struct bpf_kfunc_call_arg_meta *meta)
9705 {
9706         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
9707                                                   BPF_RB_ROOT, BPF_RB_NODE,
9708                                                   &meta->arg_rbtree_root.field);
9709 }
9710
9711 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
9712                             int insn_idx)
9713 {
9714         const char *func_name = meta->func_name, *ref_tname;
9715         const struct btf *btf = meta->btf;
9716         const struct btf_param *args;
9717         u32 i, nargs;
9718         int ret;
9719
9720         args = (const struct btf_param *)(meta->func_proto + 1);
9721         nargs = btf_type_vlen(meta->func_proto);
9722         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
9723                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
9724                         MAX_BPF_FUNC_REG_ARGS);
9725                 return -EINVAL;
9726         }
9727
9728         /* Check that BTF function arguments match actual types that the
9729          * verifier sees.
9730          */
9731         for (i = 0; i < nargs; i++) {
9732                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
9733                 const struct btf_type *t, *ref_t, *resolve_ret;
9734                 enum bpf_arg_type arg_type = ARG_DONTCARE;
9735                 u32 regno = i + 1, ref_id, type_size;
9736                 bool is_ret_buf_sz = false;
9737                 int kf_arg_type;
9738
9739                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
9740
9741                 if (is_kfunc_arg_ignore(btf, &args[i]))
9742                         continue;
9743
9744                 if (btf_type_is_scalar(t)) {
9745                         if (reg->type != SCALAR_VALUE) {
9746                                 verbose(env, "R%d is not a scalar\n", regno);
9747                                 return -EINVAL;
9748                         }
9749
9750                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
9751                                 if (meta->arg_constant.found) {
9752                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
9753                                         return -EFAULT;
9754                                 }
9755                                 if (!tnum_is_const(reg->var_off)) {
9756                                         verbose(env, "R%d must be a known constant\n", regno);
9757                                         return -EINVAL;
9758                                 }
9759                                 ret = mark_chain_precision(env, regno);
9760                                 if (ret < 0)
9761                                         return ret;
9762                                 meta->arg_constant.found = true;
9763                                 meta->arg_constant.value = reg->var_off.value;
9764                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
9765                                 meta->r0_rdonly = true;
9766                                 is_ret_buf_sz = true;
9767                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
9768                                 is_ret_buf_sz = true;
9769                         }
9770
9771                         if (is_ret_buf_sz) {
9772                                 if (meta->r0_size) {
9773                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
9774                                         return -EINVAL;
9775                                 }
9776
9777                                 if (!tnum_is_const(reg->var_off)) {
9778                                         verbose(env, "R%d is not a const\n", regno);
9779                                         return -EINVAL;
9780                                 }
9781
9782                                 meta->r0_size = reg->var_off.value;
9783                                 ret = mark_chain_precision(env, regno);
9784                                 if (ret)
9785                                         return ret;
9786                         }
9787                         continue;
9788                 }
9789
9790                 if (!btf_type_is_ptr(t)) {
9791                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
9792                         return -EINVAL;
9793                 }
9794
9795                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
9796                     (register_is_null(reg) || type_may_be_null(reg->type))) {
9797                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
9798                         return -EACCES;
9799                 }
9800
9801                 if (reg->ref_obj_id) {
9802                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
9803                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
9804                                         regno, reg->ref_obj_id,
9805                                         meta->ref_obj_id);
9806                                 return -EFAULT;
9807                         }
9808                         meta->ref_obj_id = reg->ref_obj_id;
9809                         if (is_kfunc_release(meta))
9810                                 meta->release_regno = regno;
9811                 }
9812
9813                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
9814                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
9815
9816                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
9817                 if (kf_arg_type < 0)
9818                         return kf_arg_type;
9819
9820                 switch (kf_arg_type) {
9821                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9822                 case KF_ARG_PTR_TO_BTF_ID:
9823                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
9824                                 break;
9825
9826                         if (!is_trusted_reg(reg)) {
9827                                 if (!is_kfunc_rcu(meta)) {
9828                                         verbose(env, "R%d must be referenced or trusted\n", regno);
9829                                         return -EINVAL;
9830                                 }
9831                                 if (!is_rcu_reg(reg)) {
9832                                         verbose(env, "R%d must be a rcu pointer\n", regno);
9833                                         return -EINVAL;
9834                                 }
9835                         }
9836
9837                         fallthrough;
9838                 case KF_ARG_PTR_TO_CTX:
9839                         /* Trusted arguments have the same offset checks as release arguments */
9840                         arg_type |= OBJ_RELEASE;
9841                         break;
9842                 case KF_ARG_PTR_TO_KPTR:
9843                 case KF_ARG_PTR_TO_DYNPTR:
9844                 case KF_ARG_PTR_TO_LIST_HEAD:
9845                 case KF_ARG_PTR_TO_LIST_NODE:
9846                 case KF_ARG_PTR_TO_RB_ROOT:
9847                 case KF_ARG_PTR_TO_RB_NODE:
9848                 case KF_ARG_PTR_TO_MEM:
9849                 case KF_ARG_PTR_TO_MEM_SIZE:
9850                 case KF_ARG_PTR_TO_CALLBACK:
9851                         /* Trusted by default */
9852                         break;
9853                 default:
9854                         WARN_ON_ONCE(1);
9855                         return -EFAULT;
9856                 }
9857
9858                 if (is_kfunc_release(meta) && reg->ref_obj_id)
9859                         arg_type |= OBJ_RELEASE;
9860                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
9861                 if (ret < 0)
9862                         return ret;
9863
9864                 switch (kf_arg_type) {
9865                 case KF_ARG_PTR_TO_CTX:
9866                         if (reg->type != PTR_TO_CTX) {
9867                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
9868                                 return -EINVAL;
9869                         }
9870
9871                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
9872                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9873                                 if (ret < 0)
9874                                         return -EINVAL;
9875                                 meta->ret_btf_id  = ret;
9876                         }
9877                         break;
9878                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
9879                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9880                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
9881                                 return -EINVAL;
9882                         }
9883                         if (!reg->ref_obj_id) {
9884                                 verbose(env, "allocated object must be referenced\n");
9885                                 return -EINVAL;
9886                         }
9887                         if (meta->btf == btf_vmlinux &&
9888                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
9889                                 meta->arg_obj_drop.btf = reg->btf;
9890                                 meta->arg_obj_drop.btf_id = reg->btf_id;
9891                         }
9892                         break;
9893                 case KF_ARG_PTR_TO_KPTR:
9894                         if (reg->type != PTR_TO_MAP_VALUE) {
9895                                 verbose(env, "arg#0 expected pointer to map value\n");
9896                                 return -EINVAL;
9897                         }
9898                         ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
9899                         if (ret < 0)
9900                                 return ret;
9901                         break;
9902                 case KF_ARG_PTR_TO_DYNPTR:
9903                 {
9904                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
9905
9906                         if (reg->type != PTR_TO_STACK &&
9907                             reg->type != CONST_PTR_TO_DYNPTR) {
9908                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
9909                                 return -EINVAL;
9910                         }
9911
9912                         if (reg->type == CONST_PTR_TO_DYNPTR)
9913                                 dynptr_arg_type |= MEM_RDONLY;
9914
9915                         if (is_kfunc_arg_uninit(btf, &args[i]))
9916                                 dynptr_arg_type |= MEM_UNINIT;
9917
9918                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
9919                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
9920                         else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
9921                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
9922
9923                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
9924                         if (ret < 0)
9925                                 return ret;
9926
9927                         if (!(dynptr_arg_type & MEM_UNINIT)) {
9928                                 int id = dynptr_id(env, reg);
9929
9930                                 if (id < 0) {
9931                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9932                                         return id;
9933                                 }
9934                                 meta->initialized_dynptr.id = id;
9935                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
9936                         }
9937
9938                         break;
9939                 }
9940                 case KF_ARG_PTR_TO_LIST_HEAD:
9941                         if (reg->type != PTR_TO_MAP_VALUE &&
9942                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9943                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9944                                 return -EINVAL;
9945                         }
9946                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9947                                 verbose(env, "allocated object must be referenced\n");
9948                                 return -EINVAL;
9949                         }
9950                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
9951                         if (ret < 0)
9952                                 return ret;
9953                         break;
9954                 case KF_ARG_PTR_TO_RB_ROOT:
9955                         if (reg->type != PTR_TO_MAP_VALUE &&
9956                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9957                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
9958                                 return -EINVAL;
9959                         }
9960                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
9961                                 verbose(env, "allocated object must be referenced\n");
9962                                 return -EINVAL;
9963                         }
9964                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
9965                         if (ret < 0)
9966                                 return ret;
9967                         break;
9968                 case KF_ARG_PTR_TO_LIST_NODE:
9969                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9970                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
9971                                 return -EINVAL;
9972                         }
9973                         if (!reg->ref_obj_id) {
9974                                 verbose(env, "allocated object must be referenced\n");
9975                                 return -EINVAL;
9976                         }
9977                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
9978                         if (ret < 0)
9979                                 return ret;
9980                         break;
9981                 case KF_ARG_PTR_TO_RB_NODE:
9982                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
9983                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
9984                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
9985                                         return -EINVAL;
9986                                 }
9987                                 if (in_rbtree_lock_required_cb(env)) {
9988                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
9989                                         return -EINVAL;
9990                                 }
9991                         } else {
9992                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
9993                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
9994                                         return -EINVAL;
9995                                 }
9996                                 if (!reg->ref_obj_id) {
9997                                         verbose(env, "allocated object must be referenced\n");
9998                                         return -EINVAL;
9999                                 }
10000                         }
10001
10002                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10003                         if (ret < 0)
10004                                 return ret;
10005                         break;
10006                 case KF_ARG_PTR_TO_BTF_ID:
10007                         /* Only base_type is checked, further checks are done here */
10008                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10009                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10010                             !reg2btf_ids[base_type(reg->type)]) {
10011                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10012                                 verbose(env, "expected %s or socket\n",
10013                                         reg_type_str(env, base_type(reg->type) |
10014                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10015                                 return -EINVAL;
10016                         }
10017                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10018                         if (ret < 0)
10019                                 return ret;
10020                         break;
10021                 case KF_ARG_PTR_TO_MEM:
10022                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10023                         if (IS_ERR(resolve_ret)) {
10024                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10025                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10026                                 return -EINVAL;
10027                         }
10028                         ret = check_mem_reg(env, reg, regno, type_size);
10029                         if (ret < 0)
10030                                 return ret;
10031                         break;
10032                 case KF_ARG_PTR_TO_MEM_SIZE:
10033                 {
10034                         struct bpf_reg_state *size_reg = &regs[regno + 1];
10035                         const struct btf_param *size_arg = &args[i + 1];
10036
10037                         ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10038                         if (ret < 0) {
10039                                 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10040                                 return ret;
10041                         }
10042
10043                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10044                                 if (meta->arg_constant.found) {
10045                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10046                                         return -EFAULT;
10047                                 }
10048                                 if (!tnum_is_const(size_reg->var_off)) {
10049                                         verbose(env, "R%d must be a known constant\n", regno + 1);
10050                                         return -EINVAL;
10051                                 }
10052                                 meta->arg_constant.found = true;
10053                                 meta->arg_constant.value = size_reg->var_off.value;
10054                         }
10055
10056                         /* Skip next '__sz' or '__szk' argument */
10057                         i++;
10058                         break;
10059                 }
10060                 case KF_ARG_PTR_TO_CALLBACK:
10061                         meta->subprogno = reg->subprogno;
10062                         break;
10063                 }
10064         }
10065
10066         if (is_kfunc_release(meta) && !meta->release_regno) {
10067                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10068                         func_name);
10069                 return -EINVAL;
10070         }
10071
10072         return 0;
10073 }
10074
10075 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10076                             int *insn_idx_p)
10077 {
10078         const struct btf_type *t, *func, *func_proto, *ptr_type;
10079         u32 i, nargs, func_id, ptr_type_id, release_ref_obj_id;
10080         struct bpf_reg_state *regs = cur_regs(env);
10081         const char *func_name, *ptr_type_name;
10082         bool sleepable, rcu_lock, rcu_unlock;
10083         struct bpf_kfunc_call_arg_meta meta;
10084         int err, insn_idx = *insn_idx_p;
10085         const struct btf_param *args;
10086         const struct btf_type *ret_t;
10087         struct btf *desc_btf;
10088         u32 *kfunc_flags;
10089
10090         /* skip for now, but return error when we find this in fixup_kfunc_call */
10091         if (!insn->imm)
10092                 return 0;
10093
10094         desc_btf = find_kfunc_desc_btf(env, insn->off);
10095         if (IS_ERR(desc_btf))
10096                 return PTR_ERR(desc_btf);
10097
10098         func_id = insn->imm;
10099         func = btf_type_by_id(desc_btf, func_id);
10100         func_name = btf_name_by_offset(desc_btf, func->name_off);
10101         func_proto = btf_type_by_id(desc_btf, func->type);
10102
10103         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10104         if (!kfunc_flags) {
10105                 verbose(env, "calling kernel function %s is not allowed\n",
10106                         func_name);
10107                 return -EACCES;
10108         }
10109
10110         /* Prepare kfunc call metadata */
10111         memset(&meta, 0, sizeof(meta));
10112         meta.btf = desc_btf;
10113         meta.func_id = func_id;
10114         meta.kfunc_flags = *kfunc_flags;
10115         meta.func_proto = func_proto;
10116         meta.func_name = func_name;
10117
10118         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10119                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10120                 return -EACCES;
10121         }
10122
10123         sleepable = is_kfunc_sleepable(&meta);
10124         if (sleepable && !env->prog->aux->sleepable) {
10125                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10126                 return -EACCES;
10127         }
10128
10129         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10130         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10131
10132         if (env->cur_state->active_rcu_lock) {
10133                 struct bpf_func_state *state;
10134                 struct bpf_reg_state *reg;
10135
10136                 if (rcu_lock) {
10137                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10138                         return -EINVAL;
10139                 } else if (rcu_unlock) {
10140                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10141                                 if (reg->type & MEM_RCU) {
10142                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
10143                                         reg->type |= PTR_UNTRUSTED;
10144                                 }
10145                         }));
10146                         env->cur_state->active_rcu_lock = false;
10147                 } else if (sleepable) {
10148                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10149                         return -EACCES;
10150                 }
10151         } else if (rcu_lock) {
10152                 env->cur_state->active_rcu_lock = true;
10153         } else if (rcu_unlock) {
10154                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10155                 return -EINVAL;
10156         }
10157
10158         /* Check the arguments */
10159         err = check_kfunc_args(env, &meta, insn_idx);
10160         if (err < 0)
10161                 return err;
10162         /* In case of release function, we get register number of refcounted
10163          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
10164          */
10165         if (meta.release_regno) {
10166                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
10167                 if (err) {
10168                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10169                                 func_name, func_id);
10170                         return err;
10171                 }
10172         }
10173
10174         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
10175             meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
10176             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10177                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10178                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10179                 if (err) {
10180                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
10181                                 func_name, func_id);
10182                         return err;
10183                 }
10184
10185                 err = release_reference(env, release_ref_obj_id);
10186                 if (err) {
10187                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10188                                 func_name, func_id);
10189                         return err;
10190                 }
10191         }
10192
10193         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10194                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10195                                         set_rbtree_add_callback_state);
10196                 if (err) {
10197                         verbose(env, "kfunc %s#%d failed callback verification\n",
10198                                 func_name, func_id);
10199                         return err;
10200                 }
10201         }
10202
10203         for (i = 0; i < CALLER_SAVED_REGS; i++)
10204                 mark_reg_not_init(env, regs, caller_saved[i]);
10205
10206         /* Check return type */
10207         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
10208
10209         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
10210                 /* Only exception is bpf_obj_new_impl */
10211                 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
10212                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10213                         return -EINVAL;
10214                 }
10215         }
10216
10217         if (btf_type_is_scalar(t)) {
10218                 mark_reg_unknown(env, regs, BPF_REG_0);
10219                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10220         } else if (btf_type_is_ptr(t)) {
10221                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10222
10223                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10224                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
10225                                 struct btf *ret_btf;
10226                                 u32 ret_btf_id;
10227
10228                                 if (unlikely(!bpf_global_ma_set))
10229                                         return -ENOMEM;
10230
10231                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10232                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10233                                         return -EINVAL;
10234                                 }
10235
10236                                 ret_btf = env->prog->aux->btf;
10237                                 ret_btf_id = meta.arg_constant.value;
10238
10239                                 /* This may be NULL due to user not supplying a BTF */
10240                                 if (!ret_btf) {
10241                                         verbose(env, "bpf_obj_new requires prog BTF\n");
10242                                         return -EINVAL;
10243                                 }
10244
10245                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10246                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
10247                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10248                                         return -EINVAL;
10249                                 }
10250
10251                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10252                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10253                                 regs[BPF_REG_0].btf = ret_btf;
10254                                 regs[BPF_REG_0].btf_id = ret_btf_id;
10255
10256                                 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
10257                                 env->insn_aux_data[insn_idx].kptr_struct_meta =
10258                                         btf_find_struct_meta(ret_btf, ret_btf_id);
10259                         } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10260                                 env->insn_aux_data[insn_idx].kptr_struct_meta =
10261                                         btf_find_struct_meta(meta.arg_obj_drop.btf,
10262                                                              meta.arg_obj_drop.btf_id);
10263                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10264                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10265                                 struct btf_field *field = meta.arg_list_head.field;
10266
10267                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10268                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10269                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10270                                 struct btf_field *field = meta.arg_rbtree_root.field;
10271
10272                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10273                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10274                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10275                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
10276                                 regs[BPF_REG_0].btf = desc_btf;
10277                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10278                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
10279                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
10280                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
10281                                         verbose(env,
10282                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
10283                                         return -EINVAL;
10284                                 }
10285
10286                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10287                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
10288                                 regs[BPF_REG_0].btf = desc_btf;
10289                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
10290                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
10291                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
10292                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
10293
10294                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10295
10296                                 if (!meta.arg_constant.found) {
10297                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
10298                                         return -EFAULT;
10299                                 }
10300
10301                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
10302
10303                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
10304                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
10305
10306                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
10307                                         regs[BPF_REG_0].type |= MEM_RDONLY;
10308                                 } else {
10309                                         /* this will set env->seen_direct_write to true */
10310                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
10311                                                 verbose(env, "the prog does not allow writes to packet data\n");
10312                                                 return -EINVAL;
10313                                         }
10314                                 }
10315
10316                                 if (!meta.initialized_dynptr.id) {
10317                                         verbose(env, "verifier internal error: no dynptr id\n");
10318                                         return -EFAULT;
10319                                 }
10320                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
10321
10322                                 /* we don't need to set BPF_REG_0's ref obj id
10323                                  * because packet slices are not refcounted (see
10324                                  * dynptr_type_refcounted)
10325                                  */
10326                         } else {
10327                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
10328                                         meta.func_name);
10329                                 return -EFAULT;
10330                         }
10331                 } else if (!__btf_type_is_struct(ptr_type)) {
10332                         if (!meta.r0_size) {
10333                                 ptr_type_name = btf_name_by_offset(desc_btf,
10334                                                                    ptr_type->name_off);
10335                                 verbose(env,
10336                                         "kernel function %s returns pointer type %s %s is not supported\n",
10337                                         func_name,
10338                                         btf_type_str(ptr_type),
10339                                         ptr_type_name);
10340                                 return -EINVAL;
10341                         }
10342
10343                         mark_reg_known_zero(env, regs, BPF_REG_0);
10344                         regs[BPF_REG_0].type = PTR_TO_MEM;
10345                         regs[BPF_REG_0].mem_size = meta.r0_size;
10346
10347                         if (meta.r0_rdonly)
10348                                 regs[BPF_REG_0].type |= MEM_RDONLY;
10349
10350                         /* Ensures we don't access the memory after a release_reference() */
10351                         if (meta.ref_obj_id)
10352                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10353                 } else {
10354                         mark_reg_known_zero(env, regs, BPF_REG_0);
10355                         regs[BPF_REG_0].btf = desc_btf;
10356                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10357                         regs[BPF_REG_0].btf_id = ptr_type_id;
10358                 }
10359
10360                 if (is_kfunc_ret_null(&meta)) {
10361                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10362                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10363                         regs[BPF_REG_0].id = ++env->id_gen;
10364                 }
10365                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10366                 if (is_kfunc_acquire(&meta)) {
10367                         int id = acquire_reference_state(env, insn_idx);
10368
10369                         if (id < 0)
10370                                 return id;
10371                         if (is_kfunc_ret_null(&meta))
10372                                 regs[BPF_REG_0].id = id;
10373                         regs[BPF_REG_0].ref_obj_id = id;
10374                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10375                         ref_set_non_owning(env, &regs[BPF_REG_0]);
10376                 }
10377
10378                 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10379                         invalidate_non_owning_refs(env);
10380
10381                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
10382                         regs[BPF_REG_0].id = ++env->id_gen;
10383         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
10384
10385         nargs = btf_type_vlen(func_proto);
10386         args = (const struct btf_param *)(func_proto + 1);
10387         for (i = 0; i < nargs; i++) {
10388                 u32 regno = i + 1;
10389
10390                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10391                 if (btf_type_is_ptr(t))
10392                         mark_btf_func_reg_size(env, regno, sizeof(void *));
10393                 else
10394                         /* scalar. ensured by btf_check_kfunc_arg_match() */
10395                         mark_btf_func_reg_size(env, regno, t->size);
10396         }
10397
10398         return 0;
10399 }
10400
10401 static bool signed_add_overflows(s64 a, s64 b)
10402 {
10403         /* Do the add in u64, where overflow is well-defined */
10404         s64 res = (s64)((u64)a + (u64)b);
10405
10406         if (b < 0)
10407                 return res > a;
10408         return res < a;
10409 }
10410
10411 static bool signed_add32_overflows(s32 a, s32 b)
10412 {
10413         /* Do the add in u32, where overflow is well-defined */
10414         s32 res = (s32)((u32)a + (u32)b);
10415
10416         if (b < 0)
10417                 return res > a;
10418         return res < a;
10419 }
10420
10421 static bool signed_sub_overflows(s64 a, s64 b)
10422 {
10423         /* Do the sub in u64, where overflow is well-defined */
10424         s64 res = (s64)((u64)a - (u64)b);
10425
10426         if (b < 0)
10427                 return res < a;
10428         return res > a;
10429 }
10430
10431 static bool signed_sub32_overflows(s32 a, s32 b)
10432 {
10433         /* Do the sub in u32, where overflow is well-defined */
10434         s32 res = (s32)((u32)a - (u32)b);
10435
10436         if (b < 0)
10437                 return res < a;
10438         return res > a;
10439 }
10440
10441 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10442                                   const struct bpf_reg_state *reg,
10443                                   enum bpf_reg_type type)
10444 {
10445         bool known = tnum_is_const(reg->var_off);
10446         s64 val = reg->var_off.value;
10447         s64 smin = reg->smin_value;
10448
10449         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10450                 verbose(env, "math between %s pointer and %lld is not allowed\n",
10451                         reg_type_str(env, type), val);
10452                 return false;
10453         }
10454
10455         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10456                 verbose(env, "%s pointer offset %d is not allowed\n",
10457                         reg_type_str(env, type), reg->off);
10458                 return false;
10459         }
10460
10461         if (smin == S64_MIN) {
10462                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10463                         reg_type_str(env, type));
10464                 return false;
10465         }
10466
10467         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10468                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
10469                         smin, reg_type_str(env, type));
10470                 return false;
10471         }
10472
10473         return true;
10474 }
10475
10476 enum {
10477         REASON_BOUNDS   = -1,
10478         REASON_TYPE     = -2,
10479         REASON_PATHS    = -3,
10480         REASON_LIMIT    = -4,
10481         REASON_STACK    = -5,
10482 };
10483
10484 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10485                               u32 *alu_limit, bool mask_to_left)
10486 {
10487         u32 max = 0, ptr_limit = 0;
10488
10489         switch (ptr_reg->type) {
10490         case PTR_TO_STACK:
10491                 /* Offset 0 is out-of-bounds, but acceptable start for the
10492                  * left direction, see BPF_REG_FP. Also, unknown scalar
10493                  * offset where we would need to deal with min/max bounds is
10494                  * currently prohibited for unprivileged.
10495                  */
10496                 max = MAX_BPF_STACK + mask_to_left;
10497                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10498                 break;
10499         case PTR_TO_MAP_VALUE:
10500                 max = ptr_reg->map_ptr->value_size;
10501                 ptr_limit = (mask_to_left ?
10502                              ptr_reg->smin_value :
10503                              ptr_reg->umax_value) + ptr_reg->off;
10504                 break;
10505         default:
10506                 return REASON_TYPE;
10507         }
10508
10509         if (ptr_limit >= max)
10510                 return REASON_LIMIT;
10511         *alu_limit = ptr_limit;
10512         return 0;
10513 }
10514
10515 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
10516                                     const struct bpf_insn *insn)
10517 {
10518         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
10519 }
10520
10521 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
10522                                        u32 alu_state, u32 alu_limit)
10523 {
10524         /* If we arrived here from different branches with different
10525          * state or limits to sanitize, then this won't work.
10526          */
10527         if (aux->alu_state &&
10528             (aux->alu_state != alu_state ||
10529              aux->alu_limit != alu_limit))
10530                 return REASON_PATHS;
10531
10532         /* Corresponding fixup done in do_misc_fixups(). */
10533         aux->alu_state = alu_state;
10534         aux->alu_limit = alu_limit;
10535         return 0;
10536 }
10537
10538 static int sanitize_val_alu(struct bpf_verifier_env *env,
10539                             struct bpf_insn *insn)
10540 {
10541         struct bpf_insn_aux_data *aux = cur_aux(env);
10542
10543         if (can_skip_alu_sanitation(env, insn))
10544                 return 0;
10545
10546         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
10547 }
10548
10549 static bool sanitize_needed(u8 opcode)
10550 {
10551         return opcode == BPF_ADD || opcode == BPF_SUB;
10552 }
10553
10554 struct bpf_sanitize_info {
10555         struct bpf_insn_aux_data aux;
10556         bool mask_to_left;
10557 };
10558
10559 static struct bpf_verifier_state *
10560 sanitize_speculative_path(struct bpf_verifier_env *env,
10561                           const struct bpf_insn *insn,
10562                           u32 next_idx, u32 curr_idx)
10563 {
10564         struct bpf_verifier_state *branch;
10565         struct bpf_reg_state *regs;
10566
10567         branch = push_stack(env, next_idx, curr_idx, true);
10568         if (branch && insn) {
10569                 regs = branch->frame[branch->curframe]->regs;
10570                 if (BPF_SRC(insn->code) == BPF_K) {
10571                         mark_reg_unknown(env, regs, insn->dst_reg);
10572                 } else if (BPF_SRC(insn->code) == BPF_X) {
10573                         mark_reg_unknown(env, regs, insn->dst_reg);
10574                         mark_reg_unknown(env, regs, insn->src_reg);
10575                 }
10576         }
10577         return branch;
10578 }
10579
10580 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
10581                             struct bpf_insn *insn,
10582                             const struct bpf_reg_state *ptr_reg,
10583                             const struct bpf_reg_state *off_reg,
10584                             struct bpf_reg_state *dst_reg,
10585                             struct bpf_sanitize_info *info,
10586                             const bool commit_window)
10587 {
10588         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
10589         struct bpf_verifier_state *vstate = env->cur_state;
10590         bool off_is_imm = tnum_is_const(off_reg->var_off);
10591         bool off_is_neg = off_reg->smin_value < 0;
10592         bool ptr_is_dst_reg = ptr_reg == dst_reg;
10593         u8 opcode = BPF_OP(insn->code);
10594         u32 alu_state, alu_limit;
10595         struct bpf_reg_state tmp;
10596         bool ret;
10597         int err;
10598
10599         if (can_skip_alu_sanitation(env, insn))
10600                 return 0;
10601
10602         /* We already marked aux for masking from non-speculative
10603          * paths, thus we got here in the first place. We only care
10604          * to explore bad access from here.
10605          */
10606         if (vstate->speculative)
10607                 goto do_sim;
10608
10609         if (!commit_window) {
10610                 if (!tnum_is_const(off_reg->var_off) &&
10611                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
10612                         return REASON_BOUNDS;
10613
10614                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
10615                                      (opcode == BPF_SUB && !off_is_neg);
10616         }
10617
10618         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
10619         if (err < 0)
10620                 return err;
10621
10622         if (commit_window) {
10623                 /* In commit phase we narrow the masking window based on
10624                  * the observed pointer move after the simulated operation.
10625                  */
10626                 alu_state = info->aux.alu_state;
10627                 alu_limit = abs(info->aux.alu_limit - alu_limit);
10628         } else {
10629                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
10630                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
10631                 alu_state |= ptr_is_dst_reg ?
10632                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
10633
10634                 /* Limit pruning on unknown scalars to enable deep search for
10635                  * potential masking differences from other program paths.
10636                  */
10637                 if (!off_is_imm)
10638                         env->explore_alu_limits = true;
10639         }
10640
10641         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
10642         if (err < 0)
10643                 return err;
10644 do_sim:
10645         /* If we're in commit phase, we're done here given we already
10646          * pushed the truncated dst_reg into the speculative verification
10647          * stack.
10648          *
10649          * Also, when register is a known constant, we rewrite register-based
10650          * operation to immediate-based, and thus do not need masking (and as
10651          * a consequence, do not need to simulate the zero-truncation either).
10652          */
10653         if (commit_window || off_is_imm)
10654                 return 0;
10655
10656         /* Simulate and find potential out-of-bounds access under
10657          * speculative execution from truncation as a result of
10658          * masking when off was not within expected range. If off
10659          * sits in dst, then we temporarily need to move ptr there
10660          * to simulate dst (== 0) +/-= ptr. Needed, for example,
10661          * for cases where we use K-based arithmetic in one direction
10662          * and truncated reg-based in the other in order to explore
10663          * bad access.
10664          */
10665         if (!ptr_is_dst_reg) {
10666                 tmp = *dst_reg;
10667                 copy_register_state(dst_reg, ptr_reg);
10668         }
10669         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
10670                                         env->insn_idx);
10671         if (!ptr_is_dst_reg && ret)
10672                 *dst_reg = tmp;
10673         return !ret ? REASON_STACK : 0;
10674 }
10675
10676 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
10677 {
10678         struct bpf_verifier_state *vstate = env->cur_state;
10679
10680         /* If we simulate paths under speculation, we don't update the
10681          * insn as 'seen' such that when we verify unreachable paths in
10682          * the non-speculative domain, sanitize_dead_code() can still
10683          * rewrite/sanitize them.
10684          */
10685         if (!vstate->speculative)
10686                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10687 }
10688
10689 static int sanitize_err(struct bpf_verifier_env *env,
10690                         const struct bpf_insn *insn, int reason,
10691                         const struct bpf_reg_state *off_reg,
10692                         const struct bpf_reg_state *dst_reg)
10693 {
10694         static const char *err = "pointer arithmetic with it prohibited for !root";
10695         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
10696         u32 dst = insn->dst_reg, src = insn->src_reg;
10697
10698         switch (reason) {
10699         case REASON_BOUNDS:
10700                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
10701                         off_reg == dst_reg ? dst : src, err);
10702                 break;
10703         case REASON_TYPE:
10704                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
10705                         off_reg == dst_reg ? src : dst, err);
10706                 break;
10707         case REASON_PATHS:
10708                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
10709                         dst, op, err);
10710                 break;
10711         case REASON_LIMIT:
10712                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
10713                         dst, op, err);
10714                 break;
10715         case REASON_STACK:
10716                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
10717                         dst, err);
10718                 break;
10719         default:
10720                 verbose(env, "verifier internal error: unknown reason (%d)\n",
10721                         reason);
10722                 break;
10723         }
10724
10725         return -EACCES;
10726 }
10727
10728 /* check that stack access falls within stack limits and that 'reg' doesn't
10729  * have a variable offset.
10730  *
10731  * Variable offset is prohibited for unprivileged mode for simplicity since it
10732  * requires corresponding support in Spectre masking for stack ALU.  See also
10733  * retrieve_ptr_limit().
10734  *
10735  *
10736  * 'off' includes 'reg->off'.
10737  */
10738 static int check_stack_access_for_ptr_arithmetic(
10739                                 struct bpf_verifier_env *env,
10740                                 int regno,
10741                                 const struct bpf_reg_state *reg,
10742                                 int off)
10743 {
10744         if (!tnum_is_const(reg->var_off)) {
10745                 char tn_buf[48];
10746
10747                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
10748                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
10749                         regno, tn_buf, off);
10750                 return -EACCES;
10751         }
10752
10753         if (off >= 0 || off < -MAX_BPF_STACK) {
10754                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
10755                         "prohibited for !root; off=%d\n", regno, off);
10756                 return -EACCES;
10757         }
10758
10759         return 0;
10760 }
10761
10762 static int sanitize_check_bounds(struct bpf_verifier_env *env,
10763                                  const struct bpf_insn *insn,
10764                                  const struct bpf_reg_state *dst_reg)
10765 {
10766         u32 dst = insn->dst_reg;
10767
10768         /* For unprivileged we require that resulting offset must be in bounds
10769          * in order to be able to sanitize access later on.
10770          */
10771         if (env->bypass_spec_v1)
10772                 return 0;
10773
10774         switch (dst_reg->type) {
10775         case PTR_TO_STACK:
10776                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
10777                                         dst_reg->off + dst_reg->var_off.value))
10778                         return -EACCES;
10779                 break;
10780         case PTR_TO_MAP_VALUE:
10781                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
10782                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
10783                                 "prohibited for !root\n", dst);
10784                         return -EACCES;
10785                 }
10786                 break;
10787         default:
10788                 break;
10789         }
10790
10791         return 0;
10792 }
10793
10794 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
10795  * Caller should also handle BPF_MOV case separately.
10796  * If we return -EACCES, caller may want to try again treating pointer as a
10797  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
10798  */
10799 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
10800                                    struct bpf_insn *insn,
10801                                    const struct bpf_reg_state *ptr_reg,
10802                                    const struct bpf_reg_state *off_reg)
10803 {
10804         struct bpf_verifier_state *vstate = env->cur_state;
10805         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10806         struct bpf_reg_state *regs = state->regs, *dst_reg;
10807         bool known = tnum_is_const(off_reg->var_off);
10808         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
10809             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
10810         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
10811             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
10812         struct bpf_sanitize_info info = {};
10813         u8 opcode = BPF_OP(insn->code);
10814         u32 dst = insn->dst_reg;
10815         int ret;
10816
10817         dst_reg = &regs[dst];
10818
10819         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
10820             smin_val > smax_val || umin_val > umax_val) {
10821                 /* Taint dst register if offset had invalid bounds derived from
10822                  * e.g. dead branches.
10823                  */
10824                 __mark_reg_unknown(env, dst_reg);
10825                 return 0;
10826         }
10827
10828         if (BPF_CLASS(insn->code) != BPF_ALU64) {
10829                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
10830                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10831                         __mark_reg_unknown(env, dst_reg);
10832                         return 0;
10833                 }
10834
10835                 verbose(env,
10836                         "R%d 32-bit pointer arithmetic prohibited\n",
10837                         dst);
10838                 return -EACCES;
10839         }
10840
10841         if (ptr_reg->type & PTR_MAYBE_NULL) {
10842                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
10843                         dst, reg_type_str(env, ptr_reg->type));
10844                 return -EACCES;
10845         }
10846
10847         switch (base_type(ptr_reg->type)) {
10848         case CONST_PTR_TO_MAP:
10849                 /* smin_val represents the known value */
10850                 if (known && smin_val == 0 && opcode == BPF_ADD)
10851                         break;
10852                 fallthrough;
10853         case PTR_TO_PACKET_END:
10854         case PTR_TO_SOCKET:
10855         case PTR_TO_SOCK_COMMON:
10856         case PTR_TO_TCP_SOCK:
10857         case PTR_TO_XDP_SOCK:
10858                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
10859                         dst, reg_type_str(env, ptr_reg->type));
10860                 return -EACCES;
10861         default:
10862                 break;
10863         }
10864
10865         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
10866          * The id may be overwritten later if we create a new variable offset.
10867          */
10868         dst_reg->type = ptr_reg->type;
10869         dst_reg->id = ptr_reg->id;
10870
10871         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
10872             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
10873                 return -EINVAL;
10874
10875         /* pointer types do not carry 32-bit bounds at the moment. */
10876         __mark_reg32_unbounded(dst_reg);
10877
10878         if (sanitize_needed(opcode)) {
10879                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
10880                                        &info, false);
10881                 if (ret < 0)
10882                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
10883         }
10884
10885         switch (opcode) {
10886         case BPF_ADD:
10887                 /* We can take a fixed offset as long as it doesn't overflow
10888                  * the s32 'off' field
10889                  */
10890                 if (known && (ptr_reg->off + smin_val ==
10891                               (s64)(s32)(ptr_reg->off + smin_val))) {
10892                         /* pointer += K.  Accumulate it into fixed offset */
10893                         dst_reg->smin_value = smin_ptr;
10894                         dst_reg->smax_value = smax_ptr;
10895                         dst_reg->umin_value = umin_ptr;
10896                         dst_reg->umax_value = umax_ptr;
10897                         dst_reg->var_off = ptr_reg->var_off;
10898                         dst_reg->off = ptr_reg->off + smin_val;
10899                         dst_reg->raw = ptr_reg->raw;
10900                         break;
10901                 }
10902                 /* A new variable offset is created.  Note that off_reg->off
10903                  * == 0, since it's a scalar.
10904                  * dst_reg gets the pointer type and since some positive
10905                  * integer value was added to the pointer, give it a new 'id'
10906                  * if it's a PTR_TO_PACKET.
10907                  * this creates a new 'base' pointer, off_reg (variable) gets
10908                  * added into the variable offset, and we copy the fixed offset
10909                  * from ptr_reg.
10910                  */
10911                 if (signed_add_overflows(smin_ptr, smin_val) ||
10912                     signed_add_overflows(smax_ptr, smax_val)) {
10913                         dst_reg->smin_value = S64_MIN;
10914                         dst_reg->smax_value = S64_MAX;
10915                 } else {
10916                         dst_reg->smin_value = smin_ptr + smin_val;
10917                         dst_reg->smax_value = smax_ptr + smax_val;
10918                 }
10919                 if (umin_ptr + umin_val < umin_ptr ||
10920                     umax_ptr + umax_val < umax_ptr) {
10921                         dst_reg->umin_value = 0;
10922                         dst_reg->umax_value = U64_MAX;
10923                 } else {
10924                         dst_reg->umin_value = umin_ptr + umin_val;
10925                         dst_reg->umax_value = umax_ptr + umax_val;
10926                 }
10927                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
10928                 dst_reg->off = ptr_reg->off;
10929                 dst_reg->raw = ptr_reg->raw;
10930                 if (reg_is_pkt_pointer(ptr_reg)) {
10931                         dst_reg->id = ++env->id_gen;
10932                         /* something was added to pkt_ptr, set range to zero */
10933                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10934                 }
10935                 break;
10936         case BPF_SUB:
10937                 if (dst_reg == off_reg) {
10938                         /* scalar -= pointer.  Creates an unknown scalar */
10939                         verbose(env, "R%d tried to subtract pointer from scalar\n",
10940                                 dst);
10941                         return -EACCES;
10942                 }
10943                 /* We don't allow subtraction from FP, because (according to
10944                  * test_verifier.c test "invalid fp arithmetic", JITs might not
10945                  * be able to deal with it.
10946                  */
10947                 if (ptr_reg->type == PTR_TO_STACK) {
10948                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
10949                                 dst);
10950                         return -EACCES;
10951                 }
10952                 if (known && (ptr_reg->off - smin_val ==
10953                               (s64)(s32)(ptr_reg->off - smin_val))) {
10954                         /* pointer -= K.  Subtract it from fixed offset */
10955                         dst_reg->smin_value = smin_ptr;
10956                         dst_reg->smax_value = smax_ptr;
10957                         dst_reg->umin_value = umin_ptr;
10958                         dst_reg->umax_value = umax_ptr;
10959                         dst_reg->var_off = ptr_reg->var_off;
10960                         dst_reg->id = ptr_reg->id;
10961                         dst_reg->off = ptr_reg->off - smin_val;
10962                         dst_reg->raw = ptr_reg->raw;
10963                         break;
10964                 }
10965                 /* A new variable offset is created.  If the subtrahend is known
10966                  * nonnegative, then any reg->range we had before is still good.
10967                  */
10968                 if (signed_sub_overflows(smin_ptr, smax_val) ||
10969                     signed_sub_overflows(smax_ptr, smin_val)) {
10970                         /* Overflow possible, we know nothing */
10971                         dst_reg->smin_value = S64_MIN;
10972                         dst_reg->smax_value = S64_MAX;
10973                 } else {
10974                         dst_reg->smin_value = smin_ptr - smax_val;
10975                         dst_reg->smax_value = smax_ptr - smin_val;
10976                 }
10977                 if (umin_ptr < umax_val) {
10978                         /* Overflow possible, we know nothing */
10979                         dst_reg->umin_value = 0;
10980                         dst_reg->umax_value = U64_MAX;
10981                 } else {
10982                         /* Cannot overflow (as long as bounds are consistent) */
10983                         dst_reg->umin_value = umin_ptr - umax_val;
10984                         dst_reg->umax_value = umax_ptr - umin_val;
10985                 }
10986                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
10987                 dst_reg->off = ptr_reg->off;
10988                 dst_reg->raw = ptr_reg->raw;
10989                 if (reg_is_pkt_pointer(ptr_reg)) {
10990                         dst_reg->id = ++env->id_gen;
10991                         /* something was added to pkt_ptr, set range to zero */
10992                         if (smin_val < 0)
10993                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
10994                 }
10995                 break;
10996         case BPF_AND:
10997         case BPF_OR:
10998         case BPF_XOR:
10999                 /* bitwise ops on pointers are troublesome, prohibit. */
11000                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11001                         dst, bpf_alu_string[opcode >> 4]);
11002                 return -EACCES;
11003         default:
11004                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
11005                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11006                         dst, bpf_alu_string[opcode >> 4]);
11007                 return -EACCES;
11008         }
11009
11010         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11011                 return -EINVAL;
11012         reg_bounds_sync(dst_reg);
11013         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11014                 return -EACCES;
11015         if (sanitize_needed(opcode)) {
11016                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11017                                        &info, true);
11018                 if (ret < 0)
11019                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
11020         }
11021
11022         return 0;
11023 }
11024
11025 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11026                                  struct bpf_reg_state *src_reg)
11027 {
11028         s32 smin_val = src_reg->s32_min_value;
11029         s32 smax_val = src_reg->s32_max_value;
11030         u32 umin_val = src_reg->u32_min_value;
11031         u32 umax_val = src_reg->u32_max_value;
11032
11033         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11034             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11035                 dst_reg->s32_min_value = S32_MIN;
11036                 dst_reg->s32_max_value = S32_MAX;
11037         } else {
11038                 dst_reg->s32_min_value += smin_val;
11039                 dst_reg->s32_max_value += smax_val;
11040         }
11041         if (dst_reg->u32_min_value + umin_val < umin_val ||
11042             dst_reg->u32_max_value + umax_val < umax_val) {
11043                 dst_reg->u32_min_value = 0;
11044                 dst_reg->u32_max_value = U32_MAX;
11045         } else {
11046                 dst_reg->u32_min_value += umin_val;
11047                 dst_reg->u32_max_value += umax_val;
11048         }
11049 }
11050
11051 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11052                                struct bpf_reg_state *src_reg)
11053 {
11054         s64 smin_val = src_reg->smin_value;
11055         s64 smax_val = src_reg->smax_value;
11056         u64 umin_val = src_reg->umin_value;
11057         u64 umax_val = src_reg->umax_value;
11058
11059         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11060             signed_add_overflows(dst_reg->smax_value, smax_val)) {
11061                 dst_reg->smin_value = S64_MIN;
11062                 dst_reg->smax_value = S64_MAX;
11063         } else {
11064                 dst_reg->smin_value += smin_val;
11065                 dst_reg->smax_value += smax_val;
11066         }
11067         if (dst_reg->umin_value + umin_val < umin_val ||
11068             dst_reg->umax_value + umax_val < umax_val) {
11069                 dst_reg->umin_value = 0;
11070                 dst_reg->umax_value = U64_MAX;
11071         } else {
11072                 dst_reg->umin_value += umin_val;
11073                 dst_reg->umax_value += umax_val;
11074         }
11075 }
11076
11077 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11078                                  struct bpf_reg_state *src_reg)
11079 {
11080         s32 smin_val = src_reg->s32_min_value;
11081         s32 smax_val = src_reg->s32_max_value;
11082         u32 umin_val = src_reg->u32_min_value;
11083         u32 umax_val = src_reg->u32_max_value;
11084
11085         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11086             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11087                 /* Overflow possible, we know nothing */
11088                 dst_reg->s32_min_value = S32_MIN;
11089                 dst_reg->s32_max_value = S32_MAX;
11090         } else {
11091                 dst_reg->s32_min_value -= smax_val;
11092                 dst_reg->s32_max_value -= smin_val;
11093         }
11094         if (dst_reg->u32_min_value < umax_val) {
11095                 /* Overflow possible, we know nothing */
11096                 dst_reg->u32_min_value = 0;
11097                 dst_reg->u32_max_value = U32_MAX;
11098         } else {
11099                 /* Cannot overflow (as long as bounds are consistent) */
11100                 dst_reg->u32_min_value -= umax_val;
11101                 dst_reg->u32_max_value -= umin_val;
11102         }
11103 }
11104
11105 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11106                                struct bpf_reg_state *src_reg)
11107 {
11108         s64 smin_val = src_reg->smin_value;
11109         s64 smax_val = src_reg->smax_value;
11110         u64 umin_val = src_reg->umin_value;
11111         u64 umax_val = src_reg->umax_value;
11112
11113         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11114             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11115                 /* Overflow possible, we know nothing */
11116                 dst_reg->smin_value = S64_MIN;
11117                 dst_reg->smax_value = S64_MAX;
11118         } else {
11119                 dst_reg->smin_value -= smax_val;
11120                 dst_reg->smax_value -= smin_val;
11121         }
11122         if (dst_reg->umin_value < umax_val) {
11123                 /* Overflow possible, we know nothing */
11124                 dst_reg->umin_value = 0;
11125                 dst_reg->umax_value = U64_MAX;
11126         } else {
11127                 /* Cannot overflow (as long as bounds are consistent) */
11128                 dst_reg->umin_value -= umax_val;
11129                 dst_reg->umax_value -= umin_val;
11130         }
11131 }
11132
11133 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11134                                  struct bpf_reg_state *src_reg)
11135 {
11136         s32 smin_val = src_reg->s32_min_value;
11137         u32 umin_val = src_reg->u32_min_value;
11138         u32 umax_val = src_reg->u32_max_value;
11139
11140         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11141                 /* Ain't nobody got time to multiply that sign */
11142                 __mark_reg32_unbounded(dst_reg);
11143                 return;
11144         }
11145         /* Both values are positive, so we can work with unsigned and
11146          * copy the result to signed (unless it exceeds S32_MAX).
11147          */
11148         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11149                 /* Potential overflow, we know nothing */
11150                 __mark_reg32_unbounded(dst_reg);
11151                 return;
11152         }
11153         dst_reg->u32_min_value *= umin_val;
11154         dst_reg->u32_max_value *= umax_val;
11155         if (dst_reg->u32_max_value > S32_MAX) {
11156                 /* Overflow possible, we know nothing */
11157                 dst_reg->s32_min_value = S32_MIN;
11158                 dst_reg->s32_max_value = S32_MAX;
11159         } else {
11160                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11161                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11162         }
11163 }
11164
11165 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11166                                struct bpf_reg_state *src_reg)
11167 {
11168         s64 smin_val = src_reg->smin_value;
11169         u64 umin_val = src_reg->umin_value;
11170         u64 umax_val = src_reg->umax_value;
11171
11172         if (smin_val < 0 || dst_reg->smin_value < 0) {
11173                 /* Ain't nobody got time to multiply that sign */
11174                 __mark_reg64_unbounded(dst_reg);
11175                 return;
11176         }
11177         /* Both values are positive, so we can work with unsigned and
11178          * copy the result to signed (unless it exceeds S64_MAX).
11179          */
11180         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11181                 /* Potential overflow, we know nothing */
11182                 __mark_reg64_unbounded(dst_reg);
11183                 return;
11184         }
11185         dst_reg->umin_value *= umin_val;
11186         dst_reg->umax_value *= umax_val;
11187         if (dst_reg->umax_value > S64_MAX) {
11188                 /* Overflow possible, we know nothing */
11189                 dst_reg->smin_value = S64_MIN;
11190                 dst_reg->smax_value = S64_MAX;
11191         } else {
11192                 dst_reg->smin_value = dst_reg->umin_value;
11193                 dst_reg->smax_value = dst_reg->umax_value;
11194         }
11195 }
11196
11197 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11198                                  struct bpf_reg_state *src_reg)
11199 {
11200         bool src_known = tnum_subreg_is_const(src_reg->var_off);
11201         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11202         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11203         s32 smin_val = src_reg->s32_min_value;
11204         u32 umax_val = src_reg->u32_max_value;
11205
11206         if (src_known && dst_known) {
11207                 __mark_reg32_known(dst_reg, var32_off.value);
11208                 return;
11209         }
11210
11211         /* We get our minimum from the var_off, since that's inherently
11212          * bitwise.  Our maximum is the minimum of the operands' maxima.
11213          */
11214         dst_reg->u32_min_value = var32_off.value;
11215         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11216         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11217                 /* Lose signed bounds when ANDing negative numbers,
11218                  * ain't nobody got time for that.
11219                  */
11220                 dst_reg->s32_min_value = S32_MIN;
11221                 dst_reg->s32_max_value = S32_MAX;
11222         } else {
11223                 /* ANDing two positives gives a positive, so safe to
11224                  * cast result into s64.
11225                  */
11226                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11227                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11228         }
11229 }
11230
11231 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11232                                struct bpf_reg_state *src_reg)
11233 {
11234         bool src_known = tnum_is_const(src_reg->var_off);
11235         bool dst_known = tnum_is_const(dst_reg->var_off);
11236         s64 smin_val = src_reg->smin_value;
11237         u64 umax_val = src_reg->umax_value;
11238
11239         if (src_known && dst_known) {
11240                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11241                 return;
11242         }
11243
11244         /* We get our minimum from the var_off, since that's inherently
11245          * bitwise.  Our maximum is the minimum of the operands' maxima.
11246          */
11247         dst_reg->umin_value = dst_reg->var_off.value;
11248         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11249         if (dst_reg->smin_value < 0 || smin_val < 0) {
11250                 /* Lose signed bounds when ANDing negative numbers,
11251                  * ain't nobody got time for that.
11252                  */
11253                 dst_reg->smin_value = S64_MIN;
11254                 dst_reg->smax_value = S64_MAX;
11255         } else {
11256                 /* ANDing two positives gives a positive, so safe to
11257                  * cast result into s64.
11258                  */
11259                 dst_reg->smin_value = dst_reg->umin_value;
11260                 dst_reg->smax_value = dst_reg->umax_value;
11261         }
11262         /* We may learn something more from the var_off */
11263         __update_reg_bounds(dst_reg);
11264 }
11265
11266 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
11267                                 struct bpf_reg_state *src_reg)
11268 {
11269         bool src_known = tnum_subreg_is_const(src_reg->var_off);
11270         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11271         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11272         s32 smin_val = src_reg->s32_min_value;
11273         u32 umin_val = src_reg->u32_min_value;
11274
11275         if (src_known && dst_known) {
11276                 __mark_reg32_known(dst_reg, var32_off.value);
11277                 return;
11278         }
11279
11280         /* We get our maximum from the var_off, and our minimum is the
11281          * maximum of the operands' minima
11282          */
11283         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
11284         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11285         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11286                 /* Lose signed bounds when ORing negative numbers,
11287                  * ain't nobody got time for that.
11288                  */
11289                 dst_reg->s32_min_value = S32_MIN;
11290                 dst_reg->s32_max_value = S32_MAX;
11291         } else {
11292                 /* ORing two positives gives a positive, so safe to
11293                  * cast result into s64.
11294                  */
11295                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11296                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11297         }
11298 }
11299
11300 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
11301                               struct bpf_reg_state *src_reg)
11302 {
11303         bool src_known = tnum_is_const(src_reg->var_off);
11304         bool dst_known = tnum_is_const(dst_reg->var_off);
11305         s64 smin_val = src_reg->smin_value;
11306         u64 umin_val = src_reg->umin_value;
11307
11308         if (src_known && dst_known) {
11309                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11310                 return;
11311         }
11312
11313         /* We get our maximum from the var_off, and our minimum is the
11314          * maximum of the operands' minima
11315          */
11316         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
11317         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11318         if (dst_reg->smin_value < 0 || smin_val < 0) {
11319                 /* Lose signed bounds when ORing negative numbers,
11320                  * ain't nobody got time for that.
11321                  */
11322                 dst_reg->smin_value = S64_MIN;
11323                 dst_reg->smax_value = S64_MAX;
11324         } else {
11325                 /* ORing two positives gives a positive, so safe to
11326                  * cast result into s64.
11327                  */
11328                 dst_reg->smin_value = dst_reg->umin_value;
11329                 dst_reg->smax_value = dst_reg->umax_value;
11330         }
11331         /* We may learn something more from the var_off */
11332         __update_reg_bounds(dst_reg);
11333 }
11334
11335 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11336                                  struct bpf_reg_state *src_reg)
11337 {
11338         bool src_known = tnum_subreg_is_const(src_reg->var_off);
11339         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11340         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11341         s32 smin_val = src_reg->s32_min_value;
11342
11343         if (src_known && dst_known) {
11344                 __mark_reg32_known(dst_reg, var32_off.value);
11345                 return;
11346         }
11347
11348         /* We get both minimum and maximum from the var32_off. */
11349         dst_reg->u32_min_value = var32_off.value;
11350         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11351
11352         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11353                 /* XORing two positive sign numbers gives a positive,
11354                  * so safe to cast u32 result into s32.
11355                  */
11356                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11357                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11358         } else {
11359                 dst_reg->s32_min_value = S32_MIN;
11360                 dst_reg->s32_max_value = S32_MAX;
11361         }
11362 }
11363
11364 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11365                                struct bpf_reg_state *src_reg)
11366 {
11367         bool src_known = tnum_is_const(src_reg->var_off);
11368         bool dst_known = tnum_is_const(dst_reg->var_off);
11369         s64 smin_val = src_reg->smin_value;
11370
11371         if (src_known && dst_known) {
11372                 /* dst_reg->var_off.value has been updated earlier */
11373                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11374                 return;
11375         }
11376
11377         /* We get both minimum and maximum from the var_off. */
11378         dst_reg->umin_value = dst_reg->var_off.value;
11379         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11380
11381         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11382                 /* XORing two positive sign numbers gives a positive,
11383                  * so safe to cast u64 result into s64.
11384                  */
11385                 dst_reg->smin_value = dst_reg->umin_value;
11386                 dst_reg->smax_value = dst_reg->umax_value;
11387         } else {
11388                 dst_reg->smin_value = S64_MIN;
11389                 dst_reg->smax_value = S64_MAX;
11390         }
11391
11392         __update_reg_bounds(dst_reg);
11393 }
11394
11395 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11396                                    u64 umin_val, u64 umax_val)
11397 {
11398         /* We lose all sign bit information (except what we can pick
11399          * up from var_off)
11400          */
11401         dst_reg->s32_min_value = S32_MIN;
11402         dst_reg->s32_max_value = S32_MAX;
11403         /* If we might shift our top bit out, then we know nothing */
11404         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11405                 dst_reg->u32_min_value = 0;
11406                 dst_reg->u32_max_value = U32_MAX;
11407         } else {
11408                 dst_reg->u32_min_value <<= umin_val;
11409                 dst_reg->u32_max_value <<= umax_val;
11410         }
11411 }
11412
11413 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11414                                  struct bpf_reg_state *src_reg)
11415 {
11416         u32 umax_val = src_reg->u32_max_value;
11417         u32 umin_val = src_reg->u32_min_value;
11418         /* u32 alu operation will zext upper bits */
11419         struct tnum subreg = tnum_subreg(dst_reg->var_off);
11420
11421         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11422         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11423         /* Not required but being careful mark reg64 bounds as unknown so
11424          * that we are forced to pick them up from tnum and zext later and
11425          * if some path skips this step we are still safe.
11426          */
11427         __mark_reg64_unbounded(dst_reg);
11428         __update_reg32_bounds(dst_reg);
11429 }
11430
11431 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11432                                    u64 umin_val, u64 umax_val)
11433 {
11434         /* Special case <<32 because it is a common compiler pattern to sign
11435          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11436          * positive we know this shift will also be positive so we can track
11437          * bounds correctly. Otherwise we lose all sign bit information except
11438          * what we can pick up from var_off. Perhaps we can generalize this
11439          * later to shifts of any length.
11440          */
11441         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11442                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11443         else
11444                 dst_reg->smax_value = S64_MAX;
11445
11446         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11447                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11448         else
11449                 dst_reg->smin_value = S64_MIN;
11450
11451         /* If we might shift our top bit out, then we know nothing */
11452         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11453                 dst_reg->umin_value = 0;
11454                 dst_reg->umax_value = U64_MAX;
11455         } else {
11456                 dst_reg->umin_value <<= umin_val;
11457                 dst_reg->umax_value <<= umax_val;
11458         }
11459 }
11460
11461 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11462                                struct bpf_reg_state *src_reg)
11463 {
11464         u64 umax_val = src_reg->umax_value;
11465         u64 umin_val = src_reg->umin_value;
11466
11467         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
11468         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11469         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11470
11471         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11472         /* We may learn something more from the var_off */
11473         __update_reg_bounds(dst_reg);
11474 }
11475
11476 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11477                                  struct bpf_reg_state *src_reg)
11478 {
11479         struct tnum subreg = tnum_subreg(dst_reg->var_off);
11480         u32 umax_val = src_reg->u32_max_value;
11481         u32 umin_val = src_reg->u32_min_value;
11482
11483         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11484          * be negative, then either:
11485          * 1) src_reg might be zero, so the sign bit of the result is
11486          *    unknown, so we lose our signed bounds
11487          * 2) it's known negative, thus the unsigned bounds capture the
11488          *    signed bounds
11489          * 3) the signed bounds cross zero, so they tell us nothing
11490          *    about the result
11491          * If the value in dst_reg is known nonnegative, then again the
11492          * unsigned bounds capture the signed bounds.
11493          * Thus, in all cases it suffices to blow away our signed bounds
11494          * and rely on inferring new ones from the unsigned bounds and
11495          * var_off of the result.
11496          */
11497         dst_reg->s32_min_value = S32_MIN;
11498         dst_reg->s32_max_value = S32_MAX;
11499
11500         dst_reg->var_off = tnum_rshift(subreg, umin_val);
11501         dst_reg->u32_min_value >>= umax_val;
11502         dst_reg->u32_max_value >>= umin_val;
11503
11504         __mark_reg64_unbounded(dst_reg);
11505         __update_reg32_bounds(dst_reg);
11506 }
11507
11508 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
11509                                struct bpf_reg_state *src_reg)
11510 {
11511         u64 umax_val = src_reg->umax_value;
11512         u64 umin_val = src_reg->umin_value;
11513
11514         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11515          * be negative, then either:
11516          * 1) src_reg might be zero, so the sign bit of the result is
11517          *    unknown, so we lose our signed bounds
11518          * 2) it's known negative, thus the unsigned bounds capture the
11519          *    signed bounds
11520          * 3) the signed bounds cross zero, so they tell us nothing
11521          *    about the result
11522          * If the value in dst_reg is known nonnegative, then again the
11523          * unsigned bounds capture the signed bounds.
11524          * Thus, in all cases it suffices to blow away our signed bounds
11525          * and rely on inferring new ones from the unsigned bounds and
11526          * var_off of the result.
11527          */
11528         dst_reg->smin_value = S64_MIN;
11529         dst_reg->smax_value = S64_MAX;
11530         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
11531         dst_reg->umin_value >>= umax_val;
11532         dst_reg->umax_value >>= umin_val;
11533
11534         /* Its not easy to operate on alu32 bounds here because it depends
11535          * on bits being shifted in. Take easy way out and mark unbounded
11536          * so we can recalculate later from tnum.
11537          */
11538         __mark_reg32_unbounded(dst_reg);
11539         __update_reg_bounds(dst_reg);
11540 }
11541
11542 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
11543                                   struct bpf_reg_state *src_reg)
11544 {
11545         u64 umin_val = src_reg->u32_min_value;
11546
11547         /* Upon reaching here, src_known is true and
11548          * umax_val is equal to umin_val.
11549          */
11550         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
11551         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
11552
11553         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
11554
11555         /* blow away the dst_reg umin_value/umax_value and rely on
11556          * dst_reg var_off to refine the result.
11557          */
11558         dst_reg->u32_min_value = 0;
11559         dst_reg->u32_max_value = U32_MAX;
11560
11561         __mark_reg64_unbounded(dst_reg);
11562         __update_reg32_bounds(dst_reg);
11563 }
11564
11565 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
11566                                 struct bpf_reg_state *src_reg)
11567 {
11568         u64 umin_val = src_reg->umin_value;
11569
11570         /* Upon reaching here, src_known is true and umax_val is equal
11571          * to umin_val.
11572          */
11573         dst_reg->smin_value >>= umin_val;
11574         dst_reg->smax_value >>= umin_val;
11575
11576         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
11577
11578         /* blow away the dst_reg umin_value/umax_value and rely on
11579          * dst_reg var_off to refine the result.
11580          */
11581         dst_reg->umin_value = 0;
11582         dst_reg->umax_value = U64_MAX;
11583
11584         /* Its not easy to operate on alu32 bounds here because it depends
11585          * on bits being shifted in from upper 32-bits. Take easy way out
11586          * and mark unbounded so we can recalculate later from tnum.
11587          */
11588         __mark_reg32_unbounded(dst_reg);
11589         __update_reg_bounds(dst_reg);
11590 }
11591
11592 /* WARNING: This function does calculations on 64-bit values, but the actual
11593  * execution may occur on 32-bit values. Therefore, things like bitshifts
11594  * need extra checks in the 32-bit case.
11595  */
11596 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
11597                                       struct bpf_insn *insn,
11598                                       struct bpf_reg_state *dst_reg,
11599                                       struct bpf_reg_state src_reg)
11600 {
11601         struct bpf_reg_state *regs = cur_regs(env);
11602         u8 opcode = BPF_OP(insn->code);
11603         bool src_known;
11604         s64 smin_val, smax_val;
11605         u64 umin_val, umax_val;
11606         s32 s32_min_val, s32_max_val;
11607         u32 u32_min_val, u32_max_val;
11608         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
11609         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
11610         int ret;
11611
11612         smin_val = src_reg.smin_value;
11613         smax_val = src_reg.smax_value;
11614         umin_val = src_reg.umin_value;
11615         umax_val = src_reg.umax_value;
11616
11617         s32_min_val = src_reg.s32_min_value;
11618         s32_max_val = src_reg.s32_max_value;
11619         u32_min_val = src_reg.u32_min_value;
11620         u32_max_val = src_reg.u32_max_value;
11621
11622         if (alu32) {
11623                 src_known = tnum_subreg_is_const(src_reg.var_off);
11624                 if ((src_known &&
11625                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
11626                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
11627                         /* Taint dst register if offset had invalid bounds
11628                          * derived from e.g. dead branches.
11629                          */
11630                         __mark_reg_unknown(env, dst_reg);
11631                         return 0;
11632                 }
11633         } else {
11634                 src_known = tnum_is_const(src_reg.var_off);
11635                 if ((src_known &&
11636                      (smin_val != smax_val || umin_val != umax_val)) ||
11637                     smin_val > smax_val || umin_val > umax_val) {
11638                         /* Taint dst register if offset had invalid bounds
11639                          * derived from e.g. dead branches.
11640                          */
11641                         __mark_reg_unknown(env, dst_reg);
11642                         return 0;
11643                 }
11644         }
11645
11646         if (!src_known &&
11647             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
11648                 __mark_reg_unknown(env, dst_reg);
11649                 return 0;
11650         }
11651
11652         if (sanitize_needed(opcode)) {
11653                 ret = sanitize_val_alu(env, insn);
11654                 if (ret < 0)
11655                         return sanitize_err(env, insn, ret, NULL, NULL);
11656         }
11657
11658         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
11659          * There are two classes of instructions: The first class we track both
11660          * alu32 and alu64 sign/unsigned bounds independently this provides the
11661          * greatest amount of precision when alu operations are mixed with jmp32
11662          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
11663          * and BPF_OR. This is possible because these ops have fairly easy to
11664          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
11665          * See alu32 verifier tests for examples. The second class of
11666          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
11667          * with regards to tracking sign/unsigned bounds because the bits may
11668          * cross subreg boundaries in the alu64 case. When this happens we mark
11669          * the reg unbounded in the subreg bound space and use the resulting
11670          * tnum to calculate an approximation of the sign/unsigned bounds.
11671          */
11672         switch (opcode) {
11673         case BPF_ADD:
11674                 scalar32_min_max_add(dst_reg, &src_reg);
11675                 scalar_min_max_add(dst_reg, &src_reg);
11676                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
11677                 break;
11678         case BPF_SUB:
11679                 scalar32_min_max_sub(dst_reg, &src_reg);
11680                 scalar_min_max_sub(dst_reg, &src_reg);
11681                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
11682                 break;
11683         case BPF_MUL:
11684                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
11685                 scalar32_min_max_mul(dst_reg, &src_reg);
11686                 scalar_min_max_mul(dst_reg, &src_reg);
11687                 break;
11688         case BPF_AND:
11689                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
11690                 scalar32_min_max_and(dst_reg, &src_reg);
11691                 scalar_min_max_and(dst_reg, &src_reg);
11692                 break;
11693         case BPF_OR:
11694                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
11695                 scalar32_min_max_or(dst_reg, &src_reg);
11696                 scalar_min_max_or(dst_reg, &src_reg);
11697                 break;
11698         case BPF_XOR:
11699                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
11700                 scalar32_min_max_xor(dst_reg, &src_reg);
11701                 scalar_min_max_xor(dst_reg, &src_reg);
11702                 break;
11703         case BPF_LSH:
11704                 if (umax_val >= insn_bitness) {
11705                         /* Shifts greater than 31 or 63 are undefined.
11706                          * This includes shifts by a negative number.
11707                          */
11708                         mark_reg_unknown(env, regs, insn->dst_reg);
11709                         break;
11710                 }
11711                 if (alu32)
11712                         scalar32_min_max_lsh(dst_reg, &src_reg);
11713                 else
11714                         scalar_min_max_lsh(dst_reg, &src_reg);
11715                 break;
11716         case BPF_RSH:
11717                 if (umax_val >= insn_bitness) {
11718                         /* Shifts greater than 31 or 63 are undefined.
11719                          * This includes shifts by a negative number.
11720                          */
11721                         mark_reg_unknown(env, regs, insn->dst_reg);
11722                         break;
11723                 }
11724                 if (alu32)
11725                         scalar32_min_max_rsh(dst_reg, &src_reg);
11726                 else
11727                         scalar_min_max_rsh(dst_reg, &src_reg);
11728                 break;
11729         case BPF_ARSH:
11730                 if (umax_val >= insn_bitness) {
11731                         /* Shifts greater than 31 or 63 are undefined.
11732                          * This includes shifts by a negative number.
11733                          */
11734                         mark_reg_unknown(env, regs, insn->dst_reg);
11735                         break;
11736                 }
11737                 if (alu32)
11738                         scalar32_min_max_arsh(dst_reg, &src_reg);
11739                 else
11740                         scalar_min_max_arsh(dst_reg, &src_reg);
11741                 break;
11742         default:
11743                 mark_reg_unknown(env, regs, insn->dst_reg);
11744                 break;
11745         }
11746
11747         /* ALU32 ops are zero extended into 64bit register */
11748         if (alu32)
11749                 zext_32_to_64(dst_reg);
11750         reg_bounds_sync(dst_reg);
11751         return 0;
11752 }
11753
11754 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
11755  * and var_off.
11756  */
11757 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
11758                                    struct bpf_insn *insn)
11759 {
11760         struct bpf_verifier_state *vstate = env->cur_state;
11761         struct bpf_func_state *state = vstate->frame[vstate->curframe];
11762         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
11763         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
11764         u8 opcode = BPF_OP(insn->code);
11765         int err;
11766
11767         dst_reg = &regs[insn->dst_reg];
11768         src_reg = NULL;
11769         if (dst_reg->type != SCALAR_VALUE)
11770                 ptr_reg = dst_reg;
11771         else
11772                 /* Make sure ID is cleared otherwise dst_reg min/max could be
11773                  * incorrectly propagated into other registers by find_equal_scalars()
11774                  */
11775                 dst_reg->id = 0;
11776         if (BPF_SRC(insn->code) == BPF_X) {
11777                 src_reg = &regs[insn->src_reg];
11778                 if (src_reg->type != SCALAR_VALUE) {
11779                         if (dst_reg->type != SCALAR_VALUE) {
11780                                 /* Combining two pointers by any ALU op yields
11781                                  * an arbitrary scalar. Disallow all math except
11782                                  * pointer subtraction
11783                                  */
11784                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11785                                         mark_reg_unknown(env, regs, insn->dst_reg);
11786                                         return 0;
11787                                 }
11788                                 verbose(env, "R%d pointer %s pointer prohibited\n",
11789                                         insn->dst_reg,
11790                                         bpf_alu_string[opcode >> 4]);
11791                                 return -EACCES;
11792                         } else {
11793                                 /* scalar += pointer
11794                                  * This is legal, but we have to reverse our
11795                                  * src/dest handling in computing the range
11796                                  */
11797                                 err = mark_chain_precision(env, insn->dst_reg);
11798                                 if (err)
11799                                         return err;
11800                                 return adjust_ptr_min_max_vals(env, insn,
11801                                                                src_reg, dst_reg);
11802                         }
11803                 } else if (ptr_reg) {
11804                         /* pointer += scalar */
11805                         err = mark_chain_precision(env, insn->src_reg);
11806                         if (err)
11807                                 return err;
11808                         return adjust_ptr_min_max_vals(env, insn,
11809                                                        dst_reg, src_reg);
11810                 } else if (dst_reg->precise) {
11811                         /* if dst_reg is precise, src_reg should be precise as well */
11812                         err = mark_chain_precision(env, insn->src_reg);
11813                         if (err)
11814                                 return err;
11815                 }
11816         } else {
11817                 /* Pretend the src is a reg with a known value, since we only
11818                  * need to be able to read from this state.
11819                  */
11820                 off_reg.type = SCALAR_VALUE;
11821                 __mark_reg_known(&off_reg, insn->imm);
11822                 src_reg = &off_reg;
11823                 if (ptr_reg) /* pointer += K */
11824                         return adjust_ptr_min_max_vals(env, insn,
11825                                                        ptr_reg, src_reg);
11826         }
11827
11828         /* Got here implies adding two SCALAR_VALUEs */
11829         if (WARN_ON_ONCE(ptr_reg)) {
11830                 print_verifier_state(env, state, true);
11831                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
11832                 return -EINVAL;
11833         }
11834         if (WARN_ON(!src_reg)) {
11835                 print_verifier_state(env, state, true);
11836                 verbose(env, "verifier internal error: no src_reg\n");
11837                 return -EINVAL;
11838         }
11839         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
11840 }
11841
11842 /* check validity of 32-bit and 64-bit arithmetic operations */
11843 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
11844 {
11845         struct bpf_reg_state *regs = cur_regs(env);
11846         u8 opcode = BPF_OP(insn->code);
11847         int err;
11848
11849         if (opcode == BPF_END || opcode == BPF_NEG) {
11850                 if (opcode == BPF_NEG) {
11851                         if (BPF_SRC(insn->code) != BPF_K ||
11852                             insn->src_reg != BPF_REG_0 ||
11853                             insn->off != 0 || insn->imm != 0) {
11854                                 verbose(env, "BPF_NEG uses reserved fields\n");
11855                                 return -EINVAL;
11856                         }
11857                 } else {
11858                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
11859                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
11860                             BPF_CLASS(insn->code) == BPF_ALU64) {
11861                                 verbose(env, "BPF_END uses reserved fields\n");
11862                                 return -EINVAL;
11863                         }
11864                 }
11865
11866                 /* check src operand */
11867                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11868                 if (err)
11869                         return err;
11870
11871                 if (is_pointer_value(env, insn->dst_reg)) {
11872                         verbose(env, "R%d pointer arithmetic prohibited\n",
11873                                 insn->dst_reg);
11874                         return -EACCES;
11875                 }
11876
11877                 /* check dest operand */
11878                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
11879                 if (err)
11880                         return err;
11881
11882         } else if (opcode == BPF_MOV) {
11883
11884                 if (BPF_SRC(insn->code) == BPF_X) {
11885                         if (insn->imm != 0 || insn->off != 0) {
11886                                 verbose(env, "BPF_MOV uses reserved fields\n");
11887                                 return -EINVAL;
11888                         }
11889
11890                         /* check src operand */
11891                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
11892                         if (err)
11893                                 return err;
11894                 } else {
11895                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11896                                 verbose(env, "BPF_MOV uses reserved fields\n");
11897                                 return -EINVAL;
11898                         }
11899                 }
11900
11901                 /* check dest operand, mark as required later */
11902                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11903                 if (err)
11904                         return err;
11905
11906                 if (BPF_SRC(insn->code) == BPF_X) {
11907                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
11908                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
11909
11910                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
11911                                 /* case: R1 = R2
11912                                  * copy register state to dest reg
11913                                  */
11914                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
11915                                         /* Assign src and dst registers the same ID
11916                                          * that will be used by find_equal_scalars()
11917                                          * to propagate min/max range.
11918                                          */
11919                                         src_reg->id = ++env->id_gen;
11920                                 copy_register_state(dst_reg, src_reg);
11921                                 dst_reg->live |= REG_LIVE_WRITTEN;
11922                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
11923                         } else {
11924                                 /* R1 = (u32) R2 */
11925                                 if (is_pointer_value(env, insn->src_reg)) {
11926                                         verbose(env,
11927                                                 "R%d partial copy of pointer\n",
11928                                                 insn->src_reg);
11929                                         return -EACCES;
11930                                 } else if (src_reg->type == SCALAR_VALUE) {
11931                                         copy_register_state(dst_reg, src_reg);
11932                                         /* Make sure ID is cleared otherwise
11933                                          * dst_reg min/max could be incorrectly
11934                                          * propagated into src_reg by find_equal_scalars()
11935                                          */
11936                                         dst_reg->id = 0;
11937                                         dst_reg->live |= REG_LIVE_WRITTEN;
11938                                         dst_reg->subreg_def = env->insn_idx + 1;
11939                                 } else {
11940                                         mark_reg_unknown(env, regs,
11941                                                          insn->dst_reg);
11942                                 }
11943                                 zext_32_to_64(dst_reg);
11944                                 reg_bounds_sync(dst_reg);
11945                         }
11946                 } else {
11947                         /* case: R = imm
11948                          * remember the value we stored into this reg
11949                          */
11950                         /* clear any state __mark_reg_known doesn't set */
11951                         mark_reg_unknown(env, regs, insn->dst_reg);
11952                         regs[insn->dst_reg].type = SCALAR_VALUE;
11953                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
11954                                 __mark_reg_known(regs + insn->dst_reg,
11955                                                  insn->imm);
11956                         } else {
11957                                 __mark_reg_known(regs + insn->dst_reg,
11958                                                  (u32)insn->imm);
11959                         }
11960                 }
11961
11962         } else if (opcode > BPF_END) {
11963                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
11964                 return -EINVAL;
11965
11966         } else {        /* all other ALU ops: and, sub, xor, add, ... */
11967
11968                 if (BPF_SRC(insn->code) == BPF_X) {
11969                         if (insn->imm != 0 || insn->off != 0) {
11970                                 verbose(env, "BPF_ALU uses reserved fields\n");
11971                                 return -EINVAL;
11972                         }
11973                         /* check src1 operand */
11974                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
11975                         if (err)
11976                                 return err;
11977                 } else {
11978                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
11979                                 verbose(env, "BPF_ALU uses reserved fields\n");
11980                                 return -EINVAL;
11981                         }
11982                 }
11983
11984                 /* check src2 operand */
11985                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11986                 if (err)
11987                         return err;
11988
11989                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
11990                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
11991                         verbose(env, "div by zero\n");
11992                         return -EINVAL;
11993                 }
11994
11995                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
11996                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
11997                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
11998
11999                         if (insn->imm < 0 || insn->imm >= size) {
12000                                 verbose(env, "invalid shift %d\n", insn->imm);
12001                                 return -EINVAL;
12002                         }
12003                 }
12004
12005                 /* check dest operand */
12006                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12007                 if (err)
12008                         return err;
12009
12010                 return adjust_reg_min_max_vals(env, insn);
12011         }
12012
12013         return 0;
12014 }
12015
12016 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12017                                    struct bpf_reg_state *dst_reg,
12018                                    enum bpf_reg_type type,
12019                                    bool range_right_open)
12020 {
12021         struct bpf_func_state *state;
12022         struct bpf_reg_state *reg;
12023         int new_range;
12024
12025         if (dst_reg->off < 0 ||
12026             (dst_reg->off == 0 && range_right_open))
12027                 /* This doesn't give us any range */
12028                 return;
12029
12030         if (dst_reg->umax_value > MAX_PACKET_OFF ||
12031             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12032                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
12033                  * than pkt_end, but that's because it's also less than pkt.
12034                  */
12035                 return;
12036
12037         new_range = dst_reg->off;
12038         if (range_right_open)
12039                 new_range++;
12040
12041         /* Examples for register markings:
12042          *
12043          * pkt_data in dst register:
12044          *
12045          *   r2 = r3;
12046          *   r2 += 8;
12047          *   if (r2 > pkt_end) goto <handle exception>
12048          *   <access okay>
12049          *
12050          *   r2 = r3;
12051          *   r2 += 8;
12052          *   if (r2 < pkt_end) goto <access okay>
12053          *   <handle exception>
12054          *
12055          *   Where:
12056          *     r2 == dst_reg, pkt_end == src_reg
12057          *     r2=pkt(id=n,off=8,r=0)
12058          *     r3=pkt(id=n,off=0,r=0)
12059          *
12060          * pkt_data in src register:
12061          *
12062          *   r2 = r3;
12063          *   r2 += 8;
12064          *   if (pkt_end >= r2) goto <access okay>
12065          *   <handle exception>
12066          *
12067          *   r2 = r3;
12068          *   r2 += 8;
12069          *   if (pkt_end <= r2) goto <handle exception>
12070          *   <access okay>
12071          *
12072          *   Where:
12073          *     pkt_end == dst_reg, r2 == src_reg
12074          *     r2=pkt(id=n,off=8,r=0)
12075          *     r3=pkt(id=n,off=0,r=0)
12076          *
12077          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12078          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12079          * and [r3, r3 + 8-1) respectively is safe to access depending on
12080          * the check.
12081          */
12082
12083         /* If our ids match, then we must have the same max_value.  And we
12084          * don't care about the other reg's fixed offset, since if it's too big
12085          * the range won't allow anything.
12086          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12087          */
12088         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12089                 if (reg->type == type && reg->id == dst_reg->id)
12090                         /* keep the maximum range already checked */
12091                         reg->range = max(reg->range, new_range);
12092         }));
12093 }
12094
12095 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12096 {
12097         struct tnum subreg = tnum_subreg(reg->var_off);
12098         s32 sval = (s32)val;
12099
12100         switch (opcode) {
12101         case BPF_JEQ:
12102                 if (tnum_is_const(subreg))
12103                         return !!tnum_equals_const(subreg, val);
12104                 break;
12105         case BPF_JNE:
12106                 if (tnum_is_const(subreg))
12107                         return !tnum_equals_const(subreg, val);
12108                 break;
12109         case BPF_JSET:
12110                 if ((~subreg.mask & subreg.value) & val)
12111                         return 1;
12112                 if (!((subreg.mask | subreg.value) & val))
12113                         return 0;
12114                 break;
12115         case BPF_JGT:
12116                 if (reg->u32_min_value > val)
12117                         return 1;
12118                 else if (reg->u32_max_value <= val)
12119                         return 0;
12120                 break;
12121         case BPF_JSGT:
12122                 if (reg->s32_min_value > sval)
12123                         return 1;
12124                 else if (reg->s32_max_value <= sval)
12125                         return 0;
12126                 break;
12127         case BPF_JLT:
12128                 if (reg->u32_max_value < val)
12129                         return 1;
12130                 else if (reg->u32_min_value >= val)
12131                         return 0;
12132                 break;
12133         case BPF_JSLT:
12134                 if (reg->s32_max_value < sval)
12135                         return 1;
12136                 else if (reg->s32_min_value >= sval)
12137                         return 0;
12138                 break;
12139         case BPF_JGE:
12140                 if (reg->u32_min_value >= val)
12141                         return 1;
12142                 else if (reg->u32_max_value < val)
12143                         return 0;
12144                 break;
12145         case BPF_JSGE:
12146                 if (reg->s32_min_value >= sval)
12147                         return 1;
12148                 else if (reg->s32_max_value < sval)
12149                         return 0;
12150                 break;
12151         case BPF_JLE:
12152                 if (reg->u32_max_value <= val)
12153                         return 1;
12154                 else if (reg->u32_min_value > val)
12155                         return 0;
12156                 break;
12157         case BPF_JSLE:
12158                 if (reg->s32_max_value <= sval)
12159                         return 1;
12160                 else if (reg->s32_min_value > sval)
12161                         return 0;
12162                 break;
12163         }
12164
12165         return -1;
12166 }
12167
12168
12169 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12170 {
12171         s64 sval = (s64)val;
12172
12173         switch (opcode) {
12174         case BPF_JEQ:
12175                 if (tnum_is_const(reg->var_off))
12176                         return !!tnum_equals_const(reg->var_off, val);
12177                 break;
12178         case BPF_JNE:
12179                 if (tnum_is_const(reg->var_off))
12180                         return !tnum_equals_const(reg->var_off, val);
12181                 break;
12182         case BPF_JSET:
12183                 if ((~reg->var_off.mask & reg->var_off.value) & val)
12184                         return 1;
12185                 if (!((reg->var_off.mask | reg->var_off.value) & val))
12186                         return 0;
12187                 break;
12188         case BPF_JGT:
12189                 if (reg->umin_value > val)
12190                         return 1;
12191                 else if (reg->umax_value <= val)
12192                         return 0;
12193                 break;
12194         case BPF_JSGT:
12195                 if (reg->smin_value > sval)
12196                         return 1;
12197                 else if (reg->smax_value <= sval)
12198                         return 0;
12199                 break;
12200         case BPF_JLT:
12201                 if (reg->umax_value < val)
12202                         return 1;
12203                 else if (reg->umin_value >= val)
12204                         return 0;
12205                 break;
12206         case BPF_JSLT:
12207                 if (reg->smax_value < sval)
12208                         return 1;
12209                 else if (reg->smin_value >= sval)
12210                         return 0;
12211                 break;
12212         case BPF_JGE:
12213                 if (reg->umin_value >= val)
12214                         return 1;
12215                 else if (reg->umax_value < val)
12216                         return 0;
12217                 break;
12218         case BPF_JSGE:
12219                 if (reg->smin_value >= sval)
12220                         return 1;
12221                 else if (reg->smax_value < sval)
12222                         return 0;
12223                 break;
12224         case BPF_JLE:
12225                 if (reg->umax_value <= val)
12226                         return 1;
12227                 else if (reg->umin_value > val)
12228                         return 0;
12229                 break;
12230         case BPF_JSLE:
12231                 if (reg->smax_value <= sval)
12232                         return 1;
12233                 else if (reg->smin_value > sval)
12234                         return 0;
12235                 break;
12236         }
12237
12238         return -1;
12239 }
12240
12241 /* compute branch direction of the expression "if (reg opcode val) goto target;"
12242  * and return:
12243  *  1 - branch will be taken and "goto target" will be executed
12244  *  0 - branch will not be taken and fall-through to next insn
12245  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
12246  *      range [0,10]
12247  */
12248 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
12249                            bool is_jmp32)
12250 {
12251         if (__is_pointer_value(false, reg)) {
12252                 if (!reg_type_not_null(reg->type))
12253                         return -1;
12254
12255                 /* If pointer is valid tests against zero will fail so we can
12256                  * use this to direct branch taken.
12257                  */
12258                 if (val != 0)
12259                         return -1;
12260
12261                 switch (opcode) {
12262                 case BPF_JEQ:
12263                         return 0;
12264                 case BPF_JNE:
12265                         return 1;
12266                 default:
12267                         return -1;
12268                 }
12269         }
12270
12271         if (is_jmp32)
12272                 return is_branch32_taken(reg, val, opcode);
12273         return is_branch64_taken(reg, val, opcode);
12274 }
12275
12276 static int flip_opcode(u32 opcode)
12277 {
12278         /* How can we transform "a <op> b" into "b <op> a"? */
12279         static const u8 opcode_flip[16] = {
12280                 /* these stay the same */
12281                 [BPF_JEQ  >> 4] = BPF_JEQ,
12282                 [BPF_JNE  >> 4] = BPF_JNE,
12283                 [BPF_JSET >> 4] = BPF_JSET,
12284                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
12285                 [BPF_JGE  >> 4] = BPF_JLE,
12286                 [BPF_JGT  >> 4] = BPF_JLT,
12287                 [BPF_JLE  >> 4] = BPF_JGE,
12288                 [BPF_JLT  >> 4] = BPF_JGT,
12289                 [BPF_JSGE >> 4] = BPF_JSLE,
12290                 [BPF_JSGT >> 4] = BPF_JSLT,
12291                 [BPF_JSLE >> 4] = BPF_JSGE,
12292                 [BPF_JSLT >> 4] = BPF_JSGT
12293         };
12294         return opcode_flip[opcode >> 4];
12295 }
12296
12297 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
12298                                    struct bpf_reg_state *src_reg,
12299                                    u8 opcode)
12300 {
12301         struct bpf_reg_state *pkt;
12302
12303         if (src_reg->type == PTR_TO_PACKET_END) {
12304                 pkt = dst_reg;
12305         } else if (dst_reg->type == PTR_TO_PACKET_END) {
12306                 pkt = src_reg;
12307                 opcode = flip_opcode(opcode);
12308         } else {
12309                 return -1;
12310         }
12311
12312         if (pkt->range >= 0)
12313                 return -1;
12314
12315         switch (opcode) {
12316         case BPF_JLE:
12317                 /* pkt <= pkt_end */
12318                 fallthrough;
12319         case BPF_JGT:
12320                 /* pkt > pkt_end */
12321                 if (pkt->range == BEYOND_PKT_END)
12322                         /* pkt has at last one extra byte beyond pkt_end */
12323                         return opcode == BPF_JGT;
12324                 break;
12325         case BPF_JLT:
12326                 /* pkt < pkt_end */
12327                 fallthrough;
12328         case BPF_JGE:
12329                 /* pkt >= pkt_end */
12330                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12331                         return opcode == BPF_JGE;
12332                 break;
12333         }
12334         return -1;
12335 }
12336
12337 /* Adjusts the register min/max values in the case that the dst_reg is the
12338  * variable register that we are working on, and src_reg is a constant or we're
12339  * simply doing a BPF_K check.
12340  * In JEQ/JNE cases we also adjust the var_off values.
12341  */
12342 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12343                             struct bpf_reg_state *false_reg,
12344                             u64 val, u32 val32,
12345                             u8 opcode, bool is_jmp32)
12346 {
12347         struct tnum false_32off = tnum_subreg(false_reg->var_off);
12348         struct tnum false_64off = false_reg->var_off;
12349         struct tnum true_32off = tnum_subreg(true_reg->var_off);
12350         struct tnum true_64off = true_reg->var_off;
12351         s64 sval = (s64)val;
12352         s32 sval32 = (s32)val32;
12353
12354         /* If the dst_reg is a pointer, we can't learn anything about its
12355          * variable offset from the compare (unless src_reg were a pointer into
12356          * the same object, but we don't bother with that.
12357          * Since false_reg and true_reg have the same type by construction, we
12358          * only need to check one of them for pointerness.
12359          */
12360         if (__is_pointer_value(false, false_reg))
12361                 return;
12362
12363         switch (opcode) {
12364         /* JEQ/JNE comparison doesn't change the register equivalence.
12365          *
12366          * r1 = r2;
12367          * if (r1 == 42) goto label;
12368          * ...
12369          * label: // here both r1 and r2 are known to be 42.
12370          *
12371          * Hence when marking register as known preserve it's ID.
12372          */
12373         case BPF_JEQ:
12374                 if (is_jmp32) {
12375                         __mark_reg32_known(true_reg, val32);
12376                         true_32off = tnum_subreg(true_reg->var_off);
12377                 } else {
12378                         ___mark_reg_known(true_reg, val);
12379                         true_64off = true_reg->var_off;
12380                 }
12381                 break;
12382         case BPF_JNE:
12383                 if (is_jmp32) {
12384                         __mark_reg32_known(false_reg, val32);
12385                         false_32off = tnum_subreg(false_reg->var_off);
12386                 } else {
12387                         ___mark_reg_known(false_reg, val);
12388                         false_64off = false_reg->var_off;
12389                 }
12390                 break;
12391         case BPF_JSET:
12392                 if (is_jmp32) {
12393                         false_32off = tnum_and(false_32off, tnum_const(~val32));
12394                         if (is_power_of_2(val32))
12395                                 true_32off = tnum_or(true_32off,
12396                                                      tnum_const(val32));
12397                 } else {
12398                         false_64off = tnum_and(false_64off, tnum_const(~val));
12399                         if (is_power_of_2(val))
12400                                 true_64off = tnum_or(true_64off,
12401                                                      tnum_const(val));
12402                 }
12403                 break;
12404         case BPF_JGE:
12405         case BPF_JGT:
12406         {
12407                 if (is_jmp32) {
12408                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
12409                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12410
12411                         false_reg->u32_max_value = min(false_reg->u32_max_value,
12412                                                        false_umax);
12413                         true_reg->u32_min_value = max(true_reg->u32_min_value,
12414                                                       true_umin);
12415                 } else {
12416                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
12417                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12418
12419                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
12420                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
12421                 }
12422                 break;
12423         }
12424         case BPF_JSGE:
12425         case BPF_JSGT:
12426         {
12427                 if (is_jmp32) {
12428                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
12429                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12430
12431                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12432                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12433                 } else {
12434                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
12435                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12436
12437                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
12438                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
12439                 }
12440                 break;
12441         }
12442         case BPF_JLE:
12443         case BPF_JLT:
12444         {
12445                 if (is_jmp32) {
12446                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
12447                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12448
12449                         false_reg->u32_min_value = max(false_reg->u32_min_value,
12450                                                        false_umin);
12451                         true_reg->u32_max_value = min(true_reg->u32_max_value,
12452                                                       true_umax);
12453                 } else {
12454                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
12455                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12456
12457                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
12458                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
12459                 }
12460                 break;
12461         }
12462         case BPF_JSLE:
12463         case BPF_JSLT:
12464         {
12465                 if (is_jmp32) {
12466                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
12467                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12468
12469                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12470                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12471                 } else {
12472                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
12473                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12474
12475                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
12476                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
12477                 }
12478                 break;
12479         }
12480         default:
12481                 return;
12482         }
12483
12484         if (is_jmp32) {
12485                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12486                                              tnum_subreg(false_32off));
12487                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12488                                             tnum_subreg(true_32off));
12489                 __reg_combine_32_into_64(false_reg);
12490                 __reg_combine_32_into_64(true_reg);
12491         } else {
12492                 false_reg->var_off = false_64off;
12493                 true_reg->var_off = true_64off;
12494                 __reg_combine_64_into_32(false_reg);
12495                 __reg_combine_64_into_32(true_reg);
12496         }
12497 }
12498
12499 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
12500  * the variable reg.
12501  */
12502 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
12503                                 struct bpf_reg_state *false_reg,
12504                                 u64 val, u32 val32,
12505                                 u8 opcode, bool is_jmp32)
12506 {
12507         opcode = flip_opcode(opcode);
12508         /* This uses zero as "not present in table"; luckily the zero opcode,
12509          * BPF_JA, can't get here.
12510          */
12511         if (opcode)
12512                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
12513 }
12514
12515 /* Regs are known to be equal, so intersect their min/max/var_off */
12516 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
12517                                   struct bpf_reg_state *dst_reg)
12518 {
12519         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
12520                                                         dst_reg->umin_value);
12521         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
12522                                                         dst_reg->umax_value);
12523         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
12524                                                         dst_reg->smin_value);
12525         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
12526                                                         dst_reg->smax_value);
12527         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
12528                                                              dst_reg->var_off);
12529         reg_bounds_sync(src_reg);
12530         reg_bounds_sync(dst_reg);
12531 }
12532
12533 static void reg_combine_min_max(struct bpf_reg_state *true_src,
12534                                 struct bpf_reg_state *true_dst,
12535                                 struct bpf_reg_state *false_src,
12536                                 struct bpf_reg_state *false_dst,
12537                                 u8 opcode)
12538 {
12539         switch (opcode) {
12540         case BPF_JEQ:
12541                 __reg_combine_min_max(true_src, true_dst);
12542                 break;
12543         case BPF_JNE:
12544                 __reg_combine_min_max(false_src, false_dst);
12545                 break;
12546         }
12547 }
12548
12549 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
12550                                  struct bpf_reg_state *reg, u32 id,
12551                                  bool is_null)
12552 {
12553         if (type_may_be_null(reg->type) && reg->id == id &&
12554             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
12555                 /* Old offset (both fixed and variable parts) should have been
12556                  * known-zero, because we don't allow pointer arithmetic on
12557                  * pointers that might be NULL. If we see this happening, don't
12558                  * convert the register.
12559                  *
12560                  * But in some cases, some helpers that return local kptrs
12561                  * advance offset for the returned pointer. In those cases, it
12562                  * is fine to expect to see reg->off.
12563                  */
12564                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
12565                         return;
12566                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
12567                     WARN_ON_ONCE(reg->off))
12568                         return;
12569
12570                 if (is_null) {
12571                         reg->type = SCALAR_VALUE;
12572                         /* We don't need id and ref_obj_id from this point
12573                          * onwards anymore, thus we should better reset it,
12574                          * so that state pruning has chances to take effect.
12575                          */
12576                         reg->id = 0;
12577                         reg->ref_obj_id = 0;
12578
12579                         return;
12580                 }
12581
12582                 mark_ptr_not_null_reg(reg);
12583
12584                 if (!reg_may_point_to_spin_lock(reg)) {
12585                         /* For not-NULL ptr, reg->ref_obj_id will be reset
12586                          * in release_reference().
12587                          *
12588                          * reg->id is still used by spin_lock ptr. Other
12589                          * than spin_lock ptr type, reg->id can be reset.
12590                          */
12591                         reg->id = 0;
12592                 }
12593         }
12594 }
12595
12596 /* The logic is similar to find_good_pkt_pointers(), both could eventually
12597  * be folded together at some point.
12598  */
12599 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
12600                                   bool is_null)
12601 {
12602         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12603         struct bpf_reg_state *regs = state->regs, *reg;
12604         u32 ref_obj_id = regs[regno].ref_obj_id;
12605         u32 id = regs[regno].id;
12606
12607         if (ref_obj_id && ref_obj_id == id && is_null)
12608                 /* regs[regno] is in the " == NULL" branch.
12609                  * No one could have freed the reference state before
12610                  * doing the NULL check.
12611                  */
12612                 WARN_ON_ONCE(release_reference_state(state, id));
12613
12614         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12615                 mark_ptr_or_null_reg(state, reg, id, is_null);
12616         }));
12617 }
12618
12619 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
12620                                    struct bpf_reg_state *dst_reg,
12621                                    struct bpf_reg_state *src_reg,
12622                                    struct bpf_verifier_state *this_branch,
12623                                    struct bpf_verifier_state *other_branch)
12624 {
12625         if (BPF_SRC(insn->code) != BPF_X)
12626                 return false;
12627
12628         /* Pointers are always 64-bit. */
12629         if (BPF_CLASS(insn->code) == BPF_JMP32)
12630                 return false;
12631
12632         switch (BPF_OP(insn->code)) {
12633         case BPF_JGT:
12634                 if ((dst_reg->type == PTR_TO_PACKET &&
12635                      src_reg->type == PTR_TO_PACKET_END) ||
12636                     (dst_reg->type == PTR_TO_PACKET_META &&
12637                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12638                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
12639                         find_good_pkt_pointers(this_branch, dst_reg,
12640                                                dst_reg->type, false);
12641                         mark_pkt_end(other_branch, insn->dst_reg, true);
12642                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12643                             src_reg->type == PTR_TO_PACKET) ||
12644                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12645                             src_reg->type == PTR_TO_PACKET_META)) {
12646                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
12647                         find_good_pkt_pointers(other_branch, src_reg,
12648                                                src_reg->type, true);
12649                         mark_pkt_end(this_branch, insn->src_reg, false);
12650                 } else {
12651                         return false;
12652                 }
12653                 break;
12654         case BPF_JLT:
12655                 if ((dst_reg->type == PTR_TO_PACKET &&
12656                      src_reg->type == PTR_TO_PACKET_END) ||
12657                     (dst_reg->type == PTR_TO_PACKET_META &&
12658                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12659                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
12660                         find_good_pkt_pointers(other_branch, dst_reg,
12661                                                dst_reg->type, true);
12662                         mark_pkt_end(this_branch, insn->dst_reg, false);
12663                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12664                             src_reg->type == PTR_TO_PACKET) ||
12665                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12666                             src_reg->type == PTR_TO_PACKET_META)) {
12667                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
12668                         find_good_pkt_pointers(this_branch, src_reg,
12669                                                src_reg->type, false);
12670                         mark_pkt_end(other_branch, insn->src_reg, true);
12671                 } else {
12672                         return false;
12673                 }
12674                 break;
12675         case BPF_JGE:
12676                 if ((dst_reg->type == PTR_TO_PACKET &&
12677                      src_reg->type == PTR_TO_PACKET_END) ||
12678                     (dst_reg->type == PTR_TO_PACKET_META &&
12679                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12680                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
12681                         find_good_pkt_pointers(this_branch, dst_reg,
12682                                                dst_reg->type, true);
12683                         mark_pkt_end(other_branch, insn->dst_reg, false);
12684                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12685                             src_reg->type == PTR_TO_PACKET) ||
12686                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12687                             src_reg->type == PTR_TO_PACKET_META)) {
12688                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
12689                         find_good_pkt_pointers(other_branch, src_reg,
12690                                                src_reg->type, false);
12691                         mark_pkt_end(this_branch, insn->src_reg, true);
12692                 } else {
12693                         return false;
12694                 }
12695                 break;
12696         case BPF_JLE:
12697                 if ((dst_reg->type == PTR_TO_PACKET &&
12698                      src_reg->type == PTR_TO_PACKET_END) ||
12699                     (dst_reg->type == PTR_TO_PACKET_META &&
12700                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
12701                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
12702                         find_good_pkt_pointers(other_branch, dst_reg,
12703                                                dst_reg->type, false);
12704                         mark_pkt_end(this_branch, insn->dst_reg, true);
12705                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
12706                             src_reg->type == PTR_TO_PACKET) ||
12707                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
12708                             src_reg->type == PTR_TO_PACKET_META)) {
12709                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
12710                         find_good_pkt_pointers(this_branch, src_reg,
12711                                                src_reg->type, true);
12712                         mark_pkt_end(other_branch, insn->src_reg, false);
12713                 } else {
12714                         return false;
12715                 }
12716                 break;
12717         default:
12718                 return false;
12719         }
12720
12721         return true;
12722 }
12723
12724 static void find_equal_scalars(struct bpf_verifier_state *vstate,
12725                                struct bpf_reg_state *known_reg)
12726 {
12727         struct bpf_func_state *state;
12728         struct bpf_reg_state *reg;
12729
12730         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12731                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
12732                         copy_register_state(reg, known_reg);
12733         }));
12734 }
12735
12736 static int check_cond_jmp_op(struct bpf_verifier_env *env,
12737                              struct bpf_insn *insn, int *insn_idx)
12738 {
12739         struct bpf_verifier_state *this_branch = env->cur_state;
12740         struct bpf_verifier_state *other_branch;
12741         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
12742         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
12743         struct bpf_reg_state *eq_branch_regs;
12744         u8 opcode = BPF_OP(insn->code);
12745         bool is_jmp32;
12746         int pred = -1;
12747         int err;
12748
12749         /* Only conditional jumps are expected to reach here. */
12750         if (opcode == BPF_JA || opcode > BPF_JSLE) {
12751                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
12752                 return -EINVAL;
12753         }
12754
12755         if (BPF_SRC(insn->code) == BPF_X) {
12756                 if (insn->imm != 0) {
12757                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12758                         return -EINVAL;
12759                 }
12760
12761                 /* check src1 operand */
12762                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12763                 if (err)
12764                         return err;
12765
12766                 if (is_pointer_value(env, insn->src_reg)) {
12767                         verbose(env, "R%d pointer comparison prohibited\n",
12768                                 insn->src_reg);
12769                         return -EACCES;
12770                 }
12771                 src_reg = &regs[insn->src_reg];
12772         } else {
12773                 if (insn->src_reg != BPF_REG_0) {
12774                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
12775                         return -EINVAL;
12776                 }
12777         }
12778
12779         /* check src2 operand */
12780         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12781         if (err)
12782                 return err;
12783
12784         dst_reg = &regs[insn->dst_reg];
12785         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
12786
12787         if (BPF_SRC(insn->code) == BPF_K) {
12788                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
12789         } else if (src_reg->type == SCALAR_VALUE &&
12790                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
12791                 pred = is_branch_taken(dst_reg,
12792                                        tnum_subreg(src_reg->var_off).value,
12793                                        opcode,
12794                                        is_jmp32);
12795         } else if (src_reg->type == SCALAR_VALUE &&
12796                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
12797                 pred = is_branch_taken(dst_reg,
12798                                        src_reg->var_off.value,
12799                                        opcode,
12800                                        is_jmp32);
12801         } else if (reg_is_pkt_pointer_any(dst_reg) &&
12802                    reg_is_pkt_pointer_any(src_reg) &&
12803                    !is_jmp32) {
12804                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
12805         }
12806
12807         if (pred >= 0) {
12808                 /* If we get here with a dst_reg pointer type it is because
12809                  * above is_branch_taken() special cased the 0 comparison.
12810                  */
12811                 if (!__is_pointer_value(false, dst_reg))
12812                         err = mark_chain_precision(env, insn->dst_reg);
12813                 if (BPF_SRC(insn->code) == BPF_X && !err &&
12814                     !__is_pointer_value(false, src_reg))
12815                         err = mark_chain_precision(env, insn->src_reg);
12816                 if (err)
12817                         return err;
12818         }
12819
12820         if (pred == 1) {
12821                 /* Only follow the goto, ignore fall-through. If needed, push
12822                  * the fall-through branch for simulation under speculative
12823                  * execution.
12824                  */
12825                 if (!env->bypass_spec_v1 &&
12826                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
12827                                                *insn_idx))
12828                         return -EFAULT;
12829                 *insn_idx += insn->off;
12830                 return 0;
12831         } else if (pred == 0) {
12832                 /* Only follow the fall-through branch, since that's where the
12833                  * program will go. If needed, push the goto branch for
12834                  * simulation under speculative execution.
12835                  */
12836                 if (!env->bypass_spec_v1 &&
12837                     !sanitize_speculative_path(env, insn,
12838                                                *insn_idx + insn->off + 1,
12839                                                *insn_idx))
12840                         return -EFAULT;
12841                 return 0;
12842         }
12843
12844         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
12845                                   false);
12846         if (!other_branch)
12847                 return -EFAULT;
12848         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
12849
12850         /* detect if we are comparing against a constant value so we can adjust
12851          * our min/max values for our dst register.
12852          * this is only legit if both are scalars (or pointers to the same
12853          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
12854          * because otherwise the different base pointers mean the offsets aren't
12855          * comparable.
12856          */
12857         if (BPF_SRC(insn->code) == BPF_X) {
12858                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
12859
12860                 if (dst_reg->type == SCALAR_VALUE &&
12861                     src_reg->type == SCALAR_VALUE) {
12862                         if (tnum_is_const(src_reg->var_off) ||
12863                             (is_jmp32 &&
12864                              tnum_is_const(tnum_subreg(src_reg->var_off))))
12865                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
12866                                                 dst_reg,
12867                                                 src_reg->var_off.value,
12868                                                 tnum_subreg(src_reg->var_off).value,
12869                                                 opcode, is_jmp32);
12870                         else if (tnum_is_const(dst_reg->var_off) ||
12871                                  (is_jmp32 &&
12872                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
12873                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
12874                                                     src_reg,
12875                                                     dst_reg->var_off.value,
12876                                                     tnum_subreg(dst_reg->var_off).value,
12877                                                     opcode, is_jmp32);
12878                         else if (!is_jmp32 &&
12879                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
12880                                 /* Comparing for equality, we can combine knowledge */
12881                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
12882                                                     &other_branch_regs[insn->dst_reg],
12883                                                     src_reg, dst_reg, opcode);
12884                         if (src_reg->id &&
12885                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
12886                                 find_equal_scalars(this_branch, src_reg);
12887                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
12888                         }
12889
12890                 }
12891         } else if (dst_reg->type == SCALAR_VALUE) {
12892                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
12893                                         dst_reg, insn->imm, (u32)insn->imm,
12894                                         opcode, is_jmp32);
12895         }
12896
12897         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
12898             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
12899                 find_equal_scalars(this_branch, dst_reg);
12900                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
12901         }
12902
12903         /* if one pointer register is compared to another pointer
12904          * register check if PTR_MAYBE_NULL could be lifted.
12905          * E.g. register A - maybe null
12906          *      register B - not null
12907          * for JNE A, B, ... - A is not null in the false branch;
12908          * for JEQ A, B, ... - A is not null in the true branch.
12909          *
12910          * Since PTR_TO_BTF_ID points to a kernel struct that does
12911          * not need to be null checked by the BPF program, i.e.,
12912          * could be null even without PTR_MAYBE_NULL marking, so
12913          * only propagate nullness when neither reg is that type.
12914          */
12915         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
12916             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
12917             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
12918             base_type(src_reg->type) != PTR_TO_BTF_ID &&
12919             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
12920                 eq_branch_regs = NULL;
12921                 switch (opcode) {
12922                 case BPF_JEQ:
12923                         eq_branch_regs = other_branch_regs;
12924                         break;
12925                 case BPF_JNE:
12926                         eq_branch_regs = regs;
12927                         break;
12928                 default:
12929                         /* do nothing */
12930                         break;
12931                 }
12932                 if (eq_branch_regs) {
12933                         if (type_may_be_null(src_reg->type))
12934                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
12935                         else
12936                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
12937                 }
12938         }
12939
12940         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
12941          * NOTE: these optimizations below are related with pointer comparison
12942          *       which will never be JMP32.
12943          */
12944         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
12945             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
12946             type_may_be_null(dst_reg->type)) {
12947                 /* Mark all identical registers in each branch as either
12948                  * safe or unknown depending R == 0 or R != 0 conditional.
12949                  */
12950                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
12951                                       opcode == BPF_JNE);
12952                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
12953                                       opcode == BPF_JEQ);
12954         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
12955                                            this_branch, other_branch) &&
12956                    is_pointer_value(env, insn->dst_reg)) {
12957                 verbose(env, "R%d pointer comparison prohibited\n",
12958                         insn->dst_reg);
12959                 return -EACCES;
12960         }
12961         if (env->log.level & BPF_LOG_LEVEL)
12962                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
12963         return 0;
12964 }
12965
12966 /* verify BPF_LD_IMM64 instruction */
12967 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
12968 {
12969         struct bpf_insn_aux_data *aux = cur_aux(env);
12970         struct bpf_reg_state *regs = cur_regs(env);
12971         struct bpf_reg_state *dst_reg;
12972         struct bpf_map *map;
12973         int err;
12974
12975         if (BPF_SIZE(insn->code) != BPF_DW) {
12976                 verbose(env, "invalid BPF_LD_IMM insn\n");
12977                 return -EINVAL;
12978         }
12979         if (insn->off != 0) {
12980                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
12981                 return -EINVAL;
12982         }
12983
12984         err = check_reg_arg(env, insn->dst_reg, DST_OP);
12985         if (err)
12986                 return err;
12987
12988         dst_reg = &regs[insn->dst_reg];
12989         if (insn->src_reg == 0) {
12990                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
12991
12992                 dst_reg->type = SCALAR_VALUE;
12993                 __mark_reg_known(&regs[insn->dst_reg], imm);
12994                 return 0;
12995         }
12996
12997         /* All special src_reg cases are listed below. From this point onwards
12998          * we either succeed and assign a corresponding dst_reg->type after
12999          * zeroing the offset, or fail and reject the program.
13000          */
13001         mark_reg_known_zero(env, regs, insn->dst_reg);
13002
13003         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13004                 dst_reg->type = aux->btf_var.reg_type;
13005                 switch (base_type(dst_reg->type)) {
13006                 case PTR_TO_MEM:
13007                         dst_reg->mem_size = aux->btf_var.mem_size;
13008                         break;
13009                 case PTR_TO_BTF_ID:
13010                         dst_reg->btf = aux->btf_var.btf;
13011                         dst_reg->btf_id = aux->btf_var.btf_id;
13012                         break;
13013                 default:
13014                         verbose(env, "bpf verifier is misconfigured\n");
13015                         return -EFAULT;
13016                 }
13017                 return 0;
13018         }
13019
13020         if (insn->src_reg == BPF_PSEUDO_FUNC) {
13021                 struct bpf_prog_aux *aux = env->prog->aux;
13022                 u32 subprogno = find_subprog(env,
13023                                              env->insn_idx + insn->imm + 1);
13024
13025                 if (!aux->func_info) {
13026                         verbose(env, "missing btf func_info\n");
13027                         return -EINVAL;
13028                 }
13029                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13030                         verbose(env, "callback function not static\n");
13031                         return -EINVAL;
13032                 }
13033
13034                 dst_reg->type = PTR_TO_FUNC;
13035                 dst_reg->subprogno = subprogno;
13036                 return 0;
13037         }
13038
13039         map = env->used_maps[aux->map_index];
13040         dst_reg->map_ptr = map;
13041
13042         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13043             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13044                 dst_reg->type = PTR_TO_MAP_VALUE;
13045                 dst_reg->off = aux->map_off;
13046                 WARN_ON_ONCE(map->max_entries != 1);
13047                 /* We want reg->id to be same (0) as map_value is not distinct */
13048         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13049                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13050                 dst_reg->type = CONST_PTR_TO_MAP;
13051         } else {
13052                 verbose(env, "bpf verifier is misconfigured\n");
13053                 return -EINVAL;
13054         }
13055
13056         return 0;
13057 }
13058
13059 static bool may_access_skb(enum bpf_prog_type type)
13060 {
13061         switch (type) {
13062         case BPF_PROG_TYPE_SOCKET_FILTER:
13063         case BPF_PROG_TYPE_SCHED_CLS:
13064         case BPF_PROG_TYPE_SCHED_ACT:
13065                 return true;
13066         default:
13067                 return false;
13068         }
13069 }
13070
13071 /* verify safety of LD_ABS|LD_IND instructions:
13072  * - they can only appear in the programs where ctx == skb
13073  * - since they are wrappers of function calls, they scratch R1-R5 registers,
13074  *   preserve R6-R9, and store return value into R0
13075  *
13076  * Implicit input:
13077  *   ctx == skb == R6 == CTX
13078  *
13079  * Explicit input:
13080  *   SRC == any register
13081  *   IMM == 32-bit immediate
13082  *
13083  * Output:
13084  *   R0 - 8/16/32-bit skb data converted to cpu endianness
13085  */
13086 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
13087 {
13088         struct bpf_reg_state *regs = cur_regs(env);
13089         static const int ctx_reg = BPF_REG_6;
13090         u8 mode = BPF_MODE(insn->code);
13091         int i, err;
13092
13093         if (!may_access_skb(resolve_prog_type(env->prog))) {
13094                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
13095                 return -EINVAL;
13096         }
13097
13098         if (!env->ops->gen_ld_abs) {
13099                 verbose(env, "bpf verifier is misconfigured\n");
13100                 return -EINVAL;
13101         }
13102
13103         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
13104             BPF_SIZE(insn->code) == BPF_DW ||
13105             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
13106                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
13107                 return -EINVAL;
13108         }
13109
13110         /* check whether implicit source operand (register R6) is readable */
13111         err = check_reg_arg(env, ctx_reg, SRC_OP);
13112         if (err)
13113                 return err;
13114
13115         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13116          * gen_ld_abs() may terminate the program at runtime, leading to
13117          * reference leak.
13118          */
13119         err = check_reference_leak(env);
13120         if (err) {
13121                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13122                 return err;
13123         }
13124
13125         if (env->cur_state->active_lock.ptr) {
13126                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13127                 return -EINVAL;
13128         }
13129
13130         if (env->cur_state->active_rcu_lock) {
13131                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13132                 return -EINVAL;
13133         }
13134
13135         if (regs[ctx_reg].type != PTR_TO_CTX) {
13136                 verbose(env,
13137                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
13138                 return -EINVAL;
13139         }
13140
13141         if (mode == BPF_IND) {
13142                 /* check explicit source operand */
13143                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13144                 if (err)
13145                         return err;
13146         }
13147
13148         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
13149         if (err < 0)
13150                 return err;
13151
13152         /* reset caller saved regs to unreadable */
13153         for (i = 0; i < CALLER_SAVED_REGS; i++) {
13154                 mark_reg_not_init(env, regs, caller_saved[i]);
13155                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13156         }
13157
13158         /* mark destination R0 register as readable, since it contains
13159          * the value fetched from the packet.
13160          * Already marked as written above.
13161          */
13162         mark_reg_unknown(env, regs, BPF_REG_0);
13163         /* ld_abs load up to 32-bit skb data. */
13164         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
13165         return 0;
13166 }
13167
13168 static int check_return_code(struct bpf_verifier_env *env)
13169 {
13170         struct tnum enforce_attach_type_range = tnum_unknown;
13171         const struct bpf_prog *prog = env->prog;
13172         struct bpf_reg_state *reg;
13173         struct tnum range = tnum_range(0, 1);
13174         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13175         int err;
13176         struct bpf_func_state *frame = env->cur_state->frame[0];
13177         const bool is_subprog = frame->subprogno;
13178
13179         /* LSM and struct_ops func-ptr's return type could be "void" */
13180         if (!is_subprog) {
13181                 switch (prog_type) {
13182                 case BPF_PROG_TYPE_LSM:
13183                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
13184                                 /* See below, can be 0 or 0-1 depending on hook. */
13185                                 break;
13186                         fallthrough;
13187                 case BPF_PROG_TYPE_STRUCT_OPS:
13188                         if (!prog->aux->attach_func_proto->type)
13189                                 return 0;
13190                         break;
13191                 default:
13192                         break;
13193                 }
13194         }
13195
13196         /* eBPF calling convention is such that R0 is used
13197          * to return the value from eBPF program.
13198          * Make sure that it's readable at this time
13199          * of bpf_exit, which means that program wrote
13200          * something into it earlier
13201          */
13202         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13203         if (err)
13204                 return err;
13205
13206         if (is_pointer_value(env, BPF_REG_0)) {
13207                 verbose(env, "R0 leaks addr as return value\n");
13208                 return -EACCES;
13209         }
13210
13211         reg = cur_regs(env) + BPF_REG_0;
13212
13213         if (frame->in_async_callback_fn) {
13214                 /* enforce return zero from async callbacks like timer */
13215                 if (reg->type != SCALAR_VALUE) {
13216                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
13217                                 reg_type_str(env, reg->type));
13218                         return -EINVAL;
13219                 }
13220
13221                 if (!tnum_in(tnum_const(0), reg->var_off)) {
13222                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13223                         return -EINVAL;
13224                 }
13225                 return 0;
13226         }
13227
13228         if (is_subprog) {
13229                 if (reg->type != SCALAR_VALUE) {
13230                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
13231                                 reg_type_str(env, reg->type));
13232                         return -EINVAL;
13233                 }
13234                 return 0;
13235         }
13236
13237         switch (prog_type) {
13238         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
13239                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
13240                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
13241                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
13242                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
13243                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
13244                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
13245                         range = tnum_range(1, 1);
13246                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
13247                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
13248                         range = tnum_range(0, 3);
13249                 break;
13250         case BPF_PROG_TYPE_CGROUP_SKB:
13251                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
13252                         range = tnum_range(0, 3);
13253                         enforce_attach_type_range = tnum_range(2, 3);
13254                 }
13255                 break;
13256         case BPF_PROG_TYPE_CGROUP_SOCK:
13257         case BPF_PROG_TYPE_SOCK_OPS:
13258         case BPF_PROG_TYPE_CGROUP_DEVICE:
13259         case BPF_PROG_TYPE_CGROUP_SYSCTL:
13260         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
13261                 break;
13262         case BPF_PROG_TYPE_RAW_TRACEPOINT:
13263                 if (!env->prog->aux->attach_btf_id)
13264                         return 0;
13265                 range = tnum_const(0);
13266                 break;
13267         case BPF_PROG_TYPE_TRACING:
13268                 switch (env->prog->expected_attach_type) {
13269                 case BPF_TRACE_FENTRY:
13270                 case BPF_TRACE_FEXIT:
13271                         range = tnum_const(0);
13272                         break;
13273                 case BPF_TRACE_RAW_TP:
13274                 case BPF_MODIFY_RETURN:
13275                         return 0;
13276                 case BPF_TRACE_ITER:
13277                         break;
13278                 default:
13279                         return -ENOTSUPP;
13280                 }
13281                 break;
13282         case BPF_PROG_TYPE_SK_LOOKUP:
13283                 range = tnum_range(SK_DROP, SK_PASS);
13284                 break;
13285
13286         case BPF_PROG_TYPE_LSM:
13287                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
13288                         /* Regular BPF_PROG_TYPE_LSM programs can return
13289                          * any value.
13290                          */
13291                         return 0;
13292                 }
13293                 if (!env->prog->aux->attach_func_proto->type) {
13294                         /* Make sure programs that attach to void
13295                          * hooks don't try to modify return value.
13296                          */
13297                         range = tnum_range(1, 1);
13298                 }
13299                 break;
13300
13301         case BPF_PROG_TYPE_EXT:
13302                 /* freplace program can return anything as its return value
13303                  * depends on the to-be-replaced kernel func or bpf program.
13304                  */
13305         default:
13306                 return 0;
13307         }
13308
13309         if (reg->type != SCALAR_VALUE) {
13310                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
13311                         reg_type_str(env, reg->type));
13312                 return -EINVAL;
13313         }
13314
13315         if (!tnum_in(range, reg->var_off)) {
13316                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
13317                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
13318                     prog_type == BPF_PROG_TYPE_LSM &&
13319                     !prog->aux->attach_func_proto->type)
13320                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
13321                 return -EINVAL;
13322         }
13323
13324         if (!tnum_is_unknown(enforce_attach_type_range) &&
13325             tnum_in(enforce_attach_type_range, reg->var_off))
13326                 env->prog->enforce_expected_attach_type = 1;
13327         return 0;
13328 }
13329
13330 /* non-recursive DFS pseudo code
13331  * 1  procedure DFS-iterative(G,v):
13332  * 2      label v as discovered
13333  * 3      let S be a stack
13334  * 4      S.push(v)
13335  * 5      while S is not empty
13336  * 6            t <- S.peek()
13337  * 7            if t is what we're looking for:
13338  * 8                return t
13339  * 9            for all edges e in G.adjacentEdges(t) do
13340  * 10               if edge e is already labelled
13341  * 11                   continue with the next edge
13342  * 12               w <- G.adjacentVertex(t,e)
13343  * 13               if vertex w is not discovered and not explored
13344  * 14                   label e as tree-edge
13345  * 15                   label w as discovered
13346  * 16                   S.push(w)
13347  * 17                   continue at 5
13348  * 18               else if vertex w is discovered
13349  * 19                   label e as back-edge
13350  * 20               else
13351  * 21                   // vertex w is explored
13352  * 22                   label e as forward- or cross-edge
13353  * 23           label t as explored
13354  * 24           S.pop()
13355  *
13356  * convention:
13357  * 0x10 - discovered
13358  * 0x11 - discovered and fall-through edge labelled
13359  * 0x12 - discovered and fall-through and branch edges labelled
13360  * 0x20 - explored
13361  */
13362
13363 enum {
13364         DISCOVERED = 0x10,
13365         EXPLORED = 0x20,
13366         FALLTHROUGH = 1,
13367         BRANCH = 2,
13368 };
13369
13370 static u32 state_htab_size(struct bpf_verifier_env *env)
13371 {
13372         return env->prog->len;
13373 }
13374
13375 static struct bpf_verifier_state_list **explored_state(
13376                                         struct bpf_verifier_env *env,
13377                                         int idx)
13378 {
13379         struct bpf_verifier_state *cur = env->cur_state;
13380         struct bpf_func_state *state = cur->frame[cur->curframe];
13381
13382         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13383 }
13384
13385 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13386 {
13387         env->insn_aux_data[idx].prune_point = true;
13388 }
13389
13390 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13391 {
13392         return env->insn_aux_data[insn_idx].prune_point;
13393 }
13394
13395 enum {
13396         DONE_EXPLORING = 0,
13397         KEEP_EXPLORING = 1,
13398 };
13399
13400 /* t, w, e - match pseudo-code above:
13401  * t - index of current instruction
13402  * w - next instruction
13403  * e - edge
13404  */
13405 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13406                      bool loop_ok)
13407 {
13408         int *insn_stack = env->cfg.insn_stack;
13409         int *insn_state = env->cfg.insn_state;
13410
13411         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13412                 return DONE_EXPLORING;
13413
13414         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13415                 return DONE_EXPLORING;
13416
13417         if (w < 0 || w >= env->prog->len) {
13418                 verbose_linfo(env, t, "%d: ", t);
13419                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
13420                 return -EINVAL;
13421         }
13422
13423         if (e == BRANCH) {
13424                 /* mark branch target for state pruning */
13425                 mark_prune_point(env, w);
13426                 mark_jmp_point(env, w);
13427         }
13428
13429         if (insn_state[w] == 0) {
13430                 /* tree-edge */
13431                 insn_state[t] = DISCOVERED | e;
13432                 insn_state[w] = DISCOVERED;
13433                 if (env->cfg.cur_stack >= env->prog->len)
13434                         return -E2BIG;
13435                 insn_stack[env->cfg.cur_stack++] = w;
13436                 return KEEP_EXPLORING;
13437         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13438                 if (loop_ok && env->bpf_capable)
13439                         return DONE_EXPLORING;
13440                 verbose_linfo(env, t, "%d: ", t);
13441                 verbose_linfo(env, w, "%d: ", w);
13442                 verbose(env, "back-edge from insn %d to %d\n", t, w);
13443                 return -EINVAL;
13444         } else if (insn_state[w] == EXPLORED) {
13445                 /* forward- or cross-edge */
13446                 insn_state[t] = DISCOVERED | e;
13447         } else {
13448                 verbose(env, "insn state internal bug\n");
13449                 return -EFAULT;
13450         }
13451         return DONE_EXPLORING;
13452 }
13453
13454 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13455                                 struct bpf_verifier_env *env,
13456                                 bool visit_callee)
13457 {
13458         int ret;
13459
13460         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13461         if (ret)
13462                 return ret;
13463
13464         mark_prune_point(env, t + 1);
13465         /* when we exit from subprog, we need to record non-linear history */
13466         mark_jmp_point(env, t + 1);
13467
13468         if (visit_callee) {
13469                 mark_prune_point(env, t);
13470                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13471                                 /* It's ok to allow recursion from CFG point of
13472                                  * view. __check_func_call() will do the actual
13473                                  * check.
13474                                  */
13475                                 bpf_pseudo_func(insns + t));
13476         }
13477         return ret;
13478 }
13479
13480 /* Visits the instruction at index t and returns one of the following:
13481  *  < 0 - an error occurred
13482  *  DONE_EXPLORING - the instruction was fully explored
13483  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
13484  */
13485 static int visit_insn(int t, struct bpf_verifier_env *env)
13486 {
13487         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
13488         int ret;
13489
13490         if (bpf_pseudo_func(insn))
13491                 return visit_func_call_insn(t, insns, env, true);
13492
13493         /* All non-branch instructions have a single fall-through edge. */
13494         if (BPF_CLASS(insn->code) != BPF_JMP &&
13495             BPF_CLASS(insn->code) != BPF_JMP32)
13496                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
13497
13498         switch (BPF_OP(insn->code)) {
13499         case BPF_EXIT:
13500                 return DONE_EXPLORING;
13501
13502         case BPF_CALL:
13503                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
13504                         /* Mark this call insn as a prune point to trigger
13505                          * is_state_visited() check before call itself is
13506                          * processed by __check_func_call(). Otherwise new
13507                          * async state will be pushed for further exploration.
13508                          */
13509                         mark_prune_point(env, t);
13510                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
13511
13512         case BPF_JA:
13513                 if (BPF_SRC(insn->code) != BPF_K)
13514                         return -EINVAL;
13515
13516                 /* unconditional jump with single edge */
13517                 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
13518                                 true);
13519                 if (ret)
13520                         return ret;
13521
13522                 mark_prune_point(env, t + insn->off + 1);
13523                 mark_jmp_point(env, t + insn->off + 1);
13524
13525                 return ret;
13526
13527         default:
13528                 /* conditional jump with two edges */
13529                 mark_prune_point(env, t);
13530
13531                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
13532                 if (ret)
13533                         return ret;
13534
13535                 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
13536         }
13537 }
13538
13539 /* non-recursive depth-first-search to detect loops in BPF program
13540  * loop == back-edge in directed graph
13541  */
13542 static int check_cfg(struct bpf_verifier_env *env)
13543 {
13544         int insn_cnt = env->prog->len;
13545         int *insn_stack, *insn_state;
13546         int ret = 0;
13547         int i;
13548
13549         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13550         if (!insn_state)
13551                 return -ENOMEM;
13552
13553         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
13554         if (!insn_stack) {
13555                 kvfree(insn_state);
13556                 return -ENOMEM;
13557         }
13558
13559         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
13560         insn_stack[0] = 0; /* 0 is the first instruction */
13561         env->cfg.cur_stack = 1;
13562
13563         while (env->cfg.cur_stack > 0) {
13564                 int t = insn_stack[env->cfg.cur_stack - 1];
13565
13566                 ret = visit_insn(t, env);
13567                 switch (ret) {
13568                 case DONE_EXPLORING:
13569                         insn_state[t] = EXPLORED;
13570                         env->cfg.cur_stack--;
13571                         break;
13572                 case KEEP_EXPLORING:
13573                         break;
13574                 default:
13575                         if (ret > 0) {
13576                                 verbose(env, "visit_insn internal bug\n");
13577                                 ret = -EFAULT;
13578                         }
13579                         goto err_free;
13580                 }
13581         }
13582
13583         if (env->cfg.cur_stack < 0) {
13584                 verbose(env, "pop stack internal bug\n");
13585                 ret = -EFAULT;
13586                 goto err_free;
13587         }
13588
13589         for (i = 0; i < insn_cnt; i++) {
13590                 if (insn_state[i] != EXPLORED) {
13591                         verbose(env, "unreachable insn %d\n", i);
13592                         ret = -EINVAL;
13593                         goto err_free;
13594                 }
13595         }
13596         ret = 0; /* cfg looks good */
13597
13598 err_free:
13599         kvfree(insn_state);
13600         kvfree(insn_stack);
13601         env->cfg.insn_state = env->cfg.insn_stack = NULL;
13602         return ret;
13603 }
13604
13605 static int check_abnormal_return(struct bpf_verifier_env *env)
13606 {
13607         int i;
13608
13609         for (i = 1; i < env->subprog_cnt; i++) {
13610                 if (env->subprog_info[i].has_ld_abs) {
13611                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
13612                         return -EINVAL;
13613                 }
13614                 if (env->subprog_info[i].has_tail_call) {
13615                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
13616                         return -EINVAL;
13617                 }
13618         }
13619         return 0;
13620 }
13621
13622 /* The minimum supported BTF func info size */
13623 #define MIN_BPF_FUNCINFO_SIZE   8
13624 #define MAX_FUNCINFO_REC_SIZE   252
13625
13626 static int check_btf_func(struct bpf_verifier_env *env,
13627                           const union bpf_attr *attr,
13628                           bpfptr_t uattr)
13629 {
13630         const struct btf_type *type, *func_proto, *ret_type;
13631         u32 i, nfuncs, urec_size, min_size;
13632         u32 krec_size = sizeof(struct bpf_func_info);
13633         struct bpf_func_info *krecord;
13634         struct bpf_func_info_aux *info_aux = NULL;
13635         struct bpf_prog *prog;
13636         const struct btf *btf;
13637         bpfptr_t urecord;
13638         u32 prev_offset = 0;
13639         bool scalar_return;
13640         int ret = -ENOMEM;
13641
13642         nfuncs = attr->func_info_cnt;
13643         if (!nfuncs) {
13644                 if (check_abnormal_return(env))
13645                         return -EINVAL;
13646                 return 0;
13647         }
13648
13649         if (nfuncs != env->subprog_cnt) {
13650                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
13651                 return -EINVAL;
13652         }
13653
13654         urec_size = attr->func_info_rec_size;
13655         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
13656             urec_size > MAX_FUNCINFO_REC_SIZE ||
13657             urec_size % sizeof(u32)) {
13658                 verbose(env, "invalid func info rec size %u\n", urec_size);
13659                 return -EINVAL;
13660         }
13661
13662         prog = env->prog;
13663         btf = prog->aux->btf;
13664
13665         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
13666         min_size = min_t(u32, krec_size, urec_size);
13667
13668         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
13669         if (!krecord)
13670                 return -ENOMEM;
13671         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
13672         if (!info_aux)
13673                 goto err_free;
13674
13675         for (i = 0; i < nfuncs; i++) {
13676                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
13677                 if (ret) {
13678                         if (ret == -E2BIG) {
13679                                 verbose(env, "nonzero tailing record in func info");
13680                                 /* set the size kernel expects so loader can zero
13681                                  * out the rest of the record.
13682                                  */
13683                                 if (copy_to_bpfptr_offset(uattr,
13684                                                           offsetof(union bpf_attr, func_info_rec_size),
13685                                                           &min_size, sizeof(min_size)))
13686                                         ret = -EFAULT;
13687                         }
13688                         goto err_free;
13689                 }
13690
13691                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
13692                         ret = -EFAULT;
13693                         goto err_free;
13694                 }
13695
13696                 /* check insn_off */
13697                 ret = -EINVAL;
13698                 if (i == 0) {
13699                         if (krecord[i].insn_off) {
13700                                 verbose(env,
13701                                         "nonzero insn_off %u for the first func info record",
13702                                         krecord[i].insn_off);
13703                                 goto err_free;
13704                         }
13705                 } else if (krecord[i].insn_off <= prev_offset) {
13706                         verbose(env,
13707                                 "same or smaller insn offset (%u) than previous func info record (%u)",
13708                                 krecord[i].insn_off, prev_offset);
13709                         goto err_free;
13710                 }
13711
13712                 if (env->subprog_info[i].start != krecord[i].insn_off) {
13713                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
13714                         goto err_free;
13715                 }
13716
13717                 /* check type_id */
13718                 type = btf_type_by_id(btf, krecord[i].type_id);
13719                 if (!type || !btf_type_is_func(type)) {
13720                         verbose(env, "invalid type id %d in func info",
13721                                 krecord[i].type_id);
13722                         goto err_free;
13723                 }
13724                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
13725
13726                 func_proto = btf_type_by_id(btf, type->type);
13727                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
13728                         /* btf_func_check() already verified it during BTF load */
13729                         goto err_free;
13730                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
13731                 scalar_return =
13732                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
13733                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
13734                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
13735                         goto err_free;
13736                 }
13737                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
13738                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
13739                         goto err_free;
13740                 }
13741
13742                 prev_offset = krecord[i].insn_off;
13743                 bpfptr_add(&urecord, urec_size);
13744         }
13745
13746         prog->aux->func_info = krecord;
13747         prog->aux->func_info_cnt = nfuncs;
13748         prog->aux->func_info_aux = info_aux;
13749         return 0;
13750
13751 err_free:
13752         kvfree(krecord);
13753         kfree(info_aux);
13754         return ret;
13755 }
13756
13757 static void adjust_btf_func(struct bpf_verifier_env *env)
13758 {
13759         struct bpf_prog_aux *aux = env->prog->aux;
13760         int i;
13761
13762         if (!aux->func_info)
13763                 return;
13764
13765         for (i = 0; i < env->subprog_cnt; i++)
13766                 aux->func_info[i].insn_off = env->subprog_info[i].start;
13767 }
13768
13769 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
13770 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
13771
13772 static int check_btf_line(struct bpf_verifier_env *env,
13773                           const union bpf_attr *attr,
13774                           bpfptr_t uattr)
13775 {
13776         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
13777         struct bpf_subprog_info *sub;
13778         struct bpf_line_info *linfo;
13779         struct bpf_prog *prog;
13780         const struct btf *btf;
13781         bpfptr_t ulinfo;
13782         int err;
13783
13784         nr_linfo = attr->line_info_cnt;
13785         if (!nr_linfo)
13786                 return 0;
13787         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
13788                 return -EINVAL;
13789
13790         rec_size = attr->line_info_rec_size;
13791         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
13792             rec_size > MAX_LINEINFO_REC_SIZE ||
13793             rec_size & (sizeof(u32) - 1))
13794                 return -EINVAL;
13795
13796         /* Need to zero it in case the userspace may
13797          * pass in a smaller bpf_line_info object.
13798          */
13799         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
13800                          GFP_KERNEL | __GFP_NOWARN);
13801         if (!linfo)
13802                 return -ENOMEM;
13803
13804         prog = env->prog;
13805         btf = prog->aux->btf;
13806
13807         s = 0;
13808         sub = env->subprog_info;
13809         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
13810         expected_size = sizeof(struct bpf_line_info);
13811         ncopy = min_t(u32, expected_size, rec_size);
13812         for (i = 0; i < nr_linfo; i++) {
13813                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
13814                 if (err) {
13815                         if (err == -E2BIG) {
13816                                 verbose(env, "nonzero tailing record in line_info");
13817                                 if (copy_to_bpfptr_offset(uattr,
13818                                                           offsetof(union bpf_attr, line_info_rec_size),
13819                                                           &expected_size, sizeof(expected_size)))
13820                                         err = -EFAULT;
13821                         }
13822                         goto err_free;
13823                 }
13824
13825                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
13826                         err = -EFAULT;
13827                         goto err_free;
13828                 }
13829
13830                 /*
13831                  * Check insn_off to ensure
13832                  * 1) strictly increasing AND
13833                  * 2) bounded by prog->len
13834                  *
13835                  * The linfo[0].insn_off == 0 check logically falls into
13836                  * the later "missing bpf_line_info for func..." case
13837                  * because the first linfo[0].insn_off must be the
13838                  * first sub also and the first sub must have
13839                  * subprog_info[0].start == 0.
13840                  */
13841                 if ((i && linfo[i].insn_off <= prev_offset) ||
13842                     linfo[i].insn_off >= prog->len) {
13843                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
13844                                 i, linfo[i].insn_off, prev_offset,
13845                                 prog->len);
13846                         err = -EINVAL;
13847                         goto err_free;
13848                 }
13849
13850                 if (!prog->insnsi[linfo[i].insn_off].code) {
13851                         verbose(env,
13852                                 "Invalid insn code at line_info[%u].insn_off\n",
13853                                 i);
13854                         err = -EINVAL;
13855                         goto err_free;
13856                 }
13857
13858                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
13859                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
13860                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
13861                         err = -EINVAL;
13862                         goto err_free;
13863                 }
13864
13865                 if (s != env->subprog_cnt) {
13866                         if (linfo[i].insn_off == sub[s].start) {
13867                                 sub[s].linfo_idx = i;
13868                                 s++;
13869                         } else if (sub[s].start < linfo[i].insn_off) {
13870                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
13871                                 err = -EINVAL;
13872                                 goto err_free;
13873                         }
13874                 }
13875
13876                 prev_offset = linfo[i].insn_off;
13877                 bpfptr_add(&ulinfo, rec_size);
13878         }
13879
13880         if (s != env->subprog_cnt) {
13881                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
13882                         env->subprog_cnt - s, s);
13883                 err = -EINVAL;
13884                 goto err_free;
13885         }
13886
13887         prog->aux->linfo = linfo;
13888         prog->aux->nr_linfo = nr_linfo;
13889
13890         return 0;
13891
13892 err_free:
13893         kvfree(linfo);
13894         return err;
13895 }
13896
13897 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
13898 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
13899
13900 static int check_core_relo(struct bpf_verifier_env *env,
13901                            const union bpf_attr *attr,
13902                            bpfptr_t uattr)
13903 {
13904         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
13905         struct bpf_core_relo core_relo = {};
13906         struct bpf_prog *prog = env->prog;
13907         const struct btf *btf = prog->aux->btf;
13908         struct bpf_core_ctx ctx = {
13909                 .log = &env->log,
13910                 .btf = btf,
13911         };
13912         bpfptr_t u_core_relo;
13913         int err;
13914
13915         nr_core_relo = attr->core_relo_cnt;
13916         if (!nr_core_relo)
13917                 return 0;
13918         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
13919                 return -EINVAL;
13920
13921         rec_size = attr->core_relo_rec_size;
13922         if (rec_size < MIN_CORE_RELO_SIZE ||
13923             rec_size > MAX_CORE_RELO_SIZE ||
13924             rec_size % sizeof(u32))
13925                 return -EINVAL;
13926
13927         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
13928         expected_size = sizeof(struct bpf_core_relo);
13929         ncopy = min_t(u32, expected_size, rec_size);
13930
13931         /* Unlike func_info and line_info, copy and apply each CO-RE
13932          * relocation record one at a time.
13933          */
13934         for (i = 0; i < nr_core_relo; i++) {
13935                 /* future proofing when sizeof(bpf_core_relo) changes */
13936                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
13937                 if (err) {
13938                         if (err == -E2BIG) {
13939                                 verbose(env, "nonzero tailing record in core_relo");
13940                                 if (copy_to_bpfptr_offset(uattr,
13941                                                           offsetof(union bpf_attr, core_relo_rec_size),
13942                                                           &expected_size, sizeof(expected_size)))
13943                                         err = -EFAULT;
13944                         }
13945                         break;
13946                 }
13947
13948                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
13949                         err = -EFAULT;
13950                         break;
13951                 }
13952
13953                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
13954                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
13955                                 i, core_relo.insn_off, prog->len);
13956                         err = -EINVAL;
13957                         break;
13958                 }
13959
13960                 err = bpf_core_apply(&ctx, &core_relo, i,
13961                                      &prog->insnsi[core_relo.insn_off / 8]);
13962                 if (err)
13963                         break;
13964                 bpfptr_add(&u_core_relo, rec_size);
13965         }
13966         return err;
13967 }
13968
13969 static int check_btf_info(struct bpf_verifier_env *env,
13970                           const union bpf_attr *attr,
13971                           bpfptr_t uattr)
13972 {
13973         struct btf *btf;
13974         int err;
13975
13976         if (!attr->func_info_cnt && !attr->line_info_cnt) {
13977                 if (check_abnormal_return(env))
13978                         return -EINVAL;
13979                 return 0;
13980         }
13981
13982         btf = btf_get_by_fd(attr->prog_btf_fd);
13983         if (IS_ERR(btf))
13984                 return PTR_ERR(btf);
13985         if (btf_is_kernel(btf)) {
13986                 btf_put(btf);
13987                 return -EACCES;
13988         }
13989         env->prog->aux->btf = btf;
13990
13991         err = check_btf_func(env, attr, uattr);
13992         if (err)
13993                 return err;
13994
13995         err = check_btf_line(env, attr, uattr);
13996         if (err)
13997                 return err;
13998
13999         err = check_core_relo(env, attr, uattr);
14000         if (err)
14001                 return err;
14002
14003         return 0;
14004 }
14005
14006 /* check %cur's range satisfies %old's */
14007 static bool range_within(struct bpf_reg_state *old,
14008                          struct bpf_reg_state *cur)
14009 {
14010         return old->umin_value <= cur->umin_value &&
14011                old->umax_value >= cur->umax_value &&
14012                old->smin_value <= cur->smin_value &&
14013                old->smax_value >= cur->smax_value &&
14014                old->u32_min_value <= cur->u32_min_value &&
14015                old->u32_max_value >= cur->u32_max_value &&
14016                old->s32_min_value <= cur->s32_min_value &&
14017                old->s32_max_value >= cur->s32_max_value;
14018 }
14019
14020 /* If in the old state two registers had the same id, then they need to have
14021  * the same id in the new state as well.  But that id could be different from
14022  * the old state, so we need to track the mapping from old to new ids.
14023  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14024  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
14025  * regs with a different old id could still have new id 9, we don't care about
14026  * that.
14027  * So we look through our idmap to see if this old id has been seen before.  If
14028  * so, we require the new id to match; otherwise, we add the id pair to the map.
14029  */
14030 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14031 {
14032         unsigned int i;
14033
14034         /* either both IDs should be set or both should be zero */
14035         if (!!old_id != !!cur_id)
14036                 return false;
14037
14038         if (old_id == 0) /* cur_id == 0 as well */
14039                 return true;
14040
14041         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14042                 if (!idmap[i].old) {
14043                         /* Reached an empty slot; haven't seen this id before */
14044                         idmap[i].old = old_id;
14045                         idmap[i].cur = cur_id;
14046                         return true;
14047                 }
14048                 if (idmap[i].old == old_id)
14049                         return idmap[i].cur == cur_id;
14050         }
14051         /* We ran out of idmap slots, which should be impossible */
14052         WARN_ON_ONCE(1);
14053         return false;
14054 }
14055
14056 static void clean_func_state(struct bpf_verifier_env *env,
14057                              struct bpf_func_state *st)
14058 {
14059         enum bpf_reg_liveness live;
14060         int i, j;
14061
14062         for (i = 0; i < BPF_REG_FP; i++) {
14063                 live = st->regs[i].live;
14064                 /* liveness must not touch this register anymore */
14065                 st->regs[i].live |= REG_LIVE_DONE;
14066                 if (!(live & REG_LIVE_READ))
14067                         /* since the register is unused, clear its state
14068                          * to make further comparison simpler
14069                          */
14070                         __mark_reg_not_init(env, &st->regs[i]);
14071         }
14072
14073         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14074                 live = st->stack[i].spilled_ptr.live;
14075                 /* liveness must not touch this stack slot anymore */
14076                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14077                 if (!(live & REG_LIVE_READ)) {
14078                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
14079                         for (j = 0; j < BPF_REG_SIZE; j++)
14080                                 st->stack[i].slot_type[j] = STACK_INVALID;
14081                 }
14082         }
14083 }
14084
14085 static void clean_verifier_state(struct bpf_verifier_env *env,
14086                                  struct bpf_verifier_state *st)
14087 {
14088         int i;
14089
14090         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14091                 /* all regs in this state in all frames were already marked */
14092                 return;
14093
14094         for (i = 0; i <= st->curframe; i++)
14095                 clean_func_state(env, st->frame[i]);
14096 }
14097
14098 /* the parentage chains form a tree.
14099  * the verifier states are added to state lists at given insn and
14100  * pushed into state stack for future exploration.
14101  * when the verifier reaches bpf_exit insn some of the verifer states
14102  * stored in the state lists have their final liveness state already,
14103  * but a lot of states will get revised from liveness point of view when
14104  * the verifier explores other branches.
14105  * Example:
14106  * 1: r0 = 1
14107  * 2: if r1 == 100 goto pc+1
14108  * 3: r0 = 2
14109  * 4: exit
14110  * when the verifier reaches exit insn the register r0 in the state list of
14111  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14112  * of insn 2 and goes exploring further. At the insn 4 it will walk the
14113  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14114  *
14115  * Since the verifier pushes the branch states as it sees them while exploring
14116  * the program the condition of walking the branch instruction for the second
14117  * time means that all states below this branch were already explored and
14118  * their final liveness marks are already propagated.
14119  * Hence when the verifier completes the search of state list in is_state_visited()
14120  * we can call this clean_live_states() function to mark all liveness states
14121  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14122  * will not be used.
14123  * This function also clears the registers and stack for states that !READ
14124  * to simplify state merging.
14125  *
14126  * Important note here that walking the same branch instruction in the callee
14127  * doesn't meant that the states are DONE. The verifier has to compare
14128  * the callsites
14129  */
14130 static void clean_live_states(struct bpf_verifier_env *env, int insn,
14131                               struct bpf_verifier_state *cur)
14132 {
14133         struct bpf_verifier_state_list *sl;
14134         int i;
14135
14136         sl = *explored_state(env, insn);
14137         while (sl) {
14138                 if (sl->state.branches)
14139                         goto next;
14140                 if (sl->state.insn_idx != insn ||
14141                     sl->state.curframe != cur->curframe)
14142                         goto next;
14143                 for (i = 0; i <= cur->curframe; i++)
14144                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14145                                 goto next;
14146                 clean_verifier_state(env, &sl->state);
14147 next:
14148                 sl = sl->next;
14149         }
14150 }
14151
14152 static bool regs_exact(const struct bpf_reg_state *rold,
14153                        const struct bpf_reg_state *rcur,
14154                        struct bpf_id_pair *idmap)
14155 {
14156         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 
14157                check_ids(rold->id, rcur->id, idmap) &&
14158                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14159 }
14160
14161 /* Returns true if (rold safe implies rcur safe) */
14162 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14163                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
14164 {
14165         if (!(rold->live & REG_LIVE_READ))
14166                 /* explored state didn't use this */
14167                 return true;
14168         if (rold->type == NOT_INIT)
14169                 /* explored state can't have used this */
14170                 return true;
14171         if (rcur->type == NOT_INIT)
14172                 return false;
14173
14174         /* Enforce that register types have to match exactly, including their
14175          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14176          * rule.
14177          *
14178          * One can make a point that using a pointer register as unbounded
14179          * SCALAR would be technically acceptable, but this could lead to
14180          * pointer leaks because scalars are allowed to leak while pointers
14181          * are not. We could make this safe in special cases if root is
14182          * calling us, but it's probably not worth the hassle.
14183          *
14184          * Also, register types that are *not* MAYBE_NULL could technically be
14185          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14186          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14187          * to the same map).
14188          * However, if the old MAYBE_NULL register then got NULL checked,
14189          * doing so could have affected others with the same id, and we can't
14190          * check for that because we lost the id when we converted to
14191          * a non-MAYBE_NULL variant.
14192          * So, as a general rule we don't allow mixing MAYBE_NULL and
14193          * non-MAYBE_NULL registers as well.
14194          */
14195         if (rold->type != rcur->type)
14196                 return false;
14197
14198         switch (base_type(rold->type)) {
14199         case SCALAR_VALUE:
14200                 if (regs_exact(rold, rcur, idmap))
14201                         return true;
14202                 if (env->explore_alu_limits)
14203                         return false;
14204                 if (!rold->precise)
14205                         return true;
14206                 /* new val must satisfy old val knowledge */
14207                 return range_within(rold, rcur) &&
14208                        tnum_in(rold->var_off, rcur->var_off);
14209         case PTR_TO_MAP_KEY:
14210         case PTR_TO_MAP_VALUE:
14211         case PTR_TO_MEM:
14212         case PTR_TO_BUF:
14213         case PTR_TO_TP_BUFFER:
14214                 /* If the new min/max/var_off satisfy the old ones and
14215                  * everything else matches, we are OK.
14216                  */
14217                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
14218                        range_within(rold, rcur) &&
14219                        tnum_in(rold->var_off, rcur->var_off) &&
14220                        check_ids(rold->id, rcur->id, idmap) &&
14221                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14222         case PTR_TO_PACKET_META:
14223         case PTR_TO_PACKET:
14224                 /* We must have at least as much range as the old ptr
14225                  * did, so that any accesses which were safe before are
14226                  * still safe.  This is true even if old range < old off,
14227                  * since someone could have accessed through (ptr - k), or
14228                  * even done ptr -= k in a register, to get a safe access.
14229                  */
14230                 if (rold->range > rcur->range)
14231                         return false;
14232                 /* If the offsets don't match, we can't trust our alignment;
14233                  * nor can we be sure that we won't fall out of range.
14234                  */
14235                 if (rold->off != rcur->off)
14236                         return false;
14237                 /* id relations must be preserved */
14238                 if (!check_ids(rold->id, rcur->id, idmap))
14239                         return false;
14240                 /* new val must satisfy old val knowledge */
14241                 return range_within(rold, rcur) &&
14242                        tnum_in(rold->var_off, rcur->var_off);
14243         case PTR_TO_STACK:
14244                 /* two stack pointers are equal only if they're pointing to
14245                  * the same stack frame, since fp-8 in foo != fp-8 in bar
14246                  */
14247                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
14248         default:
14249                 return regs_exact(rold, rcur, idmap);
14250         }
14251 }
14252
14253 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
14254                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
14255 {
14256         int i, spi;
14257
14258         /* walk slots of the explored stack and ignore any additional
14259          * slots in the current stack, since explored(safe) state
14260          * didn't use them
14261          */
14262         for (i = 0; i < old->allocated_stack; i++) {
14263                 spi = i / BPF_REG_SIZE;
14264
14265                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
14266                         i += BPF_REG_SIZE - 1;
14267                         /* explored state didn't use this */
14268                         continue;
14269                 }
14270
14271                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
14272                         continue;
14273
14274                 if (env->allow_uninit_stack &&
14275                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
14276                         continue;
14277
14278                 /* explored stack has more populated slots than current stack
14279                  * and these slots were used
14280                  */
14281                 if (i >= cur->allocated_stack)
14282                         return false;
14283
14284                 /* if old state was safe with misc data in the stack
14285                  * it will be safe with zero-initialized stack.
14286                  * The opposite is not true
14287                  */
14288                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
14289                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
14290                         continue;
14291                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
14292                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
14293                         /* Ex: old explored (safe) state has STACK_SPILL in
14294                          * this stack slot, but current has STACK_MISC ->
14295                          * this verifier states are not equivalent,
14296                          * return false to continue verification of this path
14297                          */
14298                         return false;
14299                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
14300                         continue;
14301                 /* Both old and cur are having same slot_type */
14302                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
14303                 case STACK_SPILL:
14304                         /* when explored and current stack slot are both storing
14305                          * spilled registers, check that stored pointers types
14306                          * are the same as well.
14307                          * Ex: explored safe path could have stored
14308                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
14309                          * but current path has stored:
14310                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
14311                          * such verifier states are not equivalent.
14312                          * return false to continue verification of this path
14313                          */
14314                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
14315                                      &cur->stack[spi].spilled_ptr, idmap))
14316                                 return false;
14317                         break;
14318                 case STACK_DYNPTR:
14319                 {
14320                         const struct bpf_reg_state *old_reg, *cur_reg;
14321
14322                         old_reg = &old->stack[spi].spilled_ptr;
14323                         cur_reg = &cur->stack[spi].spilled_ptr;
14324                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
14325                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
14326                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14327                                 return false;
14328                         break;
14329                 }
14330                 case STACK_MISC:
14331                 case STACK_ZERO:
14332                 case STACK_INVALID:
14333                         continue;
14334                 /* Ensure that new unhandled slot types return false by default */
14335                 default:
14336                         return false;
14337                 }
14338         }
14339         return true;
14340 }
14341
14342 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14343                     struct bpf_id_pair *idmap)
14344 {
14345         int i;
14346
14347         if (old->acquired_refs != cur->acquired_refs)
14348                 return false;
14349
14350         for (i = 0; i < old->acquired_refs; i++) {
14351                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14352                         return false;
14353         }
14354
14355         return true;
14356 }
14357
14358 /* compare two verifier states
14359  *
14360  * all states stored in state_list are known to be valid, since
14361  * verifier reached 'bpf_exit' instruction through them
14362  *
14363  * this function is called when verifier exploring different branches of
14364  * execution popped from the state stack. If it sees an old state that has
14365  * more strict register state and more strict stack state then this execution
14366  * branch doesn't need to be explored further, since verifier already
14367  * concluded that more strict state leads to valid finish.
14368  *
14369  * Therefore two states are equivalent if register state is more conservative
14370  * and explored stack state is more conservative than the current one.
14371  * Example:
14372  *       explored                   current
14373  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14374  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14375  *
14376  * In other words if current stack state (one being explored) has more
14377  * valid slots than old one that already passed validation, it means
14378  * the verifier can stop exploring and conclude that current state is valid too
14379  *
14380  * Similarly with registers. If explored state has register type as invalid
14381  * whereas register type in current state is meaningful, it means that
14382  * the current state will reach 'bpf_exit' instruction safely
14383  */
14384 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14385                               struct bpf_func_state *cur)
14386 {
14387         int i;
14388
14389         for (i = 0; i < MAX_BPF_REG; i++)
14390                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
14391                              env->idmap_scratch))
14392                         return false;
14393
14394         if (!stacksafe(env, old, cur, env->idmap_scratch))
14395                 return false;
14396
14397         if (!refsafe(old, cur, env->idmap_scratch))
14398                 return false;
14399
14400         return true;
14401 }
14402
14403 static bool states_equal(struct bpf_verifier_env *env,
14404                          struct bpf_verifier_state *old,
14405                          struct bpf_verifier_state *cur)
14406 {
14407         int i;
14408
14409         if (old->curframe != cur->curframe)
14410                 return false;
14411
14412         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14413
14414         /* Verification state from speculative execution simulation
14415          * must never prune a non-speculative execution one.
14416          */
14417         if (old->speculative && !cur->speculative)
14418                 return false;
14419
14420         if (old->active_lock.ptr != cur->active_lock.ptr)
14421                 return false;
14422
14423         /* Old and cur active_lock's have to be either both present
14424          * or both absent.
14425          */
14426         if (!!old->active_lock.id != !!cur->active_lock.id)
14427                 return false;
14428
14429         if (old->active_lock.id &&
14430             !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14431                 return false;
14432
14433         if (old->active_rcu_lock != cur->active_rcu_lock)
14434                 return false;
14435
14436         /* for states to be equal callsites have to be the same
14437          * and all frame states need to be equivalent
14438          */
14439         for (i = 0; i <= old->curframe; i++) {
14440                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
14441                         return false;
14442                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
14443                         return false;
14444         }
14445         return true;
14446 }
14447
14448 /* Return 0 if no propagation happened. Return negative error code if error
14449  * happened. Otherwise, return the propagated bit.
14450  */
14451 static int propagate_liveness_reg(struct bpf_verifier_env *env,
14452                                   struct bpf_reg_state *reg,
14453                                   struct bpf_reg_state *parent_reg)
14454 {
14455         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
14456         u8 flag = reg->live & REG_LIVE_READ;
14457         int err;
14458
14459         /* When comes here, read flags of PARENT_REG or REG could be any of
14460          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
14461          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
14462          */
14463         if (parent_flag == REG_LIVE_READ64 ||
14464             /* Or if there is no read flag from REG. */
14465             !flag ||
14466             /* Or if the read flag from REG is the same as PARENT_REG. */
14467             parent_flag == flag)
14468                 return 0;
14469
14470         err = mark_reg_read(env, reg, parent_reg, flag);
14471         if (err)
14472                 return err;
14473
14474         return flag;
14475 }
14476
14477 /* A write screens off any subsequent reads; but write marks come from the
14478  * straight-line code between a state and its parent.  When we arrive at an
14479  * equivalent state (jump target or such) we didn't arrive by the straight-line
14480  * code, so read marks in the state must propagate to the parent regardless
14481  * of the state's write marks. That's what 'parent == state->parent' comparison
14482  * in mark_reg_read() is for.
14483  */
14484 static int propagate_liveness(struct bpf_verifier_env *env,
14485                               const struct bpf_verifier_state *vstate,
14486                               struct bpf_verifier_state *vparent)
14487 {
14488         struct bpf_reg_state *state_reg, *parent_reg;
14489         struct bpf_func_state *state, *parent;
14490         int i, frame, err = 0;
14491
14492         if (vparent->curframe != vstate->curframe) {
14493                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
14494                      vparent->curframe, vstate->curframe);
14495                 return -EFAULT;
14496         }
14497         /* Propagate read liveness of registers... */
14498         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
14499         for (frame = 0; frame <= vstate->curframe; frame++) {
14500                 parent = vparent->frame[frame];
14501                 state = vstate->frame[frame];
14502                 parent_reg = parent->regs;
14503                 state_reg = state->regs;
14504                 /* We don't need to worry about FP liveness, it's read-only */
14505                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
14506                         err = propagate_liveness_reg(env, &state_reg[i],
14507                                                      &parent_reg[i]);
14508                         if (err < 0)
14509                                 return err;
14510                         if (err == REG_LIVE_READ64)
14511                                 mark_insn_zext(env, &parent_reg[i]);
14512                 }
14513
14514                 /* Propagate stack slots. */
14515                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
14516                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
14517                         parent_reg = &parent->stack[i].spilled_ptr;
14518                         state_reg = &state->stack[i].spilled_ptr;
14519                         err = propagate_liveness_reg(env, state_reg,
14520                                                      parent_reg);
14521                         if (err < 0)
14522                                 return err;
14523                 }
14524         }
14525         return 0;
14526 }
14527
14528 /* find precise scalars in the previous equivalent state and
14529  * propagate them into the current state
14530  */
14531 static int propagate_precision(struct bpf_verifier_env *env,
14532                                const struct bpf_verifier_state *old)
14533 {
14534         struct bpf_reg_state *state_reg;
14535         struct bpf_func_state *state;
14536         int i, err = 0, fr;
14537
14538         for (fr = old->curframe; fr >= 0; fr--) {
14539                 state = old->frame[fr];
14540                 state_reg = state->regs;
14541                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
14542                         if (state_reg->type != SCALAR_VALUE ||
14543                             !state_reg->precise)
14544                                 continue;
14545                         if (env->log.level & BPF_LOG_LEVEL2)
14546                                 verbose(env, "frame %d: propagating r%d\n", i, fr);
14547                         err = mark_chain_precision_frame(env, fr, i);
14548                         if (err < 0)
14549                                 return err;
14550                 }
14551
14552                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
14553                         if (!is_spilled_reg(&state->stack[i]))
14554                                 continue;
14555                         state_reg = &state->stack[i].spilled_ptr;
14556                         if (state_reg->type != SCALAR_VALUE ||
14557                             !state_reg->precise)
14558                                 continue;
14559                         if (env->log.level & BPF_LOG_LEVEL2)
14560                                 verbose(env, "frame %d: propagating fp%d\n",
14561                                         (-i - 1) * BPF_REG_SIZE, fr);
14562                         err = mark_chain_precision_stack_frame(env, fr, i);
14563                         if (err < 0)
14564                                 return err;
14565                 }
14566         }
14567         return 0;
14568 }
14569
14570 static bool states_maybe_looping(struct bpf_verifier_state *old,
14571                                  struct bpf_verifier_state *cur)
14572 {
14573         struct bpf_func_state *fold, *fcur;
14574         int i, fr = cur->curframe;
14575
14576         if (old->curframe != fr)
14577                 return false;
14578
14579         fold = old->frame[fr];
14580         fcur = cur->frame[fr];
14581         for (i = 0; i < MAX_BPF_REG; i++)
14582                 if (memcmp(&fold->regs[i], &fcur->regs[i],
14583                            offsetof(struct bpf_reg_state, parent)))
14584                         return false;
14585         return true;
14586 }
14587
14588
14589 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
14590 {
14591         struct bpf_verifier_state_list *new_sl;
14592         struct bpf_verifier_state_list *sl, **pprev;
14593         struct bpf_verifier_state *cur = env->cur_state, *new;
14594         int i, j, err, states_cnt = 0;
14595         bool add_new_state = env->test_state_freq ? true : false;
14596
14597         /* bpf progs typically have pruning point every 4 instructions
14598          * http://vger.kernel.org/bpfconf2019.html#session-1
14599          * Do not add new state for future pruning if the verifier hasn't seen
14600          * at least 2 jumps and at least 8 instructions.
14601          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
14602          * In tests that amounts to up to 50% reduction into total verifier
14603          * memory consumption and 20% verifier time speedup.
14604          */
14605         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
14606             env->insn_processed - env->prev_insn_processed >= 8)
14607                 add_new_state = true;
14608
14609         pprev = explored_state(env, insn_idx);
14610         sl = *pprev;
14611
14612         clean_live_states(env, insn_idx, cur);
14613
14614         while (sl) {
14615                 states_cnt++;
14616                 if (sl->state.insn_idx != insn_idx)
14617                         goto next;
14618
14619                 if (sl->state.branches) {
14620                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
14621
14622                         if (frame->in_async_callback_fn &&
14623                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
14624                                 /* Different async_entry_cnt means that the verifier is
14625                                  * processing another entry into async callback.
14626                                  * Seeing the same state is not an indication of infinite
14627                                  * loop or infinite recursion.
14628                                  * But finding the same state doesn't mean that it's safe
14629                                  * to stop processing the current state. The previous state
14630                                  * hasn't yet reached bpf_exit, since state.branches > 0.
14631                                  * Checking in_async_callback_fn alone is not enough either.
14632                                  * Since the verifier still needs to catch infinite loops
14633                                  * inside async callbacks.
14634                                  */
14635                         } else if (states_maybe_looping(&sl->state, cur) &&
14636                                    states_equal(env, &sl->state, cur)) {
14637                                 verbose_linfo(env, insn_idx, "; ");
14638                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
14639                                 return -EINVAL;
14640                         }
14641                         /* if the verifier is processing a loop, avoid adding new state
14642                          * too often, since different loop iterations have distinct
14643                          * states and may not help future pruning.
14644                          * This threshold shouldn't be too low to make sure that
14645                          * a loop with large bound will be rejected quickly.
14646                          * The most abusive loop will be:
14647                          * r1 += 1
14648                          * if r1 < 1000000 goto pc-2
14649                          * 1M insn_procssed limit / 100 == 10k peak states.
14650                          * This threshold shouldn't be too high either, since states
14651                          * at the end of the loop are likely to be useful in pruning.
14652                          */
14653                         if (!env->test_state_freq &&
14654                             env->jmps_processed - env->prev_jmps_processed < 20 &&
14655                             env->insn_processed - env->prev_insn_processed < 100)
14656                                 add_new_state = false;
14657                         goto miss;
14658                 }
14659                 if (states_equal(env, &sl->state, cur)) {
14660                         sl->hit_cnt++;
14661                         /* reached equivalent register/stack state,
14662                          * prune the search.
14663                          * Registers read by the continuation are read by us.
14664                          * If we have any write marks in env->cur_state, they
14665                          * will prevent corresponding reads in the continuation
14666                          * from reaching our parent (an explored_state).  Our
14667                          * own state will get the read marks recorded, but
14668                          * they'll be immediately forgotten as we're pruning
14669                          * this state and will pop a new one.
14670                          */
14671                         err = propagate_liveness(env, &sl->state, cur);
14672
14673                         /* if previous state reached the exit with precision and
14674                          * current state is equivalent to it (except precsion marks)
14675                          * the precision needs to be propagated back in
14676                          * the current state.
14677                          */
14678                         err = err ? : push_jmp_history(env, cur);
14679                         err = err ? : propagate_precision(env, &sl->state);
14680                         if (err)
14681                                 return err;
14682                         return 1;
14683                 }
14684 miss:
14685                 /* when new state is not going to be added do not increase miss count.
14686                  * Otherwise several loop iterations will remove the state
14687                  * recorded earlier. The goal of these heuristics is to have
14688                  * states from some iterations of the loop (some in the beginning
14689                  * and some at the end) to help pruning.
14690                  */
14691                 if (add_new_state)
14692                         sl->miss_cnt++;
14693                 /* heuristic to determine whether this state is beneficial
14694                  * to keep checking from state equivalence point of view.
14695                  * Higher numbers increase max_states_per_insn and verification time,
14696                  * but do not meaningfully decrease insn_processed.
14697                  */
14698                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
14699                         /* the state is unlikely to be useful. Remove it to
14700                          * speed up verification
14701                          */
14702                         *pprev = sl->next;
14703                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
14704                                 u32 br = sl->state.branches;
14705
14706                                 WARN_ONCE(br,
14707                                           "BUG live_done but branches_to_explore %d\n",
14708                                           br);
14709                                 free_verifier_state(&sl->state, false);
14710                                 kfree(sl);
14711                                 env->peak_states--;
14712                         } else {
14713                                 /* cannot free this state, since parentage chain may
14714                                  * walk it later. Add it for free_list instead to
14715                                  * be freed at the end of verification
14716                                  */
14717                                 sl->next = env->free_list;
14718                                 env->free_list = sl;
14719                         }
14720                         sl = *pprev;
14721                         continue;
14722                 }
14723 next:
14724                 pprev = &sl->next;
14725                 sl = *pprev;
14726         }
14727
14728         if (env->max_states_per_insn < states_cnt)
14729                 env->max_states_per_insn = states_cnt;
14730
14731         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
14732                 return 0;
14733
14734         if (!add_new_state)
14735                 return 0;
14736
14737         /* There were no equivalent states, remember the current one.
14738          * Technically the current state is not proven to be safe yet,
14739          * but it will either reach outer most bpf_exit (which means it's safe)
14740          * or it will be rejected. When there are no loops the verifier won't be
14741          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
14742          * again on the way to bpf_exit.
14743          * When looping the sl->state.branches will be > 0 and this state
14744          * will not be considered for equivalence until branches == 0.
14745          */
14746         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
14747         if (!new_sl)
14748                 return -ENOMEM;
14749         env->total_states++;
14750         env->peak_states++;
14751         env->prev_jmps_processed = env->jmps_processed;
14752         env->prev_insn_processed = env->insn_processed;
14753
14754         /* forget precise markings we inherited, see __mark_chain_precision */
14755         if (env->bpf_capable)
14756                 mark_all_scalars_imprecise(env, cur);
14757
14758         /* add new state to the head of linked list */
14759         new = &new_sl->state;
14760         err = copy_verifier_state(new, cur);
14761         if (err) {
14762                 free_verifier_state(new, false);
14763                 kfree(new_sl);
14764                 return err;
14765         }
14766         new->insn_idx = insn_idx;
14767         WARN_ONCE(new->branches != 1,
14768                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
14769
14770         cur->parent = new;
14771         cur->first_insn_idx = insn_idx;
14772         clear_jmp_history(cur);
14773         new_sl->next = *explored_state(env, insn_idx);
14774         *explored_state(env, insn_idx) = new_sl;
14775         /* connect new state to parentage chain. Current frame needs all
14776          * registers connected. Only r6 - r9 of the callers are alive (pushed
14777          * to the stack implicitly by JITs) so in callers' frames connect just
14778          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
14779          * the state of the call instruction (with WRITTEN set), and r0 comes
14780          * from callee with its full parentage chain, anyway.
14781          */
14782         /* clear write marks in current state: the writes we did are not writes
14783          * our child did, so they don't screen off its reads from us.
14784          * (There are no read marks in current state, because reads always mark
14785          * their parent and current state never has children yet.  Only
14786          * explored_states can get read marks.)
14787          */
14788         for (j = 0; j <= cur->curframe; j++) {
14789                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
14790                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
14791                 for (i = 0; i < BPF_REG_FP; i++)
14792                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
14793         }
14794
14795         /* all stack frames are accessible from callee, clear them all */
14796         for (j = 0; j <= cur->curframe; j++) {
14797                 struct bpf_func_state *frame = cur->frame[j];
14798                 struct bpf_func_state *newframe = new->frame[j];
14799
14800                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
14801                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
14802                         frame->stack[i].spilled_ptr.parent =
14803                                                 &newframe->stack[i].spilled_ptr;
14804                 }
14805         }
14806         return 0;
14807 }
14808
14809 /* Return true if it's OK to have the same insn return a different type. */
14810 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
14811 {
14812         switch (base_type(type)) {
14813         case PTR_TO_CTX:
14814         case PTR_TO_SOCKET:
14815         case PTR_TO_SOCK_COMMON:
14816         case PTR_TO_TCP_SOCK:
14817         case PTR_TO_XDP_SOCK:
14818         case PTR_TO_BTF_ID:
14819                 return false;
14820         default:
14821                 return true;
14822         }
14823 }
14824
14825 /* If an instruction was previously used with particular pointer types, then we
14826  * need to be careful to avoid cases such as the below, where it may be ok
14827  * for one branch accessing the pointer, but not ok for the other branch:
14828  *
14829  * R1 = sock_ptr
14830  * goto X;
14831  * ...
14832  * R1 = some_other_valid_ptr;
14833  * goto X;
14834  * ...
14835  * R2 = *(u32 *)(R1 + 0);
14836  */
14837 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
14838 {
14839         return src != prev && (!reg_type_mismatch_ok(src) ||
14840                                !reg_type_mismatch_ok(prev));
14841 }
14842
14843 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
14844                              bool allow_trust_missmatch)
14845 {
14846         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
14847
14848         if (*prev_type == NOT_INIT) {
14849                 /* Saw a valid insn
14850                  * dst_reg = *(u32 *)(src_reg + off)
14851                  * save type to validate intersecting paths
14852                  */
14853                 *prev_type = type;
14854         } else if (reg_type_mismatch(type, *prev_type)) {
14855                 /* Abuser program is trying to use the same insn
14856                  * dst_reg = *(u32*) (src_reg + off)
14857                  * with different pointer types:
14858                  * src_reg == ctx in one branch and
14859                  * src_reg == stack|map in some other branch.
14860                  * Reject it.
14861                  */
14862                 if (allow_trust_missmatch &&
14863                     base_type(type) == PTR_TO_BTF_ID &&
14864                     base_type(*prev_type) == PTR_TO_BTF_ID) {
14865                         /*
14866                          * Have to support a use case when one path through
14867                          * the program yields TRUSTED pointer while another
14868                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
14869                          * BPF_PROBE_MEM.
14870                          */
14871                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
14872                 } else {
14873                         verbose(env, "same insn cannot be used with different pointers\n");
14874                         return -EINVAL;
14875                 }
14876         }
14877
14878         return 0;
14879 }
14880
14881 static int do_check(struct bpf_verifier_env *env)
14882 {
14883         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14884         struct bpf_verifier_state *state = env->cur_state;
14885         struct bpf_insn *insns = env->prog->insnsi;
14886         struct bpf_reg_state *regs;
14887         int insn_cnt = env->prog->len;
14888         bool do_print_state = false;
14889         int prev_insn_idx = -1;
14890
14891         for (;;) {
14892                 struct bpf_insn *insn;
14893                 u8 class;
14894                 int err;
14895
14896                 env->prev_insn_idx = prev_insn_idx;
14897                 if (env->insn_idx >= insn_cnt) {
14898                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
14899                                 env->insn_idx, insn_cnt);
14900                         return -EFAULT;
14901                 }
14902
14903                 insn = &insns[env->insn_idx];
14904                 class = BPF_CLASS(insn->code);
14905
14906                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
14907                         verbose(env,
14908                                 "BPF program is too large. Processed %d insn\n",
14909                                 env->insn_processed);
14910                         return -E2BIG;
14911                 }
14912
14913                 state->last_insn_idx = env->prev_insn_idx;
14914
14915                 if (is_prune_point(env, env->insn_idx)) {
14916                         err = is_state_visited(env, env->insn_idx);
14917                         if (err < 0)
14918                                 return err;
14919                         if (err == 1) {
14920                                 /* found equivalent state, can prune the search */
14921                                 if (env->log.level & BPF_LOG_LEVEL) {
14922                                         if (do_print_state)
14923                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
14924                                                         env->prev_insn_idx, env->insn_idx,
14925                                                         env->cur_state->speculative ?
14926                                                         " (speculative execution)" : "");
14927                                         else
14928                                                 verbose(env, "%d: safe\n", env->insn_idx);
14929                                 }
14930                                 goto process_bpf_exit;
14931                         }
14932                 }
14933
14934                 if (is_jmp_point(env, env->insn_idx)) {
14935                         err = push_jmp_history(env, state);
14936                         if (err)
14937                                 return err;
14938                 }
14939
14940                 if (signal_pending(current))
14941                         return -EAGAIN;
14942
14943                 if (need_resched())
14944                         cond_resched();
14945
14946                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
14947                         verbose(env, "\nfrom %d to %d%s:",
14948                                 env->prev_insn_idx, env->insn_idx,
14949                                 env->cur_state->speculative ?
14950                                 " (speculative execution)" : "");
14951                         print_verifier_state(env, state->frame[state->curframe], true);
14952                         do_print_state = false;
14953                 }
14954
14955                 if (env->log.level & BPF_LOG_LEVEL) {
14956                         const struct bpf_insn_cbs cbs = {
14957                                 .cb_call        = disasm_kfunc_name,
14958                                 .cb_print       = verbose,
14959                                 .private_data   = env,
14960                         };
14961
14962                         if (verifier_state_scratched(env))
14963                                 print_insn_state(env, state->frame[state->curframe]);
14964
14965                         verbose_linfo(env, env->insn_idx, "; ");
14966                         env->prev_log_len = env->log.len_used;
14967                         verbose(env, "%d: ", env->insn_idx);
14968                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
14969                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
14970                         env->prev_log_len = env->log.len_used;
14971                 }
14972
14973                 if (bpf_prog_is_offloaded(env->prog->aux)) {
14974                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
14975                                                            env->prev_insn_idx);
14976                         if (err)
14977                                 return err;
14978                 }
14979
14980                 regs = cur_regs(env);
14981                 sanitize_mark_insn_seen(env);
14982                 prev_insn_idx = env->insn_idx;
14983
14984                 if (class == BPF_ALU || class == BPF_ALU64) {
14985                         err = check_alu_op(env, insn);
14986                         if (err)
14987                                 return err;
14988
14989                 } else if (class == BPF_LDX) {
14990                         enum bpf_reg_type src_reg_type;
14991
14992                         /* check for reserved fields is already done */
14993
14994                         /* check src operand */
14995                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
14996                         if (err)
14997                                 return err;
14998
14999                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15000                         if (err)
15001                                 return err;
15002
15003                         src_reg_type = regs[insn->src_reg].type;
15004
15005                         /* check that memory (src_reg + off) is readable,
15006                          * the state of dst_reg will be updated by this func
15007                          */
15008                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
15009                                                insn->off, BPF_SIZE(insn->code),
15010                                                BPF_READ, insn->dst_reg, false);
15011                         if (err)
15012                                 return err;
15013
15014                         err = save_aux_ptr_type(env, src_reg_type, true);
15015                         if (err)
15016                                 return err;
15017                 } else if (class == BPF_STX) {
15018                         enum bpf_reg_type dst_reg_type;
15019
15020                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15021                                 err = check_atomic(env, env->insn_idx, insn);
15022                                 if (err)
15023                                         return err;
15024                                 env->insn_idx++;
15025                                 continue;
15026                         }
15027
15028                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15029                                 verbose(env, "BPF_STX uses reserved fields\n");
15030                                 return -EINVAL;
15031                         }
15032
15033                         /* check src1 operand */
15034                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
15035                         if (err)
15036                                 return err;
15037                         /* check src2 operand */
15038                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15039                         if (err)
15040                                 return err;
15041
15042                         dst_reg_type = regs[insn->dst_reg].type;
15043
15044                         /* check that memory (dst_reg + off) is writeable */
15045                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15046                                                insn->off, BPF_SIZE(insn->code),
15047                                                BPF_WRITE, insn->src_reg, false);
15048                         if (err)
15049                                 return err;
15050
15051                         err = save_aux_ptr_type(env, dst_reg_type, false);
15052                         if (err)
15053                                 return err;
15054                 } else if (class == BPF_ST) {
15055                         enum bpf_reg_type dst_reg_type;
15056
15057                         if (BPF_MODE(insn->code) != BPF_MEM ||
15058                             insn->src_reg != BPF_REG_0) {
15059                                 verbose(env, "BPF_ST uses reserved fields\n");
15060                                 return -EINVAL;
15061                         }
15062                         /* check src operand */
15063                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15064                         if (err)
15065                                 return err;
15066
15067                         dst_reg_type = regs[insn->dst_reg].type;
15068
15069                         /* check that memory (dst_reg + off) is writeable */
15070                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15071                                                insn->off, BPF_SIZE(insn->code),
15072                                                BPF_WRITE, -1, false);
15073                         if (err)
15074                                 return err;
15075
15076                         err = save_aux_ptr_type(env, dst_reg_type, false);
15077                         if (err)
15078                                 return err;
15079                 } else if (class == BPF_JMP || class == BPF_JMP32) {
15080                         u8 opcode = BPF_OP(insn->code);
15081
15082                         env->jmps_processed++;
15083                         if (opcode == BPF_CALL) {
15084                                 if (BPF_SRC(insn->code) != BPF_K ||
15085                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
15086                                      && insn->off != 0) ||
15087                                     (insn->src_reg != BPF_REG_0 &&
15088                                      insn->src_reg != BPF_PSEUDO_CALL &&
15089                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
15090                                     insn->dst_reg != BPF_REG_0 ||
15091                                     class == BPF_JMP32) {
15092                                         verbose(env, "BPF_CALL uses reserved fields\n");
15093                                         return -EINVAL;
15094                                 }
15095
15096                                 if (env->cur_state->active_lock.ptr) {
15097                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
15098                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
15099                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
15100                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
15101                                                 verbose(env, "function calls are not allowed while holding a lock\n");
15102                                                 return -EINVAL;
15103                                         }
15104                                 }
15105                                 if (insn->src_reg == BPF_PSEUDO_CALL)
15106                                         err = check_func_call(env, insn, &env->insn_idx);
15107                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
15108                                         err = check_kfunc_call(env, insn, &env->insn_idx);
15109                                 else
15110                                         err = check_helper_call(env, insn, &env->insn_idx);
15111                                 if (err)
15112                                         return err;
15113
15114                                 mark_reg_scratched(env, BPF_REG_0);
15115                         } else if (opcode == BPF_JA) {
15116                                 if (BPF_SRC(insn->code) != BPF_K ||
15117                                     insn->imm != 0 ||
15118                                     insn->src_reg != BPF_REG_0 ||
15119                                     insn->dst_reg != BPF_REG_0 ||
15120                                     class == BPF_JMP32) {
15121                                         verbose(env, "BPF_JA uses reserved fields\n");
15122                                         return -EINVAL;
15123                                 }
15124
15125                                 env->insn_idx += insn->off + 1;
15126                                 continue;
15127
15128                         } else if (opcode == BPF_EXIT) {
15129                                 if (BPF_SRC(insn->code) != BPF_K ||
15130                                     insn->imm != 0 ||
15131                                     insn->src_reg != BPF_REG_0 ||
15132                                     insn->dst_reg != BPF_REG_0 ||
15133                                     class == BPF_JMP32) {
15134                                         verbose(env, "BPF_EXIT uses reserved fields\n");
15135                                         return -EINVAL;
15136                                 }
15137
15138                                 if (env->cur_state->active_lock.ptr &&
15139                                     !in_rbtree_lock_required_cb(env)) {
15140                                         verbose(env, "bpf_spin_unlock is missing\n");
15141                                         return -EINVAL;
15142                                 }
15143
15144                                 if (env->cur_state->active_rcu_lock) {
15145                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
15146                                         return -EINVAL;
15147                                 }
15148
15149                                 /* We must do check_reference_leak here before
15150                                  * prepare_func_exit to handle the case when
15151                                  * state->curframe > 0, it may be a callback
15152                                  * function, for which reference_state must
15153                                  * match caller reference state when it exits.
15154                                  */
15155                                 err = check_reference_leak(env);
15156                                 if (err)
15157                                         return err;
15158
15159                                 if (state->curframe) {
15160                                         /* exit from nested function */
15161                                         err = prepare_func_exit(env, &env->insn_idx);
15162                                         if (err)
15163                                                 return err;
15164                                         do_print_state = true;
15165                                         continue;
15166                                 }
15167
15168                                 err = check_return_code(env);
15169                                 if (err)
15170                                         return err;
15171 process_bpf_exit:
15172                                 mark_verifier_state_scratched(env);
15173                                 update_branch_counts(env, env->cur_state);
15174                                 err = pop_stack(env, &prev_insn_idx,
15175                                                 &env->insn_idx, pop_log);
15176                                 if (err < 0) {
15177                                         if (err != -ENOENT)
15178                                                 return err;
15179                                         break;
15180                                 } else {
15181                                         do_print_state = true;
15182                                         continue;
15183                                 }
15184                         } else {
15185                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
15186                                 if (err)
15187                                         return err;
15188                         }
15189                 } else if (class == BPF_LD) {
15190                         u8 mode = BPF_MODE(insn->code);
15191
15192                         if (mode == BPF_ABS || mode == BPF_IND) {
15193                                 err = check_ld_abs(env, insn);
15194                                 if (err)
15195                                         return err;
15196
15197                         } else if (mode == BPF_IMM) {
15198                                 err = check_ld_imm(env, insn);
15199                                 if (err)
15200                                         return err;
15201
15202                                 env->insn_idx++;
15203                                 sanitize_mark_insn_seen(env);
15204                         } else {
15205                                 verbose(env, "invalid BPF_LD mode\n");
15206                                 return -EINVAL;
15207                         }
15208                 } else {
15209                         verbose(env, "unknown insn class %d\n", class);
15210                         return -EINVAL;
15211                 }
15212
15213                 env->insn_idx++;
15214         }
15215
15216         return 0;
15217 }
15218
15219 static int find_btf_percpu_datasec(struct btf *btf)
15220 {
15221         const struct btf_type *t;
15222         const char *tname;
15223         int i, n;
15224
15225         /*
15226          * Both vmlinux and module each have their own ".data..percpu"
15227          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
15228          * types to look at only module's own BTF types.
15229          */
15230         n = btf_nr_types(btf);
15231         if (btf_is_module(btf))
15232                 i = btf_nr_types(btf_vmlinux);
15233         else
15234                 i = 1;
15235
15236         for(; i < n; i++) {
15237                 t = btf_type_by_id(btf, i);
15238                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
15239                         continue;
15240
15241                 tname = btf_name_by_offset(btf, t->name_off);
15242                 if (!strcmp(tname, ".data..percpu"))
15243                         return i;
15244         }
15245
15246         return -ENOENT;
15247 }
15248
15249 /* replace pseudo btf_id with kernel symbol address */
15250 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
15251                                struct bpf_insn *insn,
15252                                struct bpf_insn_aux_data *aux)
15253 {
15254         const struct btf_var_secinfo *vsi;
15255         const struct btf_type *datasec;
15256         struct btf_mod_pair *btf_mod;
15257         const struct btf_type *t;
15258         const char *sym_name;
15259         bool percpu = false;
15260         u32 type, id = insn->imm;
15261         struct btf *btf;
15262         s32 datasec_id;
15263         u64 addr;
15264         int i, btf_fd, err;
15265
15266         btf_fd = insn[1].imm;
15267         if (btf_fd) {
15268                 btf = btf_get_by_fd(btf_fd);
15269                 if (IS_ERR(btf)) {
15270                         verbose(env, "invalid module BTF object FD specified.\n");
15271                         return -EINVAL;
15272                 }
15273         } else {
15274                 if (!btf_vmlinux) {
15275                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
15276                         return -EINVAL;
15277                 }
15278                 btf = btf_vmlinux;
15279                 btf_get(btf);
15280         }
15281
15282         t = btf_type_by_id(btf, id);
15283         if (!t) {
15284                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
15285                 err = -ENOENT;
15286                 goto err_put;
15287         }
15288
15289         if (!btf_type_is_var(t)) {
15290                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
15291                 err = -EINVAL;
15292                 goto err_put;
15293         }
15294
15295         sym_name = btf_name_by_offset(btf, t->name_off);
15296         addr = kallsyms_lookup_name(sym_name);
15297         if (!addr) {
15298                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
15299                         sym_name);
15300                 err = -ENOENT;
15301                 goto err_put;
15302         }
15303
15304         datasec_id = find_btf_percpu_datasec(btf);
15305         if (datasec_id > 0) {
15306                 datasec = btf_type_by_id(btf, datasec_id);
15307                 for_each_vsi(i, datasec, vsi) {
15308                         if (vsi->type == id) {
15309                                 percpu = true;
15310                                 break;
15311                         }
15312                 }
15313         }
15314
15315         insn[0].imm = (u32)addr;
15316         insn[1].imm = addr >> 32;
15317
15318         type = t->type;
15319         t = btf_type_skip_modifiers(btf, type, NULL);
15320         if (percpu) {
15321                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
15322                 aux->btf_var.btf = btf;
15323                 aux->btf_var.btf_id = type;
15324         } else if (!btf_type_is_struct(t)) {
15325                 const struct btf_type *ret;
15326                 const char *tname;
15327                 u32 tsize;
15328
15329                 /* resolve the type size of ksym. */
15330                 ret = btf_resolve_size(btf, t, &tsize);
15331                 if (IS_ERR(ret)) {
15332                         tname = btf_name_by_offset(btf, t->name_off);
15333                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
15334                                 tname, PTR_ERR(ret));
15335                         err = -EINVAL;
15336                         goto err_put;
15337                 }
15338                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
15339                 aux->btf_var.mem_size = tsize;
15340         } else {
15341                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
15342                 aux->btf_var.btf = btf;
15343                 aux->btf_var.btf_id = type;
15344         }
15345
15346         /* check whether we recorded this BTF (and maybe module) already */
15347         for (i = 0; i < env->used_btf_cnt; i++) {
15348                 if (env->used_btfs[i].btf == btf) {
15349                         btf_put(btf);
15350                         return 0;
15351                 }
15352         }
15353
15354         if (env->used_btf_cnt >= MAX_USED_BTFS) {
15355                 err = -E2BIG;
15356                 goto err_put;
15357         }
15358
15359         btf_mod = &env->used_btfs[env->used_btf_cnt];
15360         btf_mod->btf = btf;
15361         btf_mod->module = NULL;
15362
15363         /* if we reference variables from kernel module, bump its refcount */
15364         if (btf_is_module(btf)) {
15365                 btf_mod->module = btf_try_get_module(btf);
15366                 if (!btf_mod->module) {
15367                         err = -ENXIO;
15368                         goto err_put;
15369                 }
15370         }
15371
15372         env->used_btf_cnt++;
15373
15374         return 0;
15375 err_put:
15376         btf_put(btf);
15377         return err;
15378 }
15379
15380 static bool is_tracing_prog_type(enum bpf_prog_type type)
15381 {
15382         switch (type) {
15383         case BPF_PROG_TYPE_KPROBE:
15384         case BPF_PROG_TYPE_TRACEPOINT:
15385         case BPF_PROG_TYPE_PERF_EVENT:
15386         case BPF_PROG_TYPE_RAW_TRACEPOINT:
15387         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
15388                 return true;
15389         default:
15390                 return false;
15391         }
15392 }
15393
15394 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
15395                                         struct bpf_map *map,
15396                                         struct bpf_prog *prog)
15397
15398 {
15399         enum bpf_prog_type prog_type = resolve_prog_type(prog);
15400
15401         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
15402             btf_record_has_field(map->record, BPF_RB_ROOT)) {
15403                 if (is_tracing_prog_type(prog_type)) {
15404                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
15405                         return -EINVAL;
15406                 }
15407         }
15408
15409         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
15410                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
15411                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
15412                         return -EINVAL;
15413                 }
15414
15415                 if (is_tracing_prog_type(prog_type)) {
15416                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
15417                         return -EINVAL;
15418                 }
15419
15420                 if (prog->aux->sleepable) {
15421                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
15422                         return -EINVAL;
15423                 }
15424         }
15425
15426         if (btf_record_has_field(map->record, BPF_TIMER)) {
15427                 if (is_tracing_prog_type(prog_type)) {
15428                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
15429                         return -EINVAL;
15430                 }
15431         }
15432
15433         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
15434             !bpf_offload_prog_map_match(prog, map)) {
15435                 verbose(env, "offload device mismatch between prog and map\n");
15436                 return -EINVAL;
15437         }
15438
15439         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
15440                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
15441                 return -EINVAL;
15442         }
15443
15444         if (prog->aux->sleepable)
15445                 switch (map->map_type) {
15446                 case BPF_MAP_TYPE_HASH:
15447                 case BPF_MAP_TYPE_LRU_HASH:
15448                 case BPF_MAP_TYPE_ARRAY:
15449                 case BPF_MAP_TYPE_PERCPU_HASH:
15450                 case BPF_MAP_TYPE_PERCPU_ARRAY:
15451                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
15452                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
15453                 case BPF_MAP_TYPE_HASH_OF_MAPS:
15454                 case BPF_MAP_TYPE_RINGBUF:
15455                 case BPF_MAP_TYPE_USER_RINGBUF:
15456                 case BPF_MAP_TYPE_INODE_STORAGE:
15457                 case BPF_MAP_TYPE_SK_STORAGE:
15458                 case BPF_MAP_TYPE_TASK_STORAGE:
15459                 case BPF_MAP_TYPE_CGRP_STORAGE:
15460                         break;
15461                 default:
15462                         verbose(env,
15463                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
15464                         return -EINVAL;
15465                 }
15466
15467         return 0;
15468 }
15469
15470 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
15471 {
15472         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
15473                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
15474 }
15475
15476 /* find and rewrite pseudo imm in ld_imm64 instructions:
15477  *
15478  * 1. if it accesses map FD, replace it with actual map pointer.
15479  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
15480  *
15481  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
15482  */
15483 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
15484 {
15485         struct bpf_insn *insn = env->prog->insnsi;
15486         int insn_cnt = env->prog->len;
15487         int i, j, err;
15488
15489         err = bpf_prog_calc_tag(env->prog);
15490         if (err)
15491                 return err;
15492
15493         for (i = 0; i < insn_cnt; i++, insn++) {
15494                 if (BPF_CLASS(insn->code) == BPF_LDX &&
15495                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
15496                         verbose(env, "BPF_LDX uses reserved fields\n");
15497                         return -EINVAL;
15498                 }
15499
15500                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
15501                         struct bpf_insn_aux_data *aux;
15502                         struct bpf_map *map;
15503                         struct fd f;
15504                         u64 addr;
15505                         u32 fd;
15506
15507                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
15508                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
15509                             insn[1].off != 0) {
15510                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
15511                                 return -EINVAL;
15512                         }
15513
15514                         if (insn[0].src_reg == 0)
15515                                 /* valid generic load 64-bit imm */
15516                                 goto next_insn;
15517
15518                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
15519                                 aux = &env->insn_aux_data[i];
15520                                 err = check_pseudo_btf_id(env, insn, aux);
15521                                 if (err)
15522                                         return err;
15523                                 goto next_insn;
15524                         }
15525
15526                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
15527                                 aux = &env->insn_aux_data[i];
15528                                 aux->ptr_type = PTR_TO_FUNC;
15529                                 goto next_insn;
15530                         }
15531
15532                         /* In final convert_pseudo_ld_imm64() step, this is
15533                          * converted into regular 64-bit imm load insn.
15534                          */
15535                         switch (insn[0].src_reg) {
15536                         case BPF_PSEUDO_MAP_VALUE:
15537                         case BPF_PSEUDO_MAP_IDX_VALUE:
15538                                 break;
15539                         case BPF_PSEUDO_MAP_FD:
15540                         case BPF_PSEUDO_MAP_IDX:
15541                                 if (insn[1].imm == 0)
15542                                         break;
15543                                 fallthrough;
15544                         default:
15545                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
15546                                 return -EINVAL;
15547                         }
15548
15549                         switch (insn[0].src_reg) {
15550                         case BPF_PSEUDO_MAP_IDX_VALUE:
15551                         case BPF_PSEUDO_MAP_IDX:
15552                                 if (bpfptr_is_null(env->fd_array)) {
15553                                         verbose(env, "fd_idx without fd_array is invalid\n");
15554                                         return -EPROTO;
15555                                 }
15556                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
15557                                                             insn[0].imm * sizeof(fd),
15558                                                             sizeof(fd)))
15559                                         return -EFAULT;
15560                                 break;
15561                         default:
15562                                 fd = insn[0].imm;
15563                                 break;
15564                         }
15565
15566                         f = fdget(fd);
15567                         map = __bpf_map_get(f);
15568                         if (IS_ERR(map)) {
15569                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
15570                                         insn[0].imm);
15571                                 return PTR_ERR(map);
15572                         }
15573
15574                         err = check_map_prog_compatibility(env, map, env->prog);
15575                         if (err) {
15576                                 fdput(f);
15577                                 return err;
15578                         }
15579
15580                         aux = &env->insn_aux_data[i];
15581                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
15582                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
15583                                 addr = (unsigned long)map;
15584                         } else {
15585                                 u32 off = insn[1].imm;
15586
15587                                 if (off >= BPF_MAX_VAR_OFF) {
15588                                         verbose(env, "direct value offset of %u is not allowed\n", off);
15589                                         fdput(f);
15590                                         return -EINVAL;
15591                                 }
15592
15593                                 if (!map->ops->map_direct_value_addr) {
15594                                         verbose(env, "no direct value access support for this map type\n");
15595                                         fdput(f);
15596                                         return -EINVAL;
15597                                 }
15598
15599                                 err = map->ops->map_direct_value_addr(map, &addr, off);
15600                                 if (err) {
15601                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
15602                                                 map->value_size, off);
15603                                         fdput(f);
15604                                         return err;
15605                                 }
15606
15607                                 aux->map_off = off;
15608                                 addr += off;
15609                         }
15610
15611                         insn[0].imm = (u32)addr;
15612                         insn[1].imm = addr >> 32;
15613
15614                         /* check whether we recorded this map already */
15615                         for (j = 0; j < env->used_map_cnt; j++) {
15616                                 if (env->used_maps[j] == map) {
15617                                         aux->map_index = j;
15618                                         fdput(f);
15619                                         goto next_insn;
15620                                 }
15621                         }
15622
15623                         if (env->used_map_cnt >= MAX_USED_MAPS) {
15624                                 fdput(f);
15625                                 return -E2BIG;
15626                         }
15627
15628                         /* hold the map. If the program is rejected by verifier,
15629                          * the map will be released by release_maps() or it
15630                          * will be used by the valid program until it's unloaded
15631                          * and all maps are released in free_used_maps()
15632                          */
15633                         bpf_map_inc(map);
15634
15635                         aux->map_index = env->used_map_cnt;
15636                         env->used_maps[env->used_map_cnt++] = map;
15637
15638                         if (bpf_map_is_cgroup_storage(map) &&
15639                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
15640                                 verbose(env, "only one cgroup storage of each type is allowed\n");
15641                                 fdput(f);
15642                                 return -EBUSY;
15643                         }
15644
15645                         fdput(f);
15646 next_insn:
15647                         insn++;
15648                         i++;
15649                         continue;
15650                 }
15651
15652                 /* Basic sanity check before we invest more work here. */
15653                 if (!bpf_opcode_in_insntable(insn->code)) {
15654                         verbose(env, "unknown opcode %02x\n", insn->code);
15655                         return -EINVAL;
15656                 }
15657         }
15658
15659         /* now all pseudo BPF_LD_IMM64 instructions load valid
15660          * 'struct bpf_map *' into a register instead of user map_fd.
15661          * These pointers will be used later by verifier to validate map access.
15662          */
15663         return 0;
15664 }
15665
15666 /* drop refcnt of maps used by the rejected program */
15667 static void release_maps(struct bpf_verifier_env *env)
15668 {
15669         __bpf_free_used_maps(env->prog->aux, env->used_maps,
15670                              env->used_map_cnt);
15671 }
15672
15673 /* drop refcnt of maps used by the rejected program */
15674 static void release_btfs(struct bpf_verifier_env *env)
15675 {
15676         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
15677                              env->used_btf_cnt);
15678 }
15679
15680 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
15681 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
15682 {
15683         struct bpf_insn *insn = env->prog->insnsi;
15684         int insn_cnt = env->prog->len;
15685         int i;
15686
15687         for (i = 0; i < insn_cnt; i++, insn++) {
15688                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
15689                         continue;
15690                 if (insn->src_reg == BPF_PSEUDO_FUNC)
15691                         continue;
15692                 insn->src_reg = 0;
15693         }
15694 }
15695
15696 /* single env->prog->insni[off] instruction was replaced with the range
15697  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
15698  * [0, off) and [off, end) to new locations, so the patched range stays zero
15699  */
15700 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
15701                                  struct bpf_insn_aux_data *new_data,
15702                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
15703 {
15704         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
15705         struct bpf_insn *insn = new_prog->insnsi;
15706         u32 old_seen = old_data[off].seen;
15707         u32 prog_len;
15708         int i;
15709
15710         /* aux info at OFF always needs adjustment, no matter fast path
15711          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
15712          * original insn at old prog.
15713          */
15714         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
15715
15716         if (cnt == 1)
15717                 return;
15718         prog_len = new_prog->len;
15719
15720         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
15721         memcpy(new_data + off + cnt - 1, old_data + off,
15722                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
15723         for (i = off; i < off + cnt - 1; i++) {
15724                 /* Expand insni[off]'s seen count to the patched range. */
15725                 new_data[i].seen = old_seen;
15726                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
15727         }
15728         env->insn_aux_data = new_data;
15729         vfree(old_data);
15730 }
15731
15732 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
15733 {
15734         int i;
15735
15736         if (len == 1)
15737                 return;
15738         /* NOTE: fake 'exit' subprog should be updated as well. */
15739         for (i = 0; i <= env->subprog_cnt; i++) {
15740                 if (env->subprog_info[i].start <= off)
15741                         continue;
15742                 env->subprog_info[i].start += len - 1;
15743         }
15744 }
15745
15746 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
15747 {
15748         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
15749         int i, sz = prog->aux->size_poke_tab;
15750         struct bpf_jit_poke_descriptor *desc;
15751
15752         for (i = 0; i < sz; i++) {
15753                 desc = &tab[i];
15754                 if (desc->insn_idx <= off)
15755                         continue;
15756                 desc->insn_idx += len - 1;
15757         }
15758 }
15759
15760 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
15761                                             const struct bpf_insn *patch, u32 len)
15762 {
15763         struct bpf_prog *new_prog;
15764         struct bpf_insn_aux_data *new_data = NULL;
15765
15766         if (len > 1) {
15767                 new_data = vzalloc(array_size(env->prog->len + len - 1,
15768                                               sizeof(struct bpf_insn_aux_data)));
15769                 if (!new_data)
15770                         return NULL;
15771         }
15772
15773         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
15774         if (IS_ERR(new_prog)) {
15775                 if (PTR_ERR(new_prog) == -ERANGE)
15776                         verbose(env,
15777                                 "insn %d cannot be patched due to 16-bit range\n",
15778                                 env->insn_aux_data[off].orig_idx);
15779                 vfree(new_data);
15780                 return NULL;
15781         }
15782         adjust_insn_aux_data(env, new_data, new_prog, off, len);
15783         adjust_subprog_starts(env, off, len);
15784         adjust_poke_descs(new_prog, off, len);
15785         return new_prog;
15786 }
15787
15788 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
15789                                               u32 off, u32 cnt)
15790 {
15791         int i, j;
15792
15793         /* find first prog starting at or after off (first to remove) */
15794         for (i = 0; i < env->subprog_cnt; i++)
15795                 if (env->subprog_info[i].start >= off)
15796                         break;
15797         /* find first prog starting at or after off + cnt (first to stay) */
15798         for (j = i; j < env->subprog_cnt; j++)
15799                 if (env->subprog_info[j].start >= off + cnt)
15800                         break;
15801         /* if j doesn't start exactly at off + cnt, we are just removing
15802          * the front of previous prog
15803          */
15804         if (env->subprog_info[j].start != off + cnt)
15805                 j--;
15806
15807         if (j > i) {
15808                 struct bpf_prog_aux *aux = env->prog->aux;
15809                 int move;
15810
15811                 /* move fake 'exit' subprog as well */
15812                 move = env->subprog_cnt + 1 - j;
15813
15814                 memmove(env->subprog_info + i,
15815                         env->subprog_info + j,
15816                         sizeof(*env->subprog_info) * move);
15817                 env->subprog_cnt -= j - i;
15818
15819                 /* remove func_info */
15820                 if (aux->func_info) {
15821                         move = aux->func_info_cnt - j;
15822
15823                         memmove(aux->func_info + i,
15824                                 aux->func_info + j,
15825                                 sizeof(*aux->func_info) * move);
15826                         aux->func_info_cnt -= j - i;
15827                         /* func_info->insn_off is set after all code rewrites,
15828                          * in adjust_btf_func() - no need to adjust
15829                          */
15830                 }
15831         } else {
15832                 /* convert i from "first prog to remove" to "first to adjust" */
15833                 if (env->subprog_info[i].start == off)
15834                         i++;
15835         }
15836
15837         /* update fake 'exit' subprog as well */
15838         for (; i <= env->subprog_cnt; i++)
15839                 env->subprog_info[i].start -= cnt;
15840
15841         return 0;
15842 }
15843
15844 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
15845                                       u32 cnt)
15846 {
15847         struct bpf_prog *prog = env->prog;
15848         u32 i, l_off, l_cnt, nr_linfo;
15849         struct bpf_line_info *linfo;
15850
15851         nr_linfo = prog->aux->nr_linfo;
15852         if (!nr_linfo)
15853                 return 0;
15854
15855         linfo = prog->aux->linfo;
15856
15857         /* find first line info to remove, count lines to be removed */
15858         for (i = 0; i < nr_linfo; i++)
15859                 if (linfo[i].insn_off >= off)
15860                         break;
15861
15862         l_off = i;
15863         l_cnt = 0;
15864         for (; i < nr_linfo; i++)
15865                 if (linfo[i].insn_off < off + cnt)
15866                         l_cnt++;
15867                 else
15868                         break;
15869
15870         /* First live insn doesn't match first live linfo, it needs to "inherit"
15871          * last removed linfo.  prog is already modified, so prog->len == off
15872          * means no live instructions after (tail of the program was removed).
15873          */
15874         if (prog->len != off && l_cnt &&
15875             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
15876                 l_cnt--;
15877                 linfo[--i].insn_off = off + cnt;
15878         }
15879
15880         /* remove the line info which refer to the removed instructions */
15881         if (l_cnt) {
15882                 memmove(linfo + l_off, linfo + i,
15883                         sizeof(*linfo) * (nr_linfo - i));
15884
15885                 prog->aux->nr_linfo -= l_cnt;
15886                 nr_linfo = prog->aux->nr_linfo;
15887         }
15888
15889         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
15890         for (i = l_off; i < nr_linfo; i++)
15891                 linfo[i].insn_off -= cnt;
15892
15893         /* fix up all subprogs (incl. 'exit') which start >= off */
15894         for (i = 0; i <= env->subprog_cnt; i++)
15895                 if (env->subprog_info[i].linfo_idx > l_off) {
15896                         /* program may have started in the removed region but
15897                          * may not be fully removed
15898                          */
15899                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
15900                                 env->subprog_info[i].linfo_idx -= l_cnt;
15901                         else
15902                                 env->subprog_info[i].linfo_idx = l_off;
15903                 }
15904
15905         return 0;
15906 }
15907
15908 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
15909 {
15910         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15911         unsigned int orig_prog_len = env->prog->len;
15912         int err;
15913
15914         if (bpf_prog_is_offloaded(env->prog->aux))
15915                 bpf_prog_offload_remove_insns(env, off, cnt);
15916
15917         err = bpf_remove_insns(env->prog, off, cnt);
15918         if (err)
15919                 return err;
15920
15921         err = adjust_subprog_starts_after_remove(env, off, cnt);
15922         if (err)
15923                 return err;
15924
15925         err = bpf_adj_linfo_after_remove(env, off, cnt);
15926         if (err)
15927                 return err;
15928
15929         memmove(aux_data + off, aux_data + off + cnt,
15930                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
15931
15932         return 0;
15933 }
15934
15935 /* The verifier does more data flow analysis than llvm and will not
15936  * explore branches that are dead at run time. Malicious programs can
15937  * have dead code too. Therefore replace all dead at-run-time code
15938  * with 'ja -1'.
15939  *
15940  * Just nops are not optimal, e.g. if they would sit at the end of the
15941  * program and through another bug we would manage to jump there, then
15942  * we'd execute beyond program memory otherwise. Returning exception
15943  * code also wouldn't work since we can have subprogs where the dead
15944  * code could be located.
15945  */
15946 static void sanitize_dead_code(struct bpf_verifier_env *env)
15947 {
15948         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15949         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
15950         struct bpf_insn *insn = env->prog->insnsi;
15951         const int insn_cnt = env->prog->len;
15952         int i;
15953
15954         for (i = 0; i < insn_cnt; i++) {
15955                 if (aux_data[i].seen)
15956                         continue;
15957                 memcpy(insn + i, &trap, sizeof(trap));
15958                 aux_data[i].zext_dst = false;
15959         }
15960 }
15961
15962 static bool insn_is_cond_jump(u8 code)
15963 {
15964         u8 op;
15965
15966         if (BPF_CLASS(code) == BPF_JMP32)
15967                 return true;
15968
15969         if (BPF_CLASS(code) != BPF_JMP)
15970                 return false;
15971
15972         op = BPF_OP(code);
15973         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
15974 }
15975
15976 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
15977 {
15978         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
15979         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
15980         struct bpf_insn *insn = env->prog->insnsi;
15981         const int insn_cnt = env->prog->len;
15982         int i;
15983
15984         for (i = 0; i < insn_cnt; i++, insn++) {
15985                 if (!insn_is_cond_jump(insn->code))
15986                         continue;
15987
15988                 if (!aux_data[i + 1].seen)
15989                         ja.off = insn->off;
15990                 else if (!aux_data[i + 1 + insn->off].seen)
15991                         ja.off = 0;
15992                 else
15993                         continue;
15994
15995                 if (bpf_prog_is_offloaded(env->prog->aux))
15996                         bpf_prog_offload_replace_insn(env, i, &ja);
15997
15998                 memcpy(insn, &ja, sizeof(ja));
15999         }
16000 }
16001
16002 static int opt_remove_dead_code(struct bpf_verifier_env *env)
16003 {
16004         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16005         int insn_cnt = env->prog->len;
16006         int i, err;
16007
16008         for (i = 0; i < insn_cnt; i++) {
16009                 int j;
16010
16011                 j = 0;
16012                 while (i + j < insn_cnt && !aux_data[i + j].seen)
16013                         j++;
16014                 if (!j)
16015                         continue;
16016
16017                 err = verifier_remove_insns(env, i, j);
16018                 if (err)
16019                         return err;
16020                 insn_cnt = env->prog->len;
16021         }
16022
16023         return 0;
16024 }
16025
16026 static int opt_remove_nops(struct bpf_verifier_env *env)
16027 {
16028         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16029         struct bpf_insn *insn = env->prog->insnsi;
16030         int insn_cnt = env->prog->len;
16031         int i, err;
16032
16033         for (i = 0; i < insn_cnt; i++) {
16034                 if (memcmp(&insn[i], &ja, sizeof(ja)))
16035                         continue;
16036
16037                 err = verifier_remove_insns(env, i, 1);
16038                 if (err)
16039                         return err;
16040                 insn_cnt--;
16041                 i--;
16042         }
16043
16044         return 0;
16045 }
16046
16047 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
16048                                          const union bpf_attr *attr)
16049 {
16050         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
16051         struct bpf_insn_aux_data *aux = env->insn_aux_data;
16052         int i, patch_len, delta = 0, len = env->prog->len;
16053         struct bpf_insn *insns = env->prog->insnsi;
16054         struct bpf_prog *new_prog;
16055         bool rnd_hi32;
16056
16057         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
16058         zext_patch[1] = BPF_ZEXT_REG(0);
16059         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
16060         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
16061         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
16062         for (i = 0; i < len; i++) {
16063                 int adj_idx = i + delta;
16064                 struct bpf_insn insn;
16065                 int load_reg;
16066
16067                 insn = insns[adj_idx];
16068                 load_reg = insn_def_regno(&insn);
16069                 if (!aux[adj_idx].zext_dst) {
16070                         u8 code, class;
16071                         u32 imm_rnd;
16072
16073                         if (!rnd_hi32)
16074                                 continue;
16075
16076                         code = insn.code;
16077                         class = BPF_CLASS(code);
16078                         if (load_reg == -1)
16079                                 continue;
16080
16081                         /* NOTE: arg "reg" (the fourth one) is only used for
16082                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
16083                          *       here.
16084                          */
16085                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
16086                                 if (class == BPF_LD &&
16087                                     BPF_MODE(code) == BPF_IMM)
16088                                         i++;
16089                                 continue;
16090                         }
16091
16092                         /* ctx load could be transformed into wider load. */
16093                         if (class == BPF_LDX &&
16094                             aux[adj_idx].ptr_type == PTR_TO_CTX)
16095                                 continue;
16096
16097                         imm_rnd = get_random_u32();
16098                         rnd_hi32_patch[0] = insn;
16099                         rnd_hi32_patch[1].imm = imm_rnd;
16100                         rnd_hi32_patch[3].dst_reg = load_reg;
16101                         patch = rnd_hi32_patch;
16102                         patch_len = 4;
16103                         goto apply_patch_buffer;
16104                 }
16105
16106                 /* Add in an zero-extend instruction if a) the JIT has requested
16107                  * it or b) it's a CMPXCHG.
16108                  *
16109                  * The latter is because: BPF_CMPXCHG always loads a value into
16110                  * R0, therefore always zero-extends. However some archs'
16111                  * equivalent instruction only does this load when the
16112                  * comparison is successful. This detail of CMPXCHG is
16113                  * orthogonal to the general zero-extension behaviour of the
16114                  * CPU, so it's treated independently of bpf_jit_needs_zext.
16115                  */
16116                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
16117                         continue;
16118
16119                 /* Zero-extension is done by the caller. */
16120                 if (bpf_pseudo_kfunc_call(&insn))
16121                         continue;
16122
16123                 if (WARN_ON(load_reg == -1)) {
16124                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
16125                         return -EFAULT;
16126                 }
16127
16128                 zext_patch[0] = insn;
16129                 zext_patch[1].dst_reg = load_reg;
16130                 zext_patch[1].src_reg = load_reg;
16131                 patch = zext_patch;
16132                 patch_len = 2;
16133 apply_patch_buffer:
16134                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
16135                 if (!new_prog)
16136                         return -ENOMEM;
16137                 env->prog = new_prog;
16138                 insns = new_prog->insnsi;
16139                 aux = env->insn_aux_data;
16140                 delta += patch_len - 1;
16141         }
16142
16143         return 0;
16144 }
16145
16146 /* convert load instructions that access fields of a context type into a
16147  * sequence of instructions that access fields of the underlying structure:
16148  *     struct __sk_buff    -> struct sk_buff
16149  *     struct bpf_sock_ops -> struct sock
16150  */
16151 static int convert_ctx_accesses(struct bpf_verifier_env *env)
16152 {
16153         const struct bpf_verifier_ops *ops = env->ops;
16154         int i, cnt, size, ctx_field_size, delta = 0;
16155         const int insn_cnt = env->prog->len;
16156         struct bpf_insn insn_buf[16], *insn;
16157         u32 target_size, size_default, off;
16158         struct bpf_prog *new_prog;
16159         enum bpf_access_type type;
16160         bool is_narrower_load;
16161
16162         if (ops->gen_prologue || env->seen_direct_write) {
16163                 if (!ops->gen_prologue) {
16164                         verbose(env, "bpf verifier is misconfigured\n");
16165                         return -EINVAL;
16166                 }
16167                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
16168                                         env->prog);
16169                 if (cnt >= ARRAY_SIZE(insn_buf)) {
16170                         verbose(env, "bpf verifier is misconfigured\n");
16171                         return -EINVAL;
16172                 } else if (cnt) {
16173                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
16174                         if (!new_prog)
16175                                 return -ENOMEM;
16176
16177                         env->prog = new_prog;
16178                         delta += cnt - 1;
16179                 }
16180         }
16181
16182         if (bpf_prog_is_offloaded(env->prog->aux))
16183                 return 0;
16184
16185         insn = env->prog->insnsi + delta;
16186
16187         for (i = 0; i < insn_cnt; i++, insn++) {
16188                 bpf_convert_ctx_access_t convert_ctx_access;
16189
16190                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
16191                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
16192                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
16193                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
16194                         type = BPF_READ;
16195                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
16196                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
16197                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
16198                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
16199                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
16200                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
16201                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
16202                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
16203                         type = BPF_WRITE;
16204                 } else {
16205                         continue;
16206                 }
16207
16208                 if (type == BPF_WRITE &&
16209                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
16210                         struct bpf_insn patch[] = {
16211                                 *insn,
16212                                 BPF_ST_NOSPEC(),
16213                         };
16214
16215                         cnt = ARRAY_SIZE(patch);
16216                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
16217                         if (!new_prog)
16218                                 return -ENOMEM;
16219
16220                         delta    += cnt - 1;
16221                         env->prog = new_prog;
16222                         insn      = new_prog->insnsi + i + delta;
16223                         continue;
16224                 }
16225
16226                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
16227                 case PTR_TO_CTX:
16228                         if (!ops->convert_ctx_access)
16229                                 continue;
16230                         convert_ctx_access = ops->convert_ctx_access;
16231                         break;
16232                 case PTR_TO_SOCKET:
16233                 case PTR_TO_SOCK_COMMON:
16234                         convert_ctx_access = bpf_sock_convert_ctx_access;
16235                         break;
16236                 case PTR_TO_TCP_SOCK:
16237                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
16238                         break;
16239                 case PTR_TO_XDP_SOCK:
16240                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
16241                         break;
16242                 case PTR_TO_BTF_ID:
16243                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
16244                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
16245                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
16246                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
16247                  * any faults for loads into such types. BPF_WRITE is disallowed
16248                  * for this case.
16249                  */
16250                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
16251                         if (type == BPF_READ) {
16252                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
16253                                         BPF_SIZE((insn)->code);
16254                                 env->prog->aux->num_exentries++;
16255                         }
16256                         continue;
16257                 default:
16258                         continue;
16259                 }
16260
16261                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
16262                 size = BPF_LDST_BYTES(insn);
16263
16264                 /* If the read access is a narrower load of the field,
16265                  * convert to a 4/8-byte load, to minimum program type specific
16266                  * convert_ctx_access changes. If conversion is successful,
16267                  * we will apply proper mask to the result.
16268                  */
16269                 is_narrower_load = size < ctx_field_size;
16270                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
16271                 off = insn->off;
16272                 if (is_narrower_load) {
16273                         u8 size_code;
16274
16275                         if (type == BPF_WRITE) {
16276                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
16277                                 return -EINVAL;
16278                         }
16279
16280                         size_code = BPF_H;
16281                         if (ctx_field_size == 4)
16282                                 size_code = BPF_W;
16283                         else if (ctx_field_size == 8)
16284                                 size_code = BPF_DW;
16285
16286                         insn->off = off & ~(size_default - 1);
16287                         insn->code = BPF_LDX | BPF_MEM | size_code;
16288                 }
16289
16290                 target_size = 0;
16291                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
16292                                          &target_size);
16293                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
16294                     (ctx_field_size && !target_size)) {
16295                         verbose(env, "bpf verifier is misconfigured\n");
16296                         return -EINVAL;
16297                 }
16298
16299                 if (is_narrower_load && size < target_size) {
16300                         u8 shift = bpf_ctx_narrow_access_offset(
16301                                 off, size, size_default) * 8;
16302                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
16303                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
16304                                 return -EINVAL;
16305                         }
16306                         if (ctx_field_size <= 4) {
16307                                 if (shift)
16308                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
16309                                                                         insn->dst_reg,
16310                                                                         shift);
16311                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
16312                                                                 (1 << size * 8) - 1);
16313                         } else {
16314                                 if (shift)
16315                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
16316                                                                         insn->dst_reg,
16317                                                                         shift);
16318                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
16319                                                                 (1ULL << size * 8) - 1);
16320                         }
16321                 }
16322
16323                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16324                 if (!new_prog)
16325                         return -ENOMEM;
16326
16327                 delta += cnt - 1;
16328
16329                 /* keep walking new program and skip insns we just inserted */
16330                 env->prog = new_prog;
16331                 insn      = new_prog->insnsi + i + delta;
16332         }
16333
16334         return 0;
16335 }
16336
16337 static int jit_subprogs(struct bpf_verifier_env *env)
16338 {
16339         struct bpf_prog *prog = env->prog, **func, *tmp;
16340         int i, j, subprog_start, subprog_end = 0, len, subprog;
16341         struct bpf_map *map_ptr;
16342         struct bpf_insn *insn;
16343         void *old_bpf_func;
16344         int err, num_exentries;
16345
16346         if (env->subprog_cnt <= 1)
16347                 return 0;
16348
16349         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16350                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
16351                         continue;
16352
16353                 /* Upon error here we cannot fall back to interpreter but
16354                  * need a hard reject of the program. Thus -EFAULT is
16355                  * propagated in any case.
16356                  */
16357                 subprog = find_subprog(env, i + insn->imm + 1);
16358                 if (subprog < 0) {
16359                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
16360                                   i + insn->imm + 1);
16361                         return -EFAULT;
16362                 }
16363                 /* temporarily remember subprog id inside insn instead of
16364                  * aux_data, since next loop will split up all insns into funcs
16365                  */
16366                 insn->off = subprog;
16367                 /* remember original imm in case JIT fails and fallback
16368                  * to interpreter will be needed
16369                  */
16370                 env->insn_aux_data[i].call_imm = insn->imm;
16371                 /* point imm to __bpf_call_base+1 from JITs point of view */
16372                 insn->imm = 1;
16373                 if (bpf_pseudo_func(insn))
16374                         /* jit (e.g. x86_64) may emit fewer instructions
16375                          * if it learns a u32 imm is the same as a u64 imm.
16376                          * Force a non zero here.
16377                          */
16378                         insn[1].imm = 1;
16379         }
16380
16381         err = bpf_prog_alloc_jited_linfo(prog);
16382         if (err)
16383                 goto out_undo_insn;
16384
16385         err = -ENOMEM;
16386         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
16387         if (!func)
16388                 goto out_undo_insn;
16389
16390         for (i = 0; i < env->subprog_cnt; i++) {
16391                 subprog_start = subprog_end;
16392                 subprog_end = env->subprog_info[i + 1].start;
16393
16394                 len = subprog_end - subprog_start;
16395                 /* bpf_prog_run() doesn't call subprogs directly,
16396                  * hence main prog stats include the runtime of subprogs.
16397                  * subprogs don't have IDs and not reachable via prog_get_next_id
16398                  * func[i]->stats will never be accessed and stays NULL
16399                  */
16400                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
16401                 if (!func[i])
16402                         goto out_free;
16403                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
16404                        len * sizeof(struct bpf_insn));
16405                 func[i]->type = prog->type;
16406                 func[i]->len = len;
16407                 if (bpf_prog_calc_tag(func[i]))
16408                         goto out_free;
16409                 func[i]->is_func = 1;
16410                 func[i]->aux->func_idx = i;
16411                 /* Below members will be freed only at prog->aux */
16412                 func[i]->aux->btf = prog->aux->btf;
16413                 func[i]->aux->func_info = prog->aux->func_info;
16414                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
16415                 func[i]->aux->poke_tab = prog->aux->poke_tab;
16416                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
16417
16418                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
16419                         struct bpf_jit_poke_descriptor *poke;
16420
16421                         poke = &prog->aux->poke_tab[j];
16422                         if (poke->insn_idx < subprog_end &&
16423                             poke->insn_idx >= subprog_start)
16424                                 poke->aux = func[i]->aux;
16425                 }
16426
16427                 func[i]->aux->name[0] = 'F';
16428                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
16429                 func[i]->jit_requested = 1;
16430                 func[i]->blinding_requested = prog->blinding_requested;
16431                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
16432                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
16433                 func[i]->aux->linfo = prog->aux->linfo;
16434                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
16435                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
16436                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
16437                 num_exentries = 0;
16438                 insn = func[i]->insnsi;
16439                 for (j = 0; j < func[i]->len; j++, insn++) {
16440                         if (BPF_CLASS(insn->code) == BPF_LDX &&
16441                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
16442                                 num_exentries++;
16443                 }
16444                 func[i]->aux->num_exentries = num_exentries;
16445                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
16446                 func[i] = bpf_int_jit_compile(func[i]);
16447                 if (!func[i]->jited) {
16448                         err = -ENOTSUPP;
16449                         goto out_free;
16450                 }
16451                 cond_resched();
16452         }
16453
16454         /* at this point all bpf functions were successfully JITed
16455          * now populate all bpf_calls with correct addresses and
16456          * run last pass of JIT
16457          */
16458         for (i = 0; i < env->subprog_cnt; i++) {
16459                 insn = func[i]->insnsi;
16460                 for (j = 0; j < func[i]->len; j++, insn++) {
16461                         if (bpf_pseudo_func(insn)) {
16462                                 subprog = insn->off;
16463                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
16464                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
16465                                 continue;
16466                         }
16467                         if (!bpf_pseudo_call(insn))
16468                                 continue;
16469                         subprog = insn->off;
16470                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
16471                 }
16472
16473                 /* we use the aux data to keep a list of the start addresses
16474                  * of the JITed images for each function in the program
16475                  *
16476                  * for some architectures, such as powerpc64, the imm field
16477                  * might not be large enough to hold the offset of the start
16478                  * address of the callee's JITed image from __bpf_call_base
16479                  *
16480                  * in such cases, we can lookup the start address of a callee
16481                  * by using its subprog id, available from the off field of
16482                  * the call instruction, as an index for this list
16483                  */
16484                 func[i]->aux->func = func;
16485                 func[i]->aux->func_cnt = env->subprog_cnt;
16486         }
16487         for (i = 0; i < env->subprog_cnt; i++) {
16488                 old_bpf_func = func[i]->bpf_func;
16489                 tmp = bpf_int_jit_compile(func[i]);
16490                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
16491                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
16492                         err = -ENOTSUPP;
16493                         goto out_free;
16494                 }
16495                 cond_resched();
16496         }
16497
16498         /* finally lock prog and jit images for all functions and
16499          * populate kallsysm
16500          */
16501         for (i = 0; i < env->subprog_cnt; i++) {
16502                 bpf_prog_lock_ro(func[i]);
16503                 bpf_prog_kallsyms_add(func[i]);
16504         }
16505
16506         /* Last step: make now unused interpreter insns from main
16507          * prog consistent for later dump requests, so they can
16508          * later look the same as if they were interpreted only.
16509          */
16510         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16511                 if (bpf_pseudo_func(insn)) {
16512                         insn[0].imm = env->insn_aux_data[i].call_imm;
16513                         insn[1].imm = insn->off;
16514                         insn->off = 0;
16515                         continue;
16516                 }
16517                 if (!bpf_pseudo_call(insn))
16518                         continue;
16519                 insn->off = env->insn_aux_data[i].call_imm;
16520                 subprog = find_subprog(env, i + insn->off + 1);
16521                 insn->imm = subprog;
16522         }
16523
16524         prog->jited = 1;
16525         prog->bpf_func = func[0]->bpf_func;
16526         prog->jited_len = func[0]->jited_len;
16527         prog->aux->func = func;
16528         prog->aux->func_cnt = env->subprog_cnt;
16529         bpf_prog_jit_attempt_done(prog);
16530         return 0;
16531 out_free:
16532         /* We failed JIT'ing, so at this point we need to unregister poke
16533          * descriptors from subprogs, so that kernel is not attempting to
16534          * patch it anymore as we're freeing the subprog JIT memory.
16535          */
16536         for (i = 0; i < prog->aux->size_poke_tab; i++) {
16537                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
16538                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
16539         }
16540         /* At this point we're guaranteed that poke descriptors are not
16541          * live anymore. We can just unlink its descriptor table as it's
16542          * released with the main prog.
16543          */
16544         for (i = 0; i < env->subprog_cnt; i++) {
16545                 if (!func[i])
16546                         continue;
16547                 func[i]->aux->poke_tab = NULL;
16548                 bpf_jit_free(func[i]);
16549         }
16550         kfree(func);
16551 out_undo_insn:
16552         /* cleanup main prog to be interpreted */
16553         prog->jit_requested = 0;
16554         prog->blinding_requested = 0;
16555         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
16556                 if (!bpf_pseudo_call(insn))
16557                         continue;
16558                 insn->off = 0;
16559                 insn->imm = env->insn_aux_data[i].call_imm;
16560         }
16561         bpf_prog_jit_attempt_done(prog);
16562         return err;
16563 }
16564
16565 static int fixup_call_args(struct bpf_verifier_env *env)
16566 {
16567 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16568         struct bpf_prog *prog = env->prog;
16569         struct bpf_insn *insn = prog->insnsi;
16570         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
16571         int i, depth;
16572 #endif
16573         int err = 0;
16574
16575         if (env->prog->jit_requested &&
16576             !bpf_prog_is_offloaded(env->prog->aux)) {
16577                 err = jit_subprogs(env);
16578                 if (err == 0)
16579                         return 0;
16580                 if (err == -EFAULT)
16581                         return err;
16582         }
16583 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
16584         if (has_kfunc_call) {
16585                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
16586                 return -EINVAL;
16587         }
16588         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
16589                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
16590                  * have to be rejected, since interpreter doesn't support them yet.
16591                  */
16592                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
16593                 return -EINVAL;
16594         }
16595         for (i = 0; i < prog->len; i++, insn++) {
16596                 if (bpf_pseudo_func(insn)) {
16597                         /* When JIT fails the progs with callback calls
16598                          * have to be rejected, since interpreter doesn't support them yet.
16599                          */
16600                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
16601                         return -EINVAL;
16602                 }
16603
16604                 if (!bpf_pseudo_call(insn))
16605                         continue;
16606                 depth = get_callee_stack_depth(env, insn, i);
16607                 if (depth < 0)
16608                         return depth;
16609                 bpf_patch_call_args(insn, depth);
16610         }
16611         err = 0;
16612 #endif
16613         return err;
16614 }
16615
16616 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
16617                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
16618 {
16619         const struct bpf_kfunc_desc *desc;
16620         void *xdp_kfunc;
16621
16622         if (!insn->imm) {
16623                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
16624                 return -EINVAL;
16625         }
16626
16627         *cnt = 0;
16628
16629         if (bpf_dev_bound_kfunc_id(insn->imm)) {
16630                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
16631                 if (xdp_kfunc) {
16632                         insn->imm = BPF_CALL_IMM(xdp_kfunc);
16633                         return 0;
16634                 }
16635
16636                 /* fallback to default kfunc when not supported by netdev */
16637         }
16638
16639         /* insn->imm has the btf func_id. Replace it with
16640          * an address (relative to __bpf_call_base).
16641          */
16642         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
16643         if (!desc) {
16644                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
16645                         insn->imm);
16646                 return -EFAULT;
16647         }
16648
16649         insn->imm = desc->imm;
16650         if (insn->off)
16651                 return 0;
16652         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
16653                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16654                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16655                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
16656
16657                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
16658                 insn_buf[1] = addr[0];
16659                 insn_buf[2] = addr[1];
16660                 insn_buf[3] = *insn;
16661                 *cnt = 4;
16662         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
16663                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
16664                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
16665
16666                 insn_buf[0] = addr[0];
16667                 insn_buf[1] = addr[1];
16668                 insn_buf[2] = *insn;
16669                 *cnt = 3;
16670         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
16671                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
16672                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
16673                 *cnt = 1;
16674         } else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
16675                 bool seen_direct_write = env->seen_direct_write;
16676                 bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
16677
16678                 if (is_rdonly)
16679                         insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);
16680
16681                 /* restore env->seen_direct_write to its original value, since
16682                  * may_access_direct_pkt_data mutates it
16683                  */
16684                 env->seen_direct_write = seen_direct_write;
16685         }
16686         return 0;
16687 }
16688
16689 /* Do various post-verification rewrites in a single program pass.
16690  * These rewrites simplify JIT and interpreter implementations.
16691  */
16692 static int do_misc_fixups(struct bpf_verifier_env *env)
16693 {
16694         struct bpf_prog *prog = env->prog;
16695         enum bpf_attach_type eatype = prog->expected_attach_type;
16696         enum bpf_prog_type prog_type = resolve_prog_type(prog);
16697         struct bpf_insn *insn = prog->insnsi;
16698         const struct bpf_func_proto *fn;
16699         const int insn_cnt = prog->len;
16700         const struct bpf_map_ops *ops;
16701         struct bpf_insn_aux_data *aux;
16702         struct bpf_insn insn_buf[16];
16703         struct bpf_prog *new_prog;
16704         struct bpf_map *map_ptr;
16705         int i, ret, cnt, delta = 0;
16706
16707         for (i = 0; i < insn_cnt; i++, insn++) {
16708                 /* Make divide-by-zero exceptions impossible. */
16709                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
16710                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
16711                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
16712                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
16713                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
16714                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
16715                         struct bpf_insn *patchlet;
16716                         struct bpf_insn chk_and_div[] = {
16717                                 /* [R,W]x div 0 -> 0 */
16718                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16719                                              BPF_JNE | BPF_K, insn->src_reg,
16720                                              0, 2, 0),
16721                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
16722                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16723                                 *insn,
16724                         };
16725                         struct bpf_insn chk_and_mod[] = {
16726                                 /* [R,W]x mod 0 -> [R,W]x */
16727                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
16728                                              BPF_JEQ | BPF_K, insn->src_reg,
16729                                              0, 1 + (is64 ? 0 : 1), 0),
16730                                 *insn,
16731                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
16732                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
16733                         };
16734
16735                         patchlet = isdiv ? chk_and_div : chk_and_mod;
16736                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
16737                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
16738
16739                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
16740                         if (!new_prog)
16741                                 return -ENOMEM;
16742
16743                         delta    += cnt - 1;
16744                         env->prog = prog = new_prog;
16745                         insn      = new_prog->insnsi + i + delta;
16746                         continue;
16747                 }
16748
16749                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
16750                 if (BPF_CLASS(insn->code) == BPF_LD &&
16751                     (BPF_MODE(insn->code) == BPF_ABS ||
16752                      BPF_MODE(insn->code) == BPF_IND)) {
16753                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
16754                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
16755                                 verbose(env, "bpf verifier is misconfigured\n");
16756                                 return -EINVAL;
16757                         }
16758
16759                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16760                         if (!new_prog)
16761                                 return -ENOMEM;
16762
16763                         delta    += cnt - 1;
16764                         env->prog = prog = new_prog;
16765                         insn      = new_prog->insnsi + i + delta;
16766                         continue;
16767                 }
16768
16769                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
16770                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
16771                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
16772                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
16773                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
16774                         struct bpf_insn *patch = &insn_buf[0];
16775                         bool issrc, isneg, isimm;
16776                         u32 off_reg;
16777
16778                         aux = &env->insn_aux_data[i + delta];
16779                         if (!aux->alu_state ||
16780                             aux->alu_state == BPF_ALU_NON_POINTER)
16781                                 continue;
16782
16783                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
16784                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
16785                                 BPF_ALU_SANITIZE_SRC;
16786                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
16787
16788                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
16789                         if (isimm) {
16790                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16791                         } else {
16792                                 if (isneg)
16793                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16794                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
16795                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
16796                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
16797                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
16798                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
16799                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
16800                         }
16801                         if (!issrc)
16802                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
16803                         insn->src_reg = BPF_REG_AX;
16804                         if (isneg)
16805                                 insn->code = insn->code == code_add ?
16806                                              code_sub : code_add;
16807                         *patch++ = *insn;
16808                         if (issrc && isneg && !isimm)
16809                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
16810                         cnt = patch - insn_buf;
16811
16812                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16813                         if (!new_prog)
16814                                 return -ENOMEM;
16815
16816                         delta    += cnt - 1;
16817                         env->prog = prog = new_prog;
16818                         insn      = new_prog->insnsi + i + delta;
16819                         continue;
16820                 }
16821
16822                 if (insn->code != (BPF_JMP | BPF_CALL))
16823                         continue;
16824                 if (insn->src_reg == BPF_PSEUDO_CALL)
16825                         continue;
16826                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16827                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
16828                         if (ret)
16829                                 return ret;
16830                         if (cnt == 0)
16831                                 continue;
16832
16833                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16834                         if (!new_prog)
16835                                 return -ENOMEM;
16836
16837                         delta    += cnt - 1;
16838                         env->prog = prog = new_prog;
16839                         insn      = new_prog->insnsi + i + delta;
16840                         continue;
16841                 }
16842
16843                 if (insn->imm == BPF_FUNC_get_route_realm)
16844                         prog->dst_needed = 1;
16845                 if (insn->imm == BPF_FUNC_get_prandom_u32)
16846                         bpf_user_rnd_init_once();
16847                 if (insn->imm == BPF_FUNC_override_return)
16848                         prog->kprobe_override = 1;
16849                 if (insn->imm == BPF_FUNC_tail_call) {
16850                         /* If we tail call into other programs, we
16851                          * cannot make any assumptions since they can
16852                          * be replaced dynamically during runtime in
16853                          * the program array.
16854                          */
16855                         prog->cb_access = 1;
16856                         if (!allow_tail_call_in_subprogs(env))
16857                                 prog->aux->stack_depth = MAX_BPF_STACK;
16858                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
16859
16860                         /* mark bpf_tail_call as different opcode to avoid
16861                          * conditional branch in the interpreter for every normal
16862                          * call and to prevent accidental JITing by JIT compiler
16863                          * that doesn't support bpf_tail_call yet
16864                          */
16865                         insn->imm = 0;
16866                         insn->code = BPF_JMP | BPF_TAIL_CALL;
16867
16868                         aux = &env->insn_aux_data[i + delta];
16869                         if (env->bpf_capable && !prog->blinding_requested &&
16870                             prog->jit_requested &&
16871                             !bpf_map_key_poisoned(aux) &&
16872                             !bpf_map_ptr_poisoned(aux) &&
16873                             !bpf_map_ptr_unpriv(aux)) {
16874                                 struct bpf_jit_poke_descriptor desc = {
16875                                         .reason = BPF_POKE_REASON_TAIL_CALL,
16876                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
16877                                         .tail_call.key = bpf_map_key_immediate(aux),
16878                                         .insn_idx = i + delta,
16879                                 };
16880
16881                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
16882                                 if (ret < 0) {
16883                                         verbose(env, "adding tail call poke descriptor failed\n");
16884                                         return ret;
16885                                 }
16886
16887                                 insn->imm = ret + 1;
16888                                 continue;
16889                         }
16890
16891                         if (!bpf_map_ptr_unpriv(aux))
16892                                 continue;
16893
16894                         /* instead of changing every JIT dealing with tail_call
16895                          * emit two extra insns:
16896                          * if (index >= max_entries) goto out;
16897                          * index &= array->index_mask;
16898                          * to avoid out-of-bounds cpu speculation
16899                          */
16900                         if (bpf_map_ptr_poisoned(aux)) {
16901                                 verbose(env, "tail_call abusing map_ptr\n");
16902                                 return -EINVAL;
16903                         }
16904
16905                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16906                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
16907                                                   map_ptr->max_entries, 2);
16908                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
16909                                                     container_of(map_ptr,
16910                                                                  struct bpf_array,
16911                                                                  map)->index_mask);
16912                         insn_buf[2] = *insn;
16913                         cnt = 3;
16914                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16915                         if (!new_prog)
16916                                 return -ENOMEM;
16917
16918                         delta    += cnt - 1;
16919                         env->prog = prog = new_prog;
16920                         insn      = new_prog->insnsi + i + delta;
16921                         continue;
16922                 }
16923
16924                 if (insn->imm == BPF_FUNC_timer_set_callback) {
16925                         /* The verifier will process callback_fn as many times as necessary
16926                          * with different maps and the register states prepared by
16927                          * set_timer_callback_state will be accurate.
16928                          *
16929                          * The following use case is valid:
16930                          *   map1 is shared by prog1, prog2, prog3.
16931                          *   prog1 calls bpf_timer_init for some map1 elements
16932                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
16933                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
16934                          *   prog3 calls bpf_timer_start for some map1 elements.
16935                          *     Those that were not both bpf_timer_init-ed and
16936                          *     bpf_timer_set_callback-ed will return -EINVAL.
16937                          */
16938                         struct bpf_insn ld_addrs[2] = {
16939                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
16940                         };
16941
16942                         insn_buf[0] = ld_addrs[0];
16943                         insn_buf[1] = ld_addrs[1];
16944                         insn_buf[2] = *insn;
16945                         cnt = 3;
16946
16947                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16948                         if (!new_prog)
16949                                 return -ENOMEM;
16950
16951                         delta    += cnt - 1;
16952                         env->prog = prog = new_prog;
16953                         insn      = new_prog->insnsi + i + delta;
16954                         goto patch_call_imm;
16955                 }
16956
16957                 if (is_storage_get_function(insn->imm)) {
16958                         if (!env->prog->aux->sleepable ||
16959                             env->insn_aux_data[i + delta].storage_get_func_atomic)
16960                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
16961                         else
16962                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
16963                         insn_buf[1] = *insn;
16964                         cnt = 2;
16965
16966                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
16967                         if (!new_prog)
16968                                 return -ENOMEM;
16969
16970                         delta += cnt - 1;
16971                         env->prog = prog = new_prog;
16972                         insn = new_prog->insnsi + i + delta;
16973                         goto patch_call_imm;
16974                 }
16975
16976                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
16977                  * and other inlining handlers are currently limited to 64 bit
16978                  * only.
16979                  */
16980                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
16981                     (insn->imm == BPF_FUNC_map_lookup_elem ||
16982                      insn->imm == BPF_FUNC_map_update_elem ||
16983                      insn->imm == BPF_FUNC_map_delete_elem ||
16984                      insn->imm == BPF_FUNC_map_push_elem   ||
16985                      insn->imm == BPF_FUNC_map_pop_elem    ||
16986                      insn->imm == BPF_FUNC_map_peek_elem   ||
16987                      insn->imm == BPF_FUNC_redirect_map    ||
16988                      insn->imm == BPF_FUNC_for_each_map_elem ||
16989                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
16990                         aux = &env->insn_aux_data[i + delta];
16991                         if (bpf_map_ptr_poisoned(aux))
16992                                 goto patch_call_imm;
16993
16994                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
16995                         ops = map_ptr->ops;
16996                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
16997                             ops->map_gen_lookup) {
16998                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
16999                                 if (cnt == -EOPNOTSUPP)
17000                                         goto patch_map_ops_generic;
17001                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17002                                         verbose(env, "bpf verifier is misconfigured\n");
17003                                         return -EINVAL;
17004                                 }
17005
17006                                 new_prog = bpf_patch_insn_data(env, i + delta,
17007                                                                insn_buf, cnt);
17008                                 if (!new_prog)
17009                                         return -ENOMEM;
17010
17011                                 delta    += cnt - 1;
17012                                 env->prog = prog = new_prog;
17013                                 insn      = new_prog->insnsi + i + delta;
17014                                 continue;
17015                         }
17016
17017                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
17018                                      (void *(*)(struct bpf_map *map, void *key))NULL));
17019                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
17020                                      (int (*)(struct bpf_map *map, void *key))NULL));
17021                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
17022                                      (int (*)(struct bpf_map *map, void *key, void *value,
17023                                               u64 flags))NULL));
17024                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
17025                                      (int (*)(struct bpf_map *map, void *value,
17026                                               u64 flags))NULL));
17027                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
17028                                      (int (*)(struct bpf_map *map, void *value))NULL));
17029                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
17030                                      (int (*)(struct bpf_map *map, void *value))NULL));
17031                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
17032                                      (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
17033                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
17034                                      (int (*)(struct bpf_map *map,
17035                                               bpf_callback_t callback_fn,
17036                                               void *callback_ctx,
17037                                               u64 flags))NULL));
17038                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
17039                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
17040
17041 patch_map_ops_generic:
17042                         switch (insn->imm) {
17043                         case BPF_FUNC_map_lookup_elem:
17044                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
17045                                 continue;
17046                         case BPF_FUNC_map_update_elem:
17047                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
17048                                 continue;
17049                         case BPF_FUNC_map_delete_elem:
17050                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
17051                                 continue;
17052                         case BPF_FUNC_map_push_elem:
17053                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
17054                                 continue;
17055                         case BPF_FUNC_map_pop_elem:
17056                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
17057                                 continue;
17058                         case BPF_FUNC_map_peek_elem:
17059                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
17060                                 continue;
17061                         case BPF_FUNC_redirect_map:
17062                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
17063                                 continue;
17064                         case BPF_FUNC_for_each_map_elem:
17065                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
17066                                 continue;
17067                         case BPF_FUNC_map_lookup_percpu_elem:
17068                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
17069                                 continue;
17070                         }
17071
17072                         goto patch_call_imm;
17073                 }
17074
17075                 /* Implement bpf_jiffies64 inline. */
17076                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17077                     insn->imm == BPF_FUNC_jiffies64) {
17078                         struct bpf_insn ld_jiffies_addr[2] = {
17079                                 BPF_LD_IMM64(BPF_REG_0,
17080                                              (unsigned long)&jiffies),
17081                         };
17082
17083                         insn_buf[0] = ld_jiffies_addr[0];
17084                         insn_buf[1] = ld_jiffies_addr[1];
17085                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
17086                                                   BPF_REG_0, 0);
17087                         cnt = 3;
17088
17089                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
17090                                                        cnt);
17091                         if (!new_prog)
17092                                 return -ENOMEM;
17093
17094                         delta    += cnt - 1;
17095                         env->prog = prog = new_prog;
17096                         insn      = new_prog->insnsi + i + delta;
17097                         continue;
17098                 }
17099
17100                 /* Implement bpf_get_func_arg inline. */
17101                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17102                     insn->imm == BPF_FUNC_get_func_arg) {
17103                         /* Load nr_args from ctx - 8 */
17104                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17105                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
17106                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
17107                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
17108                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
17109                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17110                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
17111                         insn_buf[7] = BPF_JMP_A(1);
17112                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
17113                         cnt = 9;
17114
17115                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17116                         if (!new_prog)
17117                                 return -ENOMEM;
17118
17119                         delta    += cnt - 1;
17120                         env->prog = prog = new_prog;
17121                         insn      = new_prog->insnsi + i + delta;
17122                         continue;
17123                 }
17124
17125                 /* Implement bpf_get_func_ret inline. */
17126                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17127                     insn->imm == BPF_FUNC_get_func_ret) {
17128                         if (eatype == BPF_TRACE_FEXIT ||
17129                             eatype == BPF_MODIFY_RETURN) {
17130                                 /* Load nr_args from ctx - 8 */
17131                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17132                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
17133                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
17134                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17135                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
17136                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
17137                                 cnt = 6;
17138                         } else {
17139                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
17140                                 cnt = 1;
17141                         }
17142
17143                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17144                         if (!new_prog)
17145                                 return -ENOMEM;
17146
17147                         delta    += cnt - 1;
17148                         env->prog = prog = new_prog;
17149                         insn      = new_prog->insnsi + i + delta;
17150                         continue;
17151                 }
17152
17153                 /* Implement get_func_arg_cnt inline. */
17154                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17155                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
17156                         /* Load nr_args from ctx - 8 */
17157                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17158
17159                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17160                         if (!new_prog)
17161                                 return -ENOMEM;
17162
17163                         env->prog = prog = new_prog;
17164                         insn      = new_prog->insnsi + i + delta;
17165                         continue;
17166                 }
17167
17168                 /* Implement bpf_get_func_ip inline. */
17169                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17170                     insn->imm == BPF_FUNC_get_func_ip) {
17171                         /* Load IP address from ctx - 16 */
17172                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
17173
17174                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17175                         if (!new_prog)
17176                                 return -ENOMEM;
17177
17178                         env->prog = prog = new_prog;
17179                         insn      = new_prog->insnsi + i + delta;
17180                         continue;
17181                 }
17182
17183 patch_call_imm:
17184                 fn = env->ops->get_func_proto(insn->imm, env->prog);
17185                 /* all functions that have prototype and verifier allowed
17186                  * programs to call them, must be real in-kernel functions
17187                  */
17188                 if (!fn->func) {
17189                         verbose(env,
17190                                 "kernel subsystem misconfigured func %s#%d\n",
17191                                 func_id_name(insn->imm), insn->imm);
17192                         return -EFAULT;
17193                 }
17194                 insn->imm = fn->func - __bpf_call_base;
17195         }
17196
17197         /* Since poke tab is now finalized, publish aux to tracker. */
17198         for (i = 0; i < prog->aux->size_poke_tab; i++) {
17199                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17200                 if (!map_ptr->ops->map_poke_track ||
17201                     !map_ptr->ops->map_poke_untrack ||
17202                     !map_ptr->ops->map_poke_run) {
17203                         verbose(env, "bpf verifier is misconfigured\n");
17204                         return -EINVAL;
17205                 }
17206
17207                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
17208                 if (ret < 0) {
17209                         verbose(env, "tracking tail call prog failed\n");
17210                         return ret;
17211                 }
17212         }
17213
17214         sort_kfunc_descs_by_imm(env->prog);
17215
17216         return 0;
17217 }
17218
17219 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
17220                                         int position,
17221                                         s32 stack_base,
17222                                         u32 callback_subprogno,
17223                                         u32 *cnt)
17224 {
17225         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
17226         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
17227         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
17228         int reg_loop_max = BPF_REG_6;
17229         int reg_loop_cnt = BPF_REG_7;
17230         int reg_loop_ctx = BPF_REG_8;
17231
17232         struct bpf_prog *new_prog;
17233         u32 callback_start;
17234         u32 call_insn_offset;
17235         s32 callback_offset;
17236
17237         /* This represents an inlined version of bpf_iter.c:bpf_loop,
17238          * be careful to modify this code in sync.
17239          */
17240         struct bpf_insn insn_buf[] = {
17241                 /* Return error and jump to the end of the patch if
17242                  * expected number of iterations is too big.
17243                  */
17244                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
17245                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
17246                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
17247                 /* spill R6, R7, R8 to use these as loop vars */
17248                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
17249                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
17250                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
17251                 /* initialize loop vars */
17252                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
17253                 BPF_MOV32_IMM(reg_loop_cnt, 0),
17254                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
17255                 /* loop header,
17256                  * if reg_loop_cnt >= reg_loop_max skip the loop body
17257                  */
17258                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
17259                 /* callback call,
17260                  * correct callback offset would be set after patching
17261                  */
17262                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
17263                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
17264                 BPF_CALL_REL(0),
17265                 /* increment loop counter */
17266                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
17267                 /* jump to loop header if callback returned 0 */
17268                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
17269                 /* return value of bpf_loop,
17270                  * set R0 to the number of iterations
17271                  */
17272                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
17273                 /* restore original values of R6, R7, R8 */
17274                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
17275                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
17276                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
17277         };
17278
17279         *cnt = ARRAY_SIZE(insn_buf);
17280         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
17281         if (!new_prog)
17282                 return new_prog;
17283
17284         /* callback start is known only after patching */
17285         callback_start = env->subprog_info[callback_subprogno].start;
17286         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
17287         call_insn_offset = position + 12;
17288         callback_offset = callback_start - call_insn_offset - 1;
17289         new_prog->insnsi[call_insn_offset].imm = callback_offset;
17290
17291         return new_prog;
17292 }
17293
17294 static bool is_bpf_loop_call(struct bpf_insn *insn)
17295 {
17296         return insn->code == (BPF_JMP | BPF_CALL) &&
17297                 insn->src_reg == 0 &&
17298                 insn->imm == BPF_FUNC_loop;
17299 }
17300
17301 /* For all sub-programs in the program (including main) check
17302  * insn_aux_data to see if there are bpf_loop calls that require
17303  * inlining. If such calls are found the calls are replaced with a
17304  * sequence of instructions produced by `inline_bpf_loop` function and
17305  * subprog stack_depth is increased by the size of 3 registers.
17306  * This stack space is used to spill values of the R6, R7, R8.  These
17307  * registers are used to store the loop bound, counter and context
17308  * variables.
17309  */
17310 static int optimize_bpf_loop(struct bpf_verifier_env *env)
17311 {
17312         struct bpf_subprog_info *subprogs = env->subprog_info;
17313         int i, cur_subprog = 0, cnt, delta = 0;
17314         struct bpf_insn *insn = env->prog->insnsi;
17315         int insn_cnt = env->prog->len;
17316         u16 stack_depth = subprogs[cur_subprog].stack_depth;
17317         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
17318         u16 stack_depth_extra = 0;
17319
17320         for (i = 0; i < insn_cnt; i++, insn++) {
17321                 struct bpf_loop_inline_state *inline_state =
17322                         &env->insn_aux_data[i + delta].loop_inline_state;
17323
17324                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
17325                         struct bpf_prog *new_prog;
17326
17327                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
17328                         new_prog = inline_bpf_loop(env,
17329                                                    i + delta,
17330                                                    -(stack_depth + stack_depth_extra),
17331                                                    inline_state->callback_subprogno,
17332                                                    &cnt);
17333                         if (!new_prog)
17334                                 return -ENOMEM;
17335
17336                         delta     += cnt - 1;
17337                         env->prog  = new_prog;
17338                         insn       = new_prog->insnsi + i + delta;
17339                 }
17340
17341                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
17342                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
17343                         cur_subprog++;
17344                         stack_depth = subprogs[cur_subprog].stack_depth;
17345                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
17346                         stack_depth_extra = 0;
17347                 }
17348         }
17349
17350         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17351
17352         return 0;
17353 }
17354
17355 static void free_states(struct bpf_verifier_env *env)
17356 {
17357         struct bpf_verifier_state_list *sl, *sln;
17358         int i;
17359
17360         sl = env->free_list;
17361         while (sl) {
17362                 sln = sl->next;
17363                 free_verifier_state(&sl->state, false);
17364                 kfree(sl);
17365                 sl = sln;
17366         }
17367         env->free_list = NULL;
17368
17369         if (!env->explored_states)
17370                 return;
17371
17372         for (i = 0; i < state_htab_size(env); i++) {
17373                 sl = env->explored_states[i];
17374
17375                 while (sl) {
17376                         sln = sl->next;
17377                         free_verifier_state(&sl->state, false);
17378                         kfree(sl);
17379                         sl = sln;
17380                 }
17381                 env->explored_states[i] = NULL;
17382         }
17383 }
17384
17385 static int do_check_common(struct bpf_verifier_env *env, int subprog)
17386 {
17387         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17388         struct bpf_verifier_state *state;
17389         struct bpf_reg_state *regs;
17390         int ret, i;
17391
17392         env->prev_linfo = NULL;
17393         env->pass_cnt++;
17394
17395         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
17396         if (!state)
17397                 return -ENOMEM;
17398         state->curframe = 0;
17399         state->speculative = false;
17400         state->branches = 1;
17401         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
17402         if (!state->frame[0]) {
17403                 kfree(state);
17404                 return -ENOMEM;
17405         }
17406         env->cur_state = state;
17407         init_func_state(env, state->frame[0],
17408                         BPF_MAIN_FUNC /* callsite */,
17409                         0 /* frameno */,
17410                         subprog);
17411         state->first_insn_idx = env->subprog_info[subprog].start;
17412         state->last_insn_idx = -1;
17413
17414         regs = state->frame[state->curframe]->regs;
17415         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
17416                 ret = btf_prepare_func_args(env, subprog, regs);
17417                 if (ret)
17418                         goto out;
17419                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
17420                         if (regs[i].type == PTR_TO_CTX)
17421                                 mark_reg_known_zero(env, regs, i);
17422                         else if (regs[i].type == SCALAR_VALUE)
17423                                 mark_reg_unknown(env, regs, i);
17424                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
17425                                 const u32 mem_size = regs[i].mem_size;
17426
17427                                 mark_reg_known_zero(env, regs, i);
17428                                 regs[i].mem_size = mem_size;
17429                                 regs[i].id = ++env->id_gen;
17430                         }
17431                 }
17432         } else {
17433                 /* 1st arg to a function */
17434                 regs[BPF_REG_1].type = PTR_TO_CTX;
17435                 mark_reg_known_zero(env, regs, BPF_REG_1);
17436                 ret = btf_check_subprog_arg_match(env, subprog, regs);
17437                 if (ret == -EFAULT)
17438                         /* unlikely verifier bug. abort.
17439                          * ret == 0 and ret < 0 are sadly acceptable for
17440                          * main() function due to backward compatibility.
17441                          * Like socket filter program may be written as:
17442                          * int bpf_prog(struct pt_regs *ctx)
17443                          * and never dereference that ctx in the program.
17444                          * 'struct pt_regs' is a type mismatch for socket
17445                          * filter that should be using 'struct __sk_buff'.
17446                          */
17447                         goto out;
17448         }
17449
17450         ret = do_check(env);
17451 out:
17452         /* check for NULL is necessary, since cur_state can be freed inside
17453          * do_check() under memory pressure.
17454          */
17455         if (env->cur_state) {
17456                 free_verifier_state(env->cur_state, true);
17457                 env->cur_state = NULL;
17458         }
17459         while (!pop_stack(env, NULL, NULL, false));
17460         if (!ret && pop_log)
17461                 bpf_vlog_reset(&env->log, 0);
17462         free_states(env);
17463         return ret;
17464 }
17465
17466 /* Verify all global functions in a BPF program one by one based on their BTF.
17467  * All global functions must pass verification. Otherwise the whole program is rejected.
17468  * Consider:
17469  * int bar(int);
17470  * int foo(int f)
17471  * {
17472  *    return bar(f);
17473  * }
17474  * int bar(int b)
17475  * {
17476  *    ...
17477  * }
17478  * foo() will be verified first for R1=any_scalar_value. During verification it
17479  * will be assumed that bar() already verified successfully and call to bar()
17480  * from foo() will be checked for type match only. Later bar() will be verified
17481  * independently to check that it's safe for R1=any_scalar_value.
17482  */
17483 static int do_check_subprogs(struct bpf_verifier_env *env)
17484 {
17485         struct bpf_prog_aux *aux = env->prog->aux;
17486         int i, ret;
17487
17488         if (!aux->func_info)
17489                 return 0;
17490
17491         for (i = 1; i < env->subprog_cnt; i++) {
17492                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
17493                         continue;
17494                 env->insn_idx = env->subprog_info[i].start;
17495                 WARN_ON_ONCE(env->insn_idx == 0);
17496                 ret = do_check_common(env, i);
17497                 if (ret) {
17498                         return ret;
17499                 } else if (env->log.level & BPF_LOG_LEVEL) {
17500                         verbose(env,
17501                                 "Func#%d is safe for any args that match its prototype\n",
17502                                 i);
17503                 }
17504         }
17505         return 0;
17506 }
17507
17508 static int do_check_main(struct bpf_verifier_env *env)
17509 {
17510         int ret;
17511
17512         env->insn_idx = 0;
17513         ret = do_check_common(env, 0);
17514         if (!ret)
17515                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17516         return ret;
17517 }
17518
17519
17520 static void print_verification_stats(struct bpf_verifier_env *env)
17521 {
17522         int i;
17523
17524         if (env->log.level & BPF_LOG_STATS) {
17525                 verbose(env, "verification time %lld usec\n",
17526                         div_u64(env->verification_time, 1000));
17527                 verbose(env, "stack depth ");
17528                 for (i = 0; i < env->subprog_cnt; i++) {
17529                         u32 depth = env->subprog_info[i].stack_depth;
17530
17531                         verbose(env, "%d", depth);
17532                         if (i + 1 < env->subprog_cnt)
17533                                 verbose(env, "+");
17534                 }
17535                 verbose(env, "\n");
17536         }
17537         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
17538                 "total_states %d peak_states %d mark_read %d\n",
17539                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
17540                 env->max_states_per_insn, env->total_states,
17541                 env->peak_states, env->longest_mark_read_walk);
17542 }
17543
17544 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
17545 {
17546         const struct btf_type *t, *func_proto;
17547         const struct bpf_struct_ops *st_ops;
17548         const struct btf_member *member;
17549         struct bpf_prog *prog = env->prog;
17550         u32 btf_id, member_idx;
17551         const char *mname;
17552
17553         if (!prog->gpl_compatible) {
17554                 verbose(env, "struct ops programs must have a GPL compatible license\n");
17555                 return -EINVAL;
17556         }
17557
17558         btf_id = prog->aux->attach_btf_id;
17559         st_ops = bpf_struct_ops_find(btf_id);
17560         if (!st_ops) {
17561                 verbose(env, "attach_btf_id %u is not a supported struct\n",
17562                         btf_id);
17563                 return -ENOTSUPP;
17564         }
17565
17566         t = st_ops->type;
17567         member_idx = prog->expected_attach_type;
17568         if (member_idx >= btf_type_vlen(t)) {
17569                 verbose(env, "attach to invalid member idx %u of struct %s\n",
17570                         member_idx, st_ops->name);
17571                 return -EINVAL;
17572         }
17573
17574         member = &btf_type_member(t)[member_idx];
17575         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
17576         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
17577                                                NULL);
17578         if (!func_proto) {
17579                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
17580                         mname, member_idx, st_ops->name);
17581                 return -EINVAL;
17582         }
17583
17584         if (st_ops->check_member) {
17585                 int err = st_ops->check_member(t, member, prog);
17586
17587                 if (err) {
17588                         verbose(env, "attach to unsupported member %s of struct %s\n",
17589                                 mname, st_ops->name);
17590                         return err;
17591                 }
17592         }
17593
17594         prog->aux->attach_func_proto = func_proto;
17595         prog->aux->attach_func_name = mname;
17596         env->ops = st_ops->verifier_ops;
17597
17598         return 0;
17599 }
17600 #define SECURITY_PREFIX "security_"
17601
17602 static int check_attach_modify_return(unsigned long addr, const char *func_name)
17603 {
17604         if (within_error_injection_list(addr) ||
17605             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
17606                 return 0;
17607
17608         return -EINVAL;
17609 }
17610
17611 /* list of non-sleepable functions that are otherwise on
17612  * ALLOW_ERROR_INJECTION list
17613  */
17614 BTF_SET_START(btf_non_sleepable_error_inject)
17615 /* Three functions below can be called from sleepable and non-sleepable context.
17616  * Assume non-sleepable from bpf safety point of view.
17617  */
17618 BTF_ID(func, __filemap_add_folio)
17619 BTF_ID(func, should_fail_alloc_page)
17620 BTF_ID(func, should_failslab)
17621 BTF_SET_END(btf_non_sleepable_error_inject)
17622
17623 static int check_non_sleepable_error_inject(u32 btf_id)
17624 {
17625         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
17626 }
17627
17628 int bpf_check_attach_target(struct bpf_verifier_log *log,
17629                             const struct bpf_prog *prog,
17630                             const struct bpf_prog *tgt_prog,
17631                             u32 btf_id,
17632                             struct bpf_attach_target_info *tgt_info)
17633 {
17634         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
17635         const char prefix[] = "btf_trace_";
17636         int ret = 0, subprog = -1, i;
17637         const struct btf_type *t;
17638         bool conservative = true;
17639         const char *tname;
17640         struct btf *btf;
17641         long addr = 0;
17642
17643         if (!btf_id) {
17644                 bpf_log(log, "Tracing programs must provide btf_id\n");
17645                 return -EINVAL;
17646         }
17647         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
17648         if (!btf) {
17649                 bpf_log(log,
17650                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
17651                 return -EINVAL;
17652         }
17653         t = btf_type_by_id(btf, btf_id);
17654         if (!t) {
17655                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
17656                 return -EINVAL;
17657         }
17658         tname = btf_name_by_offset(btf, t->name_off);
17659         if (!tname) {
17660                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
17661                 return -EINVAL;
17662         }
17663         if (tgt_prog) {
17664                 struct bpf_prog_aux *aux = tgt_prog->aux;
17665
17666                 if (bpf_prog_is_dev_bound(prog->aux) &&
17667                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
17668                         bpf_log(log, "Target program bound device mismatch");
17669                         return -EINVAL;
17670                 }
17671
17672                 for (i = 0; i < aux->func_info_cnt; i++)
17673                         if (aux->func_info[i].type_id == btf_id) {
17674                                 subprog = i;
17675                                 break;
17676                         }
17677                 if (subprog == -1) {
17678                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
17679                         return -EINVAL;
17680                 }
17681                 conservative = aux->func_info_aux[subprog].unreliable;
17682                 if (prog_extension) {
17683                         if (conservative) {
17684                                 bpf_log(log,
17685                                         "Cannot replace static functions\n");
17686                                 return -EINVAL;
17687                         }
17688                         if (!prog->jit_requested) {
17689                                 bpf_log(log,
17690                                         "Extension programs should be JITed\n");
17691                                 return -EINVAL;
17692                         }
17693                 }
17694                 if (!tgt_prog->jited) {
17695                         bpf_log(log, "Can attach to only JITed progs\n");
17696                         return -EINVAL;
17697                 }
17698                 if (tgt_prog->type == prog->type) {
17699                         /* Cannot fentry/fexit another fentry/fexit program.
17700                          * Cannot attach program extension to another extension.
17701                          * It's ok to attach fentry/fexit to extension program.
17702                          */
17703                         bpf_log(log, "Cannot recursively attach\n");
17704                         return -EINVAL;
17705                 }
17706                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
17707                     prog_extension &&
17708                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
17709                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
17710                         /* Program extensions can extend all program types
17711                          * except fentry/fexit. The reason is the following.
17712                          * The fentry/fexit programs are used for performance
17713                          * analysis, stats and can be attached to any program
17714                          * type except themselves. When extension program is
17715                          * replacing XDP function it is necessary to allow
17716                          * performance analysis of all functions. Both original
17717                          * XDP program and its program extension. Hence
17718                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
17719                          * allowed. If extending of fentry/fexit was allowed it
17720                          * would be possible to create long call chain
17721                          * fentry->extension->fentry->extension beyond
17722                          * reasonable stack size. Hence extending fentry is not
17723                          * allowed.
17724                          */
17725                         bpf_log(log, "Cannot extend fentry/fexit\n");
17726                         return -EINVAL;
17727                 }
17728         } else {
17729                 if (prog_extension) {
17730                         bpf_log(log, "Cannot replace kernel functions\n");
17731                         return -EINVAL;
17732                 }
17733         }
17734
17735         switch (prog->expected_attach_type) {
17736         case BPF_TRACE_RAW_TP:
17737                 if (tgt_prog) {
17738                         bpf_log(log,
17739                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
17740                         return -EINVAL;
17741                 }
17742                 if (!btf_type_is_typedef(t)) {
17743                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
17744                                 btf_id);
17745                         return -EINVAL;
17746                 }
17747                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
17748                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
17749                                 btf_id, tname);
17750                         return -EINVAL;
17751                 }
17752                 tname += sizeof(prefix) - 1;
17753                 t = btf_type_by_id(btf, t->type);
17754                 if (!btf_type_is_ptr(t))
17755                         /* should never happen in valid vmlinux build */
17756                         return -EINVAL;
17757                 t = btf_type_by_id(btf, t->type);
17758                 if (!btf_type_is_func_proto(t))
17759                         /* should never happen in valid vmlinux build */
17760                         return -EINVAL;
17761
17762                 break;
17763         case BPF_TRACE_ITER:
17764                 if (!btf_type_is_func(t)) {
17765                         bpf_log(log, "attach_btf_id %u is not a function\n",
17766                                 btf_id);
17767                         return -EINVAL;
17768                 }
17769                 t = btf_type_by_id(btf, t->type);
17770                 if (!btf_type_is_func_proto(t))
17771                         return -EINVAL;
17772                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17773                 if (ret)
17774                         return ret;
17775                 break;
17776         default:
17777                 if (!prog_extension)
17778                         return -EINVAL;
17779                 fallthrough;
17780         case BPF_MODIFY_RETURN:
17781         case BPF_LSM_MAC:
17782         case BPF_LSM_CGROUP:
17783         case BPF_TRACE_FENTRY:
17784         case BPF_TRACE_FEXIT:
17785                 if (!btf_type_is_func(t)) {
17786                         bpf_log(log, "attach_btf_id %u is not a function\n",
17787                                 btf_id);
17788                         return -EINVAL;
17789                 }
17790                 if (prog_extension &&
17791                     btf_check_type_match(log, prog, btf, t))
17792                         return -EINVAL;
17793                 t = btf_type_by_id(btf, t->type);
17794                 if (!btf_type_is_func_proto(t))
17795                         return -EINVAL;
17796
17797                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
17798                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
17799                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
17800                         return -EINVAL;
17801
17802                 if (tgt_prog && conservative)
17803                         t = NULL;
17804
17805                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
17806                 if (ret < 0)
17807                         return ret;
17808
17809                 if (tgt_prog) {
17810                         if (subprog == 0)
17811                                 addr = (long) tgt_prog->bpf_func;
17812                         else
17813                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
17814                 } else {
17815                         addr = kallsyms_lookup_name(tname);
17816                         if (!addr) {
17817                                 bpf_log(log,
17818                                         "The address of function %s cannot be found\n",
17819                                         tname);
17820                                 return -ENOENT;
17821                         }
17822                 }
17823
17824                 if (prog->aux->sleepable) {
17825                         ret = -EINVAL;
17826                         switch (prog->type) {
17827                         case BPF_PROG_TYPE_TRACING:
17828
17829                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
17830                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
17831                                  */
17832                                 if (!check_non_sleepable_error_inject(btf_id) &&
17833                                     within_error_injection_list(addr))
17834                                         ret = 0;
17835                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
17836                                  * in the fmodret id set with the KF_SLEEPABLE flag.
17837                                  */
17838                                 else {
17839                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
17840
17841                                         if (flags && (*flags & KF_SLEEPABLE))
17842                                                 ret = 0;
17843                                 }
17844                                 break;
17845                         case BPF_PROG_TYPE_LSM:
17846                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
17847                                  * Only some of them are sleepable.
17848                                  */
17849                                 if (bpf_lsm_is_sleepable_hook(btf_id))
17850                                         ret = 0;
17851                                 break;
17852                         default:
17853                                 break;
17854                         }
17855                         if (ret) {
17856                                 bpf_log(log, "%s is not sleepable\n", tname);
17857                                 return ret;
17858                         }
17859                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
17860                         if (tgt_prog) {
17861                                 bpf_log(log, "can't modify return codes of BPF programs\n");
17862                                 return -EINVAL;
17863                         }
17864                         ret = -EINVAL;
17865                         if (btf_kfunc_is_modify_return(btf, btf_id) ||
17866                             !check_attach_modify_return(addr, tname))
17867                                 ret = 0;
17868                         if (ret) {
17869                                 bpf_log(log, "%s() is not modifiable\n", tname);
17870                                 return ret;
17871                         }
17872                 }
17873
17874                 break;
17875         }
17876         tgt_info->tgt_addr = addr;
17877         tgt_info->tgt_name = tname;
17878         tgt_info->tgt_type = t;
17879         return 0;
17880 }
17881
17882 BTF_SET_START(btf_id_deny)
17883 BTF_ID_UNUSED
17884 #ifdef CONFIG_SMP
17885 BTF_ID(func, migrate_disable)
17886 BTF_ID(func, migrate_enable)
17887 #endif
17888 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
17889 BTF_ID(func, rcu_read_unlock_strict)
17890 #endif
17891 BTF_SET_END(btf_id_deny)
17892
17893 static bool can_be_sleepable(struct bpf_prog *prog)
17894 {
17895         if (prog->type == BPF_PROG_TYPE_TRACING) {
17896                 switch (prog->expected_attach_type) {
17897                 case BPF_TRACE_FENTRY:
17898                 case BPF_TRACE_FEXIT:
17899                 case BPF_MODIFY_RETURN:
17900                 case BPF_TRACE_ITER:
17901                         return true;
17902                 default:
17903                         return false;
17904                 }
17905         }
17906         return prog->type == BPF_PROG_TYPE_LSM ||
17907                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
17908                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
17909 }
17910
17911 static int check_attach_btf_id(struct bpf_verifier_env *env)
17912 {
17913         struct bpf_prog *prog = env->prog;
17914         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
17915         struct bpf_attach_target_info tgt_info = {};
17916         u32 btf_id = prog->aux->attach_btf_id;
17917         struct bpf_trampoline *tr;
17918         int ret;
17919         u64 key;
17920
17921         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
17922                 if (prog->aux->sleepable)
17923                         /* attach_btf_id checked to be zero already */
17924                         return 0;
17925                 verbose(env, "Syscall programs can only be sleepable\n");
17926                 return -EINVAL;
17927         }
17928
17929         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
17930                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
17931                 return -EINVAL;
17932         }
17933
17934         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
17935                 return check_struct_ops_btf_id(env);
17936
17937         if (prog->type != BPF_PROG_TYPE_TRACING &&
17938             prog->type != BPF_PROG_TYPE_LSM &&
17939             prog->type != BPF_PROG_TYPE_EXT)
17940                 return 0;
17941
17942         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
17943         if (ret)
17944                 return ret;
17945
17946         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
17947                 /* to make freplace equivalent to their targets, they need to
17948                  * inherit env->ops and expected_attach_type for the rest of the
17949                  * verification
17950                  */
17951                 env->ops = bpf_verifier_ops[tgt_prog->type];
17952                 prog->expected_attach_type = tgt_prog->expected_attach_type;
17953         }
17954
17955         /* store info about the attachment target that will be used later */
17956         prog->aux->attach_func_proto = tgt_info.tgt_type;
17957         prog->aux->attach_func_name = tgt_info.tgt_name;
17958
17959         if (tgt_prog) {
17960                 prog->aux->saved_dst_prog_type = tgt_prog->type;
17961                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
17962         }
17963
17964         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
17965                 prog->aux->attach_btf_trace = true;
17966                 return 0;
17967         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
17968                 if (!bpf_iter_prog_supported(prog))
17969                         return -EINVAL;
17970                 return 0;
17971         }
17972
17973         if (prog->type == BPF_PROG_TYPE_LSM) {
17974                 ret = bpf_lsm_verify_prog(&env->log, prog);
17975                 if (ret < 0)
17976                         return ret;
17977         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
17978                    btf_id_set_contains(&btf_id_deny, btf_id)) {
17979                 return -EINVAL;
17980         }
17981
17982         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
17983         tr = bpf_trampoline_get(key, &tgt_info);
17984         if (!tr)
17985                 return -ENOMEM;
17986
17987         prog->aux->dst_trampoline = tr;
17988         return 0;
17989 }
17990
17991 struct btf *bpf_get_btf_vmlinux(void)
17992 {
17993         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
17994                 mutex_lock(&bpf_verifier_lock);
17995                 if (!btf_vmlinux)
17996                         btf_vmlinux = btf_parse_vmlinux();
17997                 mutex_unlock(&bpf_verifier_lock);
17998         }
17999         return btf_vmlinux;
18000 }
18001
18002 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
18003 {
18004         u64 start_time = ktime_get_ns();
18005         struct bpf_verifier_env *env;
18006         struct bpf_verifier_log *log;
18007         int i, len, ret = -EINVAL;
18008         bool is_priv;
18009
18010         /* no program is valid */
18011         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
18012                 return -EINVAL;
18013
18014         /* 'struct bpf_verifier_env' can be global, but since it's not small,
18015          * allocate/free it every time bpf_check() is called
18016          */
18017         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
18018         if (!env)
18019                 return -ENOMEM;
18020         log = &env->log;
18021
18022         len = (*prog)->len;
18023         env->insn_aux_data =
18024                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
18025         ret = -ENOMEM;
18026         if (!env->insn_aux_data)
18027                 goto err_free_env;
18028         for (i = 0; i < len; i++)
18029                 env->insn_aux_data[i].orig_idx = i;
18030         env->prog = *prog;
18031         env->ops = bpf_verifier_ops[env->prog->type];
18032         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
18033         is_priv = bpf_capable();
18034
18035         bpf_get_btf_vmlinux();
18036
18037         /* grab the mutex to protect few globals used by verifier */
18038         if (!is_priv)
18039                 mutex_lock(&bpf_verifier_lock);
18040
18041         if (attr->log_level || attr->log_buf || attr->log_size) {
18042                 /* user requested verbose verifier output
18043                  * and supplied buffer to store the verification trace
18044                  */
18045                 log->level = attr->log_level;
18046                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
18047                 log->len_total = attr->log_size;
18048
18049                 /* log attributes have to be sane */
18050                 if (!bpf_verifier_log_attr_valid(log)) {
18051                         ret = -EINVAL;
18052                         goto err_unlock;
18053                 }
18054         }
18055
18056         mark_verifier_state_clean(env);
18057
18058         if (IS_ERR(btf_vmlinux)) {
18059                 /* Either gcc or pahole or kernel are broken. */
18060                 verbose(env, "in-kernel BTF is malformed\n");
18061                 ret = PTR_ERR(btf_vmlinux);
18062                 goto skip_full_check;
18063         }
18064
18065         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
18066         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
18067                 env->strict_alignment = true;
18068         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
18069                 env->strict_alignment = false;
18070
18071         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
18072         env->allow_uninit_stack = bpf_allow_uninit_stack();
18073         env->bypass_spec_v1 = bpf_bypass_spec_v1();
18074         env->bypass_spec_v4 = bpf_bypass_spec_v4();
18075         env->bpf_capable = bpf_capable();
18076
18077         if (is_priv)
18078                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
18079
18080         env->explored_states = kvcalloc(state_htab_size(env),
18081                                        sizeof(struct bpf_verifier_state_list *),
18082                                        GFP_USER);
18083         ret = -ENOMEM;
18084         if (!env->explored_states)
18085                 goto skip_full_check;
18086
18087         ret = add_subprog_and_kfunc(env);
18088         if (ret < 0)
18089                 goto skip_full_check;
18090
18091         ret = check_subprogs(env);
18092         if (ret < 0)
18093                 goto skip_full_check;
18094
18095         ret = check_btf_info(env, attr, uattr);
18096         if (ret < 0)
18097                 goto skip_full_check;
18098
18099         ret = check_attach_btf_id(env);
18100         if (ret)
18101                 goto skip_full_check;
18102
18103         ret = resolve_pseudo_ldimm64(env);
18104         if (ret < 0)
18105                 goto skip_full_check;
18106
18107         if (bpf_prog_is_offloaded(env->prog->aux)) {
18108                 ret = bpf_prog_offload_verifier_prep(env->prog);
18109                 if (ret)
18110                         goto skip_full_check;
18111         }
18112
18113         ret = check_cfg(env);
18114         if (ret < 0)
18115                 goto skip_full_check;
18116
18117         ret = do_check_subprogs(env);
18118         ret = ret ?: do_check_main(env);
18119
18120         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
18121                 ret = bpf_prog_offload_finalize(env);
18122
18123 skip_full_check:
18124         kvfree(env->explored_states);
18125
18126         if (ret == 0)
18127                 ret = check_max_stack_depth(env);
18128
18129         /* instruction rewrites happen after this point */
18130         if (ret == 0)
18131                 ret = optimize_bpf_loop(env);
18132
18133         if (is_priv) {
18134                 if (ret == 0)
18135                         opt_hard_wire_dead_code_branches(env);
18136                 if (ret == 0)
18137                         ret = opt_remove_dead_code(env);
18138                 if (ret == 0)
18139                         ret = opt_remove_nops(env);
18140         } else {
18141                 if (ret == 0)
18142                         sanitize_dead_code(env);
18143         }
18144
18145         if (ret == 0)
18146                 /* program is valid, convert *(u32*)(ctx + off) accesses */
18147                 ret = convert_ctx_accesses(env);
18148
18149         if (ret == 0)
18150                 ret = do_misc_fixups(env);
18151
18152         /* do 32-bit optimization after insn patching has done so those patched
18153          * insns could be handled correctly.
18154          */
18155         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
18156                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
18157                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
18158                                                                      : false;
18159         }
18160
18161         if (ret == 0)
18162                 ret = fixup_call_args(env);
18163
18164         env->verification_time = ktime_get_ns() - start_time;
18165         print_verification_stats(env);
18166         env->prog->aux->verified_insns = env->insn_processed;
18167
18168         if (log->level && bpf_verifier_log_full(log))
18169                 ret = -ENOSPC;
18170         if (log->level && !log->ubuf) {
18171                 ret = -EFAULT;
18172                 goto err_release_maps;
18173         }
18174
18175         if (ret)
18176                 goto err_release_maps;
18177
18178         if (env->used_map_cnt) {
18179                 /* if program passed verifier, update used_maps in bpf_prog_info */
18180                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
18181                                                           sizeof(env->used_maps[0]),
18182                                                           GFP_KERNEL);
18183
18184                 if (!env->prog->aux->used_maps) {
18185                         ret = -ENOMEM;
18186                         goto err_release_maps;
18187                 }
18188
18189                 memcpy(env->prog->aux->used_maps, env->used_maps,
18190                        sizeof(env->used_maps[0]) * env->used_map_cnt);
18191                 env->prog->aux->used_map_cnt = env->used_map_cnt;
18192         }
18193         if (env->used_btf_cnt) {
18194                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
18195                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
18196                                                           sizeof(env->used_btfs[0]),
18197                                                           GFP_KERNEL);
18198                 if (!env->prog->aux->used_btfs) {
18199                         ret = -ENOMEM;
18200                         goto err_release_maps;
18201                 }
18202
18203                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
18204                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
18205                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
18206         }
18207         if (env->used_map_cnt || env->used_btf_cnt) {
18208                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
18209                  * bpf_ld_imm64 instructions
18210                  */
18211                 convert_pseudo_ld_imm64(env);
18212         }
18213
18214         adjust_btf_func(env);
18215
18216 err_release_maps:
18217         if (!env->prog->aux->used_maps)
18218                 /* if we didn't copy map pointers into bpf_prog_info, release
18219                  * them now. Otherwise free_used_maps() will release them.
18220                  */
18221                 release_maps(env);
18222         if (!env->prog->aux->used_btfs)
18223                 release_btfs(env);
18224
18225         /* extension progs temporarily inherit the attach_type of their targets
18226            for verification purposes, so set it back to zero before returning
18227          */
18228         if (env->prog->type == BPF_PROG_TYPE_EXT)
18229                 env->prog->expected_attach_type = 0;
18230
18231         *prog = env->prog;
18232 err_unlock:
18233         if (!is_priv)
18234                 mutex_unlock(&bpf_verifier_lock);
18235         vfree(env->insn_aux_data);
18236 err_free_env:
18237         kfree(env);
18238         return ret;
18239 }