bpf: Introduce might_sleep field in bpf_func_proto
[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
194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198
199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203
204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205                               const struct bpf_map *map, bool unpriv)
206 {
207         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208         unpriv |= bpf_map_ptr_unpriv(aux);
209         aux->map_ptr_state = (unsigned long)map |
210                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212
213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215         return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217
218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222
223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227
228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230         bool poisoned = bpf_map_key_poisoned(aux);
231
232         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235
236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238         return insn->code == (BPF_JMP | BPF_CALL) &&
239                insn->src_reg == BPF_PSEUDO_CALL;
240 }
241
242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244         return insn->code == (BPF_JMP | BPF_CALL) &&
245                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247
248 struct bpf_call_arg_meta {
249         struct bpf_map *map_ptr;
250         bool raw_mode;
251         bool pkt_access;
252         u8 release_regno;
253         int regno;
254         int access_size;
255         int mem_size;
256         u64 msize_max_value;
257         int ref_obj_id;
258         int map_uid;
259         int func_id;
260         struct btf *btf;
261         u32 btf_id;
262         struct btf *ret_btf;
263         u32 ret_btf_id;
264         u32 subprogno;
265         struct btf_field *kptr_field;
266         u8 uninit_dynptr_regno;
267 };
268
269 struct btf *btf_vmlinux;
270
271 static DEFINE_MUTEX(bpf_verifier_lock);
272
273 static const struct bpf_line_info *
274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276         const struct bpf_line_info *linfo;
277         const struct bpf_prog *prog;
278         u32 i, nr_linfo;
279
280         prog = env->prog;
281         nr_linfo = prog->aux->nr_linfo;
282
283         if (!nr_linfo || insn_off >= prog->len)
284                 return NULL;
285
286         linfo = prog->aux->linfo;
287         for (i = 1; i < nr_linfo; i++)
288                 if (insn_off < linfo[i].insn_off)
289                         break;
290
291         return &linfo[i - 1];
292 }
293
294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295                        va_list args)
296 {
297         unsigned int n;
298
299         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300
301         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302                   "verifier log line truncated - local buffer too short\n");
303
304         if (log->level == BPF_LOG_KERNEL) {
305                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306
307                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308                 return;
309         }
310
311         n = min(log->len_total - log->len_used - 1, n);
312         log->kbuf[n] = '\0';
313         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314                 log->len_used += n;
315         else
316                 log->ubuf = NULL;
317 }
318
319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321         char zero = 0;
322
323         if (!bpf_verifier_log_needed(log))
324                 return;
325
326         log->len_used = new_pos;
327         if (put_user(zero, log->ubuf + new_pos))
328                 log->ubuf = NULL;
329 }
330
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336                                            const char *fmt, ...)
337 {
338         va_list args;
339
340         if (!bpf_verifier_log_needed(&env->log))
341                 return;
342
343         va_start(args, fmt);
344         bpf_verifier_vlog(&env->log, fmt, args);
345         va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348
349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351         struct bpf_verifier_env *env = private_data;
352         va_list args;
353
354         if (!bpf_verifier_log_needed(&env->log))
355                 return;
356
357         va_start(args, fmt);
358         bpf_verifier_vlog(&env->log, fmt, args);
359         va_end(args);
360 }
361
362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363                             const char *fmt, ...)
364 {
365         va_list args;
366
367         if (!bpf_verifier_log_needed(log))
368                 return;
369
370         va_start(args, fmt);
371         bpf_verifier_vlog(log, fmt, args);
372         va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375
376 static const char *ltrim(const char *s)
377 {
378         while (isspace(*s))
379                 s++;
380
381         return s;
382 }
383
384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385                                          u32 insn_off,
386                                          const char *prefix_fmt, ...)
387 {
388         const struct bpf_line_info *linfo;
389
390         if (!bpf_verifier_log_needed(&env->log))
391                 return;
392
393         linfo = find_linfo(env, insn_off);
394         if (!linfo || linfo == env->prev_linfo)
395                 return;
396
397         if (prefix_fmt) {
398                 va_list args;
399
400                 va_start(args, prefix_fmt);
401                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402                 va_end(args);
403         }
404
405         verbose(env, "%s\n",
406                 ltrim(btf_name_by_offset(env->prog->aux->btf,
407                                          linfo->line_off)));
408
409         env->prev_linfo = linfo;
410 }
411
412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413                                    struct bpf_reg_state *reg,
414                                    struct tnum *range, const char *ctx,
415                                    const char *reg_name)
416 {
417         char tn_buf[48];
418
419         verbose(env, "At %s the register %s ", ctx, reg_name);
420         if (!tnum_is_unknown(reg->var_off)) {
421                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422                 verbose(env, "has value %s", tn_buf);
423         } else {
424                 verbose(env, "has unknown scalar value");
425         }
426         tnum_strn(tn_buf, sizeof(tn_buf), *range);
427         verbose(env, " should have been in %s\n", tn_buf);
428 }
429
430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432         type = base_type(type);
433         return type == PTR_TO_PACKET ||
434                type == PTR_TO_PACKET_META;
435 }
436
437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439         return type == PTR_TO_SOCKET ||
440                 type == PTR_TO_SOCK_COMMON ||
441                 type == PTR_TO_TCP_SOCK ||
442                 type == PTR_TO_XDP_SOCK;
443 }
444
445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447         return type == PTR_TO_SOCKET ||
448                 type == PTR_TO_TCP_SOCK ||
449                 type == PTR_TO_MAP_VALUE ||
450                 type == PTR_TO_MAP_KEY ||
451                 type == PTR_TO_SOCK_COMMON;
452 }
453
454 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
455 {
456         struct btf_record *rec = NULL;
457         struct btf_struct_meta *meta;
458
459         if (reg->type == PTR_TO_MAP_VALUE) {
460                 rec = reg->map_ptr->record;
461         } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
462                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
463                 if (meta)
464                         rec = meta->record;
465         }
466         return rec;
467 }
468
469 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
470 {
471         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
472 }
473
474 static bool type_is_rdonly_mem(u32 type)
475 {
476         return type & MEM_RDONLY;
477 }
478
479 static bool type_may_be_null(u32 type)
480 {
481         return type & PTR_MAYBE_NULL;
482 }
483
484 static bool is_acquire_function(enum bpf_func_id func_id,
485                                 const struct bpf_map *map)
486 {
487         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
488
489         if (func_id == BPF_FUNC_sk_lookup_tcp ||
490             func_id == BPF_FUNC_sk_lookup_udp ||
491             func_id == BPF_FUNC_skc_lookup_tcp ||
492             func_id == BPF_FUNC_ringbuf_reserve ||
493             func_id == BPF_FUNC_kptr_xchg)
494                 return true;
495
496         if (func_id == BPF_FUNC_map_lookup_elem &&
497             (map_type == BPF_MAP_TYPE_SOCKMAP ||
498              map_type == BPF_MAP_TYPE_SOCKHASH))
499                 return true;
500
501         return false;
502 }
503
504 static bool is_ptr_cast_function(enum bpf_func_id func_id)
505 {
506         return func_id == BPF_FUNC_tcp_sock ||
507                 func_id == BPF_FUNC_sk_fullsock ||
508                 func_id == BPF_FUNC_skc_to_tcp_sock ||
509                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
510                 func_id == BPF_FUNC_skc_to_udp6_sock ||
511                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
512                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
513                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
514 }
515
516 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
517 {
518         return func_id == BPF_FUNC_dynptr_data;
519 }
520
521 static bool is_callback_calling_function(enum bpf_func_id func_id)
522 {
523         return func_id == BPF_FUNC_for_each_map_elem ||
524                func_id == BPF_FUNC_timer_set_callback ||
525                func_id == BPF_FUNC_find_vma ||
526                func_id == BPF_FUNC_loop ||
527                func_id == BPF_FUNC_user_ringbuf_drain;
528 }
529
530 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
531                                         const struct bpf_map *map)
532 {
533         int ref_obj_uses = 0;
534
535         if (is_ptr_cast_function(func_id))
536                 ref_obj_uses++;
537         if (is_acquire_function(func_id, map))
538                 ref_obj_uses++;
539         if (is_dynptr_ref_function(func_id))
540                 ref_obj_uses++;
541
542         return ref_obj_uses > 1;
543 }
544
545 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
546 {
547         return BPF_CLASS(insn->code) == BPF_STX &&
548                BPF_MODE(insn->code) == BPF_ATOMIC &&
549                insn->imm == BPF_CMPXCHG;
550 }
551
552 /* string representation of 'enum bpf_reg_type'
553  *
554  * Note that reg_type_str() can not appear more than once in a single verbose()
555  * statement.
556  */
557 static const char *reg_type_str(struct bpf_verifier_env *env,
558                                 enum bpf_reg_type type)
559 {
560         char postfix[16] = {0}, prefix[64] = {0};
561         static const char * const str[] = {
562                 [NOT_INIT]              = "?",
563                 [SCALAR_VALUE]          = "scalar",
564                 [PTR_TO_CTX]            = "ctx",
565                 [CONST_PTR_TO_MAP]      = "map_ptr",
566                 [PTR_TO_MAP_VALUE]      = "map_value",
567                 [PTR_TO_STACK]          = "fp",
568                 [PTR_TO_PACKET]         = "pkt",
569                 [PTR_TO_PACKET_META]    = "pkt_meta",
570                 [PTR_TO_PACKET_END]     = "pkt_end",
571                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
572                 [PTR_TO_SOCKET]         = "sock",
573                 [PTR_TO_SOCK_COMMON]    = "sock_common",
574                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
575                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
576                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
577                 [PTR_TO_BTF_ID]         = "ptr_",
578                 [PTR_TO_MEM]            = "mem",
579                 [PTR_TO_BUF]            = "buf",
580                 [PTR_TO_FUNC]           = "func",
581                 [PTR_TO_MAP_KEY]        = "map_key",
582                 [PTR_TO_DYNPTR]         = "dynptr_ptr",
583         };
584
585         if (type & PTR_MAYBE_NULL) {
586                 if (base_type(type) == PTR_TO_BTF_ID)
587                         strncpy(postfix, "or_null_", 16);
588                 else
589                         strncpy(postfix, "_or_null", 16);
590         }
591
592         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s",
593                  type & MEM_RDONLY ? "rdonly_" : "",
594                  type & MEM_RINGBUF ? "ringbuf_" : "",
595                  type & MEM_USER ? "user_" : "",
596                  type & MEM_PERCPU ? "percpu_" : "",
597                  type & PTR_UNTRUSTED ? "untrusted_" : "",
598                  type & PTR_TRUSTED ? "trusted_" : ""
599         );
600
601         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
602                  prefix, str[base_type(type)], postfix);
603         return env->type_str_buf;
604 }
605
606 static char slot_type_char[] = {
607         [STACK_INVALID] = '?',
608         [STACK_SPILL]   = 'r',
609         [STACK_MISC]    = 'm',
610         [STACK_ZERO]    = '0',
611         [STACK_DYNPTR]  = 'd',
612 };
613
614 static void print_liveness(struct bpf_verifier_env *env,
615                            enum bpf_reg_liveness live)
616 {
617         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
618             verbose(env, "_");
619         if (live & REG_LIVE_READ)
620                 verbose(env, "r");
621         if (live & REG_LIVE_WRITTEN)
622                 verbose(env, "w");
623         if (live & REG_LIVE_DONE)
624                 verbose(env, "D");
625 }
626
627 static int get_spi(s32 off)
628 {
629         return (-off - 1) / BPF_REG_SIZE;
630 }
631
632 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
633 {
634         int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
635
636         /* We need to check that slots between [spi - nr_slots + 1, spi] are
637          * within [0, allocated_stack).
638          *
639          * Please note that the spi grows downwards. For example, a dynptr
640          * takes the size of two stack slots; the first slot will be at
641          * spi and the second slot will be at spi - 1.
642          */
643         return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
644 }
645
646 static struct bpf_func_state *func(struct bpf_verifier_env *env,
647                                    const struct bpf_reg_state *reg)
648 {
649         struct bpf_verifier_state *cur = env->cur_state;
650
651         return cur->frame[reg->frameno];
652 }
653
654 static const char *kernel_type_name(const struct btf* btf, u32 id)
655 {
656         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
657 }
658
659 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
660 {
661         env->scratched_regs |= 1U << regno;
662 }
663
664 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
665 {
666         env->scratched_stack_slots |= 1ULL << spi;
667 }
668
669 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
670 {
671         return (env->scratched_regs >> regno) & 1;
672 }
673
674 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
675 {
676         return (env->scratched_stack_slots >> regno) & 1;
677 }
678
679 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
680 {
681         return env->scratched_regs || env->scratched_stack_slots;
682 }
683
684 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
685 {
686         env->scratched_regs = 0U;
687         env->scratched_stack_slots = 0ULL;
688 }
689
690 /* Used for printing the entire verifier state. */
691 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
692 {
693         env->scratched_regs = ~0U;
694         env->scratched_stack_slots = ~0ULL;
695 }
696
697 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
698 {
699         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
700         case DYNPTR_TYPE_LOCAL:
701                 return BPF_DYNPTR_TYPE_LOCAL;
702         case DYNPTR_TYPE_RINGBUF:
703                 return BPF_DYNPTR_TYPE_RINGBUF;
704         default:
705                 return BPF_DYNPTR_TYPE_INVALID;
706         }
707 }
708
709 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
710 {
711         return type == BPF_DYNPTR_TYPE_RINGBUF;
712 }
713
714 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
715                                    enum bpf_arg_type arg_type, int insn_idx)
716 {
717         struct bpf_func_state *state = func(env, reg);
718         enum bpf_dynptr_type type;
719         int spi, i, id;
720
721         spi = get_spi(reg->off);
722
723         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
724                 return -EINVAL;
725
726         for (i = 0; i < BPF_REG_SIZE; i++) {
727                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
728                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
729         }
730
731         type = arg_to_dynptr_type(arg_type);
732         if (type == BPF_DYNPTR_TYPE_INVALID)
733                 return -EINVAL;
734
735         state->stack[spi].spilled_ptr.dynptr.first_slot = true;
736         state->stack[spi].spilled_ptr.dynptr.type = type;
737         state->stack[spi - 1].spilled_ptr.dynptr.type = type;
738
739         if (dynptr_type_refcounted(type)) {
740                 /* The id is used to track proper releasing */
741                 id = acquire_reference_state(env, insn_idx);
742                 if (id < 0)
743                         return id;
744
745                 state->stack[spi].spilled_ptr.id = id;
746                 state->stack[spi - 1].spilled_ptr.id = id;
747         }
748
749         return 0;
750 }
751
752 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
753 {
754         struct bpf_func_state *state = func(env, reg);
755         int spi, i;
756
757         spi = get_spi(reg->off);
758
759         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
760                 return -EINVAL;
761
762         for (i = 0; i < BPF_REG_SIZE; i++) {
763                 state->stack[spi].slot_type[i] = STACK_INVALID;
764                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
765         }
766
767         /* Invalidate any slices associated with this dynptr */
768         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
769                 release_reference(env, state->stack[spi].spilled_ptr.id);
770                 state->stack[spi].spilled_ptr.id = 0;
771                 state->stack[spi - 1].spilled_ptr.id = 0;
772         }
773
774         state->stack[spi].spilled_ptr.dynptr.first_slot = false;
775         state->stack[spi].spilled_ptr.dynptr.type = 0;
776         state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
777
778         return 0;
779 }
780
781 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
782 {
783         struct bpf_func_state *state = func(env, reg);
784         int spi = get_spi(reg->off);
785         int i;
786
787         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
788                 return true;
789
790         for (i = 0; i < BPF_REG_SIZE; i++) {
791                 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
792                     state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
793                         return false;
794         }
795
796         return true;
797 }
798
799 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
800                               struct bpf_reg_state *reg)
801 {
802         struct bpf_func_state *state = func(env, reg);
803         int spi = get_spi(reg->off);
804         int i;
805
806         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
807             !state->stack[spi].spilled_ptr.dynptr.first_slot)
808                 return false;
809
810         for (i = 0; i < BPF_REG_SIZE; i++) {
811                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
812                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
813                         return false;
814         }
815
816         return true;
817 }
818
819 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
820                              struct bpf_reg_state *reg,
821                              enum bpf_arg_type arg_type)
822 {
823         struct bpf_func_state *state = func(env, reg);
824         enum bpf_dynptr_type dynptr_type;
825         int spi = get_spi(reg->off);
826
827         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
828         if (arg_type == ARG_PTR_TO_DYNPTR)
829                 return true;
830
831         dynptr_type = arg_to_dynptr_type(arg_type);
832
833         return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
834 }
835
836 /* The reg state of a pointer or a bounded scalar was saved when
837  * it was spilled to the stack.
838  */
839 static bool is_spilled_reg(const struct bpf_stack_state *stack)
840 {
841         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
842 }
843
844 static void scrub_spilled_slot(u8 *stype)
845 {
846         if (*stype != STACK_INVALID)
847                 *stype = STACK_MISC;
848 }
849
850 static void print_verifier_state(struct bpf_verifier_env *env,
851                                  const struct bpf_func_state *state,
852                                  bool print_all)
853 {
854         const struct bpf_reg_state *reg;
855         enum bpf_reg_type t;
856         int i;
857
858         if (state->frameno)
859                 verbose(env, " frame%d:", state->frameno);
860         for (i = 0; i < MAX_BPF_REG; i++) {
861                 reg = &state->regs[i];
862                 t = reg->type;
863                 if (t == NOT_INIT)
864                         continue;
865                 if (!print_all && !reg_scratched(env, i))
866                         continue;
867                 verbose(env, " R%d", i);
868                 print_liveness(env, reg->live);
869                 verbose(env, "=");
870                 if (t == SCALAR_VALUE && reg->precise)
871                         verbose(env, "P");
872                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
873                     tnum_is_const(reg->var_off)) {
874                         /* reg->off should be 0 for SCALAR_VALUE */
875                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
876                         verbose(env, "%lld", reg->var_off.value + reg->off);
877                 } else {
878                         const char *sep = "";
879
880                         verbose(env, "%s", reg_type_str(env, t));
881                         if (base_type(t) == PTR_TO_BTF_ID)
882                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
883                         verbose(env, "(");
884 /*
885  * _a stands for append, was shortened to avoid multiline statements below.
886  * This macro is used to output a comma separated list of attributes.
887  */
888 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
889
890                         if (reg->id)
891                                 verbose_a("id=%d", reg->id);
892                         if (reg->ref_obj_id)
893                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
894                         if (t != SCALAR_VALUE)
895                                 verbose_a("off=%d", reg->off);
896                         if (type_is_pkt_pointer(t))
897                                 verbose_a("r=%d", reg->range);
898                         else if (base_type(t) == CONST_PTR_TO_MAP ||
899                                  base_type(t) == PTR_TO_MAP_KEY ||
900                                  base_type(t) == PTR_TO_MAP_VALUE)
901                                 verbose_a("ks=%d,vs=%d",
902                                           reg->map_ptr->key_size,
903                                           reg->map_ptr->value_size);
904                         if (tnum_is_const(reg->var_off)) {
905                                 /* Typically an immediate SCALAR_VALUE, but
906                                  * could be a pointer whose offset is too big
907                                  * for reg->off
908                                  */
909                                 verbose_a("imm=%llx", reg->var_off.value);
910                         } else {
911                                 if (reg->smin_value != reg->umin_value &&
912                                     reg->smin_value != S64_MIN)
913                                         verbose_a("smin=%lld", (long long)reg->smin_value);
914                                 if (reg->smax_value != reg->umax_value &&
915                                     reg->smax_value != S64_MAX)
916                                         verbose_a("smax=%lld", (long long)reg->smax_value);
917                                 if (reg->umin_value != 0)
918                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
919                                 if (reg->umax_value != U64_MAX)
920                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
921                                 if (!tnum_is_unknown(reg->var_off)) {
922                                         char tn_buf[48];
923
924                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
925                                         verbose_a("var_off=%s", tn_buf);
926                                 }
927                                 if (reg->s32_min_value != reg->smin_value &&
928                                     reg->s32_min_value != S32_MIN)
929                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
930                                 if (reg->s32_max_value != reg->smax_value &&
931                                     reg->s32_max_value != S32_MAX)
932                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
933                                 if (reg->u32_min_value != reg->umin_value &&
934                                     reg->u32_min_value != U32_MIN)
935                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
936                                 if (reg->u32_max_value != reg->umax_value &&
937                                     reg->u32_max_value != U32_MAX)
938                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
939                         }
940 #undef verbose_a
941
942                         verbose(env, ")");
943                 }
944         }
945         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
946                 char types_buf[BPF_REG_SIZE + 1];
947                 bool valid = false;
948                 int j;
949
950                 for (j = 0; j < BPF_REG_SIZE; j++) {
951                         if (state->stack[i].slot_type[j] != STACK_INVALID)
952                                 valid = true;
953                         types_buf[j] = slot_type_char[
954                                         state->stack[i].slot_type[j]];
955                 }
956                 types_buf[BPF_REG_SIZE] = 0;
957                 if (!valid)
958                         continue;
959                 if (!print_all && !stack_slot_scratched(env, i))
960                         continue;
961                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
962                 print_liveness(env, state->stack[i].spilled_ptr.live);
963                 if (is_spilled_reg(&state->stack[i])) {
964                         reg = &state->stack[i].spilled_ptr;
965                         t = reg->type;
966                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
967                         if (t == SCALAR_VALUE && reg->precise)
968                                 verbose(env, "P");
969                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
970                                 verbose(env, "%lld", reg->var_off.value + reg->off);
971                 } else {
972                         verbose(env, "=%s", types_buf);
973                 }
974         }
975         if (state->acquired_refs && state->refs[0].id) {
976                 verbose(env, " refs=%d", state->refs[0].id);
977                 for (i = 1; i < state->acquired_refs; i++)
978                         if (state->refs[i].id)
979                                 verbose(env, ",%d", state->refs[i].id);
980         }
981         if (state->in_callback_fn)
982                 verbose(env, " cb");
983         if (state->in_async_callback_fn)
984                 verbose(env, " async_cb");
985         verbose(env, "\n");
986         mark_verifier_state_clean(env);
987 }
988
989 static inline u32 vlog_alignment(u32 pos)
990 {
991         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
992                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
993 }
994
995 static void print_insn_state(struct bpf_verifier_env *env,
996                              const struct bpf_func_state *state)
997 {
998         if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
999                 /* remove new line character */
1000                 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1001                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1002         } else {
1003                 verbose(env, "%d:", env->insn_idx);
1004         }
1005         print_verifier_state(env, state, false);
1006 }
1007
1008 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1009  * small to hold src. This is different from krealloc since we don't want to preserve
1010  * the contents of dst.
1011  *
1012  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1013  * not be allocated.
1014  */
1015 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1016 {
1017         size_t bytes;
1018
1019         if (ZERO_OR_NULL_PTR(src))
1020                 goto out;
1021
1022         if (unlikely(check_mul_overflow(n, size, &bytes)))
1023                 return NULL;
1024
1025         if (ksize(dst) < ksize(src)) {
1026                 kfree(dst);
1027                 dst = kmalloc_track_caller(kmalloc_size_roundup(bytes), flags);
1028                 if (!dst)
1029                         return NULL;
1030         }
1031
1032         memcpy(dst, src, bytes);
1033 out:
1034         return dst ? dst : ZERO_SIZE_PTR;
1035 }
1036
1037 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1038  * small to hold new_n items. new items are zeroed out if the array grows.
1039  *
1040  * Contrary to krealloc_array, does not free arr if new_n is zero.
1041  */
1042 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1043 {
1044         size_t alloc_size;
1045         void *new_arr;
1046
1047         if (!new_n || old_n == new_n)
1048                 goto out;
1049
1050         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1051         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1052         if (!new_arr) {
1053                 kfree(arr);
1054                 return NULL;
1055         }
1056         arr = new_arr;
1057
1058         if (new_n > old_n)
1059                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1060
1061 out:
1062         return arr ? arr : ZERO_SIZE_PTR;
1063 }
1064
1065 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1066 {
1067         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1068                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1069         if (!dst->refs)
1070                 return -ENOMEM;
1071
1072         dst->acquired_refs = src->acquired_refs;
1073         return 0;
1074 }
1075
1076 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1077 {
1078         size_t n = src->allocated_stack / BPF_REG_SIZE;
1079
1080         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1081                                 GFP_KERNEL);
1082         if (!dst->stack)
1083                 return -ENOMEM;
1084
1085         dst->allocated_stack = src->allocated_stack;
1086         return 0;
1087 }
1088
1089 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1090 {
1091         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1092                                     sizeof(struct bpf_reference_state));
1093         if (!state->refs)
1094                 return -ENOMEM;
1095
1096         state->acquired_refs = n;
1097         return 0;
1098 }
1099
1100 static int grow_stack_state(struct bpf_func_state *state, int size)
1101 {
1102         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1103
1104         if (old_n >= n)
1105                 return 0;
1106
1107         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1108         if (!state->stack)
1109                 return -ENOMEM;
1110
1111         state->allocated_stack = size;
1112         return 0;
1113 }
1114
1115 /* Acquire a pointer id from the env and update the state->refs to include
1116  * this new pointer reference.
1117  * On success, returns a valid pointer id to associate with the register
1118  * On failure, returns a negative errno.
1119  */
1120 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1121 {
1122         struct bpf_func_state *state = cur_func(env);
1123         int new_ofs = state->acquired_refs;
1124         int id, err;
1125
1126         err = resize_reference_state(state, state->acquired_refs + 1);
1127         if (err)
1128                 return err;
1129         id = ++env->id_gen;
1130         state->refs[new_ofs].id = id;
1131         state->refs[new_ofs].insn_idx = insn_idx;
1132         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1133
1134         return id;
1135 }
1136
1137 /* release function corresponding to acquire_reference_state(). Idempotent. */
1138 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1139 {
1140         int i, last_idx;
1141
1142         last_idx = state->acquired_refs - 1;
1143         for (i = 0; i < state->acquired_refs; i++) {
1144                 if (state->refs[i].id == ptr_id) {
1145                         /* Cannot release caller references in callbacks */
1146                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1147                                 return -EINVAL;
1148                         if (last_idx && i != last_idx)
1149                                 memcpy(&state->refs[i], &state->refs[last_idx],
1150                                        sizeof(*state->refs));
1151                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1152                         state->acquired_refs--;
1153                         return 0;
1154                 }
1155         }
1156         return -EINVAL;
1157 }
1158
1159 static void free_func_state(struct bpf_func_state *state)
1160 {
1161         if (!state)
1162                 return;
1163         kfree(state->refs);
1164         kfree(state->stack);
1165         kfree(state);
1166 }
1167
1168 static void clear_jmp_history(struct bpf_verifier_state *state)
1169 {
1170         kfree(state->jmp_history);
1171         state->jmp_history = NULL;
1172         state->jmp_history_cnt = 0;
1173 }
1174
1175 static void free_verifier_state(struct bpf_verifier_state *state,
1176                                 bool free_self)
1177 {
1178         int i;
1179
1180         for (i = 0; i <= state->curframe; i++) {
1181                 free_func_state(state->frame[i]);
1182                 state->frame[i] = NULL;
1183         }
1184         clear_jmp_history(state);
1185         if (free_self)
1186                 kfree(state);
1187 }
1188
1189 /* copy verifier state from src to dst growing dst stack space
1190  * when necessary to accommodate larger src stack
1191  */
1192 static int copy_func_state(struct bpf_func_state *dst,
1193                            const struct bpf_func_state *src)
1194 {
1195         int err;
1196
1197         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1198         err = copy_reference_state(dst, src);
1199         if (err)
1200                 return err;
1201         return copy_stack_state(dst, src);
1202 }
1203
1204 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1205                                const struct bpf_verifier_state *src)
1206 {
1207         struct bpf_func_state *dst;
1208         int i, err;
1209
1210         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1211                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1212                                             GFP_USER);
1213         if (!dst_state->jmp_history)
1214                 return -ENOMEM;
1215         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1216
1217         /* if dst has more stack frames then src frame, free them */
1218         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1219                 free_func_state(dst_state->frame[i]);
1220                 dst_state->frame[i] = NULL;
1221         }
1222         dst_state->speculative = src->speculative;
1223         dst_state->curframe = src->curframe;
1224         dst_state->active_lock.ptr = src->active_lock.ptr;
1225         dst_state->active_lock.id = src->active_lock.id;
1226         dst_state->branches = src->branches;
1227         dst_state->parent = src->parent;
1228         dst_state->first_insn_idx = src->first_insn_idx;
1229         dst_state->last_insn_idx = src->last_insn_idx;
1230         for (i = 0; i <= src->curframe; i++) {
1231                 dst = dst_state->frame[i];
1232                 if (!dst) {
1233                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1234                         if (!dst)
1235                                 return -ENOMEM;
1236                         dst_state->frame[i] = dst;
1237                 }
1238                 err = copy_func_state(dst, src->frame[i]);
1239                 if (err)
1240                         return err;
1241         }
1242         return 0;
1243 }
1244
1245 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1246 {
1247         while (st) {
1248                 u32 br = --st->branches;
1249
1250                 /* WARN_ON(br > 1) technically makes sense here,
1251                  * but see comment in push_stack(), hence:
1252                  */
1253                 WARN_ONCE((int)br < 0,
1254                           "BUG update_branch_counts:branches_to_explore=%d\n",
1255                           br);
1256                 if (br)
1257                         break;
1258                 st = st->parent;
1259         }
1260 }
1261
1262 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1263                      int *insn_idx, bool pop_log)
1264 {
1265         struct bpf_verifier_state *cur = env->cur_state;
1266         struct bpf_verifier_stack_elem *elem, *head = env->head;
1267         int err;
1268
1269         if (env->head == NULL)
1270                 return -ENOENT;
1271
1272         if (cur) {
1273                 err = copy_verifier_state(cur, &head->st);
1274                 if (err)
1275                         return err;
1276         }
1277         if (pop_log)
1278                 bpf_vlog_reset(&env->log, head->log_pos);
1279         if (insn_idx)
1280                 *insn_idx = head->insn_idx;
1281         if (prev_insn_idx)
1282                 *prev_insn_idx = head->prev_insn_idx;
1283         elem = head->next;
1284         free_verifier_state(&head->st, false);
1285         kfree(head);
1286         env->head = elem;
1287         env->stack_size--;
1288         return 0;
1289 }
1290
1291 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1292                                              int insn_idx, int prev_insn_idx,
1293                                              bool speculative)
1294 {
1295         struct bpf_verifier_state *cur = env->cur_state;
1296         struct bpf_verifier_stack_elem *elem;
1297         int err;
1298
1299         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1300         if (!elem)
1301                 goto err;
1302
1303         elem->insn_idx = insn_idx;
1304         elem->prev_insn_idx = prev_insn_idx;
1305         elem->next = env->head;
1306         elem->log_pos = env->log.len_used;
1307         env->head = elem;
1308         env->stack_size++;
1309         err = copy_verifier_state(&elem->st, cur);
1310         if (err)
1311                 goto err;
1312         elem->st.speculative |= speculative;
1313         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1314                 verbose(env, "The sequence of %d jumps is too complex.\n",
1315                         env->stack_size);
1316                 goto err;
1317         }
1318         if (elem->st.parent) {
1319                 ++elem->st.parent->branches;
1320                 /* WARN_ON(branches > 2) technically makes sense here,
1321                  * but
1322                  * 1. speculative states will bump 'branches' for non-branch
1323                  * instructions
1324                  * 2. is_state_visited() heuristics may decide not to create
1325                  * a new state for a sequence of branches and all such current
1326                  * and cloned states will be pointing to a single parent state
1327                  * which might have large 'branches' count.
1328                  */
1329         }
1330         return &elem->st;
1331 err:
1332         free_verifier_state(env->cur_state, true);
1333         env->cur_state = NULL;
1334         /* pop all elements and return */
1335         while (!pop_stack(env, NULL, NULL, false));
1336         return NULL;
1337 }
1338
1339 #define CALLER_SAVED_REGS 6
1340 static const int caller_saved[CALLER_SAVED_REGS] = {
1341         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1342 };
1343
1344 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1345                                 struct bpf_reg_state *reg);
1346
1347 /* This helper doesn't clear reg->id */
1348 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1349 {
1350         reg->var_off = tnum_const(imm);
1351         reg->smin_value = (s64)imm;
1352         reg->smax_value = (s64)imm;
1353         reg->umin_value = imm;
1354         reg->umax_value = imm;
1355
1356         reg->s32_min_value = (s32)imm;
1357         reg->s32_max_value = (s32)imm;
1358         reg->u32_min_value = (u32)imm;
1359         reg->u32_max_value = (u32)imm;
1360 }
1361
1362 /* Mark the unknown part of a register (variable offset or scalar value) as
1363  * known to have the value @imm.
1364  */
1365 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1366 {
1367         /* Clear id, off, and union(map_ptr, range) */
1368         memset(((u8 *)reg) + sizeof(reg->type), 0,
1369                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1370         ___mark_reg_known(reg, imm);
1371 }
1372
1373 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1374 {
1375         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1376         reg->s32_min_value = (s32)imm;
1377         reg->s32_max_value = (s32)imm;
1378         reg->u32_min_value = (u32)imm;
1379         reg->u32_max_value = (u32)imm;
1380 }
1381
1382 /* Mark the 'variable offset' part of a register as zero.  This should be
1383  * used only on registers holding a pointer type.
1384  */
1385 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1386 {
1387         __mark_reg_known(reg, 0);
1388 }
1389
1390 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1391 {
1392         __mark_reg_known(reg, 0);
1393         reg->type = SCALAR_VALUE;
1394 }
1395
1396 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1397                                 struct bpf_reg_state *regs, u32 regno)
1398 {
1399         if (WARN_ON(regno >= MAX_BPF_REG)) {
1400                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1401                 /* Something bad happened, let's kill all regs */
1402                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1403                         __mark_reg_not_init(env, regs + regno);
1404                 return;
1405         }
1406         __mark_reg_known_zero(regs + regno);
1407 }
1408
1409 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1410 {
1411         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1412                 const struct bpf_map *map = reg->map_ptr;
1413
1414                 if (map->inner_map_meta) {
1415                         reg->type = CONST_PTR_TO_MAP;
1416                         reg->map_ptr = map->inner_map_meta;
1417                         /* transfer reg's id which is unique for every map_lookup_elem
1418                          * as UID of the inner map.
1419                          */
1420                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1421                                 reg->map_uid = reg->id;
1422                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1423                         reg->type = PTR_TO_XDP_SOCK;
1424                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1425                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1426                         reg->type = PTR_TO_SOCKET;
1427                 } else {
1428                         reg->type = PTR_TO_MAP_VALUE;
1429                 }
1430                 return;
1431         }
1432
1433         reg->type &= ~PTR_MAYBE_NULL;
1434 }
1435
1436 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1437 {
1438         return type_is_pkt_pointer(reg->type);
1439 }
1440
1441 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1442 {
1443         return reg_is_pkt_pointer(reg) ||
1444                reg->type == PTR_TO_PACKET_END;
1445 }
1446
1447 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1448 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1449                                     enum bpf_reg_type which)
1450 {
1451         /* The register can already have a range from prior markings.
1452          * This is fine as long as it hasn't been advanced from its
1453          * origin.
1454          */
1455         return reg->type == which &&
1456                reg->id == 0 &&
1457                reg->off == 0 &&
1458                tnum_equals_const(reg->var_off, 0);
1459 }
1460
1461 /* Reset the min/max bounds of a register */
1462 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1463 {
1464         reg->smin_value = S64_MIN;
1465         reg->smax_value = S64_MAX;
1466         reg->umin_value = 0;
1467         reg->umax_value = U64_MAX;
1468
1469         reg->s32_min_value = S32_MIN;
1470         reg->s32_max_value = S32_MAX;
1471         reg->u32_min_value = 0;
1472         reg->u32_max_value = U32_MAX;
1473 }
1474
1475 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1476 {
1477         reg->smin_value = S64_MIN;
1478         reg->smax_value = S64_MAX;
1479         reg->umin_value = 0;
1480         reg->umax_value = U64_MAX;
1481 }
1482
1483 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1484 {
1485         reg->s32_min_value = S32_MIN;
1486         reg->s32_max_value = S32_MAX;
1487         reg->u32_min_value = 0;
1488         reg->u32_max_value = U32_MAX;
1489 }
1490
1491 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1492 {
1493         struct tnum var32_off = tnum_subreg(reg->var_off);
1494
1495         /* min signed is max(sign bit) | min(other bits) */
1496         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1497                         var32_off.value | (var32_off.mask & S32_MIN));
1498         /* max signed is min(sign bit) | max(other bits) */
1499         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1500                         var32_off.value | (var32_off.mask & S32_MAX));
1501         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1502         reg->u32_max_value = min(reg->u32_max_value,
1503                                  (u32)(var32_off.value | var32_off.mask));
1504 }
1505
1506 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1507 {
1508         /* min signed is max(sign bit) | min(other bits) */
1509         reg->smin_value = max_t(s64, reg->smin_value,
1510                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1511         /* max signed is min(sign bit) | max(other bits) */
1512         reg->smax_value = min_t(s64, reg->smax_value,
1513                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1514         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1515         reg->umax_value = min(reg->umax_value,
1516                               reg->var_off.value | reg->var_off.mask);
1517 }
1518
1519 static void __update_reg_bounds(struct bpf_reg_state *reg)
1520 {
1521         __update_reg32_bounds(reg);
1522         __update_reg64_bounds(reg);
1523 }
1524
1525 /* Uses signed min/max values to inform unsigned, and vice-versa */
1526 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1527 {
1528         /* Learn sign from signed bounds.
1529          * If we cannot cross the sign boundary, then signed and unsigned bounds
1530          * are the same, so combine.  This works even in the negative case, e.g.
1531          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1532          */
1533         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1534                 reg->s32_min_value = reg->u32_min_value =
1535                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1536                 reg->s32_max_value = reg->u32_max_value =
1537                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1538                 return;
1539         }
1540         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1541          * boundary, so we must be careful.
1542          */
1543         if ((s32)reg->u32_max_value >= 0) {
1544                 /* Positive.  We can't learn anything from the smin, but smax
1545                  * is positive, hence safe.
1546                  */
1547                 reg->s32_min_value = reg->u32_min_value;
1548                 reg->s32_max_value = reg->u32_max_value =
1549                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1550         } else if ((s32)reg->u32_min_value < 0) {
1551                 /* Negative.  We can't learn anything from the smax, but smin
1552                  * is negative, hence safe.
1553                  */
1554                 reg->s32_min_value = reg->u32_min_value =
1555                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1556                 reg->s32_max_value = reg->u32_max_value;
1557         }
1558 }
1559
1560 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1561 {
1562         /* Learn sign from signed bounds.
1563          * If we cannot cross the sign boundary, then signed and unsigned bounds
1564          * are the same, so combine.  This works even in the negative case, e.g.
1565          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1566          */
1567         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1568                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1569                                                           reg->umin_value);
1570                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1571                                                           reg->umax_value);
1572                 return;
1573         }
1574         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1575          * boundary, so we must be careful.
1576          */
1577         if ((s64)reg->umax_value >= 0) {
1578                 /* Positive.  We can't learn anything from the smin, but smax
1579                  * is positive, hence safe.
1580                  */
1581                 reg->smin_value = reg->umin_value;
1582                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1583                                                           reg->umax_value);
1584         } else if ((s64)reg->umin_value < 0) {
1585                 /* Negative.  We can't learn anything from the smax, but smin
1586                  * is negative, hence safe.
1587                  */
1588                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1589                                                           reg->umin_value);
1590                 reg->smax_value = reg->umax_value;
1591         }
1592 }
1593
1594 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1595 {
1596         __reg32_deduce_bounds(reg);
1597         __reg64_deduce_bounds(reg);
1598 }
1599
1600 /* Attempts to improve var_off based on unsigned min/max information */
1601 static void __reg_bound_offset(struct bpf_reg_state *reg)
1602 {
1603         struct tnum var64_off = tnum_intersect(reg->var_off,
1604                                                tnum_range(reg->umin_value,
1605                                                           reg->umax_value));
1606         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1607                                                 tnum_range(reg->u32_min_value,
1608                                                            reg->u32_max_value));
1609
1610         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1611 }
1612
1613 static void reg_bounds_sync(struct bpf_reg_state *reg)
1614 {
1615         /* We might have learned new bounds from the var_off. */
1616         __update_reg_bounds(reg);
1617         /* We might have learned something about the sign bit. */
1618         __reg_deduce_bounds(reg);
1619         /* We might have learned some bits from the bounds. */
1620         __reg_bound_offset(reg);
1621         /* Intersecting with the old var_off might have improved our bounds
1622          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1623          * then new var_off is (0; 0x7f...fc) which improves our umax.
1624          */
1625         __update_reg_bounds(reg);
1626 }
1627
1628 static bool __reg32_bound_s64(s32 a)
1629 {
1630         return a >= 0 && a <= S32_MAX;
1631 }
1632
1633 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1634 {
1635         reg->umin_value = reg->u32_min_value;
1636         reg->umax_value = reg->u32_max_value;
1637
1638         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1639          * be positive otherwise set to worse case bounds and refine later
1640          * from tnum.
1641          */
1642         if (__reg32_bound_s64(reg->s32_min_value) &&
1643             __reg32_bound_s64(reg->s32_max_value)) {
1644                 reg->smin_value = reg->s32_min_value;
1645                 reg->smax_value = reg->s32_max_value;
1646         } else {
1647                 reg->smin_value = 0;
1648                 reg->smax_value = U32_MAX;
1649         }
1650 }
1651
1652 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1653 {
1654         /* special case when 64-bit register has upper 32-bit register
1655          * zeroed. Typically happens after zext or <<32, >>32 sequence
1656          * allowing us to use 32-bit bounds directly,
1657          */
1658         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1659                 __reg_assign_32_into_64(reg);
1660         } else {
1661                 /* Otherwise the best we can do is push lower 32bit known and
1662                  * unknown bits into register (var_off set from jmp logic)
1663                  * then learn as much as possible from the 64-bit tnum
1664                  * known and unknown bits. The previous smin/smax bounds are
1665                  * invalid here because of jmp32 compare so mark them unknown
1666                  * so they do not impact tnum bounds calculation.
1667                  */
1668                 __mark_reg64_unbounded(reg);
1669         }
1670         reg_bounds_sync(reg);
1671 }
1672
1673 static bool __reg64_bound_s32(s64 a)
1674 {
1675         return a >= S32_MIN && a <= S32_MAX;
1676 }
1677
1678 static bool __reg64_bound_u32(u64 a)
1679 {
1680         return a >= U32_MIN && a <= U32_MAX;
1681 }
1682
1683 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1684 {
1685         __mark_reg32_unbounded(reg);
1686         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1687                 reg->s32_min_value = (s32)reg->smin_value;
1688                 reg->s32_max_value = (s32)reg->smax_value;
1689         }
1690         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1691                 reg->u32_min_value = (u32)reg->umin_value;
1692                 reg->u32_max_value = (u32)reg->umax_value;
1693         }
1694         reg_bounds_sync(reg);
1695 }
1696
1697 /* Mark a register as having a completely unknown (scalar) value. */
1698 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1699                                struct bpf_reg_state *reg)
1700 {
1701         /*
1702          * Clear type, id, off, and union(map_ptr, range) and
1703          * padding between 'type' and union
1704          */
1705         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1706         reg->type = SCALAR_VALUE;
1707         reg->var_off = tnum_unknown;
1708         reg->frameno = 0;
1709         reg->precise = !env->bpf_capable;
1710         __mark_reg_unbounded(reg);
1711 }
1712
1713 static void mark_reg_unknown(struct bpf_verifier_env *env,
1714                              struct bpf_reg_state *regs, u32 regno)
1715 {
1716         if (WARN_ON(regno >= MAX_BPF_REG)) {
1717                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1718                 /* Something bad happened, let's kill all regs except FP */
1719                 for (regno = 0; regno < BPF_REG_FP; regno++)
1720                         __mark_reg_not_init(env, regs + regno);
1721                 return;
1722         }
1723         __mark_reg_unknown(env, regs + regno);
1724 }
1725
1726 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1727                                 struct bpf_reg_state *reg)
1728 {
1729         __mark_reg_unknown(env, reg);
1730         reg->type = NOT_INIT;
1731 }
1732
1733 static void mark_reg_not_init(struct bpf_verifier_env *env,
1734                               struct bpf_reg_state *regs, u32 regno)
1735 {
1736         if (WARN_ON(regno >= MAX_BPF_REG)) {
1737                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1738                 /* Something bad happened, let's kill all regs except FP */
1739                 for (regno = 0; regno < BPF_REG_FP; regno++)
1740                         __mark_reg_not_init(env, regs + regno);
1741                 return;
1742         }
1743         __mark_reg_not_init(env, regs + regno);
1744 }
1745
1746 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1747                             struct bpf_reg_state *regs, u32 regno,
1748                             enum bpf_reg_type reg_type,
1749                             struct btf *btf, u32 btf_id,
1750                             enum bpf_type_flag flag)
1751 {
1752         if (reg_type == SCALAR_VALUE) {
1753                 mark_reg_unknown(env, regs, regno);
1754                 return;
1755         }
1756         mark_reg_known_zero(env, regs, regno);
1757         regs[regno].type = PTR_TO_BTF_ID | flag;
1758         regs[regno].btf = btf;
1759         regs[regno].btf_id = btf_id;
1760 }
1761
1762 #define DEF_NOT_SUBREG  (0)
1763 static void init_reg_state(struct bpf_verifier_env *env,
1764                            struct bpf_func_state *state)
1765 {
1766         struct bpf_reg_state *regs = state->regs;
1767         int i;
1768
1769         for (i = 0; i < MAX_BPF_REG; i++) {
1770                 mark_reg_not_init(env, regs, i);
1771                 regs[i].live = REG_LIVE_NONE;
1772                 regs[i].parent = NULL;
1773                 regs[i].subreg_def = DEF_NOT_SUBREG;
1774         }
1775
1776         /* frame pointer */
1777         regs[BPF_REG_FP].type = PTR_TO_STACK;
1778         mark_reg_known_zero(env, regs, BPF_REG_FP);
1779         regs[BPF_REG_FP].frameno = state->frameno;
1780 }
1781
1782 #define BPF_MAIN_FUNC (-1)
1783 static void init_func_state(struct bpf_verifier_env *env,
1784                             struct bpf_func_state *state,
1785                             int callsite, int frameno, int subprogno)
1786 {
1787         state->callsite = callsite;
1788         state->frameno = frameno;
1789         state->subprogno = subprogno;
1790         state->callback_ret_range = tnum_range(0, 0);
1791         init_reg_state(env, state);
1792         mark_verifier_state_scratched(env);
1793 }
1794
1795 /* Similar to push_stack(), but for async callbacks */
1796 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1797                                                 int insn_idx, int prev_insn_idx,
1798                                                 int subprog)
1799 {
1800         struct bpf_verifier_stack_elem *elem;
1801         struct bpf_func_state *frame;
1802
1803         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1804         if (!elem)
1805                 goto err;
1806
1807         elem->insn_idx = insn_idx;
1808         elem->prev_insn_idx = prev_insn_idx;
1809         elem->next = env->head;
1810         elem->log_pos = env->log.len_used;
1811         env->head = elem;
1812         env->stack_size++;
1813         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1814                 verbose(env,
1815                         "The sequence of %d jumps is too complex for async cb.\n",
1816                         env->stack_size);
1817                 goto err;
1818         }
1819         /* Unlike push_stack() do not copy_verifier_state().
1820          * The caller state doesn't matter.
1821          * This is async callback. It starts in a fresh stack.
1822          * Initialize it similar to do_check_common().
1823          */
1824         elem->st.branches = 1;
1825         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1826         if (!frame)
1827                 goto err;
1828         init_func_state(env, frame,
1829                         BPF_MAIN_FUNC /* callsite */,
1830                         0 /* frameno within this callchain */,
1831                         subprog /* subprog number within this prog */);
1832         elem->st.frame[0] = frame;
1833         return &elem->st;
1834 err:
1835         free_verifier_state(env->cur_state, true);
1836         env->cur_state = NULL;
1837         /* pop all elements and return */
1838         while (!pop_stack(env, NULL, NULL, false));
1839         return NULL;
1840 }
1841
1842
1843 enum reg_arg_type {
1844         SRC_OP,         /* register is used as source operand */
1845         DST_OP,         /* register is used as destination operand */
1846         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1847 };
1848
1849 static int cmp_subprogs(const void *a, const void *b)
1850 {
1851         return ((struct bpf_subprog_info *)a)->start -
1852                ((struct bpf_subprog_info *)b)->start;
1853 }
1854
1855 static int find_subprog(struct bpf_verifier_env *env, int off)
1856 {
1857         struct bpf_subprog_info *p;
1858
1859         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1860                     sizeof(env->subprog_info[0]), cmp_subprogs);
1861         if (!p)
1862                 return -ENOENT;
1863         return p - env->subprog_info;
1864
1865 }
1866
1867 static int add_subprog(struct bpf_verifier_env *env, int off)
1868 {
1869         int insn_cnt = env->prog->len;
1870         int ret;
1871
1872         if (off >= insn_cnt || off < 0) {
1873                 verbose(env, "call to invalid destination\n");
1874                 return -EINVAL;
1875         }
1876         ret = find_subprog(env, off);
1877         if (ret >= 0)
1878                 return ret;
1879         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1880                 verbose(env, "too many subprograms\n");
1881                 return -E2BIG;
1882         }
1883         /* determine subprog starts. The end is one before the next starts */
1884         env->subprog_info[env->subprog_cnt++].start = off;
1885         sort(env->subprog_info, env->subprog_cnt,
1886              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1887         return env->subprog_cnt - 1;
1888 }
1889
1890 #define MAX_KFUNC_DESCS 256
1891 #define MAX_KFUNC_BTFS  256
1892
1893 struct bpf_kfunc_desc {
1894         struct btf_func_model func_model;
1895         u32 func_id;
1896         s32 imm;
1897         u16 offset;
1898 };
1899
1900 struct bpf_kfunc_btf {
1901         struct btf *btf;
1902         struct module *module;
1903         u16 offset;
1904 };
1905
1906 struct bpf_kfunc_desc_tab {
1907         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1908         u32 nr_descs;
1909 };
1910
1911 struct bpf_kfunc_btf_tab {
1912         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1913         u32 nr_descs;
1914 };
1915
1916 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1917 {
1918         const struct bpf_kfunc_desc *d0 = a;
1919         const struct bpf_kfunc_desc *d1 = b;
1920
1921         /* func_id is not greater than BTF_MAX_TYPE */
1922         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1923 }
1924
1925 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1926 {
1927         const struct bpf_kfunc_btf *d0 = a;
1928         const struct bpf_kfunc_btf *d1 = b;
1929
1930         return d0->offset - d1->offset;
1931 }
1932
1933 static const struct bpf_kfunc_desc *
1934 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1935 {
1936         struct bpf_kfunc_desc desc = {
1937                 .func_id = func_id,
1938                 .offset = offset,
1939         };
1940         struct bpf_kfunc_desc_tab *tab;
1941
1942         tab = prog->aux->kfunc_tab;
1943         return bsearch(&desc, tab->descs, tab->nr_descs,
1944                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1945 }
1946
1947 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1948                                          s16 offset)
1949 {
1950         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1951         struct bpf_kfunc_btf_tab *tab;
1952         struct bpf_kfunc_btf *b;
1953         struct module *mod;
1954         struct btf *btf;
1955         int btf_fd;
1956
1957         tab = env->prog->aux->kfunc_btf_tab;
1958         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1959                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1960         if (!b) {
1961                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1962                         verbose(env, "too many different module BTFs\n");
1963                         return ERR_PTR(-E2BIG);
1964                 }
1965
1966                 if (bpfptr_is_null(env->fd_array)) {
1967                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1968                         return ERR_PTR(-EPROTO);
1969                 }
1970
1971                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1972                                             offset * sizeof(btf_fd),
1973                                             sizeof(btf_fd)))
1974                         return ERR_PTR(-EFAULT);
1975
1976                 btf = btf_get_by_fd(btf_fd);
1977                 if (IS_ERR(btf)) {
1978                         verbose(env, "invalid module BTF fd specified\n");
1979                         return btf;
1980                 }
1981
1982                 if (!btf_is_module(btf)) {
1983                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1984                         btf_put(btf);
1985                         return ERR_PTR(-EINVAL);
1986                 }
1987
1988                 mod = btf_try_get_module(btf);
1989                 if (!mod) {
1990                         btf_put(btf);
1991                         return ERR_PTR(-ENXIO);
1992                 }
1993
1994                 b = &tab->descs[tab->nr_descs++];
1995                 b->btf = btf;
1996                 b->module = mod;
1997                 b->offset = offset;
1998
1999                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2000                      kfunc_btf_cmp_by_off, NULL);
2001         }
2002         return b->btf;
2003 }
2004
2005 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2006 {
2007         if (!tab)
2008                 return;
2009
2010         while (tab->nr_descs--) {
2011                 module_put(tab->descs[tab->nr_descs].module);
2012                 btf_put(tab->descs[tab->nr_descs].btf);
2013         }
2014         kfree(tab);
2015 }
2016
2017 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2018 {
2019         if (offset) {
2020                 if (offset < 0) {
2021                         /* In the future, this can be allowed to increase limit
2022                          * of fd index into fd_array, interpreted as u16.
2023                          */
2024                         verbose(env, "negative offset disallowed for kernel module function call\n");
2025                         return ERR_PTR(-EINVAL);
2026                 }
2027
2028                 return __find_kfunc_desc_btf(env, offset);
2029         }
2030         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2031 }
2032
2033 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2034 {
2035         const struct btf_type *func, *func_proto;
2036         struct bpf_kfunc_btf_tab *btf_tab;
2037         struct bpf_kfunc_desc_tab *tab;
2038         struct bpf_prog_aux *prog_aux;
2039         struct bpf_kfunc_desc *desc;
2040         const char *func_name;
2041         struct btf *desc_btf;
2042         unsigned long call_imm;
2043         unsigned long addr;
2044         int err;
2045
2046         prog_aux = env->prog->aux;
2047         tab = prog_aux->kfunc_tab;
2048         btf_tab = prog_aux->kfunc_btf_tab;
2049         if (!tab) {
2050                 if (!btf_vmlinux) {
2051                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2052                         return -ENOTSUPP;
2053                 }
2054
2055                 if (!env->prog->jit_requested) {
2056                         verbose(env, "JIT is required for calling kernel function\n");
2057                         return -ENOTSUPP;
2058                 }
2059
2060                 if (!bpf_jit_supports_kfunc_call()) {
2061                         verbose(env, "JIT does not support calling kernel function\n");
2062                         return -ENOTSUPP;
2063                 }
2064
2065                 if (!env->prog->gpl_compatible) {
2066                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2067                         return -EINVAL;
2068                 }
2069
2070                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2071                 if (!tab)
2072                         return -ENOMEM;
2073                 prog_aux->kfunc_tab = tab;
2074         }
2075
2076         /* func_id == 0 is always invalid, but instead of returning an error, be
2077          * conservative and wait until the code elimination pass before returning
2078          * error, so that invalid calls that get pruned out can be in BPF programs
2079          * loaded from userspace.  It is also required that offset be untouched
2080          * for such calls.
2081          */
2082         if (!func_id && !offset)
2083                 return 0;
2084
2085         if (!btf_tab && offset) {
2086                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2087                 if (!btf_tab)
2088                         return -ENOMEM;
2089                 prog_aux->kfunc_btf_tab = btf_tab;
2090         }
2091
2092         desc_btf = find_kfunc_desc_btf(env, offset);
2093         if (IS_ERR(desc_btf)) {
2094                 verbose(env, "failed to find BTF for kernel function\n");
2095                 return PTR_ERR(desc_btf);
2096         }
2097
2098         if (find_kfunc_desc(env->prog, func_id, offset))
2099                 return 0;
2100
2101         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2102                 verbose(env, "too many different kernel function calls\n");
2103                 return -E2BIG;
2104         }
2105
2106         func = btf_type_by_id(desc_btf, func_id);
2107         if (!func || !btf_type_is_func(func)) {
2108                 verbose(env, "kernel btf_id %u is not a function\n",
2109                         func_id);
2110                 return -EINVAL;
2111         }
2112         func_proto = btf_type_by_id(desc_btf, func->type);
2113         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2114                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2115                         func_id);
2116                 return -EINVAL;
2117         }
2118
2119         func_name = btf_name_by_offset(desc_btf, func->name_off);
2120         addr = kallsyms_lookup_name(func_name);
2121         if (!addr) {
2122                 verbose(env, "cannot find address for kernel function %s\n",
2123                         func_name);
2124                 return -EINVAL;
2125         }
2126
2127         call_imm = BPF_CALL_IMM(addr);
2128         /* Check whether or not the relative offset overflows desc->imm */
2129         if ((unsigned long)(s32)call_imm != call_imm) {
2130                 verbose(env, "address of kernel function %s is out of range\n",
2131                         func_name);
2132                 return -EINVAL;
2133         }
2134
2135         desc = &tab->descs[tab->nr_descs++];
2136         desc->func_id = func_id;
2137         desc->imm = call_imm;
2138         desc->offset = offset;
2139         err = btf_distill_func_proto(&env->log, desc_btf,
2140                                      func_proto, func_name,
2141                                      &desc->func_model);
2142         if (!err)
2143                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2144                      kfunc_desc_cmp_by_id_off, NULL);
2145         return err;
2146 }
2147
2148 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2149 {
2150         const struct bpf_kfunc_desc *d0 = a;
2151         const struct bpf_kfunc_desc *d1 = b;
2152
2153         if (d0->imm > d1->imm)
2154                 return 1;
2155         else if (d0->imm < d1->imm)
2156                 return -1;
2157         return 0;
2158 }
2159
2160 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2161 {
2162         struct bpf_kfunc_desc_tab *tab;
2163
2164         tab = prog->aux->kfunc_tab;
2165         if (!tab)
2166                 return;
2167
2168         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2169              kfunc_desc_cmp_by_imm, NULL);
2170 }
2171
2172 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2173 {
2174         return !!prog->aux->kfunc_tab;
2175 }
2176
2177 const struct btf_func_model *
2178 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2179                          const struct bpf_insn *insn)
2180 {
2181         const struct bpf_kfunc_desc desc = {
2182                 .imm = insn->imm,
2183         };
2184         const struct bpf_kfunc_desc *res;
2185         struct bpf_kfunc_desc_tab *tab;
2186
2187         tab = prog->aux->kfunc_tab;
2188         res = bsearch(&desc, tab->descs, tab->nr_descs,
2189                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2190
2191         return res ? &res->func_model : NULL;
2192 }
2193
2194 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2195 {
2196         struct bpf_subprog_info *subprog = env->subprog_info;
2197         struct bpf_insn *insn = env->prog->insnsi;
2198         int i, ret, insn_cnt = env->prog->len;
2199
2200         /* Add entry function. */
2201         ret = add_subprog(env, 0);
2202         if (ret)
2203                 return ret;
2204
2205         for (i = 0; i < insn_cnt; i++, insn++) {
2206                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2207                     !bpf_pseudo_kfunc_call(insn))
2208                         continue;
2209
2210                 if (!env->bpf_capable) {
2211                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2212                         return -EPERM;
2213                 }
2214
2215                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2216                         ret = add_subprog(env, i + insn->imm + 1);
2217                 else
2218                         ret = add_kfunc_call(env, insn->imm, insn->off);
2219
2220                 if (ret < 0)
2221                         return ret;
2222         }
2223
2224         /* Add a fake 'exit' subprog which could simplify subprog iteration
2225          * logic. 'subprog_cnt' should not be increased.
2226          */
2227         subprog[env->subprog_cnt].start = insn_cnt;
2228
2229         if (env->log.level & BPF_LOG_LEVEL2)
2230                 for (i = 0; i < env->subprog_cnt; i++)
2231                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2232
2233         return 0;
2234 }
2235
2236 static int check_subprogs(struct bpf_verifier_env *env)
2237 {
2238         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2239         struct bpf_subprog_info *subprog = env->subprog_info;
2240         struct bpf_insn *insn = env->prog->insnsi;
2241         int insn_cnt = env->prog->len;
2242
2243         /* now check that all jumps are within the same subprog */
2244         subprog_start = subprog[cur_subprog].start;
2245         subprog_end = subprog[cur_subprog + 1].start;
2246         for (i = 0; i < insn_cnt; i++) {
2247                 u8 code = insn[i].code;
2248
2249                 if (code == (BPF_JMP | BPF_CALL) &&
2250                     insn[i].imm == BPF_FUNC_tail_call &&
2251                     insn[i].src_reg != BPF_PSEUDO_CALL)
2252                         subprog[cur_subprog].has_tail_call = true;
2253                 if (BPF_CLASS(code) == BPF_LD &&
2254                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2255                         subprog[cur_subprog].has_ld_abs = true;
2256                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2257                         goto next;
2258                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2259                         goto next;
2260                 off = i + insn[i].off + 1;
2261                 if (off < subprog_start || off >= subprog_end) {
2262                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2263                         return -EINVAL;
2264                 }
2265 next:
2266                 if (i == subprog_end - 1) {
2267                         /* to avoid fall-through from one subprog into another
2268                          * the last insn of the subprog should be either exit
2269                          * or unconditional jump back
2270                          */
2271                         if (code != (BPF_JMP | BPF_EXIT) &&
2272                             code != (BPF_JMP | BPF_JA)) {
2273                                 verbose(env, "last insn is not an exit or jmp\n");
2274                                 return -EINVAL;
2275                         }
2276                         subprog_start = subprog_end;
2277                         cur_subprog++;
2278                         if (cur_subprog < env->subprog_cnt)
2279                                 subprog_end = subprog[cur_subprog + 1].start;
2280                 }
2281         }
2282         return 0;
2283 }
2284
2285 /* Parentage chain of this register (or stack slot) should take care of all
2286  * issues like callee-saved registers, stack slot allocation time, etc.
2287  */
2288 static int mark_reg_read(struct bpf_verifier_env *env,
2289                          const struct bpf_reg_state *state,
2290                          struct bpf_reg_state *parent, u8 flag)
2291 {
2292         bool writes = parent == state->parent; /* Observe write marks */
2293         int cnt = 0;
2294
2295         while (parent) {
2296                 /* if read wasn't screened by an earlier write ... */
2297                 if (writes && state->live & REG_LIVE_WRITTEN)
2298                         break;
2299                 if (parent->live & REG_LIVE_DONE) {
2300                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2301                                 reg_type_str(env, parent->type),
2302                                 parent->var_off.value, parent->off);
2303                         return -EFAULT;
2304                 }
2305                 /* The first condition is more likely to be true than the
2306                  * second, checked it first.
2307                  */
2308                 if ((parent->live & REG_LIVE_READ) == flag ||
2309                     parent->live & REG_LIVE_READ64)
2310                         /* The parentage chain never changes and
2311                          * this parent was already marked as LIVE_READ.
2312                          * There is no need to keep walking the chain again and
2313                          * keep re-marking all parents as LIVE_READ.
2314                          * This case happens when the same register is read
2315                          * multiple times without writes into it in-between.
2316                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2317                          * then no need to set the weak REG_LIVE_READ32.
2318                          */
2319                         break;
2320                 /* ... then we depend on parent's value */
2321                 parent->live |= flag;
2322                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2323                 if (flag == REG_LIVE_READ64)
2324                         parent->live &= ~REG_LIVE_READ32;
2325                 state = parent;
2326                 parent = state->parent;
2327                 writes = true;
2328                 cnt++;
2329         }
2330
2331         if (env->longest_mark_read_walk < cnt)
2332                 env->longest_mark_read_walk = cnt;
2333         return 0;
2334 }
2335
2336 /* This function is supposed to be used by the following 32-bit optimization
2337  * code only. It returns TRUE if the source or destination register operates
2338  * on 64-bit, otherwise return FALSE.
2339  */
2340 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2341                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2342 {
2343         u8 code, class, op;
2344
2345         code = insn->code;
2346         class = BPF_CLASS(code);
2347         op = BPF_OP(code);
2348         if (class == BPF_JMP) {
2349                 /* BPF_EXIT for "main" will reach here. Return TRUE
2350                  * conservatively.
2351                  */
2352                 if (op == BPF_EXIT)
2353                         return true;
2354                 if (op == BPF_CALL) {
2355                         /* BPF to BPF call will reach here because of marking
2356                          * caller saved clobber with DST_OP_NO_MARK for which we
2357                          * don't care the register def because they are anyway
2358                          * marked as NOT_INIT already.
2359                          */
2360                         if (insn->src_reg == BPF_PSEUDO_CALL)
2361                                 return false;
2362                         /* Helper call will reach here because of arg type
2363                          * check, conservatively return TRUE.
2364                          */
2365                         if (t == SRC_OP)
2366                                 return true;
2367
2368                         return false;
2369                 }
2370         }
2371
2372         if (class == BPF_ALU64 || class == BPF_JMP ||
2373             /* BPF_END always use BPF_ALU class. */
2374             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2375                 return true;
2376
2377         if (class == BPF_ALU || class == BPF_JMP32)
2378                 return false;
2379
2380         if (class == BPF_LDX) {
2381                 if (t != SRC_OP)
2382                         return BPF_SIZE(code) == BPF_DW;
2383                 /* LDX source must be ptr. */
2384                 return true;
2385         }
2386
2387         if (class == BPF_STX) {
2388                 /* BPF_STX (including atomic variants) has multiple source
2389                  * operands, one of which is a ptr. Check whether the caller is
2390                  * asking about it.
2391                  */
2392                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2393                         return true;
2394                 return BPF_SIZE(code) == BPF_DW;
2395         }
2396
2397         if (class == BPF_LD) {
2398                 u8 mode = BPF_MODE(code);
2399
2400                 /* LD_IMM64 */
2401                 if (mode == BPF_IMM)
2402                         return true;
2403
2404                 /* Both LD_IND and LD_ABS return 32-bit data. */
2405                 if (t != SRC_OP)
2406                         return  false;
2407
2408                 /* Implicit ctx ptr. */
2409                 if (regno == BPF_REG_6)
2410                         return true;
2411
2412                 /* Explicit source could be any width. */
2413                 return true;
2414         }
2415
2416         if (class == BPF_ST)
2417                 /* The only source register for BPF_ST is a ptr. */
2418                 return true;
2419
2420         /* Conservatively return true at default. */
2421         return true;
2422 }
2423
2424 /* Return the regno defined by the insn, or -1. */
2425 static int insn_def_regno(const struct bpf_insn *insn)
2426 {
2427         switch (BPF_CLASS(insn->code)) {
2428         case BPF_JMP:
2429         case BPF_JMP32:
2430         case BPF_ST:
2431                 return -1;
2432         case BPF_STX:
2433                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2434                     (insn->imm & BPF_FETCH)) {
2435                         if (insn->imm == BPF_CMPXCHG)
2436                                 return BPF_REG_0;
2437                         else
2438                                 return insn->src_reg;
2439                 } else {
2440                         return -1;
2441                 }
2442         default:
2443                 return insn->dst_reg;
2444         }
2445 }
2446
2447 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2448 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2449 {
2450         int dst_reg = insn_def_regno(insn);
2451
2452         if (dst_reg == -1)
2453                 return false;
2454
2455         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2456 }
2457
2458 static void mark_insn_zext(struct bpf_verifier_env *env,
2459                            struct bpf_reg_state *reg)
2460 {
2461         s32 def_idx = reg->subreg_def;
2462
2463         if (def_idx == DEF_NOT_SUBREG)
2464                 return;
2465
2466         env->insn_aux_data[def_idx - 1].zext_dst = true;
2467         /* The dst will be zero extended, so won't be sub-register anymore. */
2468         reg->subreg_def = DEF_NOT_SUBREG;
2469 }
2470
2471 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2472                          enum reg_arg_type t)
2473 {
2474         struct bpf_verifier_state *vstate = env->cur_state;
2475         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2476         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2477         struct bpf_reg_state *reg, *regs = state->regs;
2478         bool rw64;
2479
2480         if (regno >= MAX_BPF_REG) {
2481                 verbose(env, "R%d is invalid\n", regno);
2482                 return -EINVAL;
2483         }
2484
2485         mark_reg_scratched(env, regno);
2486
2487         reg = &regs[regno];
2488         rw64 = is_reg64(env, insn, regno, reg, t);
2489         if (t == SRC_OP) {
2490                 /* check whether register used as source operand can be read */
2491                 if (reg->type == NOT_INIT) {
2492                         verbose(env, "R%d !read_ok\n", regno);
2493                         return -EACCES;
2494                 }
2495                 /* We don't need to worry about FP liveness because it's read-only */
2496                 if (regno == BPF_REG_FP)
2497                         return 0;
2498
2499                 if (rw64)
2500                         mark_insn_zext(env, reg);
2501
2502                 return mark_reg_read(env, reg, reg->parent,
2503                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2504         } else {
2505                 /* check whether register used as dest operand can be written to */
2506                 if (regno == BPF_REG_FP) {
2507                         verbose(env, "frame pointer is read only\n");
2508                         return -EACCES;
2509                 }
2510                 reg->live |= REG_LIVE_WRITTEN;
2511                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2512                 if (t == DST_OP)
2513                         mark_reg_unknown(env, regs, regno);
2514         }
2515         return 0;
2516 }
2517
2518 /* for any branch, call, exit record the history of jmps in the given state */
2519 static int push_jmp_history(struct bpf_verifier_env *env,
2520                             struct bpf_verifier_state *cur)
2521 {
2522         u32 cnt = cur->jmp_history_cnt;
2523         struct bpf_idx_pair *p;
2524         size_t alloc_size;
2525
2526         cnt++;
2527         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2528         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2529         if (!p)
2530                 return -ENOMEM;
2531         p[cnt - 1].idx = env->insn_idx;
2532         p[cnt - 1].prev_idx = env->prev_insn_idx;
2533         cur->jmp_history = p;
2534         cur->jmp_history_cnt = cnt;
2535         return 0;
2536 }
2537
2538 /* Backtrack one insn at a time. If idx is not at the top of recorded
2539  * history then previous instruction came from straight line execution.
2540  */
2541 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2542                              u32 *history)
2543 {
2544         u32 cnt = *history;
2545
2546         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2547                 i = st->jmp_history[cnt - 1].prev_idx;
2548                 (*history)--;
2549         } else {
2550                 i--;
2551         }
2552         return i;
2553 }
2554
2555 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2556 {
2557         const struct btf_type *func;
2558         struct btf *desc_btf;
2559
2560         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2561                 return NULL;
2562
2563         desc_btf = find_kfunc_desc_btf(data, insn->off);
2564         if (IS_ERR(desc_btf))
2565                 return "<error>";
2566
2567         func = btf_type_by_id(desc_btf, insn->imm);
2568         return btf_name_by_offset(desc_btf, func->name_off);
2569 }
2570
2571 /* For given verifier state backtrack_insn() is called from the last insn to
2572  * the first insn. Its purpose is to compute a bitmask of registers and
2573  * stack slots that needs precision in the parent verifier state.
2574  */
2575 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2576                           u32 *reg_mask, u64 *stack_mask)
2577 {
2578         const struct bpf_insn_cbs cbs = {
2579                 .cb_call        = disasm_kfunc_name,
2580                 .cb_print       = verbose,
2581                 .private_data   = env,
2582         };
2583         struct bpf_insn *insn = env->prog->insnsi + idx;
2584         u8 class = BPF_CLASS(insn->code);
2585         u8 opcode = BPF_OP(insn->code);
2586         u8 mode = BPF_MODE(insn->code);
2587         u32 dreg = 1u << insn->dst_reg;
2588         u32 sreg = 1u << insn->src_reg;
2589         u32 spi;
2590
2591         if (insn->code == 0)
2592                 return 0;
2593         if (env->log.level & BPF_LOG_LEVEL2) {
2594                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2595                 verbose(env, "%d: ", idx);
2596                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2597         }
2598
2599         if (class == BPF_ALU || class == BPF_ALU64) {
2600                 if (!(*reg_mask & dreg))
2601                         return 0;
2602                 if (opcode == BPF_MOV) {
2603                         if (BPF_SRC(insn->code) == BPF_X) {
2604                                 /* dreg = sreg
2605                                  * dreg needs precision after this insn
2606                                  * sreg needs precision before this insn
2607                                  */
2608                                 *reg_mask &= ~dreg;
2609                                 *reg_mask |= sreg;
2610                         } else {
2611                                 /* dreg = K
2612                                  * dreg needs precision after this insn.
2613                                  * Corresponding register is already marked
2614                                  * as precise=true in this verifier state.
2615                                  * No further markings in parent are necessary
2616                                  */
2617                                 *reg_mask &= ~dreg;
2618                         }
2619                 } else {
2620                         if (BPF_SRC(insn->code) == BPF_X) {
2621                                 /* dreg += sreg
2622                                  * both dreg and sreg need precision
2623                                  * before this insn
2624                                  */
2625                                 *reg_mask |= sreg;
2626                         } /* else dreg += K
2627                            * dreg still needs precision before this insn
2628                            */
2629                 }
2630         } else if (class == BPF_LDX) {
2631                 if (!(*reg_mask & dreg))
2632                         return 0;
2633                 *reg_mask &= ~dreg;
2634
2635                 /* scalars can only be spilled into stack w/o losing precision.
2636                  * Load from any other memory can be zero extended.
2637                  * The desire to keep that precision is already indicated
2638                  * by 'precise' mark in corresponding register of this state.
2639                  * No further tracking necessary.
2640                  */
2641                 if (insn->src_reg != BPF_REG_FP)
2642                         return 0;
2643
2644                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2645                  * that [fp - off] slot contains scalar that needs to be
2646                  * tracked with precision
2647                  */
2648                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2649                 if (spi >= 64) {
2650                         verbose(env, "BUG spi %d\n", spi);
2651                         WARN_ONCE(1, "verifier backtracking bug");
2652                         return -EFAULT;
2653                 }
2654                 *stack_mask |= 1ull << spi;
2655         } else if (class == BPF_STX || class == BPF_ST) {
2656                 if (*reg_mask & dreg)
2657                         /* stx & st shouldn't be using _scalar_ dst_reg
2658                          * to access memory. It means backtracking
2659                          * encountered a case of pointer subtraction.
2660                          */
2661                         return -ENOTSUPP;
2662                 /* scalars can only be spilled into stack */
2663                 if (insn->dst_reg != BPF_REG_FP)
2664                         return 0;
2665                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2666                 if (spi >= 64) {
2667                         verbose(env, "BUG spi %d\n", spi);
2668                         WARN_ONCE(1, "verifier backtracking bug");
2669                         return -EFAULT;
2670                 }
2671                 if (!(*stack_mask & (1ull << spi)))
2672                         return 0;
2673                 *stack_mask &= ~(1ull << spi);
2674                 if (class == BPF_STX)
2675                         *reg_mask |= sreg;
2676         } else if (class == BPF_JMP || class == BPF_JMP32) {
2677                 if (opcode == BPF_CALL) {
2678                         if (insn->src_reg == BPF_PSEUDO_CALL)
2679                                 return -ENOTSUPP;
2680                         /* BPF helpers that invoke callback subprogs are
2681                          * equivalent to BPF_PSEUDO_CALL above
2682                          */
2683                         if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2684                                 return -ENOTSUPP;
2685                         /* regular helper call sets R0 */
2686                         *reg_mask &= ~1;
2687                         if (*reg_mask & 0x3f) {
2688                                 /* if backtracing was looking for registers R1-R5
2689                                  * they should have been found already.
2690                                  */
2691                                 verbose(env, "BUG regs %x\n", *reg_mask);
2692                                 WARN_ONCE(1, "verifier backtracking bug");
2693                                 return -EFAULT;
2694                         }
2695                 } else if (opcode == BPF_EXIT) {
2696                         return -ENOTSUPP;
2697                 }
2698         } else if (class == BPF_LD) {
2699                 if (!(*reg_mask & dreg))
2700                         return 0;
2701                 *reg_mask &= ~dreg;
2702                 /* It's ld_imm64 or ld_abs or ld_ind.
2703                  * For ld_imm64 no further tracking of precision
2704                  * into parent is necessary
2705                  */
2706                 if (mode == BPF_IND || mode == BPF_ABS)
2707                         /* to be analyzed */
2708                         return -ENOTSUPP;
2709         }
2710         return 0;
2711 }
2712
2713 /* the scalar precision tracking algorithm:
2714  * . at the start all registers have precise=false.
2715  * . scalar ranges are tracked as normal through alu and jmp insns.
2716  * . once precise value of the scalar register is used in:
2717  *   .  ptr + scalar alu
2718  *   . if (scalar cond K|scalar)
2719  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2720  *   backtrack through the verifier states and mark all registers and
2721  *   stack slots with spilled constants that these scalar regisers
2722  *   should be precise.
2723  * . during state pruning two registers (or spilled stack slots)
2724  *   are equivalent if both are not precise.
2725  *
2726  * Note the verifier cannot simply walk register parentage chain,
2727  * since many different registers and stack slots could have been
2728  * used to compute single precise scalar.
2729  *
2730  * The approach of starting with precise=true for all registers and then
2731  * backtrack to mark a register as not precise when the verifier detects
2732  * that program doesn't care about specific value (e.g., when helper
2733  * takes register as ARG_ANYTHING parameter) is not safe.
2734  *
2735  * It's ok to walk single parentage chain of the verifier states.
2736  * It's possible that this backtracking will go all the way till 1st insn.
2737  * All other branches will be explored for needing precision later.
2738  *
2739  * The backtracking needs to deal with cases like:
2740  *   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)
2741  * r9 -= r8
2742  * r5 = r9
2743  * if r5 > 0x79f goto pc+7
2744  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2745  * r5 += 1
2746  * ...
2747  * call bpf_perf_event_output#25
2748  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2749  *
2750  * and this case:
2751  * r6 = 1
2752  * call foo // uses callee's r6 inside to compute r0
2753  * r0 += r6
2754  * if r0 == 0 goto
2755  *
2756  * to track above reg_mask/stack_mask needs to be independent for each frame.
2757  *
2758  * Also if parent's curframe > frame where backtracking started,
2759  * the verifier need to mark registers in both frames, otherwise callees
2760  * may incorrectly prune callers. This is similar to
2761  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2762  *
2763  * For now backtracking falls back into conservative marking.
2764  */
2765 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2766                                      struct bpf_verifier_state *st)
2767 {
2768         struct bpf_func_state *func;
2769         struct bpf_reg_state *reg;
2770         int i, j;
2771
2772         /* big hammer: mark all scalars precise in this path.
2773          * pop_stack may still get !precise scalars.
2774          * We also skip current state and go straight to first parent state,
2775          * because precision markings in current non-checkpointed state are
2776          * not needed. See why in the comment in __mark_chain_precision below.
2777          */
2778         for (st = st->parent; st; st = st->parent) {
2779                 for (i = 0; i <= st->curframe; i++) {
2780                         func = st->frame[i];
2781                         for (j = 0; j < BPF_REG_FP; j++) {
2782                                 reg = &func->regs[j];
2783                                 if (reg->type != SCALAR_VALUE)
2784                                         continue;
2785                                 reg->precise = true;
2786                         }
2787                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2788                                 if (!is_spilled_reg(&func->stack[j]))
2789                                         continue;
2790                                 reg = &func->stack[j].spilled_ptr;
2791                                 if (reg->type != SCALAR_VALUE)
2792                                         continue;
2793                                 reg->precise = true;
2794                         }
2795                 }
2796         }
2797 }
2798
2799 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2800 {
2801         struct bpf_func_state *func;
2802         struct bpf_reg_state *reg;
2803         int i, j;
2804
2805         for (i = 0; i <= st->curframe; i++) {
2806                 func = st->frame[i];
2807                 for (j = 0; j < BPF_REG_FP; j++) {
2808                         reg = &func->regs[j];
2809                         if (reg->type != SCALAR_VALUE)
2810                                 continue;
2811                         reg->precise = false;
2812                 }
2813                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2814                         if (!is_spilled_reg(&func->stack[j]))
2815                                 continue;
2816                         reg = &func->stack[j].spilled_ptr;
2817                         if (reg->type != SCALAR_VALUE)
2818                                 continue;
2819                         reg->precise = false;
2820                 }
2821         }
2822 }
2823
2824 /*
2825  * __mark_chain_precision() backtracks BPF program instruction sequence and
2826  * chain of verifier states making sure that register *regno* (if regno >= 0)
2827  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2828  * SCALARS, as well as any other registers and slots that contribute to
2829  * a tracked state of given registers/stack slots, depending on specific BPF
2830  * assembly instructions (see backtrack_insns() for exact instruction handling
2831  * logic). This backtracking relies on recorded jmp_history and is able to
2832  * traverse entire chain of parent states. This process ends only when all the
2833  * necessary registers/slots and their transitive dependencies are marked as
2834  * precise.
2835  *
2836  * One important and subtle aspect is that precise marks *do not matter* in
2837  * the currently verified state (current state). It is important to understand
2838  * why this is the case.
2839  *
2840  * First, note that current state is the state that is not yet "checkpointed",
2841  * i.e., it is not yet put into env->explored_states, and it has no children
2842  * states as well. It's ephemeral, and can end up either a) being discarded if
2843  * compatible explored state is found at some point or BPF_EXIT instruction is
2844  * reached or b) checkpointed and put into env->explored_states, branching out
2845  * into one or more children states.
2846  *
2847  * In the former case, precise markings in current state are completely
2848  * ignored by state comparison code (see regsafe() for details). Only
2849  * checkpointed ("old") state precise markings are important, and if old
2850  * state's register/slot is precise, regsafe() assumes current state's
2851  * register/slot as precise and checks value ranges exactly and precisely. If
2852  * states turn out to be compatible, current state's necessary precise
2853  * markings and any required parent states' precise markings are enforced
2854  * after the fact with propagate_precision() logic, after the fact. But it's
2855  * important to realize that in this case, even after marking current state
2856  * registers/slots as precise, we immediately discard current state. So what
2857  * actually matters is any of the precise markings propagated into current
2858  * state's parent states, which are always checkpointed (due to b) case above).
2859  * As such, for scenario a) it doesn't matter if current state has precise
2860  * markings set or not.
2861  *
2862  * Now, for the scenario b), checkpointing and forking into child(ren)
2863  * state(s). Note that before current state gets to checkpointing step, any
2864  * processed instruction always assumes precise SCALAR register/slot
2865  * knowledge: if precise value or range is useful to prune jump branch, BPF
2866  * verifier takes this opportunity enthusiastically. Similarly, when
2867  * register's value is used to calculate offset or memory address, exact
2868  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2869  * what we mentioned above about state comparison ignoring precise markings
2870  * during state comparison, BPF verifier ignores and also assumes precise
2871  * markings *at will* during instruction verification process. But as verifier
2872  * assumes precision, it also propagates any precision dependencies across
2873  * parent states, which are not yet finalized, so can be further restricted
2874  * based on new knowledge gained from restrictions enforced by their children
2875  * states. This is so that once those parent states are finalized, i.e., when
2876  * they have no more active children state, state comparison logic in
2877  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2878  * required for correctness.
2879  *
2880  * To build a bit more intuition, note also that once a state is checkpointed,
2881  * the path we took to get to that state is not important. This is crucial
2882  * property for state pruning. When state is checkpointed and finalized at
2883  * some instruction index, it can be correctly and safely used to "short
2884  * circuit" any *compatible* state that reaches exactly the same instruction
2885  * index. I.e., if we jumped to that instruction from a completely different
2886  * code path than original finalized state was derived from, it doesn't
2887  * matter, current state can be discarded because from that instruction
2888  * forward having a compatible state will ensure we will safely reach the
2889  * exit. States describe preconditions for further exploration, but completely
2890  * forget the history of how we got here.
2891  *
2892  * This also means that even if we needed precise SCALAR range to get to
2893  * finalized state, but from that point forward *that same* SCALAR register is
2894  * never used in a precise context (i.e., it's precise value is not needed for
2895  * correctness), it's correct and safe to mark such register as "imprecise"
2896  * (i.e., precise marking set to false). This is what we rely on when we do
2897  * not set precise marking in current state. If no child state requires
2898  * precision for any given SCALAR register, it's safe to dictate that it can
2899  * be imprecise. If any child state does require this register to be precise,
2900  * we'll mark it precise later retroactively during precise markings
2901  * propagation from child state to parent states.
2902  *
2903  * Skipping precise marking setting in current state is a mild version of
2904  * relying on the above observation. But we can utilize this property even
2905  * more aggressively by proactively forgetting any precise marking in the
2906  * current state (which we inherited from the parent state), right before we
2907  * checkpoint it and branch off into new child state. This is done by
2908  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2909  * finalized states which help in short circuiting more future states.
2910  */
2911 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2912                                   int spi)
2913 {
2914         struct bpf_verifier_state *st = env->cur_state;
2915         int first_idx = st->first_insn_idx;
2916         int last_idx = env->insn_idx;
2917         struct bpf_func_state *func;
2918         struct bpf_reg_state *reg;
2919         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2920         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2921         bool skip_first = true;
2922         bool new_marks = false;
2923         int i, err;
2924
2925         if (!env->bpf_capable)
2926                 return 0;
2927
2928         /* Do sanity checks against current state of register and/or stack
2929          * slot, but don't set precise flag in current state, as precision
2930          * tracking in the current state is unnecessary.
2931          */
2932         func = st->frame[frame];
2933         if (regno >= 0) {
2934                 reg = &func->regs[regno];
2935                 if (reg->type != SCALAR_VALUE) {
2936                         WARN_ONCE(1, "backtracing misuse");
2937                         return -EFAULT;
2938                 }
2939                 new_marks = true;
2940         }
2941
2942         while (spi >= 0) {
2943                 if (!is_spilled_reg(&func->stack[spi])) {
2944                         stack_mask = 0;
2945                         break;
2946                 }
2947                 reg = &func->stack[spi].spilled_ptr;
2948                 if (reg->type != SCALAR_VALUE) {
2949                         stack_mask = 0;
2950                         break;
2951                 }
2952                 new_marks = true;
2953                 break;
2954         }
2955
2956         if (!new_marks)
2957                 return 0;
2958         if (!reg_mask && !stack_mask)
2959                 return 0;
2960
2961         for (;;) {
2962                 DECLARE_BITMAP(mask, 64);
2963                 u32 history = st->jmp_history_cnt;
2964
2965                 if (env->log.level & BPF_LOG_LEVEL2)
2966                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2967
2968                 if (last_idx < 0) {
2969                         /* we are at the entry into subprog, which
2970                          * is expected for global funcs, but only if
2971                          * requested precise registers are R1-R5
2972                          * (which are global func's input arguments)
2973                          */
2974                         if (st->curframe == 0 &&
2975                             st->frame[0]->subprogno > 0 &&
2976                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
2977                             stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2978                                 bitmap_from_u64(mask, reg_mask);
2979                                 for_each_set_bit(i, mask, 32) {
2980                                         reg = &st->frame[0]->regs[i];
2981                                         if (reg->type != SCALAR_VALUE) {
2982                                                 reg_mask &= ~(1u << i);
2983                                                 continue;
2984                                         }
2985                                         reg->precise = true;
2986                                 }
2987                                 return 0;
2988                         }
2989
2990                         verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2991                                 st->frame[0]->subprogno, reg_mask, stack_mask);
2992                         WARN_ONCE(1, "verifier backtracking bug");
2993                         return -EFAULT;
2994                 }
2995
2996                 for (i = last_idx;;) {
2997                         if (skip_first) {
2998                                 err = 0;
2999                                 skip_first = false;
3000                         } else {
3001                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3002                         }
3003                         if (err == -ENOTSUPP) {
3004                                 mark_all_scalars_precise(env, st);
3005                                 return 0;
3006                         } else if (err) {
3007                                 return err;
3008                         }
3009                         if (!reg_mask && !stack_mask)
3010                                 /* Found assignment(s) into tracked register in this state.
3011                                  * Since this state is already marked, just return.
3012                                  * Nothing to be tracked further in the parent state.
3013                                  */
3014                                 return 0;
3015                         if (i == first_idx)
3016                                 break;
3017                         i = get_prev_insn_idx(st, i, &history);
3018                         if (i >= env->prog->len) {
3019                                 /* This can happen if backtracking reached insn 0
3020                                  * and there are still reg_mask or stack_mask
3021                                  * to backtrack.
3022                                  * It means the backtracking missed the spot where
3023                                  * particular register was initialized with a constant.
3024                                  */
3025                                 verbose(env, "BUG backtracking idx %d\n", i);
3026                                 WARN_ONCE(1, "verifier backtracking bug");
3027                                 return -EFAULT;
3028                         }
3029                 }
3030                 st = st->parent;
3031                 if (!st)
3032                         break;
3033
3034                 new_marks = false;
3035                 func = st->frame[frame];
3036                 bitmap_from_u64(mask, reg_mask);
3037                 for_each_set_bit(i, mask, 32) {
3038                         reg = &func->regs[i];
3039                         if (reg->type != SCALAR_VALUE) {
3040                                 reg_mask &= ~(1u << i);
3041                                 continue;
3042                         }
3043                         if (!reg->precise)
3044                                 new_marks = true;
3045                         reg->precise = true;
3046                 }
3047
3048                 bitmap_from_u64(mask, stack_mask);
3049                 for_each_set_bit(i, mask, 64) {
3050                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
3051                                 /* the sequence of instructions:
3052                                  * 2: (bf) r3 = r10
3053                                  * 3: (7b) *(u64 *)(r3 -8) = r0
3054                                  * 4: (79) r4 = *(u64 *)(r10 -8)
3055                                  * doesn't contain jmps. It's backtracked
3056                                  * as a single block.
3057                                  * During backtracking insn 3 is not recognized as
3058                                  * stack access, so at the end of backtracking
3059                                  * stack slot fp-8 is still marked in stack_mask.
3060                                  * However the parent state may not have accessed
3061                                  * fp-8 and it's "unallocated" stack space.
3062                                  * In such case fallback to conservative.
3063                                  */
3064                                 mark_all_scalars_precise(env, st);
3065                                 return 0;
3066                         }
3067
3068                         if (!is_spilled_reg(&func->stack[i])) {
3069                                 stack_mask &= ~(1ull << i);
3070                                 continue;
3071                         }
3072                         reg = &func->stack[i].spilled_ptr;
3073                         if (reg->type != SCALAR_VALUE) {
3074                                 stack_mask &= ~(1ull << i);
3075                                 continue;
3076                         }
3077                         if (!reg->precise)
3078                                 new_marks = true;
3079                         reg->precise = true;
3080                 }
3081                 if (env->log.level & BPF_LOG_LEVEL2) {
3082                         verbose(env, "parent %s regs=%x stack=%llx marks:",
3083                                 new_marks ? "didn't have" : "already had",
3084                                 reg_mask, stack_mask);
3085                         print_verifier_state(env, func, true);
3086                 }
3087
3088                 if (!reg_mask && !stack_mask)
3089                         break;
3090                 if (!new_marks)
3091                         break;
3092
3093                 last_idx = st->last_insn_idx;
3094                 first_idx = st->first_insn_idx;
3095         }
3096         return 0;
3097 }
3098
3099 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3100 {
3101         return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3102 }
3103
3104 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3105 {
3106         return __mark_chain_precision(env, frame, regno, -1);
3107 }
3108
3109 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3110 {
3111         return __mark_chain_precision(env, frame, -1, spi);
3112 }
3113
3114 static bool is_spillable_regtype(enum bpf_reg_type type)
3115 {
3116         switch (base_type(type)) {
3117         case PTR_TO_MAP_VALUE:
3118         case PTR_TO_STACK:
3119         case PTR_TO_CTX:
3120         case PTR_TO_PACKET:
3121         case PTR_TO_PACKET_META:
3122         case PTR_TO_PACKET_END:
3123         case PTR_TO_FLOW_KEYS:
3124         case CONST_PTR_TO_MAP:
3125         case PTR_TO_SOCKET:
3126         case PTR_TO_SOCK_COMMON:
3127         case PTR_TO_TCP_SOCK:
3128         case PTR_TO_XDP_SOCK:
3129         case PTR_TO_BTF_ID:
3130         case PTR_TO_BUF:
3131         case PTR_TO_MEM:
3132         case PTR_TO_FUNC:
3133         case PTR_TO_MAP_KEY:
3134                 return true;
3135         default:
3136                 return false;
3137         }
3138 }
3139
3140 /* Does this register contain a constant zero? */
3141 static bool register_is_null(struct bpf_reg_state *reg)
3142 {
3143         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3144 }
3145
3146 static bool register_is_const(struct bpf_reg_state *reg)
3147 {
3148         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3149 }
3150
3151 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3152 {
3153         return tnum_is_unknown(reg->var_off) &&
3154                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3155                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3156                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3157                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3158 }
3159
3160 static bool register_is_bounded(struct bpf_reg_state *reg)
3161 {
3162         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3163 }
3164
3165 static bool __is_pointer_value(bool allow_ptr_leaks,
3166                                const struct bpf_reg_state *reg)
3167 {
3168         if (allow_ptr_leaks)
3169                 return false;
3170
3171         return reg->type != SCALAR_VALUE;
3172 }
3173
3174 static void save_register_state(struct bpf_func_state *state,
3175                                 int spi, struct bpf_reg_state *reg,
3176                                 int size)
3177 {
3178         int i;
3179
3180         state->stack[spi].spilled_ptr = *reg;
3181         if (size == BPF_REG_SIZE)
3182                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3183
3184         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3185                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3186
3187         /* size < 8 bytes spill */
3188         for (; i; i--)
3189                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3190 }
3191
3192 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3193  * stack boundary and alignment are checked in check_mem_access()
3194  */
3195 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3196                                        /* stack frame we're writing to */
3197                                        struct bpf_func_state *state,
3198                                        int off, int size, int value_regno,
3199                                        int insn_idx)
3200 {
3201         struct bpf_func_state *cur; /* state of the current function */
3202         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3203         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3204         struct bpf_reg_state *reg = NULL;
3205
3206         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3207         if (err)
3208                 return err;
3209         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3210          * so it's aligned access and [off, off + size) are within stack limits
3211          */
3212         if (!env->allow_ptr_leaks &&
3213             state->stack[spi].slot_type[0] == STACK_SPILL &&
3214             size != BPF_REG_SIZE) {
3215                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3216                 return -EACCES;
3217         }
3218
3219         cur = env->cur_state->frame[env->cur_state->curframe];
3220         if (value_regno >= 0)
3221                 reg = &cur->regs[value_regno];
3222         if (!env->bypass_spec_v4) {
3223                 bool sanitize = reg && is_spillable_regtype(reg->type);
3224
3225                 for (i = 0; i < size; i++) {
3226                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3227                                 sanitize = true;
3228                                 break;
3229                         }
3230                 }
3231
3232                 if (sanitize)
3233                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3234         }
3235
3236         mark_stack_slot_scratched(env, spi);
3237         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3238             !register_is_null(reg) && env->bpf_capable) {
3239                 if (dst_reg != BPF_REG_FP) {
3240                         /* The backtracking logic can only recognize explicit
3241                          * stack slot address like [fp - 8]. Other spill of
3242                          * scalar via different register has to be conservative.
3243                          * Backtrack from here and mark all registers as precise
3244                          * that contributed into 'reg' being a constant.
3245                          */
3246                         err = mark_chain_precision(env, value_regno);
3247                         if (err)
3248                                 return err;
3249                 }
3250                 save_register_state(state, spi, reg, size);
3251         } else if (reg && is_spillable_regtype(reg->type)) {
3252                 /* register containing pointer is being spilled into stack */
3253                 if (size != BPF_REG_SIZE) {
3254                         verbose_linfo(env, insn_idx, "; ");
3255                         verbose(env, "invalid size of register spill\n");
3256                         return -EACCES;
3257                 }
3258                 if (state != cur && reg->type == PTR_TO_STACK) {
3259                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3260                         return -EINVAL;
3261                 }
3262                 save_register_state(state, spi, reg, size);
3263         } else {
3264                 u8 type = STACK_MISC;
3265
3266                 /* regular write of data into stack destroys any spilled ptr */
3267                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3268                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3269                 if (is_spilled_reg(&state->stack[spi]))
3270                         for (i = 0; i < BPF_REG_SIZE; i++)
3271                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3272
3273                 /* only mark the slot as written if all 8 bytes were written
3274                  * otherwise read propagation may incorrectly stop too soon
3275                  * when stack slots are partially written.
3276                  * This heuristic means that read propagation will be
3277                  * conservative, since it will add reg_live_read marks
3278                  * to stack slots all the way to first state when programs
3279                  * writes+reads less than 8 bytes
3280                  */
3281                 if (size == BPF_REG_SIZE)
3282                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3283
3284                 /* when we zero initialize stack slots mark them as such */
3285                 if (reg && register_is_null(reg)) {
3286                         /* backtracking doesn't work for STACK_ZERO yet. */
3287                         err = mark_chain_precision(env, value_regno);
3288                         if (err)
3289                                 return err;
3290                         type = STACK_ZERO;
3291                 }
3292
3293                 /* Mark slots affected by this stack write. */
3294                 for (i = 0; i < size; i++)
3295                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3296                                 type;
3297         }
3298         return 0;
3299 }
3300
3301 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3302  * known to contain a variable offset.
3303  * This function checks whether the write is permitted and conservatively
3304  * tracks the effects of the write, considering that each stack slot in the
3305  * dynamic range is potentially written to.
3306  *
3307  * 'off' includes 'regno->off'.
3308  * 'value_regno' can be -1, meaning that an unknown value is being written to
3309  * the stack.
3310  *
3311  * Spilled pointers in range are not marked as written because we don't know
3312  * what's going to be actually written. This means that read propagation for
3313  * future reads cannot be terminated by this write.
3314  *
3315  * For privileged programs, uninitialized stack slots are considered
3316  * initialized by this write (even though we don't know exactly what offsets
3317  * are going to be written to). The idea is that we don't want the verifier to
3318  * reject future reads that access slots written to through variable offsets.
3319  */
3320 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3321                                      /* func where register points to */
3322                                      struct bpf_func_state *state,
3323                                      int ptr_regno, int off, int size,
3324                                      int value_regno, int insn_idx)
3325 {
3326         struct bpf_func_state *cur; /* state of the current function */
3327         int min_off, max_off;
3328         int i, err;
3329         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3330         bool writing_zero = false;
3331         /* set if the fact that we're writing a zero is used to let any
3332          * stack slots remain STACK_ZERO
3333          */
3334         bool zero_used = false;
3335
3336         cur = env->cur_state->frame[env->cur_state->curframe];
3337         ptr_reg = &cur->regs[ptr_regno];
3338         min_off = ptr_reg->smin_value + off;
3339         max_off = ptr_reg->smax_value + off + size;
3340         if (value_regno >= 0)
3341                 value_reg = &cur->regs[value_regno];
3342         if (value_reg && register_is_null(value_reg))
3343                 writing_zero = true;
3344
3345         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3346         if (err)
3347                 return err;
3348
3349
3350         /* Variable offset writes destroy any spilled pointers in range. */
3351         for (i = min_off; i < max_off; i++) {
3352                 u8 new_type, *stype;
3353                 int slot, spi;
3354
3355                 slot = -i - 1;
3356                 spi = slot / BPF_REG_SIZE;
3357                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3358                 mark_stack_slot_scratched(env, spi);
3359
3360                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3361                         /* Reject the write if range we may write to has not
3362                          * been initialized beforehand. If we didn't reject
3363                          * here, the ptr status would be erased below (even
3364                          * though not all slots are actually overwritten),
3365                          * possibly opening the door to leaks.
3366                          *
3367                          * We do however catch STACK_INVALID case below, and
3368                          * only allow reading possibly uninitialized memory
3369                          * later for CAP_PERFMON, as the write may not happen to
3370                          * that slot.
3371                          */
3372                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3373                                 insn_idx, i);
3374                         return -EINVAL;
3375                 }
3376
3377                 /* Erase all spilled pointers. */
3378                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3379
3380                 /* Update the slot type. */
3381                 new_type = STACK_MISC;
3382                 if (writing_zero && *stype == STACK_ZERO) {
3383                         new_type = STACK_ZERO;
3384                         zero_used = true;
3385                 }
3386                 /* If the slot is STACK_INVALID, we check whether it's OK to
3387                  * pretend that it will be initialized by this write. The slot
3388                  * might not actually be written to, and so if we mark it as
3389                  * initialized future reads might leak uninitialized memory.
3390                  * For privileged programs, we will accept such reads to slots
3391                  * that may or may not be written because, if we're reject
3392                  * them, the error would be too confusing.
3393                  */
3394                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3395                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3396                                         insn_idx, i);
3397                         return -EINVAL;
3398                 }
3399                 *stype = new_type;
3400         }
3401         if (zero_used) {
3402                 /* backtracking doesn't work for STACK_ZERO yet. */
3403                 err = mark_chain_precision(env, value_regno);
3404                 if (err)
3405                         return err;
3406         }
3407         return 0;
3408 }
3409
3410 /* When register 'dst_regno' is assigned some values from stack[min_off,
3411  * max_off), we set the register's type according to the types of the
3412  * respective stack slots. If all the stack values are known to be zeros, then
3413  * so is the destination reg. Otherwise, the register is considered to be
3414  * SCALAR. This function does not deal with register filling; the caller must
3415  * ensure that all spilled registers in the stack range have been marked as
3416  * read.
3417  */
3418 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3419                                 /* func where src register points to */
3420                                 struct bpf_func_state *ptr_state,
3421                                 int min_off, int max_off, int dst_regno)
3422 {
3423         struct bpf_verifier_state *vstate = env->cur_state;
3424         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3425         int i, slot, spi;
3426         u8 *stype;
3427         int zeros = 0;
3428
3429         for (i = min_off; i < max_off; i++) {
3430                 slot = -i - 1;
3431                 spi = slot / BPF_REG_SIZE;
3432                 stype = ptr_state->stack[spi].slot_type;
3433                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3434                         break;
3435                 zeros++;
3436         }
3437         if (zeros == max_off - min_off) {
3438                 /* any access_size read into register is zero extended,
3439                  * so the whole register == const_zero
3440                  */
3441                 __mark_reg_const_zero(&state->regs[dst_regno]);
3442                 /* backtracking doesn't support STACK_ZERO yet,
3443                  * so mark it precise here, so that later
3444                  * backtracking can stop here.
3445                  * Backtracking may not need this if this register
3446                  * doesn't participate in pointer adjustment.
3447                  * Forward propagation of precise flag is not
3448                  * necessary either. This mark is only to stop
3449                  * backtracking. Any register that contributed
3450                  * to const 0 was marked precise before spill.
3451                  */
3452                 state->regs[dst_regno].precise = true;
3453         } else {
3454                 /* have read misc data from the stack */
3455                 mark_reg_unknown(env, state->regs, dst_regno);
3456         }
3457         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3458 }
3459
3460 /* Read the stack at 'off' and put the results into the register indicated by
3461  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3462  * spilled reg.
3463  *
3464  * 'dst_regno' can be -1, meaning that the read value is not going to a
3465  * register.
3466  *
3467  * The access is assumed to be within the current stack bounds.
3468  */
3469 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3470                                       /* func where src register points to */
3471                                       struct bpf_func_state *reg_state,
3472                                       int off, int size, int dst_regno)
3473 {
3474         struct bpf_verifier_state *vstate = env->cur_state;
3475         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3476         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3477         struct bpf_reg_state *reg;
3478         u8 *stype, type;
3479
3480         stype = reg_state->stack[spi].slot_type;
3481         reg = &reg_state->stack[spi].spilled_ptr;
3482
3483         if (is_spilled_reg(&reg_state->stack[spi])) {
3484                 u8 spill_size = 1;
3485
3486                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3487                         spill_size++;
3488
3489                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3490                         if (reg->type != SCALAR_VALUE) {
3491                                 verbose_linfo(env, env->insn_idx, "; ");
3492                                 verbose(env, "invalid size of register fill\n");
3493                                 return -EACCES;
3494                         }
3495
3496                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3497                         if (dst_regno < 0)
3498                                 return 0;
3499
3500                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3501                                 /* The earlier check_reg_arg() has decided the
3502                                  * subreg_def for this insn.  Save it first.
3503                                  */
3504                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3505
3506                                 state->regs[dst_regno] = *reg;
3507                                 state->regs[dst_regno].subreg_def = subreg_def;
3508                         } else {
3509                                 for (i = 0; i < size; i++) {
3510                                         type = stype[(slot - i) % BPF_REG_SIZE];
3511                                         if (type == STACK_SPILL)
3512                                                 continue;
3513                                         if (type == STACK_MISC)
3514                                                 continue;
3515                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3516                                                 off, i, size);
3517                                         return -EACCES;
3518                                 }
3519                                 mark_reg_unknown(env, state->regs, dst_regno);
3520                         }
3521                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3522                         return 0;
3523                 }
3524
3525                 if (dst_regno >= 0) {
3526                         /* restore register state from stack */
3527                         state->regs[dst_regno] = *reg;
3528                         /* mark reg as written since spilled pointer state likely
3529                          * has its liveness marks cleared by is_state_visited()
3530                          * which resets stack/reg liveness for state transitions
3531                          */
3532                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3533                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3534                         /* If dst_regno==-1, the caller is asking us whether
3535                          * it is acceptable to use this value as a SCALAR_VALUE
3536                          * (e.g. for XADD).
3537                          * We must not allow unprivileged callers to do that
3538                          * with spilled pointers.
3539                          */
3540                         verbose(env, "leaking pointer from stack off %d\n",
3541                                 off);
3542                         return -EACCES;
3543                 }
3544                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3545         } else {
3546                 for (i = 0; i < size; i++) {
3547                         type = stype[(slot - i) % BPF_REG_SIZE];
3548                         if (type == STACK_MISC)
3549                                 continue;
3550                         if (type == STACK_ZERO)
3551                                 continue;
3552                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3553                                 off, i, size);
3554                         return -EACCES;
3555                 }
3556                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3557                 if (dst_regno >= 0)
3558                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3559         }
3560         return 0;
3561 }
3562
3563 enum bpf_access_src {
3564         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3565         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3566 };
3567
3568 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3569                                          int regno, int off, int access_size,
3570                                          bool zero_size_allowed,
3571                                          enum bpf_access_src type,
3572                                          struct bpf_call_arg_meta *meta);
3573
3574 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3575 {
3576         return cur_regs(env) + regno;
3577 }
3578
3579 /* Read the stack at 'ptr_regno + off' and put the result into the register
3580  * 'dst_regno'.
3581  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3582  * but not its variable offset.
3583  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3584  *
3585  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3586  * filling registers (i.e. reads of spilled register cannot be detected when
3587  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3588  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3589  * offset; for a fixed offset check_stack_read_fixed_off should be used
3590  * instead.
3591  */
3592 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3593                                     int ptr_regno, int off, int size, int dst_regno)
3594 {
3595         /* The state of the source register. */
3596         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3597         struct bpf_func_state *ptr_state = func(env, reg);
3598         int err;
3599         int min_off, max_off;
3600
3601         /* Note that we pass a NULL meta, so raw access will not be permitted.
3602          */
3603         err = check_stack_range_initialized(env, ptr_regno, off, size,
3604                                             false, ACCESS_DIRECT, NULL);
3605         if (err)
3606                 return err;
3607
3608         min_off = reg->smin_value + off;
3609         max_off = reg->smax_value + off;
3610         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3611         return 0;
3612 }
3613
3614 /* check_stack_read dispatches to check_stack_read_fixed_off or
3615  * check_stack_read_var_off.
3616  *
3617  * The caller must ensure that the offset falls within the allocated stack
3618  * bounds.
3619  *
3620  * 'dst_regno' is a register which will receive the value from the stack. It
3621  * can be -1, meaning that the read value is not going to a register.
3622  */
3623 static int check_stack_read(struct bpf_verifier_env *env,
3624                             int ptr_regno, int off, int size,
3625                             int dst_regno)
3626 {
3627         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3628         struct bpf_func_state *state = func(env, reg);
3629         int err;
3630         /* Some accesses are only permitted with a static offset. */
3631         bool var_off = !tnum_is_const(reg->var_off);
3632
3633         /* The offset is required to be static when reads don't go to a
3634          * register, in order to not leak pointers (see
3635          * check_stack_read_fixed_off).
3636          */
3637         if (dst_regno < 0 && var_off) {
3638                 char tn_buf[48];
3639
3640                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3641                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3642                         tn_buf, off, size);
3643                 return -EACCES;
3644         }
3645         /* Variable offset is prohibited for unprivileged mode for simplicity
3646          * since it requires corresponding support in Spectre masking for stack
3647          * ALU. See also retrieve_ptr_limit().
3648          */
3649         if (!env->bypass_spec_v1 && var_off) {
3650                 char tn_buf[48];
3651
3652                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3653                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3654                                 ptr_regno, tn_buf);
3655                 return -EACCES;
3656         }
3657
3658         if (!var_off) {
3659                 off += reg->var_off.value;
3660                 err = check_stack_read_fixed_off(env, state, off, size,
3661                                                  dst_regno);
3662         } else {
3663                 /* Variable offset stack reads need more conservative handling
3664                  * than fixed offset ones. Note that dst_regno >= 0 on this
3665                  * branch.
3666                  */
3667                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3668                                                dst_regno);
3669         }
3670         return err;
3671 }
3672
3673
3674 /* check_stack_write dispatches to check_stack_write_fixed_off or
3675  * check_stack_write_var_off.
3676  *
3677  * 'ptr_regno' is the register used as a pointer into the stack.
3678  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3679  * 'value_regno' is the register whose value we're writing to the stack. It can
3680  * be -1, meaning that we're not writing from a register.
3681  *
3682  * The caller must ensure that the offset falls within the maximum stack size.
3683  */
3684 static int check_stack_write(struct bpf_verifier_env *env,
3685                              int ptr_regno, int off, int size,
3686                              int value_regno, int insn_idx)
3687 {
3688         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3689         struct bpf_func_state *state = func(env, reg);
3690         int err;
3691
3692         if (tnum_is_const(reg->var_off)) {
3693                 off += reg->var_off.value;
3694                 err = check_stack_write_fixed_off(env, state, off, size,
3695                                                   value_regno, insn_idx);
3696         } else {
3697                 /* Variable offset stack reads need more conservative handling
3698                  * than fixed offset ones.
3699                  */
3700                 err = check_stack_write_var_off(env, state,
3701                                                 ptr_regno, off, size,
3702                                                 value_regno, insn_idx);
3703         }
3704         return err;
3705 }
3706
3707 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3708                                  int off, int size, enum bpf_access_type type)
3709 {
3710         struct bpf_reg_state *regs = cur_regs(env);
3711         struct bpf_map *map = regs[regno].map_ptr;
3712         u32 cap = bpf_map_flags_to_cap(map);
3713
3714         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3715                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3716                         map->value_size, off, size);
3717                 return -EACCES;
3718         }
3719
3720         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3721                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3722                         map->value_size, off, size);
3723                 return -EACCES;
3724         }
3725
3726         return 0;
3727 }
3728
3729 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3730 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3731                               int off, int size, u32 mem_size,
3732                               bool zero_size_allowed)
3733 {
3734         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3735         struct bpf_reg_state *reg;
3736
3737         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3738                 return 0;
3739
3740         reg = &cur_regs(env)[regno];
3741         switch (reg->type) {
3742         case PTR_TO_MAP_KEY:
3743                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3744                         mem_size, off, size);
3745                 break;
3746         case PTR_TO_MAP_VALUE:
3747                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3748                         mem_size, off, size);
3749                 break;
3750         case PTR_TO_PACKET:
3751         case PTR_TO_PACKET_META:
3752         case PTR_TO_PACKET_END:
3753                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3754                         off, size, regno, reg->id, off, mem_size);
3755                 break;
3756         case PTR_TO_MEM:
3757         default:
3758                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3759                         mem_size, off, size);
3760         }
3761
3762         return -EACCES;
3763 }
3764
3765 /* check read/write into a memory region with possible variable offset */
3766 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3767                                    int off, int size, u32 mem_size,
3768                                    bool zero_size_allowed)
3769 {
3770         struct bpf_verifier_state *vstate = env->cur_state;
3771         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3772         struct bpf_reg_state *reg = &state->regs[regno];
3773         int err;
3774
3775         /* We may have adjusted the register pointing to memory region, so we
3776          * need to try adding each of min_value and max_value to off
3777          * to make sure our theoretical access will be safe.
3778          *
3779          * The minimum value is only important with signed
3780          * comparisons where we can't assume the floor of a
3781          * value is 0.  If we are using signed variables for our
3782          * index'es we need to make sure that whatever we use
3783          * will have a set floor within our range.
3784          */
3785         if (reg->smin_value < 0 &&
3786             (reg->smin_value == S64_MIN ||
3787              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3788               reg->smin_value + off < 0)) {
3789                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3790                         regno);
3791                 return -EACCES;
3792         }
3793         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3794                                  mem_size, zero_size_allowed);
3795         if (err) {
3796                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3797                         regno);
3798                 return err;
3799         }
3800
3801         /* If we haven't set a max value then we need to bail since we can't be
3802          * sure we won't do bad things.
3803          * If reg->umax_value + off could overflow, treat that as unbounded too.
3804          */
3805         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3806                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3807                         regno);
3808                 return -EACCES;
3809         }
3810         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3811                                  mem_size, zero_size_allowed);
3812         if (err) {
3813                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3814                         regno);
3815                 return err;
3816         }
3817
3818         return 0;
3819 }
3820
3821 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3822                                const struct bpf_reg_state *reg, int regno,
3823                                bool fixed_off_ok)
3824 {
3825         /* Access to this pointer-typed register or passing it to a helper
3826          * is only allowed in its original, unmodified form.
3827          */
3828
3829         if (reg->off < 0) {
3830                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3831                         reg_type_str(env, reg->type), regno, reg->off);
3832                 return -EACCES;
3833         }
3834
3835         if (!fixed_off_ok && reg->off) {
3836                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3837                         reg_type_str(env, reg->type), regno, reg->off);
3838                 return -EACCES;
3839         }
3840
3841         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3842                 char tn_buf[48];
3843
3844                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3845                 verbose(env, "variable %s access var_off=%s disallowed\n",
3846                         reg_type_str(env, reg->type), tn_buf);
3847                 return -EACCES;
3848         }
3849
3850         return 0;
3851 }
3852
3853 int check_ptr_off_reg(struct bpf_verifier_env *env,
3854                       const struct bpf_reg_state *reg, int regno)
3855 {
3856         return __check_ptr_off_reg(env, reg, regno, false);
3857 }
3858
3859 static int map_kptr_match_type(struct bpf_verifier_env *env,
3860                                struct btf_field *kptr_field,
3861                                struct bpf_reg_state *reg, u32 regno)
3862 {
3863         const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3864         int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
3865         const char *reg_name = "";
3866
3867         /* Only unreferenced case accepts untrusted pointers */
3868         if (kptr_field->type == BPF_KPTR_UNREF)
3869                 perm_flags |= PTR_UNTRUSTED;
3870
3871         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3872                 goto bad_type;
3873
3874         if (!btf_is_kernel(reg->btf)) {
3875                 verbose(env, "R%d must point to kernel BTF\n", regno);
3876                 return -EINVAL;
3877         }
3878         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3879         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3880
3881         /* For ref_ptr case, release function check should ensure we get one
3882          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3883          * normal store of unreferenced kptr, we must ensure var_off is zero.
3884          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3885          * reg->off and reg->ref_obj_id are not needed here.
3886          */
3887         if (__check_ptr_off_reg(env, reg, regno, true))
3888                 return -EACCES;
3889
3890         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3891          * we also need to take into account the reg->off.
3892          *
3893          * We want to support cases like:
3894          *
3895          * struct foo {
3896          *         struct bar br;
3897          *         struct baz bz;
3898          * };
3899          *
3900          * struct foo *v;
3901          * v = func();        // PTR_TO_BTF_ID
3902          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3903          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3904          *                    // first member type of struct after comparison fails
3905          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3906          *                    // to match type
3907          *
3908          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3909          * is zero. We must also ensure that btf_struct_ids_match does not walk
3910          * the struct to match type against first member of struct, i.e. reject
3911          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3912          * strict mode to true for type match.
3913          */
3914         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3915                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3916                                   kptr_field->type == BPF_KPTR_REF))
3917                 goto bad_type;
3918         return 0;
3919 bad_type:
3920         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3921                 reg_type_str(env, reg->type), reg_name);
3922         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3923         if (kptr_field->type == BPF_KPTR_UNREF)
3924                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3925                         targ_name);
3926         else
3927                 verbose(env, "\n");
3928         return -EINVAL;
3929 }
3930
3931 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3932                                  int value_regno, int insn_idx,
3933                                  struct btf_field *kptr_field)
3934 {
3935         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3936         int class = BPF_CLASS(insn->code);
3937         struct bpf_reg_state *val_reg;
3938
3939         /* Things we already checked for in check_map_access and caller:
3940          *  - Reject cases where variable offset may touch kptr
3941          *  - size of access (must be BPF_DW)
3942          *  - tnum_is_const(reg->var_off)
3943          *  - kptr_field->offset == off + reg->var_off.value
3944          */
3945         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3946         if (BPF_MODE(insn->code) != BPF_MEM) {
3947                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3948                 return -EACCES;
3949         }
3950
3951         /* We only allow loading referenced kptr, since it will be marked as
3952          * untrusted, similar to unreferenced kptr.
3953          */
3954         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
3955                 verbose(env, "store to referenced kptr disallowed\n");
3956                 return -EACCES;
3957         }
3958
3959         if (class == BPF_LDX) {
3960                 val_reg = reg_state(env, value_regno);
3961                 /* We can simply mark the value_regno receiving the pointer
3962                  * value from map as PTR_TO_BTF_ID, with the correct type.
3963                  */
3964                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
3965                                 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3966                 /* For mark_ptr_or_null_reg */
3967                 val_reg->id = ++env->id_gen;
3968         } else if (class == BPF_STX) {
3969                 val_reg = reg_state(env, value_regno);
3970                 if (!register_is_null(val_reg) &&
3971                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
3972                         return -EACCES;
3973         } else if (class == BPF_ST) {
3974                 if (insn->imm) {
3975                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3976                                 kptr_field->offset);
3977                         return -EACCES;
3978                 }
3979         } else {
3980                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3981                 return -EACCES;
3982         }
3983         return 0;
3984 }
3985
3986 /* check read/write into a map element with possible variable offset */
3987 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3988                             int off, int size, bool zero_size_allowed,
3989                             enum bpf_access_src src)
3990 {
3991         struct bpf_verifier_state *vstate = env->cur_state;
3992         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3993         struct bpf_reg_state *reg = &state->regs[regno];
3994         struct bpf_map *map = reg->map_ptr;
3995         struct btf_record *rec;
3996         int err, i;
3997
3998         err = check_mem_region_access(env, regno, off, size, map->value_size,
3999                                       zero_size_allowed);
4000         if (err)
4001                 return err;
4002
4003         if (IS_ERR_OR_NULL(map->record))
4004                 return 0;
4005         rec = map->record;
4006         for (i = 0; i < rec->cnt; i++) {
4007                 struct btf_field *field = &rec->fields[i];
4008                 u32 p = field->offset;
4009
4010                 /* If any part of a field  can be touched by load/store, reject
4011                  * this program. To check that [x1, x2) overlaps with [y1, y2),
4012                  * it is sufficient to check x1 < y2 && y1 < x2.
4013                  */
4014                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4015                     p < reg->umax_value + off + size) {
4016                         switch (field->type) {
4017                         case BPF_KPTR_UNREF:
4018                         case BPF_KPTR_REF:
4019                                 if (src != ACCESS_DIRECT) {
4020                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
4021                                         return -EACCES;
4022                                 }
4023                                 if (!tnum_is_const(reg->var_off)) {
4024                                         verbose(env, "kptr access cannot have variable offset\n");
4025                                         return -EACCES;
4026                                 }
4027                                 if (p != off + reg->var_off.value) {
4028                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4029                                                 p, off + reg->var_off.value);
4030                                         return -EACCES;
4031                                 }
4032                                 if (size != bpf_size_to_bytes(BPF_DW)) {
4033                                         verbose(env, "kptr access size must be BPF_DW\n");
4034                                         return -EACCES;
4035                                 }
4036                                 break;
4037                         default:
4038                                 verbose(env, "%s cannot be accessed directly by load/store\n",
4039                                         btf_field_type_name(field->type));
4040                                 return -EACCES;
4041                         }
4042                 }
4043         }
4044         return 0;
4045 }
4046
4047 #define MAX_PACKET_OFF 0xffff
4048
4049 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4050                                        const struct bpf_call_arg_meta *meta,
4051                                        enum bpf_access_type t)
4052 {
4053         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4054
4055         switch (prog_type) {
4056         /* Program types only with direct read access go here! */
4057         case BPF_PROG_TYPE_LWT_IN:
4058         case BPF_PROG_TYPE_LWT_OUT:
4059         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4060         case BPF_PROG_TYPE_SK_REUSEPORT:
4061         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4062         case BPF_PROG_TYPE_CGROUP_SKB:
4063                 if (t == BPF_WRITE)
4064                         return false;
4065                 fallthrough;
4066
4067         /* Program types with direct read + write access go here! */
4068         case BPF_PROG_TYPE_SCHED_CLS:
4069         case BPF_PROG_TYPE_SCHED_ACT:
4070         case BPF_PROG_TYPE_XDP:
4071         case BPF_PROG_TYPE_LWT_XMIT:
4072         case BPF_PROG_TYPE_SK_SKB:
4073         case BPF_PROG_TYPE_SK_MSG:
4074                 if (meta)
4075                         return meta->pkt_access;
4076
4077                 env->seen_direct_write = true;
4078                 return true;
4079
4080         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4081                 if (t == BPF_WRITE)
4082                         env->seen_direct_write = true;
4083
4084                 return true;
4085
4086         default:
4087                 return false;
4088         }
4089 }
4090
4091 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4092                                int size, bool zero_size_allowed)
4093 {
4094         struct bpf_reg_state *regs = cur_regs(env);
4095         struct bpf_reg_state *reg = &regs[regno];
4096         int err;
4097
4098         /* We may have added a variable offset to the packet pointer; but any
4099          * reg->range we have comes after that.  We are only checking the fixed
4100          * offset.
4101          */
4102
4103         /* We don't allow negative numbers, because we aren't tracking enough
4104          * detail to prove they're safe.
4105          */
4106         if (reg->smin_value < 0) {
4107                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4108                         regno);
4109                 return -EACCES;
4110         }
4111
4112         err = reg->range < 0 ? -EINVAL :
4113               __check_mem_access(env, regno, off, size, reg->range,
4114                                  zero_size_allowed);
4115         if (err) {
4116                 verbose(env, "R%d offset is outside of the packet\n", regno);
4117                 return err;
4118         }
4119
4120         /* __check_mem_access has made sure "off + size - 1" is within u16.
4121          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4122          * otherwise find_good_pkt_pointers would have refused to set range info
4123          * that __check_mem_access would have rejected this pkt access.
4124          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4125          */
4126         env->prog->aux->max_pkt_offset =
4127                 max_t(u32, env->prog->aux->max_pkt_offset,
4128                       off + reg->umax_value + size - 1);
4129
4130         return err;
4131 }
4132
4133 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4134 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4135                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4136                             struct btf **btf, u32 *btf_id)
4137 {
4138         struct bpf_insn_access_aux info = {
4139                 .reg_type = *reg_type,
4140                 .log = &env->log,
4141         };
4142
4143         if (env->ops->is_valid_access &&
4144             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4145                 /* A non zero info.ctx_field_size indicates that this field is a
4146                  * candidate for later verifier transformation to load the whole
4147                  * field and then apply a mask when accessed with a narrower
4148                  * access than actual ctx access size. A zero info.ctx_field_size
4149                  * will only allow for whole field access and rejects any other
4150                  * type of narrower access.
4151                  */
4152                 *reg_type = info.reg_type;
4153
4154                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4155                         *btf = info.btf;
4156                         *btf_id = info.btf_id;
4157                 } else {
4158                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4159                 }
4160                 /* remember the offset of last byte accessed in ctx */
4161                 if (env->prog->aux->max_ctx_offset < off + size)
4162                         env->prog->aux->max_ctx_offset = off + size;
4163                 return 0;
4164         }
4165
4166         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4167         return -EACCES;
4168 }
4169
4170 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4171                                   int size)
4172 {
4173         if (size < 0 || off < 0 ||
4174             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4175                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4176                         off, size);
4177                 return -EACCES;
4178         }
4179         return 0;
4180 }
4181
4182 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4183                              u32 regno, int off, int size,
4184                              enum bpf_access_type t)
4185 {
4186         struct bpf_reg_state *regs = cur_regs(env);
4187         struct bpf_reg_state *reg = &regs[regno];
4188         struct bpf_insn_access_aux info = {};
4189         bool valid;
4190
4191         if (reg->smin_value < 0) {
4192                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4193                         regno);
4194                 return -EACCES;
4195         }
4196
4197         switch (reg->type) {
4198         case PTR_TO_SOCK_COMMON:
4199                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4200                 break;
4201         case PTR_TO_SOCKET:
4202                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4203                 break;
4204         case PTR_TO_TCP_SOCK:
4205                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4206                 break;
4207         case PTR_TO_XDP_SOCK:
4208                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4209                 break;
4210         default:
4211                 valid = false;
4212         }
4213
4214
4215         if (valid) {
4216                 env->insn_aux_data[insn_idx].ctx_field_size =
4217                         info.ctx_field_size;
4218                 return 0;
4219         }
4220
4221         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4222                 regno, reg_type_str(env, reg->type), off, size);
4223
4224         return -EACCES;
4225 }
4226
4227 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4228 {
4229         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4230 }
4231
4232 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4233 {
4234         const struct bpf_reg_state *reg = reg_state(env, regno);
4235
4236         return reg->type == PTR_TO_CTX;
4237 }
4238
4239 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4240 {
4241         const struct bpf_reg_state *reg = reg_state(env, regno);
4242
4243         return type_is_sk_pointer(reg->type);
4244 }
4245
4246 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4247 {
4248         const struct bpf_reg_state *reg = reg_state(env, regno);
4249
4250         return type_is_pkt_pointer(reg->type);
4251 }
4252
4253 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4254 {
4255         const struct bpf_reg_state *reg = reg_state(env, regno);
4256
4257         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4258         return reg->type == PTR_TO_FLOW_KEYS;
4259 }
4260
4261 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4262                                    const struct bpf_reg_state *reg,
4263                                    int off, int size, bool strict)
4264 {
4265         struct tnum reg_off;
4266         int ip_align;
4267
4268         /* Byte size accesses are always allowed. */
4269         if (!strict || size == 1)
4270                 return 0;
4271
4272         /* For platforms that do not have a Kconfig enabling
4273          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4274          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4275          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4276          * to this code only in strict mode where we want to emulate
4277          * the NET_IP_ALIGN==2 checking.  Therefore use an
4278          * unconditional IP align value of '2'.
4279          */
4280         ip_align = 2;
4281
4282         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4283         if (!tnum_is_aligned(reg_off, size)) {
4284                 char tn_buf[48];
4285
4286                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4287                 verbose(env,
4288                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4289                         ip_align, tn_buf, reg->off, off, size);
4290                 return -EACCES;
4291         }
4292
4293         return 0;
4294 }
4295
4296 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4297                                        const struct bpf_reg_state *reg,
4298                                        const char *pointer_desc,
4299                                        int off, int size, bool strict)
4300 {
4301         struct tnum reg_off;
4302
4303         /* Byte size accesses are always allowed. */
4304         if (!strict || size == 1)
4305                 return 0;
4306
4307         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4308         if (!tnum_is_aligned(reg_off, size)) {
4309                 char tn_buf[48];
4310
4311                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4312                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4313                         pointer_desc, tn_buf, reg->off, off, size);
4314                 return -EACCES;
4315         }
4316
4317         return 0;
4318 }
4319
4320 static int check_ptr_alignment(struct bpf_verifier_env *env,
4321                                const struct bpf_reg_state *reg, int off,
4322                                int size, bool strict_alignment_once)
4323 {
4324         bool strict = env->strict_alignment || strict_alignment_once;
4325         const char *pointer_desc = "";
4326
4327         switch (reg->type) {
4328         case PTR_TO_PACKET:
4329         case PTR_TO_PACKET_META:
4330                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4331                  * right in front, treat it the very same way.
4332                  */
4333                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4334         case PTR_TO_FLOW_KEYS:
4335                 pointer_desc = "flow keys ";
4336                 break;
4337         case PTR_TO_MAP_KEY:
4338                 pointer_desc = "key ";
4339                 break;
4340         case PTR_TO_MAP_VALUE:
4341                 pointer_desc = "value ";
4342                 break;
4343         case PTR_TO_CTX:
4344                 pointer_desc = "context ";
4345                 break;
4346         case PTR_TO_STACK:
4347                 pointer_desc = "stack ";
4348                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4349                  * and check_stack_read_fixed_off() relies on stack accesses being
4350                  * aligned.
4351                  */
4352                 strict = true;
4353                 break;
4354         case PTR_TO_SOCKET:
4355                 pointer_desc = "sock ";
4356                 break;
4357         case PTR_TO_SOCK_COMMON:
4358                 pointer_desc = "sock_common ";
4359                 break;
4360         case PTR_TO_TCP_SOCK:
4361                 pointer_desc = "tcp_sock ";
4362                 break;
4363         case PTR_TO_XDP_SOCK:
4364                 pointer_desc = "xdp_sock ";
4365                 break;
4366         default:
4367                 break;
4368         }
4369         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4370                                            strict);
4371 }
4372
4373 static int update_stack_depth(struct bpf_verifier_env *env,
4374                               const struct bpf_func_state *func,
4375                               int off)
4376 {
4377         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4378
4379         if (stack >= -off)
4380                 return 0;
4381
4382         /* update known max for given subprogram */
4383         env->subprog_info[func->subprogno].stack_depth = -off;
4384         return 0;
4385 }
4386
4387 /* starting from main bpf function walk all instructions of the function
4388  * and recursively walk all callees that given function can call.
4389  * Ignore jump and exit insns.
4390  * Since recursion is prevented by check_cfg() this algorithm
4391  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4392  */
4393 static int check_max_stack_depth(struct bpf_verifier_env *env)
4394 {
4395         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4396         struct bpf_subprog_info *subprog = env->subprog_info;
4397         struct bpf_insn *insn = env->prog->insnsi;
4398         bool tail_call_reachable = false;
4399         int ret_insn[MAX_CALL_FRAMES];
4400         int ret_prog[MAX_CALL_FRAMES];
4401         int j;
4402
4403 process_func:
4404         /* protect against potential stack overflow that might happen when
4405          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4406          * depth for such case down to 256 so that the worst case scenario
4407          * would result in 8k stack size (32 which is tailcall limit * 256 =
4408          * 8k).
4409          *
4410          * To get the idea what might happen, see an example:
4411          * func1 -> sub rsp, 128
4412          *  subfunc1 -> sub rsp, 256
4413          *  tailcall1 -> add rsp, 256
4414          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4415          *   subfunc2 -> sub rsp, 64
4416          *   subfunc22 -> sub rsp, 128
4417          *   tailcall2 -> add rsp, 128
4418          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4419          *
4420          * tailcall will unwind the current stack frame but it will not get rid
4421          * of caller's stack as shown on the example above.
4422          */
4423         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4424                 verbose(env,
4425                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4426                         depth);
4427                 return -EACCES;
4428         }
4429         /* round up to 32-bytes, since this is granularity
4430          * of interpreter stack size
4431          */
4432         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4433         if (depth > MAX_BPF_STACK) {
4434                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4435                         frame + 1, depth);
4436                 return -EACCES;
4437         }
4438 continue_func:
4439         subprog_end = subprog[idx + 1].start;
4440         for (; i < subprog_end; i++) {
4441                 int next_insn;
4442
4443                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4444                         continue;
4445                 /* remember insn and function to return to */
4446                 ret_insn[frame] = i + 1;
4447                 ret_prog[frame] = idx;
4448
4449                 /* find the callee */
4450                 next_insn = i + insn[i].imm + 1;
4451                 idx = find_subprog(env, next_insn);
4452                 if (idx < 0) {
4453                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4454                                   next_insn);
4455                         return -EFAULT;
4456                 }
4457                 if (subprog[idx].is_async_cb) {
4458                         if (subprog[idx].has_tail_call) {
4459                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4460                                 return -EFAULT;
4461                         }
4462                          /* async callbacks don't increase bpf prog stack size */
4463                         continue;
4464                 }
4465                 i = next_insn;
4466
4467                 if (subprog[idx].has_tail_call)
4468                         tail_call_reachable = true;
4469
4470                 frame++;
4471                 if (frame >= MAX_CALL_FRAMES) {
4472                         verbose(env, "the call stack of %d frames is too deep !\n",
4473                                 frame);
4474                         return -E2BIG;
4475                 }
4476                 goto process_func;
4477         }
4478         /* if tail call got detected across bpf2bpf calls then mark each of the
4479          * currently present subprog frames as tail call reachable subprogs;
4480          * this info will be utilized by JIT so that we will be preserving the
4481          * tail call counter throughout bpf2bpf calls combined with tailcalls
4482          */
4483         if (tail_call_reachable)
4484                 for (j = 0; j < frame; j++)
4485                         subprog[ret_prog[j]].tail_call_reachable = true;
4486         if (subprog[0].tail_call_reachable)
4487                 env->prog->aux->tail_call_reachable = true;
4488
4489         /* end of for() loop means the last insn of the 'subprog'
4490          * was reached. Doesn't matter whether it was JA or EXIT
4491          */
4492         if (frame == 0)
4493                 return 0;
4494         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4495         frame--;
4496         i = ret_insn[frame];
4497         idx = ret_prog[frame];
4498         goto continue_func;
4499 }
4500
4501 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4502 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4503                                   const struct bpf_insn *insn, int idx)
4504 {
4505         int start = idx + insn->imm + 1, subprog;
4506
4507         subprog = find_subprog(env, start);
4508         if (subprog < 0) {
4509                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4510                           start);
4511                 return -EFAULT;
4512         }
4513         return env->subprog_info[subprog].stack_depth;
4514 }
4515 #endif
4516
4517 static int __check_buffer_access(struct bpf_verifier_env *env,
4518                                  const char *buf_info,
4519                                  const struct bpf_reg_state *reg,
4520                                  int regno, int off, int size)
4521 {
4522         if (off < 0) {
4523                 verbose(env,
4524                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4525                         regno, buf_info, off, size);
4526                 return -EACCES;
4527         }
4528         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4529                 char tn_buf[48];
4530
4531                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4532                 verbose(env,
4533                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4534                         regno, off, tn_buf);
4535                 return -EACCES;
4536         }
4537
4538         return 0;
4539 }
4540
4541 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4542                                   const struct bpf_reg_state *reg,
4543                                   int regno, int off, int size)
4544 {
4545         int err;
4546
4547         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4548         if (err)
4549                 return err;
4550
4551         if (off + size > env->prog->aux->max_tp_access)
4552                 env->prog->aux->max_tp_access = off + size;
4553
4554         return 0;
4555 }
4556
4557 static int check_buffer_access(struct bpf_verifier_env *env,
4558                                const struct bpf_reg_state *reg,
4559                                int regno, int off, int size,
4560                                bool zero_size_allowed,
4561                                u32 *max_access)
4562 {
4563         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4564         int err;
4565
4566         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4567         if (err)
4568                 return err;
4569
4570         if (off + size > *max_access)
4571                 *max_access = off + size;
4572
4573         return 0;
4574 }
4575
4576 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4577 static void zext_32_to_64(struct bpf_reg_state *reg)
4578 {
4579         reg->var_off = tnum_subreg(reg->var_off);
4580         __reg_assign_32_into_64(reg);
4581 }
4582
4583 /* truncate register to smaller size (in bytes)
4584  * must be called with size < BPF_REG_SIZE
4585  */
4586 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4587 {
4588         u64 mask;
4589
4590         /* clear high bits in bit representation */
4591         reg->var_off = tnum_cast(reg->var_off, size);
4592
4593         /* fix arithmetic bounds */
4594         mask = ((u64)1 << (size * 8)) - 1;
4595         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4596                 reg->umin_value &= mask;
4597                 reg->umax_value &= mask;
4598         } else {
4599                 reg->umin_value = 0;
4600                 reg->umax_value = mask;
4601         }
4602         reg->smin_value = reg->umin_value;
4603         reg->smax_value = reg->umax_value;
4604
4605         /* If size is smaller than 32bit register the 32bit register
4606          * values are also truncated so we push 64-bit bounds into
4607          * 32-bit bounds. Above were truncated < 32-bits already.
4608          */
4609         if (size >= 4)
4610                 return;
4611         __reg_combine_64_into_32(reg);
4612 }
4613
4614 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4615 {
4616         /* A map is considered read-only if the following condition are true:
4617          *
4618          * 1) BPF program side cannot change any of the map content. The
4619          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4620          *    and was set at map creation time.
4621          * 2) The map value(s) have been initialized from user space by a
4622          *    loader and then "frozen", such that no new map update/delete
4623          *    operations from syscall side are possible for the rest of
4624          *    the map's lifetime from that point onwards.
4625          * 3) Any parallel/pending map update/delete operations from syscall
4626          *    side have been completed. Only after that point, it's safe to
4627          *    assume that map value(s) are immutable.
4628          */
4629         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4630                READ_ONCE(map->frozen) &&
4631                !bpf_map_write_active(map);
4632 }
4633
4634 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4635 {
4636         void *ptr;
4637         u64 addr;
4638         int err;
4639
4640         err = map->ops->map_direct_value_addr(map, &addr, off);
4641         if (err)
4642                 return err;
4643         ptr = (void *)(long)addr + off;
4644
4645         switch (size) {
4646         case sizeof(u8):
4647                 *val = (u64)*(u8 *)ptr;
4648                 break;
4649         case sizeof(u16):
4650                 *val = (u64)*(u16 *)ptr;
4651                 break;
4652         case sizeof(u32):
4653                 *val = (u64)*(u32 *)ptr;
4654                 break;
4655         case sizeof(u64):
4656                 *val = *(u64 *)ptr;
4657                 break;
4658         default:
4659                 return -EINVAL;
4660         }
4661         return 0;
4662 }
4663
4664 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4665                                    struct bpf_reg_state *regs,
4666                                    int regno, int off, int size,
4667                                    enum bpf_access_type atype,
4668                                    int value_regno)
4669 {
4670         struct bpf_reg_state *reg = regs + regno;
4671         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4672         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4673         enum bpf_type_flag flag = 0;
4674         u32 btf_id;
4675         int ret;
4676
4677         if (off < 0) {
4678                 verbose(env,
4679                         "R%d is ptr_%s invalid negative access: off=%d\n",
4680                         regno, tname, off);
4681                 return -EACCES;
4682         }
4683         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4684                 char tn_buf[48];
4685
4686                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4687                 verbose(env,
4688                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4689                         regno, tname, off, tn_buf);
4690                 return -EACCES;
4691         }
4692
4693         if (reg->type & MEM_USER) {
4694                 verbose(env,
4695                         "R%d is ptr_%s access user memory: off=%d\n",
4696                         regno, tname, off);
4697                 return -EACCES;
4698         }
4699
4700         if (reg->type & MEM_PERCPU) {
4701                 verbose(env,
4702                         "R%d is ptr_%s access percpu memory: off=%d\n",
4703                         regno, tname, off);
4704                 return -EACCES;
4705         }
4706
4707         if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4708                 if (!btf_is_kernel(reg->btf)) {
4709                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4710                         return -EFAULT;
4711                 }
4712                 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4713         } else {
4714                 /* Writes are permitted with default btf_struct_access for
4715                  * program allocated objects (which always have ref_obj_id > 0),
4716                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4717                  */
4718                 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
4719                         verbose(env, "only read is supported\n");
4720                         return -EACCES;
4721                 }
4722
4723                 if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4724                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4725                         return -EFAULT;
4726                 }
4727
4728                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
4729         }
4730
4731         if (ret < 0)
4732                 return ret;
4733
4734         /* If this is an untrusted pointer, all pointers formed by walking it
4735          * also inherit the untrusted flag.
4736          */
4737         if (type_flag(reg->type) & PTR_UNTRUSTED)
4738                 flag |= PTR_UNTRUSTED;
4739
4740         /* Any pointer obtained from walking a trusted pointer is no longer trusted. */
4741         flag &= ~PTR_TRUSTED;
4742
4743         if (atype == BPF_READ && value_regno >= 0)
4744                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4745
4746         return 0;
4747 }
4748
4749 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4750                                    struct bpf_reg_state *regs,
4751                                    int regno, int off, int size,
4752                                    enum bpf_access_type atype,
4753                                    int value_regno)
4754 {
4755         struct bpf_reg_state *reg = regs + regno;
4756         struct bpf_map *map = reg->map_ptr;
4757         struct bpf_reg_state map_reg;
4758         enum bpf_type_flag flag = 0;
4759         const struct btf_type *t;
4760         const char *tname;
4761         u32 btf_id;
4762         int ret;
4763
4764         if (!btf_vmlinux) {
4765                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4766                 return -ENOTSUPP;
4767         }
4768
4769         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4770                 verbose(env, "map_ptr access not supported for map type %d\n",
4771                         map->map_type);
4772                 return -ENOTSUPP;
4773         }
4774
4775         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4776         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4777
4778         if (!env->allow_ptr_to_map_access) {
4779                 verbose(env,
4780                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4781                         tname);
4782                 return -EPERM;
4783         }
4784
4785         if (off < 0) {
4786                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4787                         regno, tname, off);
4788                 return -EACCES;
4789         }
4790
4791         if (atype != BPF_READ) {
4792                 verbose(env, "only read from %s is supported\n", tname);
4793                 return -EACCES;
4794         }
4795
4796         /* Simulate access to a PTR_TO_BTF_ID */
4797         memset(&map_reg, 0, sizeof(map_reg));
4798         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4799         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
4800         if (ret < 0)
4801                 return ret;
4802
4803         if (value_regno >= 0)
4804                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4805
4806         return 0;
4807 }
4808
4809 /* Check that the stack access at the given offset is within bounds. The
4810  * maximum valid offset is -1.
4811  *
4812  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4813  * -state->allocated_stack for reads.
4814  */
4815 static int check_stack_slot_within_bounds(int off,
4816                                           struct bpf_func_state *state,
4817                                           enum bpf_access_type t)
4818 {
4819         int min_valid_off;
4820
4821         if (t == BPF_WRITE)
4822                 min_valid_off = -MAX_BPF_STACK;
4823         else
4824                 min_valid_off = -state->allocated_stack;
4825
4826         if (off < min_valid_off || off > -1)
4827                 return -EACCES;
4828         return 0;
4829 }
4830
4831 /* Check that the stack access at 'regno + off' falls within the maximum stack
4832  * bounds.
4833  *
4834  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4835  */
4836 static int check_stack_access_within_bounds(
4837                 struct bpf_verifier_env *env,
4838                 int regno, int off, int access_size,
4839                 enum bpf_access_src src, enum bpf_access_type type)
4840 {
4841         struct bpf_reg_state *regs = cur_regs(env);
4842         struct bpf_reg_state *reg = regs + regno;
4843         struct bpf_func_state *state = func(env, reg);
4844         int min_off, max_off;
4845         int err;
4846         char *err_extra;
4847
4848         if (src == ACCESS_HELPER)
4849                 /* We don't know if helpers are reading or writing (or both). */
4850                 err_extra = " indirect access to";
4851         else if (type == BPF_READ)
4852                 err_extra = " read from";
4853         else
4854                 err_extra = " write to";
4855
4856         if (tnum_is_const(reg->var_off)) {
4857                 min_off = reg->var_off.value + off;
4858                 if (access_size > 0)
4859                         max_off = min_off + access_size - 1;
4860                 else
4861                         max_off = min_off;
4862         } else {
4863                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4864                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4865                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4866                                 err_extra, regno);
4867                         return -EACCES;
4868                 }
4869                 min_off = reg->smin_value + off;
4870                 if (access_size > 0)
4871                         max_off = reg->smax_value + off + access_size - 1;
4872                 else
4873                         max_off = min_off;
4874         }
4875
4876         err = check_stack_slot_within_bounds(min_off, state, type);
4877         if (!err)
4878                 err = check_stack_slot_within_bounds(max_off, state, type);
4879
4880         if (err) {
4881                 if (tnum_is_const(reg->var_off)) {
4882                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4883                                 err_extra, regno, off, access_size);
4884                 } else {
4885                         char tn_buf[48];
4886
4887                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4888                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4889                                 err_extra, regno, tn_buf, access_size);
4890                 }
4891         }
4892         return err;
4893 }
4894
4895 /* check whether memory at (regno + off) is accessible for t = (read | write)
4896  * if t==write, value_regno is a register which value is stored into memory
4897  * if t==read, value_regno is a register which will receive the value from memory
4898  * if t==write && value_regno==-1, some unknown value is stored into memory
4899  * if t==read && value_regno==-1, don't care what we read from memory
4900  */
4901 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4902                             int off, int bpf_size, enum bpf_access_type t,
4903                             int value_regno, bool strict_alignment_once)
4904 {
4905         struct bpf_reg_state *regs = cur_regs(env);
4906         struct bpf_reg_state *reg = regs + regno;
4907         struct bpf_func_state *state;
4908         int size, err = 0;
4909
4910         size = bpf_size_to_bytes(bpf_size);
4911         if (size < 0)
4912                 return size;
4913
4914         /* alignment checks will add in reg->off themselves */
4915         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4916         if (err)
4917                 return err;
4918
4919         /* for access checks, reg->off is just part of off */
4920         off += reg->off;
4921
4922         if (reg->type == PTR_TO_MAP_KEY) {
4923                 if (t == BPF_WRITE) {
4924                         verbose(env, "write to change key R%d not allowed\n", regno);
4925                         return -EACCES;
4926                 }
4927
4928                 err = check_mem_region_access(env, regno, off, size,
4929                                               reg->map_ptr->key_size, false);
4930                 if (err)
4931                         return err;
4932                 if (value_regno >= 0)
4933                         mark_reg_unknown(env, regs, value_regno);
4934         } else if (reg->type == PTR_TO_MAP_VALUE) {
4935                 struct btf_field *kptr_field = NULL;
4936
4937                 if (t == BPF_WRITE && value_regno >= 0 &&
4938                     is_pointer_value(env, value_regno)) {
4939                         verbose(env, "R%d leaks addr into map\n", value_regno);
4940                         return -EACCES;
4941                 }
4942                 err = check_map_access_type(env, regno, off, size, t);
4943                 if (err)
4944                         return err;
4945                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4946                 if (err)
4947                         return err;
4948                 if (tnum_is_const(reg->var_off))
4949                         kptr_field = btf_record_find(reg->map_ptr->record,
4950                                                      off + reg->var_off.value, BPF_KPTR);
4951                 if (kptr_field) {
4952                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
4953                 } else if (t == BPF_READ && value_regno >= 0) {
4954                         struct bpf_map *map = reg->map_ptr;
4955
4956                         /* if map is read-only, track its contents as scalars */
4957                         if (tnum_is_const(reg->var_off) &&
4958                             bpf_map_is_rdonly(map) &&
4959                             map->ops->map_direct_value_addr) {
4960                                 int map_off = off + reg->var_off.value;
4961                                 u64 val = 0;
4962
4963                                 err = bpf_map_direct_read(map, map_off, size,
4964                                                           &val);
4965                                 if (err)
4966                                         return err;
4967
4968                                 regs[value_regno].type = SCALAR_VALUE;
4969                                 __mark_reg_known(&regs[value_regno], val);
4970                         } else {
4971                                 mark_reg_unknown(env, regs, value_regno);
4972                         }
4973                 }
4974         } else if (base_type(reg->type) == PTR_TO_MEM) {
4975                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4976
4977                 if (type_may_be_null(reg->type)) {
4978                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4979                                 reg_type_str(env, reg->type));
4980                         return -EACCES;
4981                 }
4982
4983                 if (t == BPF_WRITE && rdonly_mem) {
4984                         verbose(env, "R%d cannot write into %s\n",
4985                                 regno, reg_type_str(env, reg->type));
4986                         return -EACCES;
4987                 }
4988
4989                 if (t == BPF_WRITE && value_regno >= 0 &&
4990                     is_pointer_value(env, value_regno)) {
4991                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4992                         return -EACCES;
4993                 }
4994
4995                 err = check_mem_region_access(env, regno, off, size,
4996                                               reg->mem_size, false);
4997                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4998                         mark_reg_unknown(env, regs, value_regno);
4999         } else if (reg->type == PTR_TO_CTX) {
5000                 enum bpf_reg_type reg_type = SCALAR_VALUE;
5001                 struct btf *btf = NULL;
5002                 u32 btf_id = 0;
5003
5004                 if (t == BPF_WRITE && value_regno >= 0 &&
5005                     is_pointer_value(env, value_regno)) {
5006                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
5007                         return -EACCES;
5008                 }
5009
5010                 err = check_ptr_off_reg(env, reg, regno);
5011                 if (err < 0)
5012                         return err;
5013
5014                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5015                                        &btf_id);
5016                 if (err)
5017                         verbose_linfo(env, insn_idx, "; ");
5018                 if (!err && t == BPF_READ && value_regno >= 0) {
5019                         /* ctx access returns either a scalar, or a
5020                          * PTR_TO_PACKET[_META,_END]. In the latter
5021                          * case, we know the offset is zero.
5022                          */
5023                         if (reg_type == SCALAR_VALUE) {
5024                                 mark_reg_unknown(env, regs, value_regno);
5025                         } else {
5026                                 mark_reg_known_zero(env, regs,
5027                                                     value_regno);
5028                                 if (type_may_be_null(reg_type))
5029                                         regs[value_regno].id = ++env->id_gen;
5030                                 /* A load of ctx field could have different
5031                                  * actual load size with the one encoded in the
5032                                  * insn. When the dst is PTR, it is for sure not
5033                                  * a sub-register.
5034                                  */
5035                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5036                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5037                                         regs[value_regno].btf = btf;
5038                                         regs[value_regno].btf_id = btf_id;
5039                                 }
5040                         }
5041                         regs[value_regno].type = reg_type;
5042                 }
5043
5044         } else if (reg->type == PTR_TO_STACK) {
5045                 /* Basic bounds checks. */
5046                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5047                 if (err)
5048                         return err;
5049
5050                 state = func(env, reg);
5051                 err = update_stack_depth(env, state, off);
5052                 if (err)
5053                         return err;
5054
5055                 if (t == BPF_READ)
5056                         err = check_stack_read(env, regno, off, size,
5057                                                value_regno);
5058                 else
5059                         err = check_stack_write(env, regno, off, size,
5060                                                 value_regno, insn_idx);
5061         } else if (reg_is_pkt_pointer(reg)) {
5062                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5063                         verbose(env, "cannot write into packet\n");
5064                         return -EACCES;
5065                 }
5066                 if (t == BPF_WRITE && value_regno >= 0 &&
5067                     is_pointer_value(env, value_regno)) {
5068                         verbose(env, "R%d leaks addr into packet\n",
5069                                 value_regno);
5070                         return -EACCES;
5071                 }
5072                 err = check_packet_access(env, regno, off, size, false);
5073                 if (!err && t == BPF_READ && value_regno >= 0)
5074                         mark_reg_unknown(env, regs, value_regno);
5075         } else if (reg->type == PTR_TO_FLOW_KEYS) {
5076                 if (t == BPF_WRITE && value_regno >= 0 &&
5077                     is_pointer_value(env, value_regno)) {
5078                         verbose(env, "R%d leaks addr into flow keys\n",
5079                                 value_regno);
5080                         return -EACCES;
5081                 }
5082
5083                 err = check_flow_keys_access(env, off, size);
5084                 if (!err && t == BPF_READ && value_regno >= 0)
5085                         mark_reg_unknown(env, regs, value_regno);
5086         } else if (type_is_sk_pointer(reg->type)) {
5087                 if (t == BPF_WRITE) {
5088                         verbose(env, "R%d cannot write into %s\n",
5089                                 regno, reg_type_str(env, reg->type));
5090                         return -EACCES;
5091                 }
5092                 err = check_sock_access(env, insn_idx, regno, off, size, t);
5093                 if (!err && value_regno >= 0)
5094                         mark_reg_unknown(env, regs, value_regno);
5095         } else if (reg->type == PTR_TO_TP_BUFFER) {
5096                 err = check_tp_buffer_access(env, reg, regno, off, size);
5097                 if (!err && t == BPF_READ && value_regno >= 0)
5098                         mark_reg_unknown(env, regs, value_regno);
5099         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5100                    !type_may_be_null(reg->type)) {
5101                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5102                                               value_regno);
5103         } else if (reg->type == CONST_PTR_TO_MAP) {
5104                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5105                                               value_regno);
5106         } else if (base_type(reg->type) == PTR_TO_BUF) {
5107                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5108                 u32 *max_access;
5109
5110                 if (rdonly_mem) {
5111                         if (t == BPF_WRITE) {
5112                                 verbose(env, "R%d cannot write into %s\n",
5113                                         regno, reg_type_str(env, reg->type));
5114                                 return -EACCES;
5115                         }
5116                         max_access = &env->prog->aux->max_rdonly_access;
5117                 } else {
5118                         max_access = &env->prog->aux->max_rdwr_access;
5119                 }
5120
5121                 err = check_buffer_access(env, reg, regno, off, size, false,
5122                                           max_access);
5123
5124                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5125                         mark_reg_unknown(env, regs, value_regno);
5126         } else {
5127                 verbose(env, "R%d invalid mem access '%s'\n", regno,
5128                         reg_type_str(env, reg->type));
5129                 return -EACCES;
5130         }
5131
5132         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5133             regs[value_regno].type == SCALAR_VALUE) {
5134                 /* b/h/w load zero-extends, mark upper bits as known 0 */
5135                 coerce_reg_to_size(&regs[value_regno], size);
5136         }
5137         return err;
5138 }
5139
5140 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5141 {
5142         int load_reg;
5143         int err;
5144
5145         switch (insn->imm) {
5146         case BPF_ADD:
5147         case BPF_ADD | BPF_FETCH:
5148         case BPF_AND:
5149         case BPF_AND | BPF_FETCH:
5150         case BPF_OR:
5151         case BPF_OR | BPF_FETCH:
5152         case BPF_XOR:
5153         case BPF_XOR | BPF_FETCH:
5154         case BPF_XCHG:
5155         case BPF_CMPXCHG:
5156                 break;
5157         default:
5158                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5159                 return -EINVAL;
5160         }
5161
5162         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5163                 verbose(env, "invalid atomic operand size\n");
5164                 return -EINVAL;
5165         }
5166
5167         /* check src1 operand */
5168         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5169         if (err)
5170                 return err;
5171
5172         /* check src2 operand */
5173         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5174         if (err)
5175                 return err;
5176
5177         if (insn->imm == BPF_CMPXCHG) {
5178                 /* Check comparison of R0 with memory location */
5179                 const u32 aux_reg = BPF_REG_0;
5180
5181                 err = check_reg_arg(env, aux_reg, SRC_OP);
5182                 if (err)
5183                         return err;
5184
5185                 if (is_pointer_value(env, aux_reg)) {
5186                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5187                         return -EACCES;
5188                 }
5189         }
5190
5191         if (is_pointer_value(env, insn->src_reg)) {
5192                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5193                 return -EACCES;
5194         }
5195
5196         if (is_ctx_reg(env, insn->dst_reg) ||
5197             is_pkt_reg(env, insn->dst_reg) ||
5198             is_flow_key_reg(env, insn->dst_reg) ||
5199             is_sk_reg(env, insn->dst_reg)) {
5200                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5201                         insn->dst_reg,
5202                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5203                 return -EACCES;
5204         }
5205
5206         if (insn->imm & BPF_FETCH) {
5207                 if (insn->imm == BPF_CMPXCHG)
5208                         load_reg = BPF_REG_0;
5209                 else
5210                         load_reg = insn->src_reg;
5211
5212                 /* check and record load of old value */
5213                 err = check_reg_arg(env, load_reg, DST_OP);
5214                 if (err)
5215                         return err;
5216         } else {
5217                 /* This instruction accesses a memory location but doesn't
5218                  * actually load it into a register.
5219                  */
5220                 load_reg = -1;
5221         }
5222
5223         /* Check whether we can read the memory, with second call for fetch
5224          * case to simulate the register fill.
5225          */
5226         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5227                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5228         if (!err && load_reg >= 0)
5229                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5230                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5231                                        true);
5232         if (err)
5233                 return err;
5234
5235         /* Check whether we can write into the same memory. */
5236         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5237                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5238         if (err)
5239                 return err;
5240
5241         return 0;
5242 }
5243
5244 /* When register 'regno' is used to read the stack (either directly or through
5245  * a helper function) make sure that it's within stack boundary and, depending
5246  * on the access type, that all elements of the stack are initialized.
5247  *
5248  * 'off' includes 'regno->off', but not its dynamic part (if any).
5249  *
5250  * All registers that have been spilled on the stack in the slots within the
5251  * read offsets are marked as read.
5252  */
5253 static int check_stack_range_initialized(
5254                 struct bpf_verifier_env *env, int regno, int off,
5255                 int access_size, bool zero_size_allowed,
5256                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5257 {
5258         struct bpf_reg_state *reg = reg_state(env, regno);
5259         struct bpf_func_state *state = func(env, reg);
5260         int err, min_off, max_off, i, j, slot, spi;
5261         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5262         enum bpf_access_type bounds_check_type;
5263         /* Some accesses can write anything into the stack, others are
5264          * read-only.
5265          */
5266         bool clobber = false;
5267
5268         if (access_size == 0 && !zero_size_allowed) {
5269                 verbose(env, "invalid zero-sized read\n");
5270                 return -EACCES;
5271         }
5272
5273         if (type == ACCESS_HELPER) {
5274                 /* The bounds checks for writes are more permissive than for
5275                  * reads. However, if raw_mode is not set, we'll do extra
5276                  * checks below.
5277                  */
5278                 bounds_check_type = BPF_WRITE;
5279                 clobber = true;
5280         } else {
5281                 bounds_check_type = BPF_READ;
5282         }
5283         err = check_stack_access_within_bounds(env, regno, off, access_size,
5284                                                type, bounds_check_type);
5285         if (err)
5286                 return err;
5287
5288
5289         if (tnum_is_const(reg->var_off)) {
5290                 min_off = max_off = reg->var_off.value + off;
5291         } else {
5292                 /* Variable offset is prohibited for unprivileged mode for
5293                  * simplicity since it requires corresponding support in
5294                  * Spectre masking for stack ALU.
5295                  * See also retrieve_ptr_limit().
5296                  */
5297                 if (!env->bypass_spec_v1) {
5298                         char tn_buf[48];
5299
5300                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5301                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5302                                 regno, err_extra, tn_buf);
5303                         return -EACCES;
5304                 }
5305                 /* Only initialized buffer on stack is allowed to be accessed
5306                  * with variable offset. With uninitialized buffer it's hard to
5307                  * guarantee that whole memory is marked as initialized on
5308                  * helper return since specific bounds are unknown what may
5309                  * cause uninitialized stack leaking.
5310                  */
5311                 if (meta && meta->raw_mode)
5312                         meta = NULL;
5313
5314                 min_off = reg->smin_value + off;
5315                 max_off = reg->smax_value + off;
5316         }
5317
5318         if (meta && meta->raw_mode) {
5319                 meta->access_size = access_size;
5320                 meta->regno = regno;
5321                 return 0;
5322         }
5323
5324         for (i = min_off; i < max_off + access_size; i++) {
5325                 u8 *stype;
5326
5327                 slot = -i - 1;
5328                 spi = slot / BPF_REG_SIZE;
5329                 if (state->allocated_stack <= slot)
5330                         goto err;
5331                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5332                 if (*stype == STACK_MISC)
5333                         goto mark;
5334                 if (*stype == STACK_ZERO) {
5335                         if (clobber) {
5336                                 /* helper can write anything into the stack */
5337                                 *stype = STACK_MISC;
5338                         }
5339                         goto mark;
5340                 }
5341
5342                 if (is_spilled_reg(&state->stack[spi]) &&
5343                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5344                      env->allow_ptr_leaks)) {
5345                         if (clobber) {
5346                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5347                                 for (j = 0; j < BPF_REG_SIZE; j++)
5348                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5349                         }
5350                         goto mark;
5351                 }
5352
5353 err:
5354                 if (tnum_is_const(reg->var_off)) {
5355                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5356                                 err_extra, regno, min_off, i - min_off, access_size);
5357                 } else {
5358                         char tn_buf[48];
5359
5360                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5361                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5362                                 err_extra, regno, tn_buf, i - min_off, access_size);
5363                 }
5364                 return -EACCES;
5365 mark:
5366                 /* reading any byte out of 8-byte 'spill_slot' will cause
5367                  * the whole slot to be marked as 'read'
5368                  */
5369                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5370                               state->stack[spi].spilled_ptr.parent,
5371                               REG_LIVE_READ64);
5372                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5373                  * be sure that whether stack slot is written to or not. Hence,
5374                  * we must still conservatively propagate reads upwards even if
5375                  * helper may write to the entire memory range.
5376                  */
5377         }
5378         return update_stack_depth(env, state, min_off);
5379 }
5380
5381 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5382                                    int access_size, bool zero_size_allowed,
5383                                    struct bpf_call_arg_meta *meta)
5384 {
5385         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5386         u32 *max_access;
5387
5388         switch (base_type(reg->type)) {
5389         case PTR_TO_PACKET:
5390         case PTR_TO_PACKET_META:
5391                 return check_packet_access(env, regno, reg->off, access_size,
5392                                            zero_size_allowed);
5393         case PTR_TO_MAP_KEY:
5394                 if (meta && meta->raw_mode) {
5395                         verbose(env, "R%d cannot write into %s\n", regno,
5396                                 reg_type_str(env, reg->type));
5397                         return -EACCES;
5398                 }
5399                 return check_mem_region_access(env, regno, reg->off, access_size,
5400                                                reg->map_ptr->key_size, false);
5401         case PTR_TO_MAP_VALUE:
5402                 if (check_map_access_type(env, regno, reg->off, access_size,
5403                                           meta && meta->raw_mode ? BPF_WRITE :
5404                                           BPF_READ))
5405                         return -EACCES;
5406                 return check_map_access(env, regno, reg->off, access_size,
5407                                         zero_size_allowed, ACCESS_HELPER);
5408         case PTR_TO_MEM:
5409                 if (type_is_rdonly_mem(reg->type)) {
5410                         if (meta && meta->raw_mode) {
5411                                 verbose(env, "R%d cannot write into %s\n", regno,
5412                                         reg_type_str(env, reg->type));
5413                                 return -EACCES;
5414                         }
5415                 }
5416                 return check_mem_region_access(env, regno, reg->off,
5417                                                access_size, reg->mem_size,
5418                                                zero_size_allowed);
5419         case PTR_TO_BUF:
5420                 if (type_is_rdonly_mem(reg->type)) {
5421                         if (meta && meta->raw_mode) {
5422                                 verbose(env, "R%d cannot write into %s\n", regno,
5423                                         reg_type_str(env, reg->type));
5424                                 return -EACCES;
5425                         }
5426
5427                         max_access = &env->prog->aux->max_rdonly_access;
5428                 } else {
5429                         max_access = &env->prog->aux->max_rdwr_access;
5430                 }
5431                 return check_buffer_access(env, reg, regno, reg->off,
5432                                            access_size, zero_size_allowed,
5433                                            max_access);
5434         case PTR_TO_STACK:
5435                 return check_stack_range_initialized(
5436                                 env,
5437                                 regno, reg->off, access_size,
5438                                 zero_size_allowed, ACCESS_HELPER, meta);
5439         case PTR_TO_CTX:
5440                 /* in case the function doesn't know how to access the context,
5441                  * (because we are in a program of type SYSCALL for example), we
5442                  * can not statically check its size.
5443                  * Dynamically check it now.
5444                  */
5445                 if (!env->ops->convert_ctx_access) {
5446                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5447                         int offset = access_size - 1;
5448
5449                         /* Allow zero-byte read from PTR_TO_CTX */
5450                         if (access_size == 0)
5451                                 return zero_size_allowed ? 0 : -EACCES;
5452
5453                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5454                                                 atype, -1, false);
5455                 }
5456
5457                 fallthrough;
5458         default: /* scalar_value or invalid ptr */
5459                 /* Allow zero-byte read from NULL, regardless of pointer type */
5460                 if (zero_size_allowed && access_size == 0 &&
5461                     register_is_null(reg))
5462                         return 0;
5463
5464                 verbose(env, "R%d type=%s ", regno,
5465                         reg_type_str(env, reg->type));
5466                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5467                 return -EACCES;
5468         }
5469 }
5470
5471 static int check_mem_size_reg(struct bpf_verifier_env *env,
5472                               struct bpf_reg_state *reg, u32 regno,
5473                               bool zero_size_allowed,
5474                               struct bpf_call_arg_meta *meta)
5475 {
5476         int err;
5477
5478         /* This is used to refine r0 return value bounds for helpers
5479          * that enforce this value as an upper bound on return values.
5480          * See do_refine_retval_range() for helpers that can refine
5481          * the return value. C type of helper is u32 so we pull register
5482          * bound from umax_value however, if negative verifier errors
5483          * out. Only upper bounds can be learned because retval is an
5484          * int type and negative retvals are allowed.
5485          */
5486         meta->msize_max_value = reg->umax_value;
5487
5488         /* The register is SCALAR_VALUE; the access check
5489          * happens using its boundaries.
5490          */
5491         if (!tnum_is_const(reg->var_off))
5492                 /* For unprivileged variable accesses, disable raw
5493                  * mode so that the program is required to
5494                  * initialize all the memory that the helper could
5495                  * just partially fill up.
5496                  */
5497                 meta = NULL;
5498
5499         if (reg->smin_value < 0) {
5500                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5501                         regno);
5502                 return -EACCES;
5503         }
5504
5505         if (reg->umin_value == 0) {
5506                 err = check_helper_mem_access(env, regno - 1, 0,
5507                                               zero_size_allowed,
5508                                               meta);
5509                 if (err)
5510                         return err;
5511         }
5512
5513         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5514                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5515                         regno);
5516                 return -EACCES;
5517         }
5518         err = check_helper_mem_access(env, regno - 1,
5519                                       reg->umax_value,
5520                                       zero_size_allowed, meta);
5521         if (!err)
5522                 err = mark_chain_precision(env, regno);
5523         return err;
5524 }
5525
5526 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5527                    u32 regno, u32 mem_size)
5528 {
5529         bool may_be_null = type_may_be_null(reg->type);
5530         struct bpf_reg_state saved_reg;
5531         struct bpf_call_arg_meta meta;
5532         int err;
5533
5534         if (register_is_null(reg))
5535                 return 0;
5536
5537         memset(&meta, 0, sizeof(meta));
5538         /* Assuming that the register contains a value check if the memory
5539          * access is safe. Temporarily save and restore the register's state as
5540          * the conversion shouldn't be visible to a caller.
5541          */
5542         if (may_be_null) {
5543                 saved_reg = *reg;
5544                 mark_ptr_not_null_reg(reg);
5545         }
5546
5547         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5548         /* Check access for BPF_WRITE */
5549         meta.raw_mode = true;
5550         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5551
5552         if (may_be_null)
5553                 *reg = saved_reg;
5554
5555         return err;
5556 }
5557
5558 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5559                                     u32 regno)
5560 {
5561         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5562         bool may_be_null = type_may_be_null(mem_reg->type);
5563         struct bpf_reg_state saved_reg;
5564         struct bpf_call_arg_meta meta;
5565         int err;
5566
5567         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5568
5569         memset(&meta, 0, sizeof(meta));
5570
5571         if (may_be_null) {
5572                 saved_reg = *mem_reg;
5573                 mark_ptr_not_null_reg(mem_reg);
5574         }
5575
5576         err = check_mem_size_reg(env, reg, regno, true, &meta);
5577         /* Check access for BPF_WRITE */
5578         meta.raw_mode = true;
5579         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5580
5581         if (may_be_null)
5582                 *mem_reg = saved_reg;
5583         return err;
5584 }
5585
5586 /* Implementation details:
5587  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5588  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
5589  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5590  * Two separate bpf_obj_new will also have different reg->id.
5591  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5592  * clears reg->id after value_or_null->value transition, since the verifier only
5593  * cares about the range of access to valid map value pointer and doesn't care
5594  * about actual address of the map element.
5595  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5596  * reg->id > 0 after value_or_null->value transition. By doing so
5597  * two bpf_map_lookups will be considered two different pointers that
5598  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5599  * returned from bpf_obj_new.
5600  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5601  * dead-locks.
5602  * Since only one bpf_spin_lock is allowed the checks are simpler than
5603  * reg_is_refcounted() logic. The verifier needs to remember only
5604  * one spin_lock instead of array of acquired_refs.
5605  * cur_state->active_lock remembers which map value element or allocated
5606  * object got locked and clears it after bpf_spin_unlock.
5607  */
5608 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5609                              bool is_lock)
5610 {
5611         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5612         struct bpf_verifier_state *cur = env->cur_state;
5613         bool is_const = tnum_is_const(reg->var_off);
5614         u64 val = reg->var_off.value;
5615         struct bpf_map *map = NULL;
5616         struct btf *btf = NULL;
5617         struct btf_record *rec;
5618
5619         if (!is_const) {
5620                 verbose(env,
5621                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5622                         regno);
5623                 return -EINVAL;
5624         }
5625         if (reg->type == PTR_TO_MAP_VALUE) {
5626                 map = reg->map_ptr;
5627                 if (!map->btf) {
5628                         verbose(env,
5629                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5630                                 map->name);
5631                         return -EINVAL;
5632                 }
5633         } else {
5634                 btf = reg->btf;
5635         }
5636
5637         rec = reg_btf_record(reg);
5638         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5639                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5640                         map ? map->name : "kptr");
5641                 return -EINVAL;
5642         }
5643         if (rec->spin_lock_off != val + reg->off) {
5644                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
5645                         val + reg->off, rec->spin_lock_off);
5646                 return -EINVAL;
5647         }
5648         if (is_lock) {
5649                 if (cur->active_lock.ptr) {
5650                         verbose(env,
5651                                 "Locking two bpf_spin_locks are not allowed\n");
5652                         return -EINVAL;
5653                 }
5654                 if (map)
5655                         cur->active_lock.ptr = map;
5656                 else
5657                         cur->active_lock.ptr = btf;
5658                 cur->active_lock.id = reg->id;
5659         } else {
5660                 struct bpf_func_state *fstate = cur_func(env);
5661                 void *ptr;
5662                 int i;
5663
5664                 if (map)
5665                         ptr = map;
5666                 else
5667                         ptr = btf;
5668
5669                 if (!cur->active_lock.ptr) {
5670                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5671                         return -EINVAL;
5672                 }
5673                 if (cur->active_lock.ptr != ptr ||
5674                     cur->active_lock.id != reg->id) {
5675                         verbose(env, "bpf_spin_unlock of different lock\n");
5676                         return -EINVAL;
5677                 }
5678                 cur->active_lock.ptr = NULL;
5679                 cur->active_lock.id = 0;
5680
5681                 for (i = 0; i < fstate->acquired_refs; i++) {
5682                         int err;
5683
5684                         /* Complain on error because this reference state cannot
5685                          * be freed before this point, as bpf_spin_lock critical
5686                          * section does not allow functions that release the
5687                          * allocated object immediately.
5688                          */
5689                         if (!fstate->refs[i].release_on_unlock)
5690                                 continue;
5691                         err = release_reference(env, fstate->refs[i].id);
5692                         if (err) {
5693                                 verbose(env, "failed to release release_on_unlock reference");
5694                                 return err;
5695                         }
5696                 }
5697         }
5698         return 0;
5699 }
5700
5701 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5702                               struct bpf_call_arg_meta *meta)
5703 {
5704         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5705         bool is_const = tnum_is_const(reg->var_off);
5706         struct bpf_map *map = reg->map_ptr;
5707         u64 val = reg->var_off.value;
5708
5709         if (!is_const) {
5710                 verbose(env,
5711                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5712                         regno);
5713                 return -EINVAL;
5714         }
5715         if (!map->btf) {
5716                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5717                         map->name);
5718                 return -EINVAL;
5719         }
5720         if (!btf_record_has_field(map->record, BPF_TIMER)) {
5721                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
5722                 return -EINVAL;
5723         }
5724         if (map->record->timer_off != val + reg->off) {
5725                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5726                         val + reg->off, map->record->timer_off);
5727                 return -EINVAL;
5728         }
5729         if (meta->map_ptr) {
5730                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5731                 return -EFAULT;
5732         }
5733         meta->map_uid = reg->map_uid;
5734         meta->map_ptr = map;
5735         return 0;
5736 }
5737
5738 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5739                              struct bpf_call_arg_meta *meta)
5740 {
5741         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5742         struct bpf_map *map_ptr = reg->map_ptr;
5743         struct btf_field *kptr_field;
5744         u32 kptr_off;
5745
5746         if (!tnum_is_const(reg->var_off)) {
5747                 verbose(env,
5748                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5749                         regno);
5750                 return -EINVAL;
5751         }
5752         if (!map_ptr->btf) {
5753                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5754                         map_ptr->name);
5755                 return -EINVAL;
5756         }
5757         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5758                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5759                 return -EINVAL;
5760         }
5761
5762         meta->map_ptr = map_ptr;
5763         kptr_off = reg->off + reg->var_off.value;
5764         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5765         if (!kptr_field) {
5766                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5767                 return -EACCES;
5768         }
5769         if (kptr_field->type != BPF_KPTR_REF) {
5770                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5771                 return -EACCES;
5772         }
5773         meta->kptr_field = kptr_field;
5774         return 0;
5775 }
5776
5777 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5778 {
5779         return type == ARG_CONST_SIZE ||
5780                type == ARG_CONST_SIZE_OR_ZERO;
5781 }
5782
5783 static bool arg_type_is_release(enum bpf_arg_type type)
5784 {
5785         return type & OBJ_RELEASE;
5786 }
5787
5788 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5789 {
5790         return base_type(type) == ARG_PTR_TO_DYNPTR;
5791 }
5792
5793 static int int_ptr_type_to_size(enum bpf_arg_type type)
5794 {
5795         if (type == ARG_PTR_TO_INT)
5796                 return sizeof(u32);
5797         else if (type == ARG_PTR_TO_LONG)
5798                 return sizeof(u64);
5799
5800         return -EINVAL;
5801 }
5802
5803 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5804                                  const struct bpf_call_arg_meta *meta,
5805                                  enum bpf_arg_type *arg_type)
5806 {
5807         if (!meta->map_ptr) {
5808                 /* kernel subsystem misconfigured verifier */
5809                 verbose(env, "invalid map_ptr to access map->type\n");
5810                 return -EACCES;
5811         }
5812
5813         switch (meta->map_ptr->map_type) {
5814         case BPF_MAP_TYPE_SOCKMAP:
5815         case BPF_MAP_TYPE_SOCKHASH:
5816                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5817                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5818                 } else {
5819                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5820                         return -EINVAL;
5821                 }
5822                 break;
5823         case BPF_MAP_TYPE_BLOOM_FILTER:
5824                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5825                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5826                 break;
5827         default:
5828                 break;
5829         }
5830         return 0;
5831 }
5832
5833 struct bpf_reg_types {
5834         const enum bpf_reg_type types[10];
5835         u32 *btf_id;
5836 };
5837
5838 static const struct bpf_reg_types sock_types = {
5839         .types = {
5840                 PTR_TO_SOCK_COMMON,
5841                 PTR_TO_SOCKET,
5842                 PTR_TO_TCP_SOCK,
5843                 PTR_TO_XDP_SOCK,
5844         },
5845 };
5846
5847 #ifdef CONFIG_NET
5848 static const struct bpf_reg_types btf_id_sock_common_types = {
5849         .types = {
5850                 PTR_TO_SOCK_COMMON,
5851                 PTR_TO_SOCKET,
5852                 PTR_TO_TCP_SOCK,
5853                 PTR_TO_XDP_SOCK,
5854                 PTR_TO_BTF_ID,
5855                 PTR_TO_BTF_ID | PTR_TRUSTED,
5856         },
5857         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5858 };
5859 #endif
5860
5861 static const struct bpf_reg_types mem_types = {
5862         .types = {
5863                 PTR_TO_STACK,
5864                 PTR_TO_PACKET,
5865                 PTR_TO_PACKET_META,
5866                 PTR_TO_MAP_KEY,
5867                 PTR_TO_MAP_VALUE,
5868                 PTR_TO_MEM,
5869                 PTR_TO_MEM | MEM_RINGBUF,
5870                 PTR_TO_BUF,
5871         },
5872 };
5873
5874 static const struct bpf_reg_types int_ptr_types = {
5875         .types = {
5876                 PTR_TO_STACK,
5877                 PTR_TO_PACKET,
5878                 PTR_TO_PACKET_META,
5879                 PTR_TO_MAP_KEY,
5880                 PTR_TO_MAP_VALUE,
5881         },
5882 };
5883
5884 static const struct bpf_reg_types spin_lock_types = {
5885         .types = {
5886                 PTR_TO_MAP_VALUE,
5887                 PTR_TO_BTF_ID | MEM_ALLOC,
5888         }
5889 };
5890
5891 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5892 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5893 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5894 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
5895 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5896 static const struct bpf_reg_types btf_ptr_types = {
5897         .types = {
5898                 PTR_TO_BTF_ID,
5899                 PTR_TO_BTF_ID | PTR_TRUSTED,
5900         },
5901 };
5902 static const struct bpf_reg_types percpu_btf_ptr_types = {
5903         .types = {
5904                 PTR_TO_BTF_ID | MEM_PERCPU,
5905                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
5906         }
5907 };
5908 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5909 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5910 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5911 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5912 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5913 static const struct bpf_reg_types dynptr_types = {
5914         .types = {
5915                 PTR_TO_STACK,
5916                 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5917         }
5918 };
5919
5920 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5921         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
5922         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
5923         [ARG_CONST_SIZE]                = &scalar_types,
5924         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5925         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5926         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5927         [ARG_PTR_TO_CTX]                = &context_types,
5928         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5929 #ifdef CONFIG_NET
5930         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5931 #endif
5932         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5933         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5934         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5935         [ARG_PTR_TO_MEM]                = &mem_types,
5936         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
5937         [ARG_PTR_TO_INT]                = &int_ptr_types,
5938         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5939         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5940         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5941         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5942         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5943         [ARG_PTR_TO_TIMER]              = &timer_types,
5944         [ARG_PTR_TO_KPTR]               = &kptr_types,
5945         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
5946 };
5947
5948 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5949                           enum bpf_arg_type arg_type,
5950                           const u32 *arg_btf_id,
5951                           struct bpf_call_arg_meta *meta)
5952 {
5953         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5954         enum bpf_reg_type expected, type = reg->type;
5955         const struct bpf_reg_types *compatible;
5956         int i, j;
5957
5958         compatible = compatible_reg_types[base_type(arg_type)];
5959         if (!compatible) {
5960                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5961                 return -EFAULT;
5962         }
5963
5964         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5965          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5966          *
5967          * Same for MAYBE_NULL:
5968          *
5969          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5970          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5971          *
5972          * Therefore we fold these flags depending on the arg_type before comparison.
5973          */
5974         if (arg_type & MEM_RDONLY)
5975                 type &= ~MEM_RDONLY;
5976         if (arg_type & PTR_MAYBE_NULL)
5977                 type &= ~PTR_MAYBE_NULL;
5978
5979         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5980                 expected = compatible->types[i];
5981                 if (expected == NOT_INIT)
5982                         break;
5983
5984                 if (type == expected)
5985                         goto found;
5986         }
5987
5988         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5989         for (j = 0; j + 1 < i; j++)
5990                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5991         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5992         return -EACCES;
5993
5994 found:
5995         if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
5996                 /* For bpf_sk_release, it needs to match against first member
5997                  * 'struct sock_common', hence make an exception for it. This
5998                  * allows bpf_sk_release to work for multiple socket types.
5999                  */
6000                 bool strict_type_match = arg_type_is_release(arg_type) &&
6001                                          meta->func_id != BPF_FUNC_sk_release;
6002
6003                 if (!arg_btf_id) {
6004                         if (!compatible->btf_id) {
6005                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6006                                 return -EFAULT;
6007                         }
6008                         arg_btf_id = compatible->btf_id;
6009                 }
6010
6011                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
6012                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
6013                                 return -EACCES;
6014                 } else {
6015                         if (arg_btf_id == BPF_PTR_POISON) {
6016                                 verbose(env, "verifier internal error:");
6017                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6018                                         regno);
6019                                 return -EACCES;
6020                         }
6021
6022                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6023                                                   btf_vmlinux, *arg_btf_id,
6024                                                   strict_type_match)) {
6025                                 verbose(env, "R%d is of type %s but %s is expected\n",
6026                                         regno, kernel_type_name(reg->btf, reg->btf_id),
6027                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
6028                                 return -EACCES;
6029                         }
6030                 }
6031         } else if (type_is_alloc(reg->type)) {
6032                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6033                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6034                         return -EFAULT;
6035                 }
6036         }
6037
6038         return 0;
6039 }
6040
6041 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6042                            const struct bpf_reg_state *reg, int regno,
6043                            enum bpf_arg_type arg_type)
6044 {
6045         enum bpf_reg_type type = reg->type;
6046         bool fixed_off_ok = false;
6047
6048         switch ((u32)type) {
6049         /* Pointer types where reg offset is explicitly allowed: */
6050         case PTR_TO_STACK:
6051                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
6052                         verbose(env, "cannot pass in dynptr at an offset\n");
6053                         return -EINVAL;
6054                 }
6055                 fallthrough;
6056         case PTR_TO_PACKET:
6057         case PTR_TO_PACKET_META:
6058         case PTR_TO_MAP_KEY:
6059         case PTR_TO_MAP_VALUE:
6060         case PTR_TO_MEM:
6061         case PTR_TO_MEM | MEM_RDONLY:
6062         case PTR_TO_MEM | MEM_RINGBUF:
6063         case PTR_TO_BUF:
6064         case PTR_TO_BUF | MEM_RDONLY:
6065         case SCALAR_VALUE:
6066                 /* Some of the argument types nevertheless require a
6067                  * zero register offset.
6068                  */
6069                 if (base_type(arg_type) != ARG_PTR_TO_RINGBUF_MEM)
6070                         return 0;
6071                 break;
6072         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6073          * fixed offset.
6074          */
6075         case PTR_TO_BTF_ID:
6076         case PTR_TO_BTF_ID | MEM_ALLOC:
6077         case PTR_TO_BTF_ID | PTR_TRUSTED:
6078         case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
6079                 /* When referenced PTR_TO_BTF_ID is passed to release function,
6080                  * it's fixed offset must be 0. In the other cases, fixed offset
6081                  * can be non-zero.
6082                  */
6083                 if (arg_type_is_release(arg_type) && reg->off) {
6084                         verbose(env, "R%d must have zero offset when passed to release func\n",
6085                                 regno);
6086                         return -EINVAL;
6087                 }
6088                 /* For arg is release pointer, fixed_off_ok must be false, but
6089                  * we already checked and rejected reg->off != 0 above, so set
6090                  * to true to allow fixed offset for all other cases.
6091                  */
6092                 fixed_off_ok = true;
6093                 break;
6094         default:
6095                 break;
6096         }
6097         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
6098 }
6099
6100 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6101 {
6102         struct bpf_func_state *state = func(env, reg);
6103         int spi = get_spi(reg->off);
6104
6105         return state->stack[spi].spilled_ptr.id;
6106 }
6107
6108 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6109                           struct bpf_call_arg_meta *meta,
6110                           const struct bpf_func_proto *fn)
6111 {
6112         u32 regno = BPF_REG_1 + arg;
6113         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6114         enum bpf_arg_type arg_type = fn->arg_type[arg];
6115         enum bpf_reg_type type = reg->type;
6116         u32 *arg_btf_id = NULL;
6117         int err = 0;
6118
6119         if (arg_type == ARG_DONTCARE)
6120                 return 0;
6121
6122         err = check_reg_arg(env, regno, SRC_OP);
6123         if (err)
6124                 return err;
6125
6126         if (arg_type == ARG_ANYTHING) {
6127                 if (is_pointer_value(env, regno)) {
6128                         verbose(env, "R%d leaks addr into helper function\n",
6129                                 regno);
6130                         return -EACCES;
6131                 }
6132                 return 0;
6133         }
6134
6135         if (type_is_pkt_pointer(type) &&
6136             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6137                 verbose(env, "helper access to the packet is not allowed\n");
6138                 return -EACCES;
6139         }
6140
6141         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6142                 err = resolve_map_arg_type(env, meta, &arg_type);
6143                 if (err)
6144                         return err;
6145         }
6146
6147         if (register_is_null(reg) && type_may_be_null(arg_type))
6148                 /* A NULL register has a SCALAR_VALUE type, so skip
6149                  * type checking.
6150                  */
6151                 goto skip_type_check;
6152
6153         /* arg_btf_id and arg_size are in a union. */
6154         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6155             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
6156                 arg_btf_id = fn->arg_btf_id[arg];
6157
6158         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6159         if (err)
6160                 return err;
6161
6162         err = check_func_arg_reg_off(env, reg, regno, arg_type);
6163         if (err)
6164                 return err;
6165
6166 skip_type_check:
6167         if (arg_type_is_release(arg_type)) {
6168                 if (arg_type_is_dynptr(arg_type)) {
6169                         struct bpf_func_state *state = func(env, reg);
6170                         int spi = get_spi(reg->off);
6171
6172                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6173                             !state->stack[spi].spilled_ptr.id) {
6174                                 verbose(env, "arg %d is an unacquired reference\n", regno);
6175                                 return -EINVAL;
6176                         }
6177                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6178                         verbose(env, "R%d must be referenced when passed to release function\n",
6179                                 regno);
6180                         return -EINVAL;
6181                 }
6182                 if (meta->release_regno) {
6183                         verbose(env, "verifier internal error: more than one release argument\n");
6184                         return -EFAULT;
6185                 }
6186                 meta->release_regno = regno;
6187         }
6188
6189         if (reg->ref_obj_id) {
6190                 if (meta->ref_obj_id) {
6191                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6192                                 regno, reg->ref_obj_id,
6193                                 meta->ref_obj_id);
6194                         return -EFAULT;
6195                 }
6196                 meta->ref_obj_id = reg->ref_obj_id;
6197         }
6198
6199         switch (base_type(arg_type)) {
6200         case ARG_CONST_MAP_PTR:
6201                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6202                 if (meta->map_ptr) {
6203                         /* Use map_uid (which is unique id of inner map) to reject:
6204                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6205                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6206                          * if (inner_map1 && inner_map2) {
6207                          *     timer = bpf_map_lookup_elem(inner_map1);
6208                          *     if (timer)
6209                          *         // mismatch would have been allowed
6210                          *         bpf_timer_init(timer, inner_map2);
6211                          * }
6212                          *
6213                          * Comparing map_ptr is enough to distinguish normal and outer maps.
6214                          */
6215                         if (meta->map_ptr != reg->map_ptr ||
6216                             meta->map_uid != reg->map_uid) {
6217                                 verbose(env,
6218                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6219                                         meta->map_uid, reg->map_uid);
6220                                 return -EINVAL;
6221                         }
6222                 }
6223                 meta->map_ptr = reg->map_ptr;
6224                 meta->map_uid = reg->map_uid;
6225                 break;
6226         case ARG_PTR_TO_MAP_KEY:
6227                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6228                  * check that [key, key + map->key_size) are within
6229                  * stack limits and initialized
6230                  */
6231                 if (!meta->map_ptr) {
6232                         /* in function declaration map_ptr must come before
6233                          * map_key, so that it's verified and known before
6234                          * we have to check map_key here. Otherwise it means
6235                          * that kernel subsystem misconfigured verifier
6236                          */
6237                         verbose(env, "invalid map_ptr to access map->key\n");
6238                         return -EACCES;
6239                 }
6240                 err = check_helper_mem_access(env, regno,
6241                                               meta->map_ptr->key_size, false,
6242                                               NULL);
6243                 break;
6244         case ARG_PTR_TO_MAP_VALUE:
6245                 if (type_may_be_null(arg_type) && register_is_null(reg))
6246                         return 0;
6247
6248                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6249                  * check [value, value + map->value_size) validity
6250                  */
6251                 if (!meta->map_ptr) {
6252                         /* kernel subsystem misconfigured verifier */
6253                         verbose(env, "invalid map_ptr to access map->value\n");
6254                         return -EACCES;
6255                 }
6256                 meta->raw_mode = arg_type & MEM_UNINIT;
6257                 err = check_helper_mem_access(env, regno,
6258                                               meta->map_ptr->value_size, false,
6259                                               meta);
6260                 break;
6261         case ARG_PTR_TO_PERCPU_BTF_ID:
6262                 if (!reg->btf_id) {
6263                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6264                         return -EACCES;
6265                 }
6266                 meta->ret_btf = reg->btf;
6267                 meta->ret_btf_id = reg->btf_id;
6268                 break;
6269         case ARG_PTR_TO_SPIN_LOCK:
6270                 if (meta->func_id == BPF_FUNC_spin_lock) {
6271                         if (process_spin_lock(env, regno, true))
6272                                 return -EACCES;
6273                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6274                         if (process_spin_lock(env, regno, false))
6275                                 return -EACCES;
6276                 } else {
6277                         verbose(env, "verifier internal error\n");
6278                         return -EFAULT;
6279                 }
6280                 break;
6281         case ARG_PTR_TO_TIMER:
6282                 if (process_timer_func(env, regno, meta))
6283                         return -EACCES;
6284                 break;
6285         case ARG_PTR_TO_FUNC:
6286                 meta->subprogno = reg->subprogno;
6287                 break;
6288         case ARG_PTR_TO_MEM:
6289                 /* The access to this pointer is only checked when we hit the
6290                  * next is_mem_size argument below.
6291                  */
6292                 meta->raw_mode = arg_type & MEM_UNINIT;
6293                 if (arg_type & MEM_FIXED_SIZE) {
6294                         err = check_helper_mem_access(env, regno,
6295                                                       fn->arg_size[arg], false,
6296                                                       meta);
6297                 }
6298                 break;
6299         case ARG_CONST_SIZE:
6300                 err = check_mem_size_reg(env, reg, regno, false, meta);
6301                 break;
6302         case ARG_CONST_SIZE_OR_ZERO:
6303                 err = check_mem_size_reg(env, reg, regno, true, meta);
6304                 break;
6305         case ARG_PTR_TO_DYNPTR:
6306                 /* We only need to check for initialized / uninitialized helper
6307                  * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6308                  * assumption is that if it is, that a helper function
6309                  * initialized the dynptr on behalf of the BPF program.
6310                  */
6311                 if (base_type(reg->type) == PTR_TO_DYNPTR)
6312                         break;
6313                 if (arg_type & MEM_UNINIT) {
6314                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6315                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6316                                 return -EINVAL;
6317                         }
6318
6319                         /* We only support one dynptr being uninitialized at the moment,
6320                          * which is sufficient for the helper functions we have right now.
6321                          */
6322                         if (meta->uninit_dynptr_regno) {
6323                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6324                                 return -EFAULT;
6325                         }
6326
6327                         meta->uninit_dynptr_regno = regno;
6328                 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6329                         verbose(env,
6330                                 "Expected an initialized dynptr as arg #%d\n",
6331                                 arg + 1);
6332                         return -EINVAL;
6333                 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6334                         const char *err_extra = "";
6335
6336                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6337                         case DYNPTR_TYPE_LOCAL:
6338                                 err_extra = "local";
6339                                 break;
6340                         case DYNPTR_TYPE_RINGBUF:
6341                                 err_extra = "ringbuf";
6342                                 break;
6343                         default:
6344                                 err_extra = "<unknown>";
6345                                 break;
6346                         }
6347                         verbose(env,
6348                                 "Expected a dynptr of type %s as arg #%d\n",
6349                                 err_extra, arg + 1);
6350                         return -EINVAL;
6351                 }
6352                 break;
6353         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6354                 if (!tnum_is_const(reg->var_off)) {
6355                         verbose(env, "R%d is not a known constant'\n",
6356                                 regno);
6357                         return -EACCES;
6358                 }
6359                 meta->mem_size = reg->var_off.value;
6360                 err = mark_chain_precision(env, regno);
6361                 if (err)
6362                         return err;
6363                 break;
6364         case ARG_PTR_TO_INT:
6365         case ARG_PTR_TO_LONG:
6366         {
6367                 int size = int_ptr_type_to_size(arg_type);
6368
6369                 err = check_helper_mem_access(env, regno, size, false, meta);
6370                 if (err)
6371                         return err;
6372                 err = check_ptr_alignment(env, reg, 0, size, true);
6373                 break;
6374         }
6375         case ARG_PTR_TO_CONST_STR:
6376         {
6377                 struct bpf_map *map = reg->map_ptr;
6378                 int map_off;
6379                 u64 map_addr;
6380                 char *str_ptr;
6381
6382                 if (!bpf_map_is_rdonly(map)) {
6383                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6384                         return -EACCES;
6385                 }
6386
6387                 if (!tnum_is_const(reg->var_off)) {
6388                         verbose(env, "R%d is not a constant address'\n", regno);
6389                         return -EACCES;
6390                 }
6391
6392                 if (!map->ops->map_direct_value_addr) {
6393                         verbose(env, "no direct value access support for this map type\n");
6394                         return -EACCES;
6395                 }
6396
6397                 err = check_map_access(env, regno, reg->off,
6398                                        map->value_size - reg->off, false,
6399                                        ACCESS_HELPER);
6400                 if (err)
6401                         return err;
6402
6403                 map_off = reg->off + reg->var_off.value;
6404                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6405                 if (err) {
6406                         verbose(env, "direct value access on string failed\n");
6407                         return err;
6408                 }
6409
6410                 str_ptr = (char *)(long)(map_addr);
6411                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6412                         verbose(env, "string is not zero-terminated\n");
6413                         return -EINVAL;
6414                 }
6415                 break;
6416         }
6417         case ARG_PTR_TO_KPTR:
6418                 if (process_kptr_func(env, regno, meta))
6419                         return -EACCES;
6420                 break;
6421         }
6422
6423         return err;
6424 }
6425
6426 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6427 {
6428         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6429         enum bpf_prog_type type = resolve_prog_type(env->prog);
6430
6431         if (func_id != BPF_FUNC_map_update_elem)
6432                 return false;
6433
6434         /* It's not possible to get access to a locked struct sock in these
6435          * contexts, so updating is safe.
6436          */
6437         switch (type) {
6438         case BPF_PROG_TYPE_TRACING:
6439                 if (eatype == BPF_TRACE_ITER)
6440                         return true;
6441                 break;
6442         case BPF_PROG_TYPE_SOCKET_FILTER:
6443         case BPF_PROG_TYPE_SCHED_CLS:
6444         case BPF_PROG_TYPE_SCHED_ACT:
6445         case BPF_PROG_TYPE_XDP:
6446         case BPF_PROG_TYPE_SK_REUSEPORT:
6447         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6448         case BPF_PROG_TYPE_SK_LOOKUP:
6449                 return true;
6450         default:
6451                 break;
6452         }
6453
6454         verbose(env, "cannot update sockmap in this context\n");
6455         return false;
6456 }
6457
6458 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6459 {
6460         return env->prog->jit_requested &&
6461                bpf_jit_supports_subprog_tailcalls();
6462 }
6463
6464 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6465                                         struct bpf_map *map, int func_id)
6466 {
6467         if (!map)
6468                 return 0;
6469
6470         /* We need a two way check, first is from map perspective ... */
6471         switch (map->map_type) {
6472         case BPF_MAP_TYPE_PROG_ARRAY:
6473                 if (func_id != BPF_FUNC_tail_call)
6474                         goto error;
6475                 break;
6476         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6477                 if (func_id != BPF_FUNC_perf_event_read &&
6478                     func_id != BPF_FUNC_perf_event_output &&
6479                     func_id != BPF_FUNC_skb_output &&
6480                     func_id != BPF_FUNC_perf_event_read_value &&
6481                     func_id != BPF_FUNC_xdp_output)
6482                         goto error;
6483                 break;
6484         case BPF_MAP_TYPE_RINGBUF:
6485                 if (func_id != BPF_FUNC_ringbuf_output &&
6486                     func_id != BPF_FUNC_ringbuf_reserve &&
6487                     func_id != BPF_FUNC_ringbuf_query &&
6488                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6489                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6490                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6491                         goto error;
6492                 break;
6493         case BPF_MAP_TYPE_USER_RINGBUF:
6494                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6495                         goto error;
6496                 break;
6497         case BPF_MAP_TYPE_STACK_TRACE:
6498                 if (func_id != BPF_FUNC_get_stackid)
6499                         goto error;
6500                 break;
6501         case BPF_MAP_TYPE_CGROUP_ARRAY:
6502                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6503                     func_id != BPF_FUNC_current_task_under_cgroup)
6504                         goto error;
6505                 break;
6506         case BPF_MAP_TYPE_CGROUP_STORAGE:
6507         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6508                 if (func_id != BPF_FUNC_get_local_storage)
6509                         goto error;
6510                 break;
6511         case BPF_MAP_TYPE_DEVMAP:
6512         case BPF_MAP_TYPE_DEVMAP_HASH:
6513                 if (func_id != BPF_FUNC_redirect_map &&
6514                     func_id != BPF_FUNC_map_lookup_elem)
6515                         goto error;
6516                 break;
6517         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6518          * appear.
6519          */
6520         case BPF_MAP_TYPE_CPUMAP:
6521                 if (func_id != BPF_FUNC_redirect_map)
6522                         goto error;
6523                 break;
6524         case BPF_MAP_TYPE_XSKMAP:
6525                 if (func_id != BPF_FUNC_redirect_map &&
6526                     func_id != BPF_FUNC_map_lookup_elem)
6527                         goto error;
6528                 break;
6529         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6530         case BPF_MAP_TYPE_HASH_OF_MAPS:
6531                 if (func_id != BPF_FUNC_map_lookup_elem)
6532                         goto error;
6533                 break;
6534         case BPF_MAP_TYPE_SOCKMAP:
6535                 if (func_id != BPF_FUNC_sk_redirect_map &&
6536                     func_id != BPF_FUNC_sock_map_update &&
6537                     func_id != BPF_FUNC_map_delete_elem &&
6538                     func_id != BPF_FUNC_msg_redirect_map &&
6539                     func_id != BPF_FUNC_sk_select_reuseport &&
6540                     func_id != BPF_FUNC_map_lookup_elem &&
6541                     !may_update_sockmap(env, func_id))
6542                         goto error;
6543                 break;
6544         case BPF_MAP_TYPE_SOCKHASH:
6545                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6546                     func_id != BPF_FUNC_sock_hash_update &&
6547                     func_id != BPF_FUNC_map_delete_elem &&
6548                     func_id != BPF_FUNC_msg_redirect_hash &&
6549                     func_id != BPF_FUNC_sk_select_reuseport &&
6550                     func_id != BPF_FUNC_map_lookup_elem &&
6551                     !may_update_sockmap(env, func_id))
6552                         goto error;
6553                 break;
6554         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6555                 if (func_id != BPF_FUNC_sk_select_reuseport)
6556                         goto error;
6557                 break;
6558         case BPF_MAP_TYPE_QUEUE:
6559         case BPF_MAP_TYPE_STACK:
6560                 if (func_id != BPF_FUNC_map_peek_elem &&
6561                     func_id != BPF_FUNC_map_pop_elem &&
6562                     func_id != BPF_FUNC_map_push_elem)
6563                         goto error;
6564                 break;
6565         case BPF_MAP_TYPE_SK_STORAGE:
6566                 if (func_id != BPF_FUNC_sk_storage_get &&
6567                     func_id != BPF_FUNC_sk_storage_delete)
6568                         goto error;
6569                 break;
6570         case BPF_MAP_TYPE_INODE_STORAGE:
6571                 if (func_id != BPF_FUNC_inode_storage_get &&
6572                     func_id != BPF_FUNC_inode_storage_delete)
6573                         goto error;
6574                 break;
6575         case BPF_MAP_TYPE_TASK_STORAGE:
6576                 if (func_id != BPF_FUNC_task_storage_get &&
6577                     func_id != BPF_FUNC_task_storage_delete)
6578                         goto error;
6579                 break;
6580         case BPF_MAP_TYPE_CGRP_STORAGE:
6581                 if (func_id != BPF_FUNC_cgrp_storage_get &&
6582                     func_id != BPF_FUNC_cgrp_storage_delete)
6583                         goto error;
6584                 break;
6585         case BPF_MAP_TYPE_BLOOM_FILTER:
6586                 if (func_id != BPF_FUNC_map_peek_elem &&
6587                     func_id != BPF_FUNC_map_push_elem)
6588                         goto error;
6589                 break;
6590         default:
6591                 break;
6592         }
6593
6594         /* ... and second from the function itself. */
6595         switch (func_id) {
6596         case BPF_FUNC_tail_call:
6597                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6598                         goto error;
6599                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6600                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6601                         return -EINVAL;
6602                 }
6603                 break;
6604         case BPF_FUNC_perf_event_read:
6605         case BPF_FUNC_perf_event_output:
6606         case BPF_FUNC_perf_event_read_value:
6607         case BPF_FUNC_skb_output:
6608         case BPF_FUNC_xdp_output:
6609                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6610                         goto error;
6611                 break;
6612         case BPF_FUNC_ringbuf_output:
6613         case BPF_FUNC_ringbuf_reserve:
6614         case BPF_FUNC_ringbuf_query:
6615         case BPF_FUNC_ringbuf_reserve_dynptr:
6616         case BPF_FUNC_ringbuf_submit_dynptr:
6617         case BPF_FUNC_ringbuf_discard_dynptr:
6618                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6619                         goto error;
6620                 break;
6621         case BPF_FUNC_user_ringbuf_drain:
6622                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6623                         goto error;
6624                 break;
6625         case BPF_FUNC_get_stackid:
6626                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6627                         goto error;
6628                 break;
6629         case BPF_FUNC_current_task_under_cgroup:
6630         case BPF_FUNC_skb_under_cgroup:
6631                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6632                         goto error;
6633                 break;
6634         case BPF_FUNC_redirect_map:
6635                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6636                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6637                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6638                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6639                         goto error;
6640                 break;
6641         case BPF_FUNC_sk_redirect_map:
6642         case BPF_FUNC_msg_redirect_map:
6643         case BPF_FUNC_sock_map_update:
6644                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6645                         goto error;
6646                 break;
6647         case BPF_FUNC_sk_redirect_hash:
6648         case BPF_FUNC_msg_redirect_hash:
6649         case BPF_FUNC_sock_hash_update:
6650                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6651                         goto error;
6652                 break;
6653         case BPF_FUNC_get_local_storage:
6654                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6655                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6656                         goto error;
6657                 break;
6658         case BPF_FUNC_sk_select_reuseport:
6659                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6660                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6661                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6662                         goto error;
6663                 break;
6664         case BPF_FUNC_map_pop_elem:
6665                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6666                     map->map_type != BPF_MAP_TYPE_STACK)
6667                         goto error;
6668                 break;
6669         case BPF_FUNC_map_peek_elem:
6670         case BPF_FUNC_map_push_elem:
6671                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6672                     map->map_type != BPF_MAP_TYPE_STACK &&
6673                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6674                         goto error;
6675                 break;
6676         case BPF_FUNC_map_lookup_percpu_elem:
6677                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6678                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6679                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6680                         goto error;
6681                 break;
6682         case BPF_FUNC_sk_storage_get:
6683         case BPF_FUNC_sk_storage_delete:
6684                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6685                         goto error;
6686                 break;
6687         case BPF_FUNC_inode_storage_get:
6688         case BPF_FUNC_inode_storage_delete:
6689                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6690                         goto error;
6691                 break;
6692         case BPF_FUNC_task_storage_get:
6693         case BPF_FUNC_task_storage_delete:
6694                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6695                         goto error;
6696                 break;
6697         case BPF_FUNC_cgrp_storage_get:
6698         case BPF_FUNC_cgrp_storage_delete:
6699                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6700                         goto error;
6701                 break;
6702         default:
6703                 break;
6704         }
6705
6706         return 0;
6707 error:
6708         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6709                 map->map_type, func_id_name(func_id), func_id);
6710         return -EINVAL;
6711 }
6712
6713 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6714 {
6715         int count = 0;
6716
6717         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6718                 count++;
6719         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6720                 count++;
6721         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6722                 count++;
6723         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6724                 count++;
6725         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6726                 count++;
6727
6728         /* We only support one arg being in raw mode at the moment,
6729          * which is sufficient for the helper functions we have
6730          * right now.
6731          */
6732         return count <= 1;
6733 }
6734
6735 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6736 {
6737         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6738         bool has_size = fn->arg_size[arg] != 0;
6739         bool is_next_size = false;
6740
6741         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6742                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6743
6744         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6745                 return is_next_size;
6746
6747         return has_size == is_next_size || is_next_size == is_fixed;
6748 }
6749
6750 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6751 {
6752         /* bpf_xxx(..., buf, len) call will access 'len'
6753          * bytes from memory 'buf'. Both arg types need
6754          * to be paired, so make sure there's no buggy
6755          * helper function specification.
6756          */
6757         if (arg_type_is_mem_size(fn->arg1_type) ||
6758             check_args_pair_invalid(fn, 0) ||
6759             check_args_pair_invalid(fn, 1) ||
6760             check_args_pair_invalid(fn, 2) ||
6761             check_args_pair_invalid(fn, 3) ||
6762             check_args_pair_invalid(fn, 4))
6763                 return false;
6764
6765         return true;
6766 }
6767
6768 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6769 {
6770         int i;
6771
6772         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6773                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
6774                         return !!fn->arg_btf_id[i];
6775                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
6776                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
6777                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6778                     /* arg_btf_id and arg_size are in a union. */
6779                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6780                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6781                         return false;
6782         }
6783
6784         return true;
6785 }
6786
6787 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6788 {
6789         return check_raw_mode_ok(fn) &&
6790                check_arg_pair_ok(fn) &&
6791                check_btf_id_ok(fn) ? 0 : -EINVAL;
6792 }
6793
6794 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6795  * are now invalid, so turn them into unknown SCALAR_VALUE.
6796  */
6797 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6798 {
6799         struct bpf_func_state *state;
6800         struct bpf_reg_state *reg;
6801
6802         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6803                 if (reg_is_pkt_pointer_any(reg))
6804                         __mark_reg_unknown(env, reg);
6805         }));
6806 }
6807
6808 enum {
6809         AT_PKT_END = -1,
6810         BEYOND_PKT_END = -2,
6811 };
6812
6813 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6814 {
6815         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6816         struct bpf_reg_state *reg = &state->regs[regn];
6817
6818         if (reg->type != PTR_TO_PACKET)
6819                 /* PTR_TO_PACKET_META is not supported yet */
6820                 return;
6821
6822         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6823          * How far beyond pkt_end it goes is unknown.
6824          * if (!range_open) it's the case of pkt >= pkt_end
6825          * if (range_open) it's the case of pkt > pkt_end
6826          * hence this pointer is at least 1 byte bigger than pkt_end
6827          */
6828         if (range_open)
6829                 reg->range = BEYOND_PKT_END;
6830         else
6831                 reg->range = AT_PKT_END;
6832 }
6833
6834 /* The pointer with the specified id has released its reference to kernel
6835  * resources. Identify all copies of the same pointer and clear the reference.
6836  */
6837 static int release_reference(struct bpf_verifier_env *env,
6838                              int ref_obj_id)
6839 {
6840         struct bpf_func_state *state;
6841         struct bpf_reg_state *reg;
6842         int err;
6843
6844         err = release_reference_state(cur_func(env), ref_obj_id);
6845         if (err)
6846                 return err;
6847
6848         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6849                 if (reg->ref_obj_id == ref_obj_id) {
6850                         if (!env->allow_ptr_leaks)
6851                                 __mark_reg_not_init(env, reg);
6852                         else
6853                                 __mark_reg_unknown(env, reg);
6854                 }
6855         }));
6856
6857         return 0;
6858 }
6859
6860 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6861                                     struct bpf_reg_state *regs)
6862 {
6863         int i;
6864
6865         /* after the call registers r0 - r5 were scratched */
6866         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6867                 mark_reg_not_init(env, regs, caller_saved[i]);
6868                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6869         }
6870 }
6871
6872 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6873                                    struct bpf_func_state *caller,
6874                                    struct bpf_func_state *callee,
6875                                    int insn_idx);
6876
6877 static int set_callee_state(struct bpf_verifier_env *env,
6878                             struct bpf_func_state *caller,
6879                             struct bpf_func_state *callee, int insn_idx);
6880
6881 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6882                              int *insn_idx, int subprog,
6883                              set_callee_state_fn set_callee_state_cb)
6884 {
6885         struct bpf_verifier_state *state = env->cur_state;
6886         struct bpf_func_info_aux *func_info_aux;
6887         struct bpf_func_state *caller, *callee;
6888         int err;
6889         bool is_global = false;
6890
6891         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6892                 verbose(env, "the call stack of %d frames is too deep\n",
6893                         state->curframe + 2);
6894                 return -E2BIG;
6895         }
6896
6897         caller = state->frame[state->curframe];
6898         if (state->frame[state->curframe + 1]) {
6899                 verbose(env, "verifier bug. Frame %d already allocated\n",
6900                         state->curframe + 1);
6901                 return -EFAULT;
6902         }
6903
6904         func_info_aux = env->prog->aux->func_info_aux;
6905         if (func_info_aux)
6906                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6907         err = btf_check_subprog_call(env, subprog, caller->regs);
6908         if (err == -EFAULT)
6909                 return err;
6910         if (is_global) {
6911                 if (err) {
6912                         verbose(env, "Caller passes invalid args into func#%d\n",
6913                                 subprog);
6914                         return err;
6915                 } else {
6916                         if (env->log.level & BPF_LOG_LEVEL)
6917                                 verbose(env,
6918                                         "Func#%d is global and valid. Skipping.\n",
6919                                         subprog);
6920                         clear_caller_saved_regs(env, caller->regs);
6921
6922                         /* All global functions return a 64-bit SCALAR_VALUE */
6923                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6924                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6925
6926                         /* continue with next insn after call */
6927                         return 0;
6928                 }
6929         }
6930
6931         /* set_callee_state is used for direct subprog calls, but we are
6932          * interested in validating only BPF helpers that can call subprogs as
6933          * callbacks
6934          */
6935         if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6936                 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6937                         func_id_name(insn->imm), insn->imm);
6938                 return -EFAULT;
6939         }
6940
6941         if (insn->code == (BPF_JMP | BPF_CALL) &&
6942             insn->src_reg == 0 &&
6943             insn->imm == BPF_FUNC_timer_set_callback) {
6944                 struct bpf_verifier_state *async_cb;
6945
6946                 /* there is no real recursion here. timer callbacks are async */
6947                 env->subprog_info[subprog].is_async_cb = true;
6948                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6949                                          *insn_idx, subprog);
6950                 if (!async_cb)
6951                         return -EFAULT;
6952                 callee = async_cb->frame[0];
6953                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6954
6955                 /* Convert bpf_timer_set_callback() args into timer callback args */
6956                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6957                 if (err)
6958                         return err;
6959
6960                 clear_caller_saved_regs(env, caller->regs);
6961                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6962                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6963                 /* continue with next insn after call */
6964                 return 0;
6965         }
6966
6967         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6968         if (!callee)
6969                 return -ENOMEM;
6970         state->frame[state->curframe + 1] = callee;
6971
6972         /* callee cannot access r0, r6 - r9 for reading and has to write
6973          * into its own stack before reading from it.
6974          * callee can read/write into caller's stack
6975          */
6976         init_func_state(env, callee,
6977                         /* remember the callsite, it will be used by bpf_exit */
6978                         *insn_idx /* callsite */,
6979                         state->curframe + 1 /* frameno within this callchain */,
6980                         subprog /* subprog number within this prog */);
6981
6982         /* Transfer references to the callee */
6983         err = copy_reference_state(callee, caller);
6984         if (err)
6985                 return err;
6986
6987         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6988         if (err)
6989                 return err;
6990
6991         clear_caller_saved_regs(env, caller->regs);
6992
6993         /* only increment it after check_reg_arg() finished */
6994         state->curframe++;
6995
6996         /* and go analyze first insn of the callee */
6997         *insn_idx = env->subprog_info[subprog].start - 1;
6998
6999         if (env->log.level & BPF_LOG_LEVEL) {
7000                 verbose(env, "caller:\n");
7001                 print_verifier_state(env, caller, true);
7002                 verbose(env, "callee:\n");
7003                 print_verifier_state(env, callee, true);
7004         }
7005         return 0;
7006 }
7007
7008 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7009                                    struct bpf_func_state *caller,
7010                                    struct bpf_func_state *callee)
7011 {
7012         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7013          *      void *callback_ctx, u64 flags);
7014          * callback_fn(struct bpf_map *map, void *key, void *value,
7015          *      void *callback_ctx);
7016          */
7017         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7018
7019         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7020         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7021         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7022
7023         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7024         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7025         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7026
7027         /* pointer to stack or null */
7028         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7029
7030         /* unused */
7031         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7032         return 0;
7033 }
7034
7035 static int set_callee_state(struct bpf_verifier_env *env,
7036                             struct bpf_func_state *caller,
7037                             struct bpf_func_state *callee, int insn_idx)
7038 {
7039         int i;
7040
7041         /* copy r1 - r5 args that callee can access.  The copy includes parent
7042          * pointers, which connects us up to the liveness chain
7043          */
7044         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7045                 callee->regs[i] = caller->regs[i];
7046         return 0;
7047 }
7048
7049 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7050                            int *insn_idx)
7051 {
7052         int subprog, target_insn;
7053
7054         target_insn = *insn_idx + insn->imm + 1;
7055         subprog = find_subprog(env, target_insn);
7056         if (subprog < 0) {
7057                 verbose(env, "verifier bug. No program starts at insn %d\n",
7058                         target_insn);
7059                 return -EFAULT;
7060         }
7061
7062         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7063 }
7064
7065 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7066                                        struct bpf_func_state *caller,
7067                                        struct bpf_func_state *callee,
7068                                        int insn_idx)
7069 {
7070         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7071         struct bpf_map *map;
7072         int err;
7073
7074         if (bpf_map_ptr_poisoned(insn_aux)) {
7075                 verbose(env, "tail_call abusing map_ptr\n");
7076                 return -EINVAL;
7077         }
7078
7079         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7080         if (!map->ops->map_set_for_each_callback_args ||
7081             !map->ops->map_for_each_callback) {
7082                 verbose(env, "callback function not allowed for map\n");
7083                 return -ENOTSUPP;
7084         }
7085
7086         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7087         if (err)
7088                 return err;
7089
7090         callee->in_callback_fn = true;
7091         callee->callback_ret_range = tnum_range(0, 1);
7092         return 0;
7093 }
7094
7095 static int set_loop_callback_state(struct bpf_verifier_env *env,
7096                                    struct bpf_func_state *caller,
7097                                    struct bpf_func_state *callee,
7098                                    int insn_idx)
7099 {
7100         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7101          *          u64 flags);
7102          * callback_fn(u32 index, void *callback_ctx);
7103          */
7104         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7105         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7106
7107         /* unused */
7108         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7109         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7110         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7111
7112         callee->in_callback_fn = true;
7113         callee->callback_ret_range = tnum_range(0, 1);
7114         return 0;
7115 }
7116
7117 static int set_timer_callback_state(struct bpf_verifier_env *env,
7118                                     struct bpf_func_state *caller,
7119                                     struct bpf_func_state *callee,
7120                                     int insn_idx)
7121 {
7122         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7123
7124         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7125          * callback_fn(struct bpf_map *map, void *key, void *value);
7126          */
7127         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7128         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7129         callee->regs[BPF_REG_1].map_ptr = map_ptr;
7130
7131         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7132         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7133         callee->regs[BPF_REG_2].map_ptr = map_ptr;
7134
7135         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7136         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7137         callee->regs[BPF_REG_3].map_ptr = map_ptr;
7138
7139         /* unused */
7140         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7141         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7142         callee->in_async_callback_fn = true;
7143         callee->callback_ret_range = tnum_range(0, 1);
7144         return 0;
7145 }
7146
7147 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7148                                        struct bpf_func_state *caller,
7149                                        struct bpf_func_state *callee,
7150                                        int insn_idx)
7151 {
7152         /* bpf_find_vma(struct task_struct *task, u64 addr,
7153          *               void *callback_fn, void *callback_ctx, u64 flags)
7154          * (callback_fn)(struct task_struct *task,
7155          *               struct vm_area_struct *vma, void *callback_ctx);
7156          */
7157         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7158
7159         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7160         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7161         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
7162         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7163
7164         /* pointer to stack or null */
7165         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7166
7167         /* unused */
7168         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7169         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7170         callee->in_callback_fn = true;
7171         callee->callback_ret_range = tnum_range(0, 1);
7172         return 0;
7173 }
7174
7175 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7176                                            struct bpf_func_state *caller,
7177                                            struct bpf_func_state *callee,
7178                                            int insn_idx)
7179 {
7180         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7181          *                        callback_ctx, u64 flags);
7182          * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7183          */
7184         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7185         callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7186         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7187         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7188
7189         /* unused */
7190         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7191         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7192         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7193
7194         callee->in_callback_fn = true;
7195         callee->callback_ret_range = tnum_range(0, 1);
7196         return 0;
7197 }
7198
7199 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7200 {
7201         struct bpf_verifier_state *state = env->cur_state;
7202         struct bpf_func_state *caller, *callee;
7203         struct bpf_reg_state *r0;
7204         int err;
7205
7206         callee = state->frame[state->curframe];
7207         r0 = &callee->regs[BPF_REG_0];
7208         if (r0->type == PTR_TO_STACK) {
7209                 /* technically it's ok to return caller's stack pointer
7210                  * (or caller's caller's pointer) back to the caller,
7211                  * since these pointers are valid. Only current stack
7212                  * pointer will be invalid as soon as function exits,
7213                  * but let's be conservative
7214                  */
7215                 verbose(env, "cannot return stack pointer to the caller\n");
7216                 return -EINVAL;
7217         }
7218
7219         state->curframe--;
7220         caller = state->frame[state->curframe];
7221         if (callee->in_callback_fn) {
7222                 /* enforce R0 return value range [0, 1]. */
7223                 struct tnum range = callee->callback_ret_range;
7224
7225                 if (r0->type != SCALAR_VALUE) {
7226                         verbose(env, "R0 not a scalar value\n");
7227                         return -EACCES;
7228                 }
7229                 if (!tnum_in(range, r0->var_off)) {
7230                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7231                         return -EINVAL;
7232                 }
7233         } else {
7234                 /* return to the caller whatever r0 had in the callee */
7235                 caller->regs[BPF_REG_0] = *r0;
7236         }
7237
7238         /* callback_fn frame should have released its own additions to parent's
7239          * reference state at this point, or check_reference_leak would
7240          * complain, hence it must be the same as the caller. There is no need
7241          * to copy it back.
7242          */
7243         if (!callee->in_callback_fn) {
7244                 /* Transfer references to the caller */
7245                 err = copy_reference_state(caller, callee);
7246                 if (err)
7247                         return err;
7248         }
7249
7250         *insn_idx = callee->callsite + 1;
7251         if (env->log.level & BPF_LOG_LEVEL) {
7252                 verbose(env, "returning from callee:\n");
7253                 print_verifier_state(env, callee, true);
7254                 verbose(env, "to caller at %d:\n", *insn_idx);
7255                 print_verifier_state(env, caller, true);
7256         }
7257         /* clear everything in the callee */
7258         free_func_state(callee);
7259         state->frame[state->curframe + 1] = NULL;
7260         return 0;
7261 }
7262
7263 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7264                                    int func_id,
7265                                    struct bpf_call_arg_meta *meta)
7266 {
7267         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7268
7269         if (ret_type != RET_INTEGER ||
7270             (func_id != BPF_FUNC_get_stack &&
7271              func_id != BPF_FUNC_get_task_stack &&
7272              func_id != BPF_FUNC_probe_read_str &&
7273              func_id != BPF_FUNC_probe_read_kernel_str &&
7274              func_id != BPF_FUNC_probe_read_user_str))
7275                 return;
7276
7277         ret_reg->smax_value = meta->msize_max_value;
7278         ret_reg->s32_max_value = meta->msize_max_value;
7279         ret_reg->smin_value = -MAX_ERRNO;
7280         ret_reg->s32_min_value = -MAX_ERRNO;
7281         reg_bounds_sync(ret_reg);
7282 }
7283
7284 static int
7285 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7286                 int func_id, int insn_idx)
7287 {
7288         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7289         struct bpf_map *map = meta->map_ptr;
7290
7291         if (func_id != BPF_FUNC_tail_call &&
7292             func_id != BPF_FUNC_map_lookup_elem &&
7293             func_id != BPF_FUNC_map_update_elem &&
7294             func_id != BPF_FUNC_map_delete_elem &&
7295             func_id != BPF_FUNC_map_push_elem &&
7296             func_id != BPF_FUNC_map_pop_elem &&
7297             func_id != BPF_FUNC_map_peek_elem &&
7298             func_id != BPF_FUNC_for_each_map_elem &&
7299             func_id != BPF_FUNC_redirect_map &&
7300             func_id != BPF_FUNC_map_lookup_percpu_elem)
7301                 return 0;
7302
7303         if (map == NULL) {
7304                 verbose(env, "kernel subsystem misconfigured verifier\n");
7305                 return -EINVAL;
7306         }
7307
7308         /* In case of read-only, some additional restrictions
7309          * need to be applied in order to prevent altering the
7310          * state of the map from program side.
7311          */
7312         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7313             (func_id == BPF_FUNC_map_delete_elem ||
7314              func_id == BPF_FUNC_map_update_elem ||
7315              func_id == BPF_FUNC_map_push_elem ||
7316              func_id == BPF_FUNC_map_pop_elem)) {
7317                 verbose(env, "write into map forbidden\n");
7318                 return -EACCES;
7319         }
7320
7321         if (!BPF_MAP_PTR(aux->map_ptr_state))
7322                 bpf_map_ptr_store(aux, meta->map_ptr,
7323                                   !meta->map_ptr->bypass_spec_v1);
7324         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7325                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7326                                   !meta->map_ptr->bypass_spec_v1);
7327         return 0;
7328 }
7329
7330 static int
7331 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7332                 int func_id, int insn_idx)
7333 {
7334         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7335         struct bpf_reg_state *regs = cur_regs(env), *reg;
7336         struct bpf_map *map = meta->map_ptr;
7337         u64 val, max;
7338         int err;
7339
7340         if (func_id != BPF_FUNC_tail_call)
7341                 return 0;
7342         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7343                 verbose(env, "kernel subsystem misconfigured verifier\n");
7344                 return -EINVAL;
7345         }
7346
7347         reg = &regs[BPF_REG_3];
7348         val = reg->var_off.value;
7349         max = map->max_entries;
7350
7351         if (!(register_is_const(reg) && val < max)) {
7352                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7353                 return 0;
7354         }
7355
7356         err = mark_chain_precision(env, BPF_REG_3);
7357         if (err)
7358                 return err;
7359         if (bpf_map_key_unseen(aux))
7360                 bpf_map_key_store(aux, val);
7361         else if (!bpf_map_key_poisoned(aux) &&
7362                   bpf_map_key_immediate(aux) != val)
7363                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7364         return 0;
7365 }
7366
7367 static int check_reference_leak(struct bpf_verifier_env *env)
7368 {
7369         struct bpf_func_state *state = cur_func(env);
7370         bool refs_lingering = false;
7371         int i;
7372
7373         if (state->frameno && !state->in_callback_fn)
7374                 return 0;
7375
7376         for (i = 0; i < state->acquired_refs; i++) {
7377                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7378                         continue;
7379                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7380                         state->refs[i].id, state->refs[i].insn_idx);
7381                 refs_lingering = true;
7382         }
7383         return refs_lingering ? -EINVAL : 0;
7384 }
7385
7386 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7387                                    struct bpf_reg_state *regs)
7388 {
7389         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7390         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7391         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7392         int err, fmt_map_off, num_args;
7393         u64 fmt_addr;
7394         char *fmt;
7395
7396         /* data must be an array of u64 */
7397         if (data_len_reg->var_off.value % 8)
7398                 return -EINVAL;
7399         num_args = data_len_reg->var_off.value / 8;
7400
7401         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7402          * and map_direct_value_addr is set.
7403          */
7404         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7405         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7406                                                   fmt_map_off);
7407         if (err) {
7408                 verbose(env, "verifier bug\n");
7409                 return -EFAULT;
7410         }
7411         fmt = (char *)(long)fmt_addr + fmt_map_off;
7412
7413         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7414          * can focus on validating the format specifiers.
7415          */
7416         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7417         if (err < 0)
7418                 verbose(env, "Invalid format string\n");
7419
7420         return err;
7421 }
7422
7423 static int check_get_func_ip(struct bpf_verifier_env *env)
7424 {
7425         enum bpf_prog_type type = resolve_prog_type(env->prog);
7426         int func_id = BPF_FUNC_get_func_ip;
7427
7428         if (type == BPF_PROG_TYPE_TRACING) {
7429                 if (!bpf_prog_has_trampoline(env->prog)) {
7430                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7431                                 func_id_name(func_id), func_id);
7432                         return -ENOTSUPP;
7433                 }
7434                 return 0;
7435         } else if (type == BPF_PROG_TYPE_KPROBE) {
7436                 return 0;
7437         }
7438
7439         verbose(env, "func %s#%d not supported for program type %d\n",
7440                 func_id_name(func_id), func_id, type);
7441         return -ENOTSUPP;
7442 }
7443
7444 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7445 {
7446         return &env->insn_aux_data[env->insn_idx];
7447 }
7448
7449 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7450 {
7451         struct bpf_reg_state *regs = cur_regs(env);
7452         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7453         bool reg_is_null = register_is_null(reg);
7454
7455         if (reg_is_null)
7456                 mark_chain_precision(env, BPF_REG_4);
7457
7458         return reg_is_null;
7459 }
7460
7461 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7462 {
7463         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7464
7465         if (!state->initialized) {
7466                 state->initialized = 1;
7467                 state->fit_for_inline = loop_flag_is_zero(env);
7468                 state->callback_subprogno = subprogno;
7469                 return;
7470         }
7471
7472         if (!state->fit_for_inline)
7473                 return;
7474
7475         state->fit_for_inline = (loop_flag_is_zero(env) &&
7476                                  state->callback_subprogno == subprogno);
7477 }
7478
7479 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7480                              int *insn_idx_p)
7481 {
7482         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7483         const struct bpf_func_proto *fn = NULL;
7484         enum bpf_return_type ret_type;
7485         enum bpf_type_flag ret_flag;
7486         struct bpf_reg_state *regs;
7487         struct bpf_call_arg_meta meta;
7488         int insn_idx = *insn_idx_p;
7489         bool changes_data;
7490         int i, err, func_id;
7491
7492         /* find function prototype */
7493         func_id = insn->imm;
7494         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7495                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7496                         func_id);
7497                 return -EINVAL;
7498         }
7499
7500         if (env->ops->get_func_proto)
7501                 fn = env->ops->get_func_proto(func_id, env->prog);
7502         if (!fn) {
7503                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7504                         func_id);
7505                 return -EINVAL;
7506         }
7507
7508         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7509         if (!env->prog->gpl_compatible && fn->gpl_only) {
7510                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7511                 return -EINVAL;
7512         }
7513
7514         if (fn->allowed && !fn->allowed(env->prog)) {
7515                 verbose(env, "helper call is not allowed in probe\n");
7516                 return -EINVAL;
7517         }
7518
7519         if (!env->prog->aux->sleepable && fn->might_sleep) {
7520                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
7521                 return -EINVAL;
7522         }
7523
7524         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7525         changes_data = bpf_helper_changes_pkt_data(fn->func);
7526         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7527                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7528                         func_id_name(func_id), func_id);
7529                 return -EINVAL;
7530         }
7531
7532         memset(&meta, 0, sizeof(meta));
7533         meta.pkt_access = fn->pkt_access;
7534
7535         err = check_func_proto(fn, func_id);
7536         if (err) {
7537                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7538                         func_id_name(func_id), func_id);
7539                 return err;
7540         }
7541
7542         meta.func_id = func_id;
7543         /* check args */
7544         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7545                 err = check_func_arg(env, i, &meta, fn);
7546                 if (err)
7547                         return err;
7548         }
7549
7550         err = record_func_map(env, &meta, func_id, insn_idx);
7551         if (err)
7552                 return err;
7553
7554         err = record_func_key(env, &meta, func_id, insn_idx);
7555         if (err)
7556                 return err;
7557
7558         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7559          * is inferred from register state.
7560          */
7561         for (i = 0; i < meta.access_size; i++) {
7562                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7563                                        BPF_WRITE, -1, false);
7564                 if (err)
7565                         return err;
7566         }
7567
7568         regs = cur_regs(env);
7569
7570         if (meta.uninit_dynptr_regno) {
7571                 /* we write BPF_DW bits (8 bytes) at a time */
7572                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7573                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7574                                                i, BPF_DW, BPF_WRITE, -1, false);
7575                         if (err)
7576                                 return err;
7577                 }
7578
7579                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7580                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7581                                               insn_idx);
7582                 if (err)
7583                         return err;
7584         }
7585
7586         if (meta.release_regno) {
7587                 err = -EINVAL;
7588                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7589                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7590                 else if (meta.ref_obj_id)
7591                         err = release_reference(env, meta.ref_obj_id);
7592                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7593                  * released is NULL, which must be > R0.
7594                  */
7595                 else if (register_is_null(&regs[meta.release_regno]))
7596                         err = 0;
7597                 if (err) {
7598                         verbose(env, "func %s#%d reference has not been acquired before\n",
7599                                 func_id_name(func_id), func_id);
7600                         return err;
7601                 }
7602         }
7603
7604         switch (func_id) {
7605         case BPF_FUNC_tail_call:
7606                 err = check_reference_leak(env);
7607                 if (err) {
7608                         verbose(env, "tail_call would lead to reference leak\n");
7609                         return err;
7610                 }
7611                 break;
7612         case BPF_FUNC_get_local_storage:
7613                 /* check that flags argument in get_local_storage(map, flags) is 0,
7614                  * this is required because get_local_storage() can't return an error.
7615                  */
7616                 if (!register_is_null(&regs[BPF_REG_2])) {
7617                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7618                         return -EINVAL;
7619                 }
7620                 break;
7621         case BPF_FUNC_for_each_map_elem:
7622                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7623                                         set_map_elem_callback_state);
7624                 break;
7625         case BPF_FUNC_timer_set_callback:
7626                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7627                                         set_timer_callback_state);
7628                 break;
7629         case BPF_FUNC_find_vma:
7630                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7631                                         set_find_vma_callback_state);
7632                 break;
7633         case BPF_FUNC_snprintf:
7634                 err = check_bpf_snprintf_call(env, regs);
7635                 break;
7636         case BPF_FUNC_loop:
7637                 update_loop_inline_state(env, meta.subprogno);
7638                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7639                                         set_loop_callback_state);
7640                 break;
7641         case BPF_FUNC_dynptr_from_mem:
7642                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7643                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7644                                 reg_type_str(env, regs[BPF_REG_1].type));
7645                         return -EACCES;
7646                 }
7647                 break;
7648         case BPF_FUNC_set_retval:
7649                 if (prog_type == BPF_PROG_TYPE_LSM &&
7650                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7651                         if (!env->prog->aux->attach_func_proto->type) {
7652                                 /* Make sure programs that attach to void
7653                                  * hooks don't try to modify return value.
7654                                  */
7655                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7656                                 return -EINVAL;
7657                         }
7658                 }
7659                 break;
7660         case BPF_FUNC_dynptr_data:
7661                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7662                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7663                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7664
7665                                 if (meta.ref_obj_id) {
7666                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7667                                         return -EFAULT;
7668                                 }
7669
7670                                 if (base_type(reg->type) != PTR_TO_DYNPTR)
7671                                         /* Find the id of the dynptr we're
7672                                          * tracking the reference of
7673                                          */
7674                                         meta.ref_obj_id = stack_slot_get_id(env, reg);
7675                                 break;
7676                         }
7677                 }
7678                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7679                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7680                         return -EFAULT;
7681                 }
7682                 break;
7683         case BPF_FUNC_user_ringbuf_drain:
7684                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7685                                         set_user_ringbuf_callback_state);
7686                 break;
7687         }
7688
7689         if (err)
7690                 return err;
7691
7692         /* reset caller saved regs */
7693         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7694                 mark_reg_not_init(env, regs, caller_saved[i]);
7695                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7696         }
7697
7698         /* helper call returns 64-bit value. */
7699         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7700
7701         /* update return register (already marked as written above) */
7702         ret_type = fn->ret_type;
7703         ret_flag = type_flag(ret_type);
7704
7705         switch (base_type(ret_type)) {
7706         case RET_INTEGER:
7707                 /* sets type to SCALAR_VALUE */
7708                 mark_reg_unknown(env, regs, BPF_REG_0);
7709                 break;
7710         case RET_VOID:
7711                 regs[BPF_REG_0].type = NOT_INIT;
7712                 break;
7713         case RET_PTR_TO_MAP_VALUE:
7714                 /* There is no offset yet applied, variable or fixed */
7715                 mark_reg_known_zero(env, regs, BPF_REG_0);
7716                 /* remember map_ptr, so that check_map_access()
7717                  * can check 'value_size' boundary of memory access
7718                  * to map element returned from bpf_map_lookup_elem()
7719                  */
7720                 if (meta.map_ptr == NULL) {
7721                         verbose(env,
7722                                 "kernel subsystem misconfigured verifier\n");
7723                         return -EINVAL;
7724                 }
7725                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7726                 regs[BPF_REG_0].map_uid = meta.map_uid;
7727                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7728                 if (!type_may_be_null(ret_type) &&
7729                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
7730                         regs[BPF_REG_0].id = ++env->id_gen;
7731                 }
7732                 break;
7733         case RET_PTR_TO_SOCKET:
7734                 mark_reg_known_zero(env, regs, BPF_REG_0);
7735                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7736                 break;
7737         case RET_PTR_TO_SOCK_COMMON:
7738                 mark_reg_known_zero(env, regs, BPF_REG_0);
7739                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7740                 break;
7741         case RET_PTR_TO_TCP_SOCK:
7742                 mark_reg_known_zero(env, regs, BPF_REG_0);
7743                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7744                 break;
7745         case RET_PTR_TO_MEM:
7746                 mark_reg_known_zero(env, regs, BPF_REG_0);
7747                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7748                 regs[BPF_REG_0].mem_size = meta.mem_size;
7749                 break;
7750         case RET_PTR_TO_MEM_OR_BTF_ID:
7751         {
7752                 const struct btf_type *t;
7753
7754                 mark_reg_known_zero(env, regs, BPF_REG_0);
7755                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7756                 if (!btf_type_is_struct(t)) {
7757                         u32 tsize;
7758                         const struct btf_type *ret;
7759                         const char *tname;
7760
7761                         /* resolve the type size of ksym. */
7762                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7763                         if (IS_ERR(ret)) {
7764                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7765                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7766                                         tname, PTR_ERR(ret));
7767                                 return -EINVAL;
7768                         }
7769                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7770                         regs[BPF_REG_0].mem_size = tsize;
7771                 } else {
7772                         /* MEM_RDONLY may be carried from ret_flag, but it
7773                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7774                          * it will confuse the check of PTR_TO_BTF_ID in
7775                          * check_mem_access().
7776                          */
7777                         ret_flag &= ~MEM_RDONLY;
7778
7779                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7780                         regs[BPF_REG_0].btf = meta.ret_btf;
7781                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7782                 }
7783                 break;
7784         }
7785         case RET_PTR_TO_BTF_ID:
7786         {
7787                 struct btf *ret_btf;
7788                 int ret_btf_id;
7789
7790                 mark_reg_known_zero(env, regs, BPF_REG_0);
7791                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7792                 if (func_id == BPF_FUNC_kptr_xchg) {
7793                         ret_btf = meta.kptr_field->kptr.btf;
7794                         ret_btf_id = meta.kptr_field->kptr.btf_id;
7795                 } else {
7796                         if (fn->ret_btf_id == BPF_PTR_POISON) {
7797                                 verbose(env, "verifier internal error:");
7798                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7799                                         func_id_name(func_id));
7800                                 return -EINVAL;
7801                         }
7802                         ret_btf = btf_vmlinux;
7803                         ret_btf_id = *fn->ret_btf_id;
7804                 }
7805                 if (ret_btf_id == 0) {
7806                         verbose(env, "invalid return type %u of func %s#%d\n",
7807                                 base_type(ret_type), func_id_name(func_id),
7808                                 func_id);
7809                         return -EINVAL;
7810                 }
7811                 regs[BPF_REG_0].btf = ret_btf;
7812                 regs[BPF_REG_0].btf_id = ret_btf_id;
7813                 break;
7814         }
7815         default:
7816                 verbose(env, "unknown return type %u of func %s#%d\n",
7817                         base_type(ret_type), func_id_name(func_id), func_id);
7818                 return -EINVAL;
7819         }
7820
7821         if (type_may_be_null(regs[BPF_REG_0].type))
7822                 regs[BPF_REG_0].id = ++env->id_gen;
7823
7824         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7825                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7826                         func_id_name(func_id), func_id);
7827                 return -EFAULT;
7828         }
7829
7830         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7831                 /* For release_reference() */
7832                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7833         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7834                 int id = acquire_reference_state(env, insn_idx);
7835
7836                 if (id < 0)
7837                         return id;
7838                 /* For mark_ptr_or_null_reg() */
7839                 regs[BPF_REG_0].id = id;
7840                 /* For release_reference() */
7841                 regs[BPF_REG_0].ref_obj_id = id;
7842         }
7843
7844         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7845
7846         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7847         if (err)
7848                 return err;
7849
7850         if ((func_id == BPF_FUNC_get_stack ||
7851              func_id == BPF_FUNC_get_task_stack) &&
7852             !env->prog->has_callchain_buf) {
7853                 const char *err_str;
7854
7855 #ifdef CONFIG_PERF_EVENTS
7856                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7857                 err_str = "cannot get callchain buffer for func %s#%d\n";
7858 #else
7859                 err = -ENOTSUPP;
7860                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7861 #endif
7862                 if (err) {
7863                         verbose(env, err_str, func_id_name(func_id), func_id);
7864                         return err;
7865                 }
7866
7867                 env->prog->has_callchain_buf = true;
7868         }
7869
7870         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7871                 env->prog->call_get_stack = true;
7872
7873         if (func_id == BPF_FUNC_get_func_ip) {
7874                 if (check_get_func_ip(env))
7875                         return -ENOTSUPP;
7876                 env->prog->call_get_func_ip = true;
7877         }
7878
7879         if (changes_data)
7880                 clear_all_pkt_pointers(env);
7881         return 0;
7882 }
7883
7884 /* mark_btf_func_reg_size() is used when the reg size is determined by
7885  * the BTF func_proto's return value size and argument.
7886  */
7887 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7888                                    size_t reg_size)
7889 {
7890         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7891
7892         if (regno == BPF_REG_0) {
7893                 /* Function return value */
7894                 reg->live |= REG_LIVE_WRITTEN;
7895                 reg->subreg_def = reg_size == sizeof(u64) ?
7896                         DEF_NOT_SUBREG : env->insn_idx + 1;
7897         } else {
7898                 /* Function argument */
7899                 if (reg_size == sizeof(u64)) {
7900                         mark_insn_zext(env, reg);
7901                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7902                 } else {
7903                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7904                 }
7905         }
7906 }
7907
7908 struct bpf_kfunc_call_arg_meta {
7909         /* In parameters */
7910         struct btf *btf;
7911         u32 func_id;
7912         u32 kfunc_flags;
7913         const struct btf_type *func_proto;
7914         const char *func_name;
7915         /* Out parameters */
7916         u32 ref_obj_id;
7917         u8 release_regno;
7918         bool r0_rdonly;
7919         u32 ret_btf_id;
7920         u64 r0_size;
7921         struct {
7922                 u64 value;
7923                 bool found;
7924         } arg_constant;
7925         struct {
7926                 struct btf *btf;
7927                 u32 btf_id;
7928         } arg_obj_drop;
7929         struct {
7930                 struct btf_field *field;
7931         } arg_list_head;
7932 };
7933
7934 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
7935 {
7936         return meta->kfunc_flags & KF_ACQUIRE;
7937 }
7938
7939 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
7940 {
7941         return meta->kfunc_flags & KF_RET_NULL;
7942 }
7943
7944 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
7945 {
7946         return meta->kfunc_flags & KF_RELEASE;
7947 }
7948
7949 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
7950 {
7951         return meta->kfunc_flags & KF_TRUSTED_ARGS;
7952 }
7953
7954 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
7955 {
7956         return meta->kfunc_flags & KF_SLEEPABLE;
7957 }
7958
7959 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
7960 {
7961         return meta->kfunc_flags & KF_DESTRUCTIVE;
7962 }
7963
7964 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
7965 {
7966         return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
7967 }
7968
7969 static bool is_trusted_reg(const struct bpf_reg_state *reg)
7970 {
7971         /* A referenced register is always trusted. */
7972         if (reg->ref_obj_id)
7973                 return true;
7974
7975         /* If a register is not referenced, it is trusted if it has either the
7976          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
7977          * other type modifiers may be safe, but we elect to take an opt-in
7978          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
7979          * not.
7980          *
7981          * Eventually, we should make PTR_TRUSTED the single source of truth
7982          * for whether a register is trusted.
7983          */
7984         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
7985                !bpf_type_has_unsafe_modifiers(reg->type);
7986 }
7987
7988 static bool __kfunc_param_match_suffix(const struct btf *btf,
7989                                        const struct btf_param *arg,
7990                                        const char *suffix)
7991 {
7992         int suffix_len = strlen(suffix), len;
7993         const char *param_name;
7994
7995         /* In the future, this can be ported to use BTF tagging */
7996         param_name = btf_name_by_offset(btf, arg->name_off);
7997         if (str_is_empty(param_name))
7998                 return false;
7999         len = strlen(param_name);
8000         if (len < suffix_len)
8001                 return false;
8002         param_name += len - suffix_len;
8003         return !strncmp(param_name, suffix, suffix_len);
8004 }
8005
8006 static bool is_kfunc_arg_mem_size(const struct btf *btf,
8007                                   const struct btf_param *arg,
8008                                   const struct bpf_reg_state *reg)
8009 {
8010         const struct btf_type *t;
8011
8012         t = btf_type_skip_modifiers(btf, arg->type, NULL);
8013         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
8014                 return false;
8015
8016         return __kfunc_param_match_suffix(btf, arg, "__sz");
8017 }
8018
8019 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8020 {
8021         return __kfunc_param_match_suffix(btf, arg, "__k");
8022 }
8023
8024 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8025 {
8026         return __kfunc_param_match_suffix(btf, arg, "__ign");
8027 }
8028
8029 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8030 {
8031         return __kfunc_param_match_suffix(btf, arg, "__alloc");
8032 }
8033
8034 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8035                                           const struct btf_param *arg,
8036                                           const char *name)
8037 {
8038         int len, target_len = strlen(name);
8039         const char *param_name;
8040
8041         param_name = btf_name_by_offset(btf, arg->name_off);
8042         if (str_is_empty(param_name))
8043                 return false;
8044         len = strlen(param_name);
8045         if (len != target_len)
8046                 return false;
8047         if (strcmp(param_name, name))
8048                 return false;
8049
8050         return true;
8051 }
8052
8053 enum {
8054         KF_ARG_DYNPTR_ID,
8055         KF_ARG_LIST_HEAD_ID,
8056         KF_ARG_LIST_NODE_ID,
8057 };
8058
8059 BTF_ID_LIST(kf_arg_btf_ids)
8060 BTF_ID(struct, bpf_dynptr_kern)
8061 BTF_ID(struct, bpf_list_head)
8062 BTF_ID(struct, bpf_list_node)
8063
8064 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8065                                     const struct btf_param *arg, int type)
8066 {
8067         const struct btf_type *t;
8068         u32 res_id;
8069
8070         t = btf_type_skip_modifiers(btf, arg->type, NULL);
8071         if (!t)
8072                 return false;
8073         if (!btf_type_is_ptr(t))
8074                 return false;
8075         t = btf_type_skip_modifiers(btf, t->type, &res_id);
8076         if (!t)
8077                 return false;
8078         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8079 }
8080
8081 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8082 {
8083         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8084 }
8085
8086 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8087 {
8088         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8089 }
8090
8091 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8092 {
8093         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
8094 }
8095
8096 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8097 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8098                                         const struct btf *btf,
8099                                         const struct btf_type *t, int rec)
8100 {
8101         const struct btf_type *member_type;
8102         const struct btf_member *member;
8103         u32 i;
8104
8105         if (!btf_type_is_struct(t))
8106                 return false;
8107
8108         for_each_member(i, t, member) {
8109                 const struct btf_array *array;
8110
8111                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8112                 if (btf_type_is_struct(member_type)) {
8113                         if (rec >= 3) {
8114                                 verbose(env, "max struct nesting depth exceeded\n");
8115                                 return false;
8116                         }
8117                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8118                                 return false;
8119                         continue;
8120                 }
8121                 if (btf_type_is_array(member_type)) {
8122                         array = btf_array(member_type);
8123                         if (!array->nelems)
8124                                 return false;
8125                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8126                         if (!btf_type_is_scalar(member_type))
8127                                 return false;
8128                         continue;
8129                 }
8130                 if (!btf_type_is_scalar(member_type))
8131                         return false;
8132         }
8133         return true;
8134 }
8135
8136
8137 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8138 #ifdef CONFIG_NET
8139         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8140         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8141         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8142 #endif
8143 };
8144
8145 enum kfunc_ptr_arg_type {
8146         KF_ARG_PTR_TO_CTX,
8147         KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
8148         KF_ARG_PTR_TO_KPTR,          /* PTR_TO_KPTR but type specific */
8149         KF_ARG_PTR_TO_DYNPTR,
8150         KF_ARG_PTR_TO_LIST_HEAD,
8151         KF_ARG_PTR_TO_LIST_NODE,
8152         KF_ARG_PTR_TO_BTF_ID,        /* Also covers reg2btf_ids conversions */
8153         KF_ARG_PTR_TO_MEM,
8154         KF_ARG_PTR_TO_MEM_SIZE,      /* Size derived from next argument, skip it */
8155 };
8156
8157 enum special_kfunc_type {
8158         KF_bpf_obj_new_impl,
8159         KF_bpf_obj_drop_impl,
8160         KF_bpf_list_push_front,
8161         KF_bpf_list_push_back,
8162         KF_bpf_list_pop_front,
8163         KF_bpf_list_pop_back,
8164         KF_bpf_cast_to_kern_ctx,
8165         KF_bpf_rdonly_cast,
8166 };
8167
8168 BTF_SET_START(special_kfunc_set)
8169 BTF_ID(func, bpf_obj_new_impl)
8170 BTF_ID(func, bpf_obj_drop_impl)
8171 BTF_ID(func, bpf_list_push_front)
8172 BTF_ID(func, bpf_list_push_back)
8173 BTF_ID(func, bpf_list_pop_front)
8174 BTF_ID(func, bpf_list_pop_back)
8175 BTF_ID(func, bpf_cast_to_kern_ctx)
8176 BTF_ID(func, bpf_rdonly_cast)
8177 BTF_SET_END(special_kfunc_set)
8178
8179 BTF_ID_LIST(special_kfunc_list)
8180 BTF_ID(func, bpf_obj_new_impl)
8181 BTF_ID(func, bpf_obj_drop_impl)
8182 BTF_ID(func, bpf_list_push_front)
8183 BTF_ID(func, bpf_list_push_back)
8184 BTF_ID(func, bpf_list_pop_front)
8185 BTF_ID(func, bpf_list_pop_back)
8186 BTF_ID(func, bpf_cast_to_kern_ctx)
8187 BTF_ID(func, bpf_rdonly_cast)
8188
8189 static enum kfunc_ptr_arg_type
8190 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8191                        struct bpf_kfunc_call_arg_meta *meta,
8192                        const struct btf_type *t, const struct btf_type *ref_t,
8193                        const char *ref_tname, const struct btf_param *args,
8194                        int argno, int nargs)
8195 {
8196         u32 regno = argno + 1;
8197         struct bpf_reg_state *regs = cur_regs(env);
8198         struct bpf_reg_state *reg = &regs[regno];
8199         bool arg_mem_size = false;
8200
8201         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8202                 return KF_ARG_PTR_TO_CTX;
8203
8204         /* In this function, we verify the kfunc's BTF as per the argument type,
8205          * leaving the rest of the verification with respect to the register
8206          * type to our caller. When a set of conditions hold in the BTF type of
8207          * arguments, we resolve it to a known kfunc_ptr_arg_type.
8208          */
8209         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8210                 return KF_ARG_PTR_TO_CTX;
8211
8212         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8213                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8214
8215         if (is_kfunc_arg_kptr_get(meta, argno)) {
8216                 if (!btf_type_is_ptr(ref_t)) {
8217                         verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8218                         return -EINVAL;
8219                 }
8220                 ref_t = btf_type_by_id(meta->btf, ref_t->type);
8221                 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8222                 if (!btf_type_is_struct(ref_t)) {
8223                         verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8224                                 meta->func_name, btf_type_str(ref_t), ref_tname);
8225                         return -EINVAL;
8226                 }
8227                 return KF_ARG_PTR_TO_KPTR;
8228         }
8229
8230         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8231                 return KF_ARG_PTR_TO_DYNPTR;
8232
8233         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8234                 return KF_ARG_PTR_TO_LIST_HEAD;
8235
8236         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8237                 return KF_ARG_PTR_TO_LIST_NODE;
8238
8239         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8240                 if (!btf_type_is_struct(ref_t)) {
8241                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8242                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8243                         return -EINVAL;
8244                 }
8245                 return KF_ARG_PTR_TO_BTF_ID;
8246         }
8247
8248         if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8249                 arg_mem_size = true;
8250
8251         /* This is the catch all argument type of register types supported by
8252          * check_helper_mem_access. However, we only allow when argument type is
8253          * pointer to scalar, or struct composed (recursively) of scalars. When
8254          * arg_mem_size is true, the pointer can be void *.
8255          */
8256         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8257             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8258                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8259                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8260                 return -EINVAL;
8261         }
8262         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8263 }
8264
8265 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8266                                         struct bpf_reg_state *reg,
8267                                         const struct btf_type *ref_t,
8268                                         const char *ref_tname, u32 ref_id,
8269                                         struct bpf_kfunc_call_arg_meta *meta,
8270                                         int argno)
8271 {
8272         const struct btf_type *reg_ref_t;
8273         bool strict_type_match = false;
8274         const struct btf *reg_btf;
8275         const char *reg_ref_tname;
8276         u32 reg_ref_id;
8277
8278         if (base_type(reg->type) == PTR_TO_BTF_ID) {
8279                 reg_btf = reg->btf;
8280                 reg_ref_id = reg->btf_id;
8281         } else {
8282                 reg_btf = btf_vmlinux;
8283                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8284         }
8285
8286         if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8287                 strict_type_match = true;
8288
8289         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8290         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8291         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8292                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8293                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8294                         btf_type_str(reg_ref_t), reg_ref_tname);
8295                 return -EINVAL;
8296         }
8297         return 0;
8298 }
8299
8300 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8301                                       struct bpf_reg_state *reg,
8302                                       const struct btf_type *ref_t,
8303                                       const char *ref_tname,
8304                                       struct bpf_kfunc_call_arg_meta *meta,
8305                                       int argno)
8306 {
8307         struct btf_field *kptr_field;
8308
8309         /* check_func_arg_reg_off allows var_off for
8310          * PTR_TO_MAP_VALUE, but we need fixed offset to find
8311          * off_desc.
8312          */
8313         if (!tnum_is_const(reg->var_off)) {
8314                 verbose(env, "arg#0 must have constant offset\n");
8315                 return -EINVAL;
8316         }
8317
8318         kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8319         if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8320                 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8321                         reg->off + reg->var_off.value);
8322                 return -EINVAL;
8323         }
8324
8325         if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8326                                   kptr_field->kptr.btf_id, true)) {
8327                 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8328                         meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8329                 return -EINVAL;
8330         }
8331         return 0;
8332 }
8333
8334 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8335 {
8336         struct bpf_func_state *state = cur_func(env);
8337         struct bpf_reg_state *reg;
8338         int i;
8339
8340         /* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8341          * subprogs, no global functions. This means that the references would
8342          * not be released inside the critical section but they may be added to
8343          * the reference state, and the acquired_refs are never copied out for a
8344          * different frame as BPF to BPF calls don't work in bpf_spin_lock
8345          * critical sections.
8346          */
8347         if (!ref_obj_id) {
8348                 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8349                 return -EFAULT;
8350         }
8351         for (i = 0; i < state->acquired_refs; i++) {
8352                 if (state->refs[i].id == ref_obj_id) {
8353                         if (state->refs[i].release_on_unlock) {
8354                                 verbose(env, "verifier internal error: expected false release_on_unlock");
8355                                 return -EFAULT;
8356                         }
8357                         state->refs[i].release_on_unlock = true;
8358                         /* Now mark everyone sharing same ref_obj_id as untrusted */
8359                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8360                                 if (reg->ref_obj_id == ref_obj_id)
8361                                         reg->type |= PTR_UNTRUSTED;
8362                         }));
8363                         return 0;
8364                 }
8365         }
8366         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8367         return -EFAULT;
8368 }
8369
8370 /* Implementation details:
8371  *
8372  * Each register points to some region of memory, which we define as an
8373  * allocation. Each allocation may embed a bpf_spin_lock which protects any
8374  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8375  * allocation. The lock and the data it protects are colocated in the same
8376  * memory region.
8377  *
8378  * Hence, everytime a register holds a pointer value pointing to such
8379  * allocation, the verifier preserves a unique reg->id for it.
8380  *
8381  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8382  * bpf_spin_lock is called.
8383  *
8384  * To enable this, lock state in the verifier captures two values:
8385  *      active_lock.ptr = Register's type specific pointer
8386  *      active_lock.id  = A unique ID for each register pointer value
8387  *
8388  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8389  * supported register types.
8390  *
8391  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8392  * allocated objects is the reg->btf pointer.
8393  *
8394  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8395  * can establish the provenance of the map value statically for each distinct
8396  * lookup into such maps. They always contain a single map value hence unique
8397  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8398  *
8399  * So, in case of global variables, they use array maps with max_entries = 1,
8400  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8401  * into the same map value as max_entries is 1, as described above).
8402  *
8403  * In case of inner map lookups, the inner map pointer has same map_ptr as the
8404  * outer map pointer (in verifier context), but each lookup into an inner map
8405  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8406  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8407  * will get different reg->id assigned to each lookup, hence different
8408  * active_lock.id.
8409  *
8410  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8411  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8412  * returned from bpf_obj_new. Each allocation receives a new reg->id.
8413  */
8414 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8415 {
8416         void *ptr;
8417         u32 id;
8418
8419         switch ((int)reg->type) {
8420         case PTR_TO_MAP_VALUE:
8421                 ptr = reg->map_ptr;
8422                 break;
8423         case PTR_TO_BTF_ID | MEM_ALLOC:
8424         case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8425                 ptr = reg->btf;
8426                 break;
8427         default:
8428                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
8429                 return -EFAULT;
8430         }
8431         id = reg->id;
8432
8433         if (!env->cur_state->active_lock.ptr)
8434                 return -EINVAL;
8435         if (env->cur_state->active_lock.ptr != ptr ||
8436             env->cur_state->active_lock.id != id) {
8437                 verbose(env, "held lock and object are not in the same allocation\n");
8438                 return -EINVAL;
8439         }
8440         return 0;
8441 }
8442
8443 static bool is_bpf_list_api_kfunc(u32 btf_id)
8444 {
8445         return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8446                btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8447                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8448                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8449 }
8450
8451 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8452                                            struct bpf_reg_state *reg, u32 regno,
8453                                            struct bpf_kfunc_call_arg_meta *meta)
8454 {
8455         struct btf_field *field;
8456         struct btf_record *rec;
8457         u32 list_head_off;
8458
8459         if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8460                 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8461                 return -EFAULT;
8462         }
8463
8464         if (!tnum_is_const(reg->var_off)) {
8465                 verbose(env,
8466                         "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8467                         regno);
8468                 return -EINVAL;
8469         }
8470
8471         rec = reg_btf_record(reg);
8472         list_head_off = reg->off + reg->var_off.value;
8473         field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8474         if (!field) {
8475                 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8476                 return -EINVAL;
8477         }
8478
8479         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8480         if (check_reg_allocation_locked(env, reg)) {
8481                 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8482                         rec->spin_lock_off);
8483                 return -EINVAL;
8484         }
8485
8486         if (meta->arg_list_head.field) {
8487                 verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8488                 return -EFAULT;
8489         }
8490         meta->arg_list_head.field = field;
8491         return 0;
8492 }
8493
8494 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8495                                            struct bpf_reg_state *reg, u32 regno,
8496                                            struct bpf_kfunc_call_arg_meta *meta)
8497 {
8498         const struct btf_type *et, *t;
8499         struct btf_field *field;
8500         struct btf_record *rec;
8501         u32 list_node_off;
8502
8503         if (meta->btf != btf_vmlinux ||
8504             (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8505              meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8506                 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8507                 return -EFAULT;
8508         }
8509
8510         if (!tnum_is_const(reg->var_off)) {
8511                 verbose(env,
8512                         "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8513                         regno);
8514                 return -EINVAL;
8515         }
8516
8517         rec = reg_btf_record(reg);
8518         list_node_off = reg->off + reg->var_off.value;
8519         field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8520         if (!field || field->offset != list_node_off) {
8521                 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8522                 return -EINVAL;
8523         }
8524
8525         field = meta->arg_list_head.field;
8526
8527         et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id);
8528         t = btf_type_by_id(reg->btf, reg->btf_id);
8529         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf,
8530                                   field->list_head.value_btf_id, true)) {
8531                 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8532                         "in struct %s, but arg is at offset=%d in struct %s\n",
8533                         field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off),
8534                         list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8535                 return -EINVAL;
8536         }
8537
8538         if (list_node_off != field->list_head.node_offset) {
8539                 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8540                         list_node_off, field->list_head.node_offset,
8541                         btf_name_by_offset(field->list_head.btf, et->name_off));
8542                 return -EINVAL;
8543         }
8544         /* Set arg#1 for expiration after unlock */
8545         return ref_set_release_on_unlock(env, reg->ref_obj_id);
8546 }
8547
8548 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8549 {
8550         const char *func_name = meta->func_name, *ref_tname;
8551         const struct btf *btf = meta->btf;
8552         const struct btf_param *args;
8553         u32 i, nargs;
8554         int ret;
8555
8556         args = (const struct btf_param *)(meta->func_proto + 1);
8557         nargs = btf_type_vlen(meta->func_proto);
8558         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8559                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8560                         MAX_BPF_FUNC_REG_ARGS);
8561                 return -EINVAL;
8562         }
8563
8564         /* Check that BTF function arguments match actual types that the
8565          * verifier sees.
8566          */
8567         for (i = 0; i < nargs; i++) {
8568                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
8569                 const struct btf_type *t, *ref_t, *resolve_ret;
8570                 enum bpf_arg_type arg_type = ARG_DONTCARE;
8571                 u32 regno = i + 1, ref_id, type_size;
8572                 bool is_ret_buf_sz = false;
8573                 int kf_arg_type;
8574
8575                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
8576
8577                 if (is_kfunc_arg_ignore(btf, &args[i]))
8578                         continue;
8579
8580                 if (btf_type_is_scalar(t)) {
8581                         if (reg->type != SCALAR_VALUE) {
8582                                 verbose(env, "R%d is not a scalar\n", regno);
8583                                 return -EINVAL;
8584                         }
8585
8586                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8587                                 if (meta->arg_constant.found) {
8588                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
8589                                         return -EFAULT;
8590                                 }
8591                                 if (!tnum_is_const(reg->var_off)) {
8592                                         verbose(env, "R%d must be a known constant\n", regno);
8593                                         return -EINVAL;
8594                                 }
8595                                 ret = mark_chain_precision(env, regno);
8596                                 if (ret < 0)
8597                                         return ret;
8598                                 meta->arg_constant.found = true;
8599                                 meta->arg_constant.value = reg->var_off.value;
8600                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
8601                                 meta->r0_rdonly = true;
8602                                 is_ret_buf_sz = true;
8603                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8604                                 is_ret_buf_sz = true;
8605                         }
8606
8607                         if (is_ret_buf_sz) {
8608                                 if (meta->r0_size) {
8609                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8610                                         return -EINVAL;
8611                                 }
8612
8613                                 if (!tnum_is_const(reg->var_off)) {
8614                                         verbose(env, "R%d is not a const\n", regno);
8615                                         return -EINVAL;
8616                                 }
8617
8618                                 meta->r0_size = reg->var_off.value;
8619                                 ret = mark_chain_precision(env, regno);
8620                                 if (ret)
8621                                         return ret;
8622                         }
8623                         continue;
8624                 }
8625
8626                 if (!btf_type_is_ptr(t)) {
8627                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8628                         return -EINVAL;
8629                 }
8630
8631                 if (reg->ref_obj_id) {
8632                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
8633                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8634                                         regno, reg->ref_obj_id,
8635                                         meta->ref_obj_id);
8636                                 return -EFAULT;
8637                         }
8638                         meta->ref_obj_id = reg->ref_obj_id;
8639                         if (is_kfunc_release(meta))
8640                                 meta->release_regno = regno;
8641                 }
8642
8643                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8644                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8645
8646                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8647                 if (kf_arg_type < 0)
8648                         return kf_arg_type;
8649
8650                 switch (kf_arg_type) {
8651                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8652                 case KF_ARG_PTR_TO_BTF_ID:
8653                         if (!is_kfunc_trusted_args(meta))
8654                                 break;
8655
8656                         if (!is_trusted_reg(reg)) {
8657                                 verbose(env, "R%d must be referenced or trusted\n", regno);
8658                                 return -EINVAL;
8659                         }
8660                         fallthrough;
8661                 case KF_ARG_PTR_TO_CTX:
8662                         /* Trusted arguments have the same offset checks as release arguments */
8663                         arg_type |= OBJ_RELEASE;
8664                         break;
8665                 case KF_ARG_PTR_TO_KPTR:
8666                 case KF_ARG_PTR_TO_DYNPTR:
8667                 case KF_ARG_PTR_TO_LIST_HEAD:
8668                 case KF_ARG_PTR_TO_LIST_NODE:
8669                 case KF_ARG_PTR_TO_MEM:
8670                 case KF_ARG_PTR_TO_MEM_SIZE:
8671                         /* Trusted by default */
8672                         break;
8673                 default:
8674                         WARN_ON_ONCE(1);
8675                         return -EFAULT;
8676                 }
8677
8678                 if (is_kfunc_release(meta) && reg->ref_obj_id)
8679                         arg_type |= OBJ_RELEASE;
8680                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8681                 if (ret < 0)
8682                         return ret;
8683
8684                 switch (kf_arg_type) {
8685                 case KF_ARG_PTR_TO_CTX:
8686                         if (reg->type != PTR_TO_CTX) {
8687                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8688                                 return -EINVAL;
8689                         }
8690
8691                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8692                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8693                                 if (ret < 0)
8694                                         return -EINVAL;
8695                                 meta->ret_btf_id  = ret;
8696                         }
8697                         break;
8698                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8699                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8700                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8701                                 return -EINVAL;
8702                         }
8703                         if (!reg->ref_obj_id) {
8704                                 verbose(env, "allocated object must be referenced\n");
8705                                 return -EINVAL;
8706                         }
8707                         if (meta->btf == btf_vmlinux &&
8708                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8709                                 meta->arg_obj_drop.btf = reg->btf;
8710                                 meta->arg_obj_drop.btf_id = reg->btf_id;
8711                         }
8712                         break;
8713                 case KF_ARG_PTR_TO_KPTR:
8714                         if (reg->type != PTR_TO_MAP_VALUE) {
8715                                 verbose(env, "arg#0 expected pointer to map value\n");
8716                                 return -EINVAL;
8717                         }
8718                         ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8719                         if (ret < 0)
8720                                 return ret;
8721                         break;
8722                 case KF_ARG_PTR_TO_DYNPTR:
8723                         if (reg->type != PTR_TO_STACK) {
8724                                 verbose(env, "arg#%d expected pointer to stack\n", i);
8725                                 return -EINVAL;
8726                         }
8727
8728                         if (!is_dynptr_reg_valid_init(env, reg)) {
8729                                 verbose(env, "arg#%d pointer type %s %s must be valid and initialized\n",
8730                                         i, btf_type_str(ref_t), ref_tname);
8731                                 return -EINVAL;
8732                         }
8733
8734                         if (!is_dynptr_type_expected(env, reg, ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL)) {
8735                                 verbose(env, "arg#%d pointer type %s %s points to unsupported dynamic pointer type\n",
8736                                         i, btf_type_str(ref_t), ref_tname);
8737                                 return -EINVAL;
8738                         }
8739                         break;
8740                 case KF_ARG_PTR_TO_LIST_HEAD:
8741                         if (reg->type != PTR_TO_MAP_VALUE &&
8742                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8743                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8744                                 return -EINVAL;
8745                         }
8746                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
8747                                 verbose(env, "allocated object must be referenced\n");
8748                                 return -EINVAL;
8749                         }
8750                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
8751                         if (ret < 0)
8752                                 return ret;
8753                         break;
8754                 case KF_ARG_PTR_TO_LIST_NODE:
8755                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8756                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8757                                 return -EINVAL;
8758                         }
8759                         if (!reg->ref_obj_id) {
8760                                 verbose(env, "allocated object must be referenced\n");
8761                                 return -EINVAL;
8762                         }
8763                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
8764                         if (ret < 0)
8765                                 return ret;
8766                         break;
8767                 case KF_ARG_PTR_TO_BTF_ID:
8768                         /* Only base_type is checked, further checks are done here */
8769                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
8770                              bpf_type_has_unsafe_modifiers(reg->type)) &&
8771                             !reg2btf_ids[base_type(reg->type)]) {
8772                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
8773                                 verbose(env, "expected %s or socket\n",
8774                                         reg_type_str(env, base_type(reg->type) |
8775                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
8776                                 return -EINVAL;
8777                         }
8778                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
8779                         if (ret < 0)
8780                                 return ret;
8781                         break;
8782                 case KF_ARG_PTR_TO_MEM:
8783                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
8784                         if (IS_ERR(resolve_ret)) {
8785                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
8786                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
8787                                 return -EINVAL;
8788                         }
8789                         ret = check_mem_reg(env, reg, regno, type_size);
8790                         if (ret < 0)
8791                                 return ret;
8792                         break;
8793                 case KF_ARG_PTR_TO_MEM_SIZE:
8794                         ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
8795                         if (ret < 0) {
8796                                 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
8797                                 return ret;
8798                         }
8799                         /* Skip next '__sz' argument */
8800                         i++;
8801                         break;
8802                 }
8803         }
8804
8805         if (is_kfunc_release(meta) && !meta->release_regno) {
8806                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
8807                         func_name);
8808                 return -EINVAL;
8809         }
8810
8811         return 0;
8812 }
8813
8814 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8815                             int *insn_idx_p)
8816 {
8817         const struct btf_type *t, *func, *func_proto, *ptr_type;
8818         struct bpf_reg_state *regs = cur_regs(env);
8819         const char *func_name, *ptr_type_name;
8820         struct bpf_kfunc_call_arg_meta meta;
8821         u32 i, nargs, func_id, ptr_type_id;
8822         int err, insn_idx = *insn_idx_p;
8823         const struct btf_param *args;
8824         const struct btf_type *ret_t;
8825         struct btf *desc_btf;
8826         u32 *kfunc_flags;
8827
8828         /* skip for now, but return error when we find this in fixup_kfunc_call */
8829         if (!insn->imm)
8830                 return 0;
8831
8832         desc_btf = find_kfunc_desc_btf(env, insn->off);
8833         if (IS_ERR(desc_btf))
8834                 return PTR_ERR(desc_btf);
8835
8836         func_id = insn->imm;
8837         func = btf_type_by_id(desc_btf, func_id);
8838         func_name = btf_name_by_offset(desc_btf, func->name_off);
8839         func_proto = btf_type_by_id(desc_btf, func->type);
8840
8841         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
8842         if (!kfunc_flags) {
8843                 verbose(env, "calling kernel function %s is not allowed\n",
8844                         func_name);
8845                 return -EACCES;
8846         }
8847
8848         /* Prepare kfunc call metadata */
8849         memset(&meta, 0, sizeof(meta));
8850         meta.btf = desc_btf;
8851         meta.func_id = func_id;
8852         meta.kfunc_flags = *kfunc_flags;
8853         meta.func_proto = func_proto;
8854         meta.func_name = func_name;
8855
8856         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
8857                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
8858                 return -EACCES;
8859         }
8860
8861         if (is_kfunc_sleepable(&meta) && !env->prog->aux->sleepable) {
8862                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
8863                 return -EACCES;
8864         }
8865
8866         /* Check the arguments */
8867         err = check_kfunc_args(env, &meta);
8868         if (err < 0)
8869                 return err;
8870         /* In case of release function, we get register number of refcounted
8871          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
8872          */
8873         if (meta.release_regno) {
8874                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
8875                 if (err) {
8876                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
8877                                 func_name, func_id);
8878                         return err;
8879                 }
8880         }
8881
8882         for (i = 0; i < CALLER_SAVED_REGS; i++)
8883                 mark_reg_not_init(env, regs, caller_saved[i]);
8884
8885         /* Check return type */
8886         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
8887
8888         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
8889                 /* Only exception is bpf_obj_new_impl */
8890                 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
8891                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
8892                         return -EINVAL;
8893                 }
8894         }
8895
8896         if (btf_type_is_scalar(t)) {
8897                 mark_reg_unknown(env, regs, BPF_REG_0);
8898                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
8899         } else if (btf_type_is_ptr(t)) {
8900                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
8901
8902                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
8903                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
8904                                 struct btf *ret_btf;
8905                                 u32 ret_btf_id;
8906
8907                                 if (unlikely(!bpf_global_ma_set))
8908                                         return -ENOMEM;
8909
8910                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
8911                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
8912                                         return -EINVAL;
8913                                 }
8914
8915                                 ret_btf = env->prog->aux->btf;
8916                                 ret_btf_id = meta.arg_constant.value;
8917
8918                                 /* This may be NULL due to user not supplying a BTF */
8919                                 if (!ret_btf) {
8920                                         verbose(env, "bpf_obj_new requires prog BTF\n");
8921                                         return -EINVAL;
8922                                 }
8923
8924                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
8925                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
8926                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
8927                                         return -EINVAL;
8928                                 }
8929
8930                                 mark_reg_known_zero(env, regs, BPF_REG_0);
8931                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8932                                 regs[BPF_REG_0].btf = ret_btf;
8933                                 regs[BPF_REG_0].btf_id = ret_btf_id;
8934
8935                                 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
8936                                 env->insn_aux_data[insn_idx].kptr_struct_meta =
8937                                         btf_find_struct_meta(ret_btf, ret_btf_id);
8938                         } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8939                                 env->insn_aux_data[insn_idx].kptr_struct_meta =
8940                                         btf_find_struct_meta(meta.arg_obj_drop.btf,
8941                                                              meta.arg_obj_drop.btf_id);
8942                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8943                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
8944                                 struct btf_field *field = meta.arg_list_head.field;
8945
8946                                 mark_reg_known_zero(env, regs, BPF_REG_0);
8947                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8948                                 regs[BPF_REG_0].btf = field->list_head.btf;
8949                                 regs[BPF_REG_0].btf_id = field->list_head.value_btf_id;
8950                                 regs[BPF_REG_0].off = field->list_head.node_offset;
8951                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8952                                 mark_reg_known_zero(env, regs, BPF_REG_0);
8953                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
8954                                 regs[BPF_REG_0].btf = desc_btf;
8955                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
8956                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
8957                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
8958                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
8959                                         verbose(env,
8960                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
8961                                         return -EINVAL;
8962                                 }
8963
8964                                 mark_reg_known_zero(env, regs, BPF_REG_0);
8965                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
8966                                 regs[BPF_REG_0].btf = desc_btf;
8967                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
8968                         } else {
8969                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
8970                                         meta.func_name);
8971                                 return -EFAULT;
8972                         }
8973                 } else if (!__btf_type_is_struct(ptr_type)) {
8974                         if (!meta.r0_size) {
8975                                 ptr_type_name = btf_name_by_offset(desc_btf,
8976                                                                    ptr_type->name_off);
8977                                 verbose(env,
8978                                         "kernel function %s returns pointer type %s %s is not supported\n",
8979                                         func_name,
8980                                         btf_type_str(ptr_type),
8981                                         ptr_type_name);
8982                                 return -EINVAL;
8983                         }
8984
8985                         mark_reg_known_zero(env, regs, BPF_REG_0);
8986                         regs[BPF_REG_0].type = PTR_TO_MEM;
8987                         regs[BPF_REG_0].mem_size = meta.r0_size;
8988
8989                         if (meta.r0_rdonly)
8990                                 regs[BPF_REG_0].type |= MEM_RDONLY;
8991
8992                         /* Ensures we don't access the memory after a release_reference() */
8993                         if (meta.ref_obj_id)
8994                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8995                 } else {
8996                         mark_reg_known_zero(env, regs, BPF_REG_0);
8997                         regs[BPF_REG_0].btf = desc_btf;
8998                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
8999                         regs[BPF_REG_0].btf_id = ptr_type_id;
9000                 }
9001
9002                 if (is_kfunc_ret_null(&meta)) {
9003                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9004                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9005                         regs[BPF_REG_0].id = ++env->id_gen;
9006                 }
9007                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
9008                 if (is_kfunc_acquire(&meta)) {
9009                         int id = acquire_reference_state(env, insn_idx);
9010
9011                         if (id < 0)
9012                                 return id;
9013                         if (is_kfunc_ret_null(&meta))
9014                                 regs[BPF_REG_0].id = id;
9015                         regs[BPF_REG_0].ref_obj_id = id;
9016                 }
9017                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9018                         regs[BPF_REG_0].id = ++env->id_gen;
9019         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9020
9021         nargs = btf_type_vlen(func_proto);
9022         args = (const struct btf_param *)(func_proto + 1);
9023         for (i = 0; i < nargs; i++) {
9024                 u32 regno = i + 1;
9025
9026                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
9027                 if (btf_type_is_ptr(t))
9028                         mark_btf_func_reg_size(env, regno, sizeof(void *));
9029                 else
9030                         /* scalar. ensured by btf_check_kfunc_arg_match() */
9031                         mark_btf_func_reg_size(env, regno, t->size);
9032         }
9033
9034         return 0;
9035 }
9036
9037 static bool signed_add_overflows(s64 a, s64 b)
9038 {
9039         /* Do the add in u64, where overflow is well-defined */
9040         s64 res = (s64)((u64)a + (u64)b);
9041
9042         if (b < 0)
9043                 return res > a;
9044         return res < a;
9045 }
9046
9047 static bool signed_add32_overflows(s32 a, s32 b)
9048 {
9049         /* Do the add in u32, where overflow is well-defined */
9050         s32 res = (s32)((u32)a + (u32)b);
9051
9052         if (b < 0)
9053                 return res > a;
9054         return res < a;
9055 }
9056
9057 static bool signed_sub_overflows(s64 a, s64 b)
9058 {
9059         /* Do the sub in u64, where overflow is well-defined */
9060         s64 res = (s64)((u64)a - (u64)b);
9061
9062         if (b < 0)
9063                 return res < a;
9064         return res > a;
9065 }
9066
9067 static bool signed_sub32_overflows(s32 a, s32 b)
9068 {
9069         /* Do the sub in u32, where overflow is well-defined */
9070         s32 res = (s32)((u32)a - (u32)b);
9071
9072         if (b < 0)
9073                 return res < a;
9074         return res > a;
9075 }
9076
9077 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9078                                   const struct bpf_reg_state *reg,
9079                                   enum bpf_reg_type type)
9080 {
9081         bool known = tnum_is_const(reg->var_off);
9082         s64 val = reg->var_off.value;
9083         s64 smin = reg->smin_value;
9084
9085         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9086                 verbose(env, "math between %s pointer and %lld is not allowed\n",
9087                         reg_type_str(env, type), val);
9088                 return false;
9089         }
9090
9091         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9092                 verbose(env, "%s pointer offset %d is not allowed\n",
9093                         reg_type_str(env, type), reg->off);
9094                 return false;
9095         }
9096
9097         if (smin == S64_MIN) {
9098                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
9099                         reg_type_str(env, type));
9100                 return false;
9101         }
9102
9103         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9104                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
9105                         smin, reg_type_str(env, type));
9106                 return false;
9107         }
9108
9109         return true;
9110 }
9111
9112 enum {
9113         REASON_BOUNDS   = -1,
9114         REASON_TYPE     = -2,
9115         REASON_PATHS    = -3,
9116         REASON_LIMIT    = -4,
9117         REASON_STACK    = -5,
9118 };
9119
9120 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
9121                               u32 *alu_limit, bool mask_to_left)
9122 {
9123         u32 max = 0, ptr_limit = 0;
9124
9125         switch (ptr_reg->type) {
9126         case PTR_TO_STACK:
9127                 /* Offset 0 is out-of-bounds, but acceptable start for the
9128                  * left direction, see BPF_REG_FP. Also, unknown scalar
9129                  * offset where we would need to deal with min/max bounds is
9130                  * currently prohibited for unprivileged.
9131                  */
9132                 max = MAX_BPF_STACK + mask_to_left;
9133                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
9134                 break;
9135         case PTR_TO_MAP_VALUE:
9136                 max = ptr_reg->map_ptr->value_size;
9137                 ptr_limit = (mask_to_left ?
9138                              ptr_reg->smin_value :
9139                              ptr_reg->umax_value) + ptr_reg->off;
9140                 break;
9141         default:
9142                 return REASON_TYPE;
9143         }
9144
9145         if (ptr_limit >= max)
9146                 return REASON_LIMIT;
9147         *alu_limit = ptr_limit;
9148         return 0;
9149 }
9150
9151 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9152                                     const struct bpf_insn *insn)
9153 {
9154         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
9155 }
9156
9157 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9158                                        u32 alu_state, u32 alu_limit)
9159 {
9160         /* If we arrived here from different branches with different
9161          * state or limits to sanitize, then this won't work.
9162          */
9163         if (aux->alu_state &&
9164             (aux->alu_state != alu_state ||
9165              aux->alu_limit != alu_limit))
9166                 return REASON_PATHS;
9167
9168         /* Corresponding fixup done in do_misc_fixups(). */
9169         aux->alu_state = alu_state;
9170         aux->alu_limit = alu_limit;
9171         return 0;
9172 }
9173
9174 static int sanitize_val_alu(struct bpf_verifier_env *env,
9175                             struct bpf_insn *insn)
9176 {
9177         struct bpf_insn_aux_data *aux = cur_aux(env);
9178
9179         if (can_skip_alu_sanitation(env, insn))
9180                 return 0;
9181
9182         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9183 }
9184
9185 static bool sanitize_needed(u8 opcode)
9186 {
9187         return opcode == BPF_ADD || opcode == BPF_SUB;
9188 }
9189
9190 struct bpf_sanitize_info {
9191         struct bpf_insn_aux_data aux;
9192         bool mask_to_left;
9193 };
9194
9195 static struct bpf_verifier_state *
9196 sanitize_speculative_path(struct bpf_verifier_env *env,
9197                           const struct bpf_insn *insn,
9198                           u32 next_idx, u32 curr_idx)
9199 {
9200         struct bpf_verifier_state *branch;
9201         struct bpf_reg_state *regs;
9202
9203         branch = push_stack(env, next_idx, curr_idx, true);
9204         if (branch && insn) {
9205                 regs = branch->frame[branch->curframe]->regs;
9206                 if (BPF_SRC(insn->code) == BPF_K) {
9207                         mark_reg_unknown(env, regs, insn->dst_reg);
9208                 } else if (BPF_SRC(insn->code) == BPF_X) {
9209                         mark_reg_unknown(env, regs, insn->dst_reg);
9210                         mark_reg_unknown(env, regs, insn->src_reg);
9211                 }
9212         }
9213         return branch;
9214 }
9215
9216 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9217                             struct bpf_insn *insn,
9218                             const struct bpf_reg_state *ptr_reg,
9219                             const struct bpf_reg_state *off_reg,
9220                             struct bpf_reg_state *dst_reg,
9221                             struct bpf_sanitize_info *info,
9222                             const bool commit_window)
9223 {
9224         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
9225         struct bpf_verifier_state *vstate = env->cur_state;
9226         bool off_is_imm = tnum_is_const(off_reg->var_off);
9227         bool off_is_neg = off_reg->smin_value < 0;
9228         bool ptr_is_dst_reg = ptr_reg == dst_reg;
9229         u8 opcode = BPF_OP(insn->code);
9230         u32 alu_state, alu_limit;
9231         struct bpf_reg_state tmp;
9232         bool ret;
9233         int err;
9234
9235         if (can_skip_alu_sanitation(env, insn))
9236                 return 0;
9237
9238         /* We already marked aux for masking from non-speculative
9239          * paths, thus we got here in the first place. We only care
9240          * to explore bad access from here.
9241          */
9242         if (vstate->speculative)
9243                 goto do_sim;
9244
9245         if (!commit_window) {
9246                 if (!tnum_is_const(off_reg->var_off) &&
9247                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9248                         return REASON_BOUNDS;
9249
9250                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
9251                                      (opcode == BPF_SUB && !off_is_neg);
9252         }
9253
9254         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
9255         if (err < 0)
9256                 return err;
9257
9258         if (commit_window) {
9259                 /* In commit phase we narrow the masking window based on
9260                  * the observed pointer move after the simulated operation.
9261                  */
9262                 alu_state = info->aux.alu_state;
9263                 alu_limit = abs(info->aux.alu_limit - alu_limit);
9264         } else {
9265                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
9266                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
9267                 alu_state |= ptr_is_dst_reg ?
9268                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
9269
9270                 /* Limit pruning on unknown scalars to enable deep search for
9271                  * potential masking differences from other program paths.
9272                  */
9273                 if (!off_is_imm)
9274                         env->explore_alu_limits = true;
9275         }
9276
9277         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9278         if (err < 0)
9279                 return err;
9280 do_sim:
9281         /* If we're in commit phase, we're done here given we already
9282          * pushed the truncated dst_reg into the speculative verification
9283          * stack.
9284          *
9285          * Also, when register is a known constant, we rewrite register-based
9286          * operation to immediate-based, and thus do not need masking (and as
9287          * a consequence, do not need to simulate the zero-truncation either).
9288          */
9289         if (commit_window || off_is_imm)
9290                 return 0;
9291
9292         /* Simulate and find potential out-of-bounds access under
9293          * speculative execution from truncation as a result of
9294          * masking when off was not within expected range. If off
9295          * sits in dst, then we temporarily need to move ptr there
9296          * to simulate dst (== 0) +/-= ptr. Needed, for example,
9297          * for cases where we use K-based arithmetic in one direction
9298          * and truncated reg-based in the other in order to explore
9299          * bad access.
9300          */
9301         if (!ptr_is_dst_reg) {
9302                 tmp = *dst_reg;
9303                 *dst_reg = *ptr_reg;
9304         }
9305         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9306                                         env->insn_idx);
9307         if (!ptr_is_dst_reg && ret)
9308                 *dst_reg = tmp;
9309         return !ret ? REASON_STACK : 0;
9310 }
9311
9312 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9313 {
9314         struct bpf_verifier_state *vstate = env->cur_state;
9315
9316         /* If we simulate paths under speculation, we don't update the
9317          * insn as 'seen' such that when we verify unreachable paths in
9318          * the non-speculative domain, sanitize_dead_code() can still
9319          * rewrite/sanitize them.
9320          */
9321         if (!vstate->speculative)
9322                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9323 }
9324
9325 static int sanitize_err(struct bpf_verifier_env *env,
9326                         const struct bpf_insn *insn, int reason,
9327                         const struct bpf_reg_state *off_reg,
9328                         const struct bpf_reg_state *dst_reg)
9329 {
9330         static const char *err = "pointer arithmetic with it prohibited for !root";
9331         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9332         u32 dst = insn->dst_reg, src = insn->src_reg;
9333
9334         switch (reason) {
9335         case REASON_BOUNDS:
9336                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9337                         off_reg == dst_reg ? dst : src, err);
9338                 break;
9339         case REASON_TYPE:
9340                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9341                         off_reg == dst_reg ? src : dst, err);
9342                 break;
9343         case REASON_PATHS:
9344                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9345                         dst, op, err);
9346                 break;
9347         case REASON_LIMIT:
9348                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9349                         dst, op, err);
9350                 break;
9351         case REASON_STACK:
9352                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9353                         dst, err);
9354                 break;
9355         default:
9356                 verbose(env, "verifier internal error: unknown reason (%d)\n",
9357                         reason);
9358                 break;
9359         }
9360
9361         return -EACCES;
9362 }
9363
9364 /* check that stack access falls within stack limits and that 'reg' doesn't
9365  * have a variable offset.
9366  *
9367  * Variable offset is prohibited for unprivileged mode for simplicity since it
9368  * requires corresponding support in Spectre masking for stack ALU.  See also
9369  * retrieve_ptr_limit().
9370  *
9371  *
9372  * 'off' includes 'reg->off'.
9373  */
9374 static int check_stack_access_for_ptr_arithmetic(
9375                                 struct bpf_verifier_env *env,
9376                                 int regno,
9377                                 const struct bpf_reg_state *reg,
9378                                 int off)
9379 {
9380         if (!tnum_is_const(reg->var_off)) {
9381                 char tn_buf[48];
9382
9383                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9384                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9385                         regno, tn_buf, off);
9386                 return -EACCES;
9387         }
9388
9389         if (off >= 0 || off < -MAX_BPF_STACK) {
9390                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
9391                         "prohibited for !root; off=%d\n", regno, off);
9392                 return -EACCES;
9393         }
9394
9395         return 0;
9396 }
9397
9398 static int sanitize_check_bounds(struct bpf_verifier_env *env,
9399                                  const struct bpf_insn *insn,
9400                                  const struct bpf_reg_state *dst_reg)
9401 {
9402         u32 dst = insn->dst_reg;
9403
9404         /* For unprivileged we require that resulting offset must be in bounds
9405          * in order to be able to sanitize access later on.
9406          */
9407         if (env->bypass_spec_v1)
9408                 return 0;
9409
9410         switch (dst_reg->type) {
9411         case PTR_TO_STACK:
9412                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9413                                         dst_reg->off + dst_reg->var_off.value))
9414                         return -EACCES;
9415                 break;
9416         case PTR_TO_MAP_VALUE:
9417                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
9418                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9419                                 "prohibited for !root\n", dst);
9420                         return -EACCES;
9421                 }
9422                 break;
9423         default:
9424                 break;
9425         }
9426
9427         return 0;
9428 }
9429
9430 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
9431  * Caller should also handle BPF_MOV case separately.
9432  * If we return -EACCES, caller may want to try again treating pointer as a
9433  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
9434  */
9435 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9436                                    struct bpf_insn *insn,
9437                                    const struct bpf_reg_state *ptr_reg,
9438                                    const struct bpf_reg_state *off_reg)
9439 {
9440         struct bpf_verifier_state *vstate = env->cur_state;
9441         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9442         struct bpf_reg_state *regs = state->regs, *dst_reg;
9443         bool known = tnum_is_const(off_reg->var_off);
9444         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9445             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9446         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9447             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9448         struct bpf_sanitize_info info = {};
9449         u8 opcode = BPF_OP(insn->code);
9450         u32 dst = insn->dst_reg;
9451         int ret;
9452
9453         dst_reg = &regs[dst];
9454
9455         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9456             smin_val > smax_val || umin_val > umax_val) {
9457                 /* Taint dst register if offset had invalid bounds derived from
9458                  * e.g. dead branches.
9459                  */
9460                 __mark_reg_unknown(env, dst_reg);
9461                 return 0;
9462         }
9463
9464         if (BPF_CLASS(insn->code) != BPF_ALU64) {
9465                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
9466                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9467                         __mark_reg_unknown(env, dst_reg);
9468                         return 0;
9469                 }
9470
9471                 verbose(env,
9472                         "R%d 32-bit pointer arithmetic prohibited\n",
9473                         dst);
9474                 return -EACCES;
9475         }
9476
9477         if (ptr_reg->type & PTR_MAYBE_NULL) {
9478                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
9479                         dst, reg_type_str(env, ptr_reg->type));
9480                 return -EACCES;
9481         }
9482
9483         switch (base_type(ptr_reg->type)) {
9484         case CONST_PTR_TO_MAP:
9485                 /* smin_val represents the known value */
9486                 if (known && smin_val == 0 && opcode == BPF_ADD)
9487                         break;
9488                 fallthrough;
9489         case PTR_TO_PACKET_END:
9490         case PTR_TO_SOCKET:
9491         case PTR_TO_SOCK_COMMON:
9492         case PTR_TO_TCP_SOCK:
9493         case PTR_TO_XDP_SOCK:
9494                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
9495                         dst, reg_type_str(env, ptr_reg->type));
9496                 return -EACCES;
9497         default:
9498                 break;
9499         }
9500
9501         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9502          * The id may be overwritten later if we create a new variable offset.
9503          */
9504         dst_reg->type = ptr_reg->type;
9505         dst_reg->id = ptr_reg->id;
9506
9507         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9508             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9509                 return -EINVAL;
9510
9511         /* pointer types do not carry 32-bit bounds at the moment. */
9512         __mark_reg32_unbounded(dst_reg);
9513
9514         if (sanitize_needed(opcode)) {
9515                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
9516                                        &info, false);
9517                 if (ret < 0)
9518                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
9519         }
9520
9521         switch (opcode) {
9522         case BPF_ADD:
9523                 /* We can take a fixed offset as long as it doesn't overflow
9524                  * the s32 'off' field
9525                  */
9526                 if (known && (ptr_reg->off + smin_val ==
9527                               (s64)(s32)(ptr_reg->off + smin_val))) {
9528                         /* pointer += K.  Accumulate it into fixed offset */
9529                         dst_reg->smin_value = smin_ptr;
9530                         dst_reg->smax_value = smax_ptr;
9531                         dst_reg->umin_value = umin_ptr;
9532                         dst_reg->umax_value = umax_ptr;
9533                         dst_reg->var_off = ptr_reg->var_off;
9534                         dst_reg->off = ptr_reg->off + smin_val;
9535                         dst_reg->raw = ptr_reg->raw;
9536                         break;
9537                 }
9538                 /* A new variable offset is created.  Note that off_reg->off
9539                  * == 0, since it's a scalar.
9540                  * dst_reg gets the pointer type and since some positive
9541                  * integer value was added to the pointer, give it a new 'id'
9542                  * if it's a PTR_TO_PACKET.
9543                  * this creates a new 'base' pointer, off_reg (variable) gets
9544                  * added into the variable offset, and we copy the fixed offset
9545                  * from ptr_reg.
9546                  */
9547                 if (signed_add_overflows(smin_ptr, smin_val) ||
9548                     signed_add_overflows(smax_ptr, smax_val)) {
9549                         dst_reg->smin_value = S64_MIN;
9550                         dst_reg->smax_value = S64_MAX;
9551                 } else {
9552                         dst_reg->smin_value = smin_ptr + smin_val;
9553                         dst_reg->smax_value = smax_ptr + smax_val;
9554                 }
9555                 if (umin_ptr + umin_val < umin_ptr ||
9556                     umax_ptr + umax_val < umax_ptr) {
9557                         dst_reg->umin_value = 0;
9558                         dst_reg->umax_value = U64_MAX;
9559                 } else {
9560                         dst_reg->umin_value = umin_ptr + umin_val;
9561                         dst_reg->umax_value = umax_ptr + umax_val;
9562                 }
9563                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9564                 dst_reg->off = ptr_reg->off;
9565                 dst_reg->raw = ptr_reg->raw;
9566                 if (reg_is_pkt_pointer(ptr_reg)) {
9567                         dst_reg->id = ++env->id_gen;
9568                         /* something was added to pkt_ptr, set range to zero */
9569                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9570                 }
9571                 break;
9572         case BPF_SUB:
9573                 if (dst_reg == off_reg) {
9574                         /* scalar -= pointer.  Creates an unknown scalar */
9575                         verbose(env, "R%d tried to subtract pointer from scalar\n",
9576                                 dst);
9577                         return -EACCES;
9578                 }
9579                 /* We don't allow subtraction from FP, because (according to
9580                  * test_verifier.c test "invalid fp arithmetic", JITs might not
9581                  * be able to deal with it.
9582                  */
9583                 if (ptr_reg->type == PTR_TO_STACK) {
9584                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
9585                                 dst);
9586                         return -EACCES;
9587                 }
9588                 if (known && (ptr_reg->off - smin_val ==
9589                               (s64)(s32)(ptr_reg->off - smin_val))) {
9590                         /* pointer -= K.  Subtract it from fixed offset */
9591                         dst_reg->smin_value = smin_ptr;
9592                         dst_reg->smax_value = smax_ptr;
9593                         dst_reg->umin_value = umin_ptr;
9594                         dst_reg->umax_value = umax_ptr;
9595                         dst_reg->var_off = ptr_reg->var_off;
9596                         dst_reg->id = ptr_reg->id;
9597                         dst_reg->off = ptr_reg->off - smin_val;
9598                         dst_reg->raw = ptr_reg->raw;
9599                         break;
9600                 }
9601                 /* A new variable offset is created.  If the subtrahend is known
9602                  * nonnegative, then any reg->range we had before is still good.
9603                  */
9604                 if (signed_sub_overflows(smin_ptr, smax_val) ||
9605                     signed_sub_overflows(smax_ptr, smin_val)) {
9606                         /* Overflow possible, we know nothing */
9607                         dst_reg->smin_value = S64_MIN;
9608                         dst_reg->smax_value = S64_MAX;
9609                 } else {
9610                         dst_reg->smin_value = smin_ptr - smax_val;
9611                         dst_reg->smax_value = smax_ptr - smin_val;
9612                 }
9613                 if (umin_ptr < umax_val) {
9614                         /* Overflow possible, we know nothing */
9615                         dst_reg->umin_value = 0;
9616                         dst_reg->umax_value = U64_MAX;
9617                 } else {
9618                         /* Cannot overflow (as long as bounds are consistent) */
9619                         dst_reg->umin_value = umin_ptr - umax_val;
9620                         dst_reg->umax_value = umax_ptr - umin_val;
9621                 }
9622                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9623                 dst_reg->off = ptr_reg->off;
9624                 dst_reg->raw = ptr_reg->raw;
9625                 if (reg_is_pkt_pointer(ptr_reg)) {
9626                         dst_reg->id = ++env->id_gen;
9627                         /* something was added to pkt_ptr, set range to zero */
9628                         if (smin_val < 0)
9629                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
9630                 }
9631                 break;
9632         case BPF_AND:
9633         case BPF_OR:
9634         case BPF_XOR:
9635                 /* bitwise ops on pointers are troublesome, prohibit. */
9636                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9637                         dst, bpf_alu_string[opcode >> 4]);
9638                 return -EACCES;
9639         default:
9640                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
9641                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9642                         dst, bpf_alu_string[opcode >> 4]);
9643                 return -EACCES;
9644         }
9645
9646         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9647                 return -EINVAL;
9648         reg_bounds_sync(dst_reg);
9649         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9650                 return -EACCES;
9651         if (sanitize_needed(opcode)) {
9652                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
9653                                        &info, true);
9654                 if (ret < 0)
9655                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
9656         }
9657
9658         return 0;
9659 }
9660
9661 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9662                                  struct bpf_reg_state *src_reg)
9663 {
9664         s32 smin_val = src_reg->s32_min_value;
9665         s32 smax_val = src_reg->s32_max_value;
9666         u32 umin_val = src_reg->u32_min_value;
9667         u32 umax_val = src_reg->u32_max_value;
9668
9669         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9670             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9671                 dst_reg->s32_min_value = S32_MIN;
9672                 dst_reg->s32_max_value = S32_MAX;
9673         } else {
9674                 dst_reg->s32_min_value += smin_val;
9675                 dst_reg->s32_max_value += smax_val;
9676         }
9677         if (dst_reg->u32_min_value + umin_val < umin_val ||
9678             dst_reg->u32_max_value + umax_val < umax_val) {
9679                 dst_reg->u32_min_value = 0;
9680                 dst_reg->u32_max_value = U32_MAX;
9681         } else {
9682                 dst_reg->u32_min_value += umin_val;
9683                 dst_reg->u32_max_value += umax_val;
9684         }
9685 }
9686
9687 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9688                                struct bpf_reg_state *src_reg)
9689 {
9690         s64 smin_val = src_reg->smin_value;
9691         s64 smax_val = src_reg->smax_value;
9692         u64 umin_val = src_reg->umin_value;
9693         u64 umax_val = src_reg->umax_value;
9694
9695         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9696             signed_add_overflows(dst_reg->smax_value, smax_val)) {
9697                 dst_reg->smin_value = S64_MIN;
9698                 dst_reg->smax_value = S64_MAX;
9699         } else {
9700                 dst_reg->smin_value += smin_val;
9701                 dst_reg->smax_value += smax_val;
9702         }
9703         if (dst_reg->umin_value + umin_val < umin_val ||
9704             dst_reg->umax_value + umax_val < umax_val) {
9705                 dst_reg->umin_value = 0;
9706                 dst_reg->umax_value = U64_MAX;
9707         } else {
9708                 dst_reg->umin_value += umin_val;
9709                 dst_reg->umax_value += umax_val;
9710         }
9711 }
9712
9713 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
9714                                  struct bpf_reg_state *src_reg)
9715 {
9716         s32 smin_val = src_reg->s32_min_value;
9717         s32 smax_val = src_reg->s32_max_value;
9718         u32 umin_val = src_reg->u32_min_value;
9719         u32 umax_val = src_reg->u32_max_value;
9720
9721         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
9722             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
9723                 /* Overflow possible, we know nothing */
9724                 dst_reg->s32_min_value = S32_MIN;
9725                 dst_reg->s32_max_value = S32_MAX;
9726         } else {
9727                 dst_reg->s32_min_value -= smax_val;
9728                 dst_reg->s32_max_value -= smin_val;
9729         }
9730         if (dst_reg->u32_min_value < umax_val) {
9731                 /* Overflow possible, we know nothing */
9732                 dst_reg->u32_min_value = 0;
9733                 dst_reg->u32_max_value = U32_MAX;
9734         } else {
9735                 /* Cannot overflow (as long as bounds are consistent) */
9736                 dst_reg->u32_min_value -= umax_val;
9737                 dst_reg->u32_max_value -= umin_val;
9738         }
9739 }
9740
9741 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
9742                                struct bpf_reg_state *src_reg)
9743 {
9744         s64 smin_val = src_reg->smin_value;
9745         s64 smax_val = src_reg->smax_value;
9746         u64 umin_val = src_reg->umin_value;
9747         u64 umax_val = src_reg->umax_value;
9748
9749         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
9750             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
9751                 /* Overflow possible, we know nothing */
9752                 dst_reg->smin_value = S64_MIN;
9753                 dst_reg->smax_value = S64_MAX;
9754         } else {
9755                 dst_reg->smin_value -= smax_val;
9756                 dst_reg->smax_value -= smin_val;
9757         }
9758         if (dst_reg->umin_value < umax_val) {
9759                 /* Overflow possible, we know nothing */
9760                 dst_reg->umin_value = 0;
9761                 dst_reg->umax_value = U64_MAX;
9762         } else {
9763                 /* Cannot overflow (as long as bounds are consistent) */
9764                 dst_reg->umin_value -= umax_val;
9765                 dst_reg->umax_value -= umin_val;
9766         }
9767 }
9768
9769 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
9770                                  struct bpf_reg_state *src_reg)
9771 {
9772         s32 smin_val = src_reg->s32_min_value;
9773         u32 umin_val = src_reg->u32_min_value;
9774         u32 umax_val = src_reg->u32_max_value;
9775
9776         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
9777                 /* Ain't nobody got time to multiply that sign */
9778                 __mark_reg32_unbounded(dst_reg);
9779                 return;
9780         }
9781         /* Both values are positive, so we can work with unsigned and
9782          * copy the result to signed (unless it exceeds S32_MAX).
9783          */
9784         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
9785                 /* Potential overflow, we know nothing */
9786                 __mark_reg32_unbounded(dst_reg);
9787                 return;
9788         }
9789         dst_reg->u32_min_value *= umin_val;
9790         dst_reg->u32_max_value *= umax_val;
9791         if (dst_reg->u32_max_value > S32_MAX) {
9792                 /* Overflow possible, we know nothing */
9793                 dst_reg->s32_min_value = S32_MIN;
9794                 dst_reg->s32_max_value = S32_MAX;
9795         } else {
9796                 dst_reg->s32_min_value = dst_reg->u32_min_value;
9797                 dst_reg->s32_max_value = dst_reg->u32_max_value;
9798         }
9799 }
9800
9801 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
9802                                struct bpf_reg_state *src_reg)
9803 {
9804         s64 smin_val = src_reg->smin_value;
9805         u64 umin_val = src_reg->umin_value;
9806         u64 umax_val = src_reg->umax_value;
9807
9808         if (smin_val < 0 || dst_reg->smin_value < 0) {
9809                 /* Ain't nobody got time to multiply that sign */
9810                 __mark_reg64_unbounded(dst_reg);
9811                 return;
9812         }
9813         /* Both values are positive, so we can work with unsigned and
9814          * copy the result to signed (unless it exceeds S64_MAX).
9815          */
9816         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
9817                 /* Potential overflow, we know nothing */
9818                 __mark_reg64_unbounded(dst_reg);
9819                 return;
9820         }
9821         dst_reg->umin_value *= umin_val;
9822         dst_reg->umax_value *= umax_val;
9823         if (dst_reg->umax_value > S64_MAX) {
9824                 /* Overflow possible, we know nothing */
9825                 dst_reg->smin_value = S64_MIN;
9826                 dst_reg->smax_value = S64_MAX;
9827         } else {
9828                 dst_reg->smin_value = dst_reg->umin_value;
9829                 dst_reg->smax_value = dst_reg->umax_value;
9830         }
9831 }
9832
9833 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
9834                                  struct bpf_reg_state *src_reg)
9835 {
9836         bool src_known = tnum_subreg_is_const(src_reg->var_off);
9837         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9838         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9839         s32 smin_val = src_reg->s32_min_value;
9840         u32 umax_val = src_reg->u32_max_value;
9841
9842         if (src_known && dst_known) {
9843                 __mark_reg32_known(dst_reg, var32_off.value);
9844                 return;
9845         }
9846
9847         /* We get our minimum from the var_off, since that's inherently
9848          * bitwise.  Our maximum is the minimum of the operands' maxima.
9849          */
9850         dst_reg->u32_min_value = var32_off.value;
9851         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
9852         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9853                 /* Lose signed bounds when ANDing negative numbers,
9854                  * ain't nobody got time for that.
9855                  */
9856                 dst_reg->s32_min_value = S32_MIN;
9857                 dst_reg->s32_max_value = S32_MAX;
9858         } else {
9859                 /* ANDing two positives gives a positive, so safe to
9860                  * cast result into s64.
9861                  */
9862                 dst_reg->s32_min_value = dst_reg->u32_min_value;
9863                 dst_reg->s32_max_value = dst_reg->u32_max_value;
9864         }
9865 }
9866
9867 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
9868                                struct bpf_reg_state *src_reg)
9869 {
9870         bool src_known = tnum_is_const(src_reg->var_off);
9871         bool dst_known = tnum_is_const(dst_reg->var_off);
9872         s64 smin_val = src_reg->smin_value;
9873         u64 umax_val = src_reg->umax_value;
9874
9875         if (src_known && dst_known) {
9876                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
9877                 return;
9878         }
9879
9880         /* We get our minimum from the var_off, since that's inherently
9881          * bitwise.  Our maximum is the minimum of the operands' maxima.
9882          */
9883         dst_reg->umin_value = dst_reg->var_off.value;
9884         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
9885         if (dst_reg->smin_value < 0 || smin_val < 0) {
9886                 /* Lose signed bounds when ANDing negative numbers,
9887                  * ain't nobody got time for that.
9888                  */
9889                 dst_reg->smin_value = S64_MIN;
9890                 dst_reg->smax_value = S64_MAX;
9891         } else {
9892                 /* ANDing two positives gives a positive, so safe to
9893                  * cast result into s64.
9894                  */
9895                 dst_reg->smin_value = dst_reg->umin_value;
9896                 dst_reg->smax_value = dst_reg->umax_value;
9897         }
9898         /* We may learn something more from the var_off */
9899         __update_reg_bounds(dst_reg);
9900 }
9901
9902 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
9903                                 struct bpf_reg_state *src_reg)
9904 {
9905         bool src_known = tnum_subreg_is_const(src_reg->var_off);
9906         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9907         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9908         s32 smin_val = src_reg->s32_min_value;
9909         u32 umin_val = src_reg->u32_min_value;
9910
9911         if (src_known && dst_known) {
9912                 __mark_reg32_known(dst_reg, var32_off.value);
9913                 return;
9914         }
9915
9916         /* We get our maximum from the var_off, and our minimum is the
9917          * maximum of the operands' minima
9918          */
9919         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
9920         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9921         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9922                 /* Lose signed bounds when ORing negative numbers,
9923                  * ain't nobody got time for that.
9924                  */
9925                 dst_reg->s32_min_value = S32_MIN;
9926                 dst_reg->s32_max_value = S32_MAX;
9927         } else {
9928                 /* ORing two positives gives a positive, so safe to
9929                  * cast result into s64.
9930                  */
9931                 dst_reg->s32_min_value = dst_reg->u32_min_value;
9932                 dst_reg->s32_max_value = dst_reg->u32_max_value;
9933         }
9934 }
9935
9936 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
9937                               struct bpf_reg_state *src_reg)
9938 {
9939         bool src_known = tnum_is_const(src_reg->var_off);
9940         bool dst_known = tnum_is_const(dst_reg->var_off);
9941         s64 smin_val = src_reg->smin_value;
9942         u64 umin_val = src_reg->umin_value;
9943
9944         if (src_known && dst_known) {
9945                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
9946                 return;
9947         }
9948
9949         /* We get our maximum from the var_off, and our minimum is the
9950          * maximum of the operands' minima
9951          */
9952         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
9953         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
9954         if (dst_reg->smin_value < 0 || smin_val < 0) {
9955                 /* Lose signed bounds when ORing negative numbers,
9956                  * ain't nobody got time for that.
9957                  */
9958                 dst_reg->smin_value = S64_MIN;
9959                 dst_reg->smax_value = S64_MAX;
9960         } else {
9961                 /* ORing two positives gives a positive, so safe to
9962                  * cast result into s64.
9963                  */
9964                 dst_reg->smin_value = dst_reg->umin_value;
9965                 dst_reg->smax_value = dst_reg->umax_value;
9966         }
9967         /* We may learn something more from the var_off */
9968         __update_reg_bounds(dst_reg);
9969 }
9970
9971 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
9972                                  struct bpf_reg_state *src_reg)
9973 {
9974         bool src_known = tnum_subreg_is_const(src_reg->var_off);
9975         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9976         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9977         s32 smin_val = src_reg->s32_min_value;
9978
9979         if (src_known && dst_known) {
9980                 __mark_reg32_known(dst_reg, var32_off.value);
9981                 return;
9982         }
9983
9984         /* We get both minimum and maximum from the var32_off. */
9985         dst_reg->u32_min_value = var32_off.value;
9986         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9987
9988         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
9989                 /* XORing two positive sign numbers gives a positive,
9990                  * so safe to cast u32 result into s32.
9991                  */
9992                 dst_reg->s32_min_value = dst_reg->u32_min_value;
9993                 dst_reg->s32_max_value = dst_reg->u32_max_value;
9994         } else {
9995                 dst_reg->s32_min_value = S32_MIN;
9996                 dst_reg->s32_max_value = S32_MAX;
9997         }
9998 }
9999
10000 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10001                                struct bpf_reg_state *src_reg)
10002 {
10003         bool src_known = tnum_is_const(src_reg->var_off);
10004         bool dst_known = tnum_is_const(dst_reg->var_off);
10005         s64 smin_val = src_reg->smin_value;
10006
10007         if (src_known && dst_known) {
10008                 /* dst_reg->var_off.value has been updated earlier */
10009                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10010                 return;
10011         }
10012
10013         /* We get both minimum and maximum from the var_off. */
10014         dst_reg->umin_value = dst_reg->var_off.value;
10015         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10016
10017         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10018                 /* XORing two positive sign numbers gives a positive,
10019                  * so safe to cast u64 result into s64.
10020                  */
10021                 dst_reg->smin_value = dst_reg->umin_value;
10022                 dst_reg->smax_value = dst_reg->umax_value;
10023         } else {
10024                 dst_reg->smin_value = S64_MIN;
10025                 dst_reg->smax_value = S64_MAX;
10026         }
10027
10028         __update_reg_bounds(dst_reg);
10029 }
10030
10031 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10032                                    u64 umin_val, u64 umax_val)
10033 {
10034         /* We lose all sign bit information (except what we can pick
10035          * up from var_off)
10036          */
10037         dst_reg->s32_min_value = S32_MIN;
10038         dst_reg->s32_max_value = S32_MAX;
10039         /* If we might shift our top bit out, then we know nothing */
10040         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10041                 dst_reg->u32_min_value = 0;
10042                 dst_reg->u32_max_value = U32_MAX;
10043         } else {
10044                 dst_reg->u32_min_value <<= umin_val;
10045                 dst_reg->u32_max_value <<= umax_val;
10046         }
10047 }
10048
10049 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10050                                  struct bpf_reg_state *src_reg)
10051 {
10052         u32 umax_val = src_reg->u32_max_value;
10053         u32 umin_val = src_reg->u32_min_value;
10054         /* u32 alu operation will zext upper bits */
10055         struct tnum subreg = tnum_subreg(dst_reg->var_off);
10056
10057         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10058         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10059         /* Not required but being careful mark reg64 bounds as unknown so
10060          * that we are forced to pick them up from tnum and zext later and
10061          * if some path skips this step we are still safe.
10062          */
10063         __mark_reg64_unbounded(dst_reg);
10064         __update_reg32_bounds(dst_reg);
10065 }
10066
10067 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10068                                    u64 umin_val, u64 umax_val)
10069 {
10070         /* Special case <<32 because it is a common compiler pattern to sign
10071          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10072          * positive we know this shift will also be positive so we can track
10073          * bounds correctly. Otherwise we lose all sign bit information except
10074          * what we can pick up from var_off. Perhaps we can generalize this
10075          * later to shifts of any length.
10076          */
10077         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10078                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10079         else
10080                 dst_reg->smax_value = S64_MAX;
10081
10082         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10083                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10084         else
10085                 dst_reg->smin_value = S64_MIN;
10086
10087         /* If we might shift our top bit out, then we know nothing */
10088         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10089                 dst_reg->umin_value = 0;
10090                 dst_reg->umax_value = U64_MAX;
10091         } else {
10092                 dst_reg->umin_value <<= umin_val;
10093                 dst_reg->umax_value <<= umax_val;
10094         }
10095 }
10096
10097 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10098                                struct bpf_reg_state *src_reg)
10099 {
10100         u64 umax_val = src_reg->umax_value;
10101         u64 umin_val = src_reg->umin_value;
10102
10103         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
10104         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10105         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10106
10107         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10108         /* We may learn something more from the var_off */
10109         __update_reg_bounds(dst_reg);
10110 }
10111
10112 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10113                                  struct bpf_reg_state *src_reg)
10114 {
10115         struct tnum subreg = tnum_subreg(dst_reg->var_off);
10116         u32 umax_val = src_reg->u32_max_value;
10117         u32 umin_val = src_reg->u32_min_value;
10118
10119         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10120          * be negative, then either:
10121          * 1) src_reg might be zero, so the sign bit of the result is
10122          *    unknown, so we lose our signed bounds
10123          * 2) it's known negative, thus the unsigned bounds capture the
10124          *    signed bounds
10125          * 3) the signed bounds cross zero, so they tell us nothing
10126          *    about the result
10127          * If the value in dst_reg is known nonnegative, then again the
10128          * unsigned bounds capture the signed bounds.
10129          * Thus, in all cases it suffices to blow away our signed bounds
10130          * and rely on inferring new ones from the unsigned bounds and
10131          * var_off of the result.
10132          */
10133         dst_reg->s32_min_value = S32_MIN;
10134         dst_reg->s32_max_value = S32_MAX;
10135
10136         dst_reg->var_off = tnum_rshift(subreg, umin_val);
10137         dst_reg->u32_min_value >>= umax_val;
10138         dst_reg->u32_max_value >>= umin_val;
10139
10140         __mark_reg64_unbounded(dst_reg);
10141         __update_reg32_bounds(dst_reg);
10142 }
10143
10144 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10145                                struct bpf_reg_state *src_reg)
10146 {
10147         u64 umax_val = src_reg->umax_value;
10148         u64 umin_val = src_reg->umin_value;
10149
10150         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
10151          * be negative, then either:
10152          * 1) src_reg might be zero, so the sign bit of the result is
10153          *    unknown, so we lose our signed bounds
10154          * 2) it's known negative, thus the unsigned bounds capture the
10155          *    signed bounds
10156          * 3) the signed bounds cross zero, so they tell us nothing
10157          *    about the result
10158          * If the value in dst_reg is known nonnegative, then again the
10159          * unsigned bounds capture the signed bounds.
10160          * Thus, in all cases it suffices to blow away our signed bounds
10161          * and rely on inferring new ones from the unsigned bounds and
10162          * var_off of the result.
10163          */
10164         dst_reg->smin_value = S64_MIN;
10165         dst_reg->smax_value = S64_MAX;
10166         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10167         dst_reg->umin_value >>= umax_val;
10168         dst_reg->umax_value >>= umin_val;
10169
10170         /* Its not easy to operate on alu32 bounds here because it depends
10171          * on bits being shifted in. Take easy way out and mark unbounded
10172          * so we can recalculate later from tnum.
10173          */
10174         __mark_reg32_unbounded(dst_reg);
10175         __update_reg_bounds(dst_reg);
10176 }
10177
10178 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10179                                   struct bpf_reg_state *src_reg)
10180 {
10181         u64 umin_val = src_reg->u32_min_value;
10182
10183         /* Upon reaching here, src_known is true and
10184          * umax_val is equal to umin_val.
10185          */
10186         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10187         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
10188
10189         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10190
10191         /* blow away the dst_reg umin_value/umax_value and rely on
10192          * dst_reg var_off to refine the result.
10193          */
10194         dst_reg->u32_min_value = 0;
10195         dst_reg->u32_max_value = U32_MAX;
10196
10197         __mark_reg64_unbounded(dst_reg);
10198         __update_reg32_bounds(dst_reg);
10199 }
10200
10201 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10202                                 struct bpf_reg_state *src_reg)
10203 {
10204         u64 umin_val = src_reg->umin_value;
10205
10206         /* Upon reaching here, src_known is true and umax_val is equal
10207          * to umin_val.
10208          */
10209         dst_reg->smin_value >>= umin_val;
10210         dst_reg->smax_value >>= umin_val;
10211
10212         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
10213
10214         /* blow away the dst_reg umin_value/umax_value and rely on
10215          * dst_reg var_off to refine the result.
10216          */
10217         dst_reg->umin_value = 0;
10218         dst_reg->umax_value = U64_MAX;
10219
10220         /* Its not easy to operate on alu32 bounds here because it depends
10221          * on bits being shifted in from upper 32-bits. Take easy way out
10222          * and mark unbounded so we can recalculate later from tnum.
10223          */
10224         __mark_reg32_unbounded(dst_reg);
10225         __update_reg_bounds(dst_reg);
10226 }
10227
10228 /* WARNING: This function does calculations on 64-bit values, but the actual
10229  * execution may occur on 32-bit values. Therefore, things like bitshifts
10230  * need extra checks in the 32-bit case.
10231  */
10232 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10233                                       struct bpf_insn *insn,
10234                                       struct bpf_reg_state *dst_reg,
10235                                       struct bpf_reg_state src_reg)
10236 {
10237         struct bpf_reg_state *regs = cur_regs(env);
10238         u8 opcode = BPF_OP(insn->code);
10239         bool src_known;
10240         s64 smin_val, smax_val;
10241         u64 umin_val, umax_val;
10242         s32 s32_min_val, s32_max_val;
10243         u32 u32_min_val, u32_max_val;
10244         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
10245         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
10246         int ret;
10247
10248         smin_val = src_reg.smin_value;
10249         smax_val = src_reg.smax_value;
10250         umin_val = src_reg.umin_value;
10251         umax_val = src_reg.umax_value;
10252
10253         s32_min_val = src_reg.s32_min_value;
10254         s32_max_val = src_reg.s32_max_value;
10255         u32_min_val = src_reg.u32_min_value;
10256         u32_max_val = src_reg.u32_max_value;
10257
10258         if (alu32) {
10259                 src_known = tnum_subreg_is_const(src_reg.var_off);
10260                 if ((src_known &&
10261                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10262                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10263                         /* Taint dst register if offset had invalid bounds
10264                          * derived from e.g. dead branches.
10265                          */
10266                         __mark_reg_unknown(env, dst_reg);
10267                         return 0;
10268                 }
10269         } else {
10270                 src_known = tnum_is_const(src_reg.var_off);
10271                 if ((src_known &&
10272                      (smin_val != smax_val || umin_val != umax_val)) ||
10273                     smin_val > smax_val || umin_val > umax_val) {
10274                         /* Taint dst register if offset had invalid bounds
10275                          * derived from e.g. dead branches.
10276                          */
10277                         __mark_reg_unknown(env, dst_reg);
10278                         return 0;
10279                 }
10280         }
10281
10282         if (!src_known &&
10283             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
10284                 __mark_reg_unknown(env, dst_reg);
10285                 return 0;
10286         }
10287
10288         if (sanitize_needed(opcode)) {
10289                 ret = sanitize_val_alu(env, insn);
10290                 if (ret < 0)
10291                         return sanitize_err(env, insn, ret, NULL, NULL);
10292         }
10293
10294         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10295          * There are two classes of instructions: The first class we track both
10296          * alu32 and alu64 sign/unsigned bounds independently this provides the
10297          * greatest amount of precision when alu operations are mixed with jmp32
10298          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10299          * and BPF_OR. This is possible because these ops have fairly easy to
10300          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10301          * See alu32 verifier tests for examples. The second class of
10302          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10303          * with regards to tracking sign/unsigned bounds because the bits may
10304          * cross subreg boundaries in the alu64 case. When this happens we mark
10305          * the reg unbounded in the subreg bound space and use the resulting
10306          * tnum to calculate an approximation of the sign/unsigned bounds.
10307          */
10308         switch (opcode) {
10309         case BPF_ADD:
10310                 scalar32_min_max_add(dst_reg, &src_reg);
10311                 scalar_min_max_add(dst_reg, &src_reg);
10312                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
10313                 break;
10314         case BPF_SUB:
10315                 scalar32_min_max_sub(dst_reg, &src_reg);
10316                 scalar_min_max_sub(dst_reg, &src_reg);
10317                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
10318                 break;
10319         case BPF_MUL:
10320                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10321                 scalar32_min_max_mul(dst_reg, &src_reg);
10322                 scalar_min_max_mul(dst_reg, &src_reg);
10323                 break;
10324         case BPF_AND:
10325                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10326                 scalar32_min_max_and(dst_reg, &src_reg);
10327                 scalar_min_max_and(dst_reg, &src_reg);
10328                 break;
10329         case BPF_OR:
10330                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10331                 scalar32_min_max_or(dst_reg, &src_reg);
10332                 scalar_min_max_or(dst_reg, &src_reg);
10333                 break;
10334         case BPF_XOR:
10335                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10336                 scalar32_min_max_xor(dst_reg, &src_reg);
10337                 scalar_min_max_xor(dst_reg, &src_reg);
10338                 break;
10339         case BPF_LSH:
10340                 if (umax_val >= insn_bitness) {
10341                         /* Shifts greater than 31 or 63 are undefined.
10342                          * This includes shifts by a negative number.
10343                          */
10344                         mark_reg_unknown(env, regs, insn->dst_reg);
10345                         break;
10346                 }
10347                 if (alu32)
10348                         scalar32_min_max_lsh(dst_reg, &src_reg);
10349                 else
10350                         scalar_min_max_lsh(dst_reg, &src_reg);
10351                 break;
10352         case BPF_RSH:
10353                 if (umax_val >= insn_bitness) {
10354                         /* Shifts greater than 31 or 63 are undefined.
10355                          * This includes shifts by a negative number.
10356                          */
10357                         mark_reg_unknown(env, regs, insn->dst_reg);
10358                         break;
10359                 }
10360                 if (alu32)
10361                         scalar32_min_max_rsh(dst_reg, &src_reg);
10362                 else
10363                         scalar_min_max_rsh(dst_reg, &src_reg);
10364                 break;
10365         case BPF_ARSH:
10366                 if (umax_val >= insn_bitness) {
10367                         /* Shifts greater than 31 or 63 are undefined.
10368                          * This includes shifts by a negative number.
10369                          */
10370                         mark_reg_unknown(env, regs, insn->dst_reg);
10371                         break;
10372                 }
10373                 if (alu32)
10374                         scalar32_min_max_arsh(dst_reg, &src_reg);
10375                 else
10376                         scalar_min_max_arsh(dst_reg, &src_reg);
10377                 break;
10378         default:
10379                 mark_reg_unknown(env, regs, insn->dst_reg);
10380                 break;
10381         }
10382
10383         /* ALU32 ops are zero extended into 64bit register */
10384         if (alu32)
10385                 zext_32_to_64(dst_reg);
10386         reg_bounds_sync(dst_reg);
10387         return 0;
10388 }
10389
10390 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10391  * and var_off.
10392  */
10393 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10394                                    struct bpf_insn *insn)
10395 {
10396         struct bpf_verifier_state *vstate = env->cur_state;
10397         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10398         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
10399         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10400         u8 opcode = BPF_OP(insn->code);
10401         int err;
10402
10403         dst_reg = &regs[insn->dst_reg];
10404         src_reg = NULL;
10405         if (dst_reg->type != SCALAR_VALUE)
10406                 ptr_reg = dst_reg;
10407         else
10408                 /* Make sure ID is cleared otherwise dst_reg min/max could be
10409                  * incorrectly propagated into other registers by find_equal_scalars()
10410                  */
10411                 dst_reg->id = 0;
10412         if (BPF_SRC(insn->code) == BPF_X) {
10413                 src_reg = &regs[insn->src_reg];
10414                 if (src_reg->type != SCALAR_VALUE) {
10415                         if (dst_reg->type != SCALAR_VALUE) {
10416                                 /* Combining two pointers by any ALU op yields
10417                                  * an arbitrary scalar. Disallow all math except
10418                                  * pointer subtraction
10419                                  */
10420                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
10421                                         mark_reg_unknown(env, regs, insn->dst_reg);
10422                                         return 0;
10423                                 }
10424                                 verbose(env, "R%d pointer %s pointer prohibited\n",
10425                                         insn->dst_reg,
10426                                         bpf_alu_string[opcode >> 4]);
10427                                 return -EACCES;
10428                         } else {
10429                                 /* scalar += pointer
10430                                  * This is legal, but we have to reverse our
10431                                  * src/dest handling in computing the range
10432                                  */
10433                                 err = mark_chain_precision(env, insn->dst_reg);
10434                                 if (err)
10435                                         return err;
10436                                 return adjust_ptr_min_max_vals(env, insn,
10437                                                                src_reg, dst_reg);
10438                         }
10439                 } else if (ptr_reg) {
10440                         /* pointer += scalar */
10441                         err = mark_chain_precision(env, insn->src_reg);
10442                         if (err)
10443                                 return err;
10444                         return adjust_ptr_min_max_vals(env, insn,
10445                                                        dst_reg, src_reg);
10446                 } else if (dst_reg->precise) {
10447                         /* if dst_reg is precise, src_reg should be precise as well */
10448                         err = mark_chain_precision(env, insn->src_reg);
10449                         if (err)
10450                                 return err;
10451                 }
10452         } else {
10453                 /* Pretend the src is a reg with a known value, since we only
10454                  * need to be able to read from this state.
10455                  */
10456                 off_reg.type = SCALAR_VALUE;
10457                 __mark_reg_known(&off_reg, insn->imm);
10458                 src_reg = &off_reg;
10459                 if (ptr_reg) /* pointer += K */
10460                         return adjust_ptr_min_max_vals(env, insn,
10461                                                        ptr_reg, src_reg);
10462         }
10463
10464         /* Got here implies adding two SCALAR_VALUEs */
10465         if (WARN_ON_ONCE(ptr_reg)) {
10466                 print_verifier_state(env, state, true);
10467                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
10468                 return -EINVAL;
10469         }
10470         if (WARN_ON(!src_reg)) {
10471                 print_verifier_state(env, state, true);
10472                 verbose(env, "verifier internal error: no src_reg\n");
10473                 return -EINVAL;
10474         }
10475         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
10476 }
10477
10478 /* check validity of 32-bit and 64-bit arithmetic operations */
10479 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
10480 {
10481         struct bpf_reg_state *regs = cur_regs(env);
10482         u8 opcode = BPF_OP(insn->code);
10483         int err;
10484
10485         if (opcode == BPF_END || opcode == BPF_NEG) {
10486                 if (opcode == BPF_NEG) {
10487                         if (BPF_SRC(insn->code) != BPF_K ||
10488                             insn->src_reg != BPF_REG_0 ||
10489                             insn->off != 0 || insn->imm != 0) {
10490                                 verbose(env, "BPF_NEG uses reserved fields\n");
10491                                 return -EINVAL;
10492                         }
10493                 } else {
10494                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
10495                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10496                             BPF_CLASS(insn->code) == BPF_ALU64) {
10497                                 verbose(env, "BPF_END uses reserved fields\n");
10498                                 return -EINVAL;
10499                         }
10500                 }
10501
10502                 /* check src operand */
10503                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10504                 if (err)
10505                         return err;
10506
10507                 if (is_pointer_value(env, insn->dst_reg)) {
10508                         verbose(env, "R%d pointer arithmetic prohibited\n",
10509                                 insn->dst_reg);
10510                         return -EACCES;
10511                 }
10512
10513                 /* check dest operand */
10514                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10515                 if (err)
10516                         return err;
10517
10518         } else if (opcode == BPF_MOV) {
10519
10520                 if (BPF_SRC(insn->code) == BPF_X) {
10521                         if (insn->imm != 0 || insn->off != 0) {
10522                                 verbose(env, "BPF_MOV uses reserved fields\n");
10523                                 return -EINVAL;
10524                         }
10525
10526                         /* check src operand */
10527                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10528                         if (err)
10529                                 return err;
10530                 } else {
10531                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10532                                 verbose(env, "BPF_MOV uses reserved fields\n");
10533                                 return -EINVAL;
10534                         }
10535                 }
10536
10537                 /* check dest operand, mark as required later */
10538                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10539                 if (err)
10540                         return err;
10541
10542                 if (BPF_SRC(insn->code) == BPF_X) {
10543                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
10544                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10545
10546                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
10547                                 /* case: R1 = R2
10548                                  * copy register state to dest reg
10549                                  */
10550                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10551                                         /* Assign src and dst registers the same ID
10552                                          * that will be used by find_equal_scalars()
10553                                          * to propagate min/max range.
10554                                          */
10555                                         src_reg->id = ++env->id_gen;
10556                                 *dst_reg = *src_reg;
10557                                 dst_reg->live |= REG_LIVE_WRITTEN;
10558                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
10559                         } else {
10560                                 /* R1 = (u32) R2 */
10561                                 if (is_pointer_value(env, insn->src_reg)) {
10562                                         verbose(env,
10563                                                 "R%d partial copy of pointer\n",
10564                                                 insn->src_reg);
10565                                         return -EACCES;
10566                                 } else if (src_reg->type == SCALAR_VALUE) {
10567                                         *dst_reg = *src_reg;
10568                                         /* Make sure ID is cleared otherwise
10569                                          * dst_reg min/max could be incorrectly
10570                                          * propagated into src_reg by find_equal_scalars()
10571                                          */
10572                                         dst_reg->id = 0;
10573                                         dst_reg->live |= REG_LIVE_WRITTEN;
10574                                         dst_reg->subreg_def = env->insn_idx + 1;
10575                                 } else {
10576                                         mark_reg_unknown(env, regs,
10577                                                          insn->dst_reg);
10578                                 }
10579                                 zext_32_to_64(dst_reg);
10580                                 reg_bounds_sync(dst_reg);
10581                         }
10582                 } else {
10583                         /* case: R = imm
10584                          * remember the value we stored into this reg
10585                          */
10586                         /* clear any state __mark_reg_known doesn't set */
10587                         mark_reg_unknown(env, regs, insn->dst_reg);
10588                         regs[insn->dst_reg].type = SCALAR_VALUE;
10589                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
10590                                 __mark_reg_known(regs + insn->dst_reg,
10591                                                  insn->imm);
10592                         } else {
10593                                 __mark_reg_known(regs + insn->dst_reg,
10594                                                  (u32)insn->imm);
10595                         }
10596                 }
10597
10598         } else if (opcode > BPF_END) {
10599                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
10600                 return -EINVAL;
10601
10602         } else {        /* all other ALU ops: and, sub, xor, add, ... */
10603
10604                 if (BPF_SRC(insn->code) == BPF_X) {
10605                         if (insn->imm != 0 || insn->off != 0) {
10606                                 verbose(env, "BPF_ALU uses reserved fields\n");
10607                                 return -EINVAL;
10608                         }
10609                         /* check src1 operand */
10610                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
10611                         if (err)
10612                                 return err;
10613                 } else {
10614                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
10615                                 verbose(env, "BPF_ALU uses reserved fields\n");
10616                                 return -EINVAL;
10617                         }
10618                 }
10619
10620                 /* check src2 operand */
10621                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10622                 if (err)
10623                         return err;
10624
10625                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10626                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
10627                         verbose(env, "div by zero\n");
10628                         return -EINVAL;
10629                 }
10630
10631                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10632                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10633                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10634
10635                         if (insn->imm < 0 || insn->imm >= size) {
10636                                 verbose(env, "invalid shift %d\n", insn->imm);
10637                                 return -EINVAL;
10638                         }
10639                 }
10640
10641                 /* check dest operand */
10642                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10643                 if (err)
10644                         return err;
10645
10646                 return adjust_reg_min_max_vals(env, insn);
10647         }
10648
10649         return 0;
10650 }
10651
10652 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
10653                                    struct bpf_reg_state *dst_reg,
10654                                    enum bpf_reg_type type,
10655                                    bool range_right_open)
10656 {
10657         struct bpf_func_state *state;
10658         struct bpf_reg_state *reg;
10659         int new_range;
10660
10661         if (dst_reg->off < 0 ||
10662             (dst_reg->off == 0 && range_right_open))
10663                 /* This doesn't give us any range */
10664                 return;
10665
10666         if (dst_reg->umax_value > MAX_PACKET_OFF ||
10667             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
10668                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
10669                  * than pkt_end, but that's because it's also less than pkt.
10670                  */
10671                 return;
10672
10673         new_range = dst_reg->off;
10674         if (range_right_open)
10675                 new_range++;
10676
10677         /* Examples for register markings:
10678          *
10679          * pkt_data in dst register:
10680          *
10681          *   r2 = r3;
10682          *   r2 += 8;
10683          *   if (r2 > pkt_end) goto <handle exception>
10684          *   <access okay>
10685          *
10686          *   r2 = r3;
10687          *   r2 += 8;
10688          *   if (r2 < pkt_end) goto <access okay>
10689          *   <handle exception>
10690          *
10691          *   Where:
10692          *     r2 == dst_reg, pkt_end == src_reg
10693          *     r2=pkt(id=n,off=8,r=0)
10694          *     r3=pkt(id=n,off=0,r=0)
10695          *
10696          * pkt_data in src register:
10697          *
10698          *   r2 = r3;
10699          *   r2 += 8;
10700          *   if (pkt_end >= r2) goto <access okay>
10701          *   <handle exception>
10702          *
10703          *   r2 = r3;
10704          *   r2 += 8;
10705          *   if (pkt_end <= r2) goto <handle exception>
10706          *   <access okay>
10707          *
10708          *   Where:
10709          *     pkt_end == dst_reg, r2 == src_reg
10710          *     r2=pkt(id=n,off=8,r=0)
10711          *     r3=pkt(id=n,off=0,r=0)
10712          *
10713          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
10714          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
10715          * and [r3, r3 + 8-1) respectively is safe to access depending on
10716          * the check.
10717          */
10718
10719         /* If our ids match, then we must have the same max_value.  And we
10720          * don't care about the other reg's fixed offset, since if it's too big
10721          * the range won't allow anything.
10722          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
10723          */
10724         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10725                 if (reg->type == type && reg->id == dst_reg->id)
10726                         /* keep the maximum range already checked */
10727                         reg->range = max(reg->range, new_range);
10728         }));
10729 }
10730
10731 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
10732 {
10733         struct tnum subreg = tnum_subreg(reg->var_off);
10734         s32 sval = (s32)val;
10735
10736         switch (opcode) {
10737         case BPF_JEQ:
10738                 if (tnum_is_const(subreg))
10739                         return !!tnum_equals_const(subreg, val);
10740                 break;
10741         case BPF_JNE:
10742                 if (tnum_is_const(subreg))
10743                         return !tnum_equals_const(subreg, val);
10744                 break;
10745         case BPF_JSET:
10746                 if ((~subreg.mask & subreg.value) & val)
10747                         return 1;
10748                 if (!((subreg.mask | subreg.value) & val))
10749                         return 0;
10750                 break;
10751         case BPF_JGT:
10752                 if (reg->u32_min_value > val)
10753                         return 1;
10754                 else if (reg->u32_max_value <= val)
10755                         return 0;
10756                 break;
10757         case BPF_JSGT:
10758                 if (reg->s32_min_value > sval)
10759                         return 1;
10760                 else if (reg->s32_max_value <= sval)
10761                         return 0;
10762                 break;
10763         case BPF_JLT:
10764                 if (reg->u32_max_value < val)
10765                         return 1;
10766                 else if (reg->u32_min_value >= val)
10767                         return 0;
10768                 break;
10769         case BPF_JSLT:
10770                 if (reg->s32_max_value < sval)
10771                         return 1;
10772                 else if (reg->s32_min_value >= sval)
10773                         return 0;
10774                 break;
10775         case BPF_JGE:
10776                 if (reg->u32_min_value >= val)
10777                         return 1;
10778                 else if (reg->u32_max_value < val)
10779                         return 0;
10780                 break;
10781         case BPF_JSGE:
10782                 if (reg->s32_min_value >= sval)
10783                         return 1;
10784                 else if (reg->s32_max_value < sval)
10785                         return 0;
10786                 break;
10787         case BPF_JLE:
10788                 if (reg->u32_max_value <= val)
10789                         return 1;
10790                 else if (reg->u32_min_value > val)
10791                         return 0;
10792                 break;
10793         case BPF_JSLE:
10794                 if (reg->s32_max_value <= sval)
10795                         return 1;
10796                 else if (reg->s32_min_value > sval)
10797                         return 0;
10798                 break;
10799         }
10800
10801         return -1;
10802 }
10803
10804
10805 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
10806 {
10807         s64 sval = (s64)val;
10808
10809         switch (opcode) {
10810         case BPF_JEQ:
10811                 if (tnum_is_const(reg->var_off))
10812                         return !!tnum_equals_const(reg->var_off, val);
10813                 break;
10814         case BPF_JNE:
10815                 if (tnum_is_const(reg->var_off))
10816                         return !tnum_equals_const(reg->var_off, val);
10817                 break;
10818         case BPF_JSET:
10819                 if ((~reg->var_off.mask & reg->var_off.value) & val)
10820                         return 1;
10821                 if (!((reg->var_off.mask | reg->var_off.value) & val))
10822                         return 0;
10823                 break;
10824         case BPF_JGT:
10825                 if (reg->umin_value > val)
10826                         return 1;
10827                 else if (reg->umax_value <= val)
10828                         return 0;
10829                 break;
10830         case BPF_JSGT:
10831                 if (reg->smin_value > sval)
10832                         return 1;
10833                 else if (reg->smax_value <= sval)
10834                         return 0;
10835                 break;
10836         case BPF_JLT:
10837                 if (reg->umax_value < val)
10838                         return 1;
10839                 else if (reg->umin_value >= val)
10840                         return 0;
10841                 break;
10842         case BPF_JSLT:
10843                 if (reg->smax_value < sval)
10844                         return 1;
10845                 else if (reg->smin_value >= sval)
10846                         return 0;
10847                 break;
10848         case BPF_JGE:
10849                 if (reg->umin_value >= val)
10850                         return 1;
10851                 else if (reg->umax_value < val)
10852                         return 0;
10853                 break;
10854         case BPF_JSGE:
10855                 if (reg->smin_value >= sval)
10856                         return 1;
10857                 else if (reg->smax_value < sval)
10858                         return 0;
10859                 break;
10860         case BPF_JLE:
10861                 if (reg->umax_value <= val)
10862                         return 1;
10863                 else if (reg->umin_value > val)
10864                         return 0;
10865                 break;
10866         case BPF_JSLE:
10867                 if (reg->smax_value <= sval)
10868                         return 1;
10869                 else if (reg->smin_value > sval)
10870                         return 0;
10871                 break;
10872         }
10873
10874         return -1;
10875 }
10876
10877 /* compute branch direction of the expression "if (reg opcode val) goto target;"
10878  * and return:
10879  *  1 - branch will be taken and "goto target" will be executed
10880  *  0 - branch will not be taken and fall-through to next insn
10881  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
10882  *      range [0,10]
10883  */
10884 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
10885                            bool is_jmp32)
10886 {
10887         if (__is_pointer_value(false, reg)) {
10888                 if (!reg_type_not_null(reg->type))
10889                         return -1;
10890
10891                 /* If pointer is valid tests against zero will fail so we can
10892                  * use this to direct branch taken.
10893                  */
10894                 if (val != 0)
10895                         return -1;
10896
10897                 switch (opcode) {
10898                 case BPF_JEQ:
10899                         return 0;
10900                 case BPF_JNE:
10901                         return 1;
10902                 default:
10903                         return -1;
10904                 }
10905         }
10906
10907         if (is_jmp32)
10908                 return is_branch32_taken(reg, val, opcode);
10909         return is_branch64_taken(reg, val, opcode);
10910 }
10911
10912 static int flip_opcode(u32 opcode)
10913 {
10914         /* How can we transform "a <op> b" into "b <op> a"? */
10915         static const u8 opcode_flip[16] = {
10916                 /* these stay the same */
10917                 [BPF_JEQ  >> 4] = BPF_JEQ,
10918                 [BPF_JNE  >> 4] = BPF_JNE,
10919                 [BPF_JSET >> 4] = BPF_JSET,
10920                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
10921                 [BPF_JGE  >> 4] = BPF_JLE,
10922                 [BPF_JGT  >> 4] = BPF_JLT,
10923                 [BPF_JLE  >> 4] = BPF_JGE,
10924                 [BPF_JLT  >> 4] = BPF_JGT,
10925                 [BPF_JSGE >> 4] = BPF_JSLE,
10926                 [BPF_JSGT >> 4] = BPF_JSLT,
10927                 [BPF_JSLE >> 4] = BPF_JSGE,
10928                 [BPF_JSLT >> 4] = BPF_JSGT
10929         };
10930         return opcode_flip[opcode >> 4];
10931 }
10932
10933 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
10934                                    struct bpf_reg_state *src_reg,
10935                                    u8 opcode)
10936 {
10937         struct bpf_reg_state *pkt;
10938
10939         if (src_reg->type == PTR_TO_PACKET_END) {
10940                 pkt = dst_reg;
10941         } else if (dst_reg->type == PTR_TO_PACKET_END) {
10942                 pkt = src_reg;
10943                 opcode = flip_opcode(opcode);
10944         } else {
10945                 return -1;
10946         }
10947
10948         if (pkt->range >= 0)
10949                 return -1;
10950
10951         switch (opcode) {
10952         case BPF_JLE:
10953                 /* pkt <= pkt_end */
10954                 fallthrough;
10955         case BPF_JGT:
10956                 /* pkt > pkt_end */
10957                 if (pkt->range == BEYOND_PKT_END)
10958                         /* pkt has at last one extra byte beyond pkt_end */
10959                         return opcode == BPF_JGT;
10960                 break;
10961         case BPF_JLT:
10962                 /* pkt < pkt_end */
10963                 fallthrough;
10964         case BPF_JGE:
10965                 /* pkt >= pkt_end */
10966                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
10967                         return opcode == BPF_JGE;
10968                 break;
10969         }
10970         return -1;
10971 }
10972
10973 /* Adjusts the register min/max values in the case that the dst_reg is the
10974  * variable register that we are working on, and src_reg is a constant or we're
10975  * simply doing a BPF_K check.
10976  * In JEQ/JNE cases we also adjust the var_off values.
10977  */
10978 static void reg_set_min_max(struct bpf_reg_state *true_reg,
10979                             struct bpf_reg_state *false_reg,
10980                             u64 val, u32 val32,
10981                             u8 opcode, bool is_jmp32)
10982 {
10983         struct tnum false_32off = tnum_subreg(false_reg->var_off);
10984         struct tnum false_64off = false_reg->var_off;
10985         struct tnum true_32off = tnum_subreg(true_reg->var_off);
10986         struct tnum true_64off = true_reg->var_off;
10987         s64 sval = (s64)val;
10988         s32 sval32 = (s32)val32;
10989
10990         /* If the dst_reg is a pointer, we can't learn anything about its
10991          * variable offset from the compare (unless src_reg were a pointer into
10992          * the same object, but we don't bother with that.
10993          * Since false_reg and true_reg have the same type by construction, we
10994          * only need to check one of them for pointerness.
10995          */
10996         if (__is_pointer_value(false, false_reg))
10997                 return;
10998
10999         switch (opcode) {
11000         /* JEQ/JNE comparison doesn't change the register equivalence.
11001          *
11002          * r1 = r2;
11003          * if (r1 == 42) goto label;
11004          * ...
11005          * label: // here both r1 and r2 are known to be 42.
11006          *
11007          * Hence when marking register as known preserve it's ID.
11008          */
11009         case BPF_JEQ:
11010                 if (is_jmp32) {
11011                         __mark_reg32_known(true_reg, val32);
11012                         true_32off = tnum_subreg(true_reg->var_off);
11013                 } else {
11014                         ___mark_reg_known(true_reg, val);
11015                         true_64off = true_reg->var_off;
11016                 }
11017                 break;
11018         case BPF_JNE:
11019                 if (is_jmp32) {
11020                         __mark_reg32_known(false_reg, val32);
11021                         false_32off = tnum_subreg(false_reg->var_off);
11022                 } else {
11023                         ___mark_reg_known(false_reg, val);
11024                         false_64off = false_reg->var_off;
11025                 }
11026                 break;
11027         case BPF_JSET:
11028                 if (is_jmp32) {
11029                         false_32off = tnum_and(false_32off, tnum_const(~val32));
11030                         if (is_power_of_2(val32))
11031                                 true_32off = tnum_or(true_32off,
11032                                                      tnum_const(val32));
11033                 } else {
11034                         false_64off = tnum_and(false_64off, tnum_const(~val));
11035                         if (is_power_of_2(val))
11036                                 true_64off = tnum_or(true_64off,
11037                                                      tnum_const(val));
11038                 }
11039                 break;
11040         case BPF_JGE:
11041         case BPF_JGT:
11042         {
11043                 if (is_jmp32) {
11044                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
11045                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11046
11047                         false_reg->u32_max_value = min(false_reg->u32_max_value,
11048                                                        false_umax);
11049                         true_reg->u32_min_value = max(true_reg->u32_min_value,
11050                                                       true_umin);
11051                 } else {
11052                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
11053                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11054
11055                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
11056                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
11057                 }
11058                 break;
11059         }
11060         case BPF_JSGE:
11061         case BPF_JSGT:
11062         {
11063                 if (is_jmp32) {
11064                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
11065                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
11066
11067                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11068                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11069                 } else {
11070                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
11071                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11072
11073                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
11074                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
11075                 }
11076                 break;
11077         }
11078         case BPF_JLE:
11079         case BPF_JLT:
11080         {
11081                 if (is_jmp32) {
11082                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
11083                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11084
11085                         false_reg->u32_min_value = max(false_reg->u32_min_value,
11086                                                        false_umin);
11087                         true_reg->u32_max_value = min(true_reg->u32_max_value,
11088                                                       true_umax);
11089                 } else {
11090                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
11091                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11092
11093                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
11094                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
11095                 }
11096                 break;
11097         }
11098         case BPF_JSLE:
11099         case BPF_JSLT:
11100         {
11101                 if (is_jmp32) {
11102                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
11103                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
11104
11105                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11106                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11107                 } else {
11108                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
11109                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11110
11111                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
11112                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
11113                 }
11114                 break;
11115         }
11116         default:
11117                 return;
11118         }
11119
11120         if (is_jmp32) {
11121                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11122                                              tnum_subreg(false_32off));
11123                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11124                                             tnum_subreg(true_32off));
11125                 __reg_combine_32_into_64(false_reg);
11126                 __reg_combine_32_into_64(true_reg);
11127         } else {
11128                 false_reg->var_off = false_64off;
11129                 true_reg->var_off = true_64off;
11130                 __reg_combine_64_into_32(false_reg);
11131                 __reg_combine_64_into_32(true_reg);
11132         }
11133 }
11134
11135 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
11136  * the variable reg.
11137  */
11138 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
11139                                 struct bpf_reg_state *false_reg,
11140                                 u64 val, u32 val32,
11141                                 u8 opcode, bool is_jmp32)
11142 {
11143         opcode = flip_opcode(opcode);
11144         /* This uses zero as "not present in table"; luckily the zero opcode,
11145          * BPF_JA, can't get here.
11146          */
11147         if (opcode)
11148                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
11149 }
11150
11151 /* Regs are known to be equal, so intersect their min/max/var_off */
11152 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11153                                   struct bpf_reg_state *dst_reg)
11154 {
11155         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11156                                                         dst_reg->umin_value);
11157         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11158                                                         dst_reg->umax_value);
11159         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11160                                                         dst_reg->smin_value);
11161         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11162                                                         dst_reg->smax_value);
11163         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11164                                                              dst_reg->var_off);
11165         reg_bounds_sync(src_reg);
11166         reg_bounds_sync(dst_reg);
11167 }
11168
11169 static void reg_combine_min_max(struct bpf_reg_state *true_src,
11170                                 struct bpf_reg_state *true_dst,
11171                                 struct bpf_reg_state *false_src,
11172                                 struct bpf_reg_state *false_dst,
11173                                 u8 opcode)
11174 {
11175         switch (opcode) {
11176         case BPF_JEQ:
11177                 __reg_combine_min_max(true_src, true_dst);
11178                 break;
11179         case BPF_JNE:
11180                 __reg_combine_min_max(false_src, false_dst);
11181                 break;
11182         }
11183 }
11184
11185 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11186                                  struct bpf_reg_state *reg, u32 id,
11187                                  bool is_null)
11188 {
11189         if (type_may_be_null(reg->type) && reg->id == id &&
11190             !WARN_ON_ONCE(!reg->id)) {
11191                 /* Old offset (both fixed and variable parts) should have been
11192                  * known-zero, because we don't allow pointer arithmetic on
11193                  * pointers that might be NULL. If we see this happening, don't
11194                  * convert the register.
11195                  *
11196                  * But in some cases, some helpers that return local kptrs
11197                  * advance offset for the returned pointer. In those cases, it
11198                  * is fine to expect to see reg->off.
11199                  */
11200                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11201                         return;
11202                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
11203                         return;
11204                 if (is_null) {
11205                         reg->type = SCALAR_VALUE;
11206                         /* We don't need id and ref_obj_id from this point
11207                          * onwards anymore, thus we should better reset it,
11208                          * so that state pruning has chances to take effect.
11209                          */
11210                         reg->id = 0;
11211                         reg->ref_obj_id = 0;
11212
11213                         return;
11214                 }
11215
11216                 mark_ptr_not_null_reg(reg);
11217
11218                 if (!reg_may_point_to_spin_lock(reg)) {
11219                         /* For not-NULL ptr, reg->ref_obj_id will be reset
11220                          * in release_reference().
11221                          *
11222                          * reg->id is still used by spin_lock ptr. Other
11223                          * than spin_lock ptr type, reg->id can be reset.
11224                          */
11225                         reg->id = 0;
11226                 }
11227         }
11228 }
11229
11230 /* The logic is similar to find_good_pkt_pointers(), both could eventually
11231  * be folded together at some point.
11232  */
11233 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11234                                   bool is_null)
11235 {
11236         struct bpf_func_state *state = vstate->frame[vstate->curframe];
11237         struct bpf_reg_state *regs = state->regs, *reg;
11238         u32 ref_obj_id = regs[regno].ref_obj_id;
11239         u32 id = regs[regno].id;
11240
11241         if (ref_obj_id && ref_obj_id == id && is_null)
11242                 /* regs[regno] is in the " == NULL" branch.
11243                  * No one could have freed the reference state before
11244                  * doing the NULL check.
11245                  */
11246                 WARN_ON_ONCE(release_reference_state(state, id));
11247
11248         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11249                 mark_ptr_or_null_reg(state, reg, id, is_null);
11250         }));
11251 }
11252
11253 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11254                                    struct bpf_reg_state *dst_reg,
11255                                    struct bpf_reg_state *src_reg,
11256                                    struct bpf_verifier_state *this_branch,
11257                                    struct bpf_verifier_state *other_branch)
11258 {
11259         if (BPF_SRC(insn->code) != BPF_X)
11260                 return false;
11261
11262         /* Pointers are always 64-bit. */
11263         if (BPF_CLASS(insn->code) == BPF_JMP32)
11264                 return false;
11265
11266         switch (BPF_OP(insn->code)) {
11267         case BPF_JGT:
11268                 if ((dst_reg->type == PTR_TO_PACKET &&
11269                      src_reg->type == PTR_TO_PACKET_END) ||
11270                     (dst_reg->type == PTR_TO_PACKET_META &&
11271                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11272                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11273                         find_good_pkt_pointers(this_branch, dst_reg,
11274                                                dst_reg->type, false);
11275                         mark_pkt_end(other_branch, insn->dst_reg, true);
11276                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11277                             src_reg->type == PTR_TO_PACKET) ||
11278                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11279                             src_reg->type == PTR_TO_PACKET_META)) {
11280                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
11281                         find_good_pkt_pointers(other_branch, src_reg,
11282                                                src_reg->type, true);
11283                         mark_pkt_end(this_branch, insn->src_reg, false);
11284                 } else {
11285                         return false;
11286                 }
11287                 break;
11288         case BPF_JLT:
11289                 if ((dst_reg->type == PTR_TO_PACKET &&
11290                      src_reg->type == PTR_TO_PACKET_END) ||
11291                     (dst_reg->type == PTR_TO_PACKET_META &&
11292                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11293                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11294                         find_good_pkt_pointers(other_branch, dst_reg,
11295                                                dst_reg->type, true);
11296                         mark_pkt_end(this_branch, insn->dst_reg, false);
11297                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11298                             src_reg->type == PTR_TO_PACKET) ||
11299                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11300                             src_reg->type == PTR_TO_PACKET_META)) {
11301                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
11302                         find_good_pkt_pointers(this_branch, src_reg,
11303                                                src_reg->type, false);
11304                         mark_pkt_end(other_branch, insn->src_reg, true);
11305                 } else {
11306                         return false;
11307                 }
11308                 break;
11309         case BPF_JGE:
11310                 if ((dst_reg->type == PTR_TO_PACKET &&
11311                      src_reg->type == PTR_TO_PACKET_END) ||
11312                     (dst_reg->type == PTR_TO_PACKET_META &&
11313                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11314                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11315                         find_good_pkt_pointers(this_branch, dst_reg,
11316                                                dst_reg->type, true);
11317                         mark_pkt_end(other_branch, insn->dst_reg, false);
11318                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11319                             src_reg->type == PTR_TO_PACKET) ||
11320                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11321                             src_reg->type == PTR_TO_PACKET_META)) {
11322                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11323                         find_good_pkt_pointers(other_branch, src_reg,
11324                                                src_reg->type, false);
11325                         mark_pkt_end(this_branch, insn->src_reg, true);
11326                 } else {
11327                         return false;
11328                 }
11329                 break;
11330         case BPF_JLE:
11331                 if ((dst_reg->type == PTR_TO_PACKET &&
11332                      src_reg->type == PTR_TO_PACKET_END) ||
11333                     (dst_reg->type == PTR_TO_PACKET_META &&
11334                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11335                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11336                         find_good_pkt_pointers(other_branch, dst_reg,
11337                                                dst_reg->type, false);
11338                         mark_pkt_end(this_branch, insn->dst_reg, true);
11339                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11340                             src_reg->type == PTR_TO_PACKET) ||
11341                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11342                             src_reg->type == PTR_TO_PACKET_META)) {
11343                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11344                         find_good_pkt_pointers(this_branch, src_reg,
11345                                                src_reg->type, true);
11346                         mark_pkt_end(other_branch, insn->src_reg, false);
11347                 } else {
11348                         return false;
11349                 }
11350                 break;
11351         default:
11352                 return false;
11353         }
11354
11355         return true;
11356 }
11357
11358 static void find_equal_scalars(struct bpf_verifier_state *vstate,
11359                                struct bpf_reg_state *known_reg)
11360 {
11361         struct bpf_func_state *state;
11362         struct bpf_reg_state *reg;
11363
11364         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11365                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11366                         *reg = *known_reg;
11367         }));
11368 }
11369
11370 static int check_cond_jmp_op(struct bpf_verifier_env *env,
11371                              struct bpf_insn *insn, int *insn_idx)
11372 {
11373         struct bpf_verifier_state *this_branch = env->cur_state;
11374         struct bpf_verifier_state *other_branch;
11375         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
11376         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
11377         struct bpf_reg_state *eq_branch_regs;
11378         u8 opcode = BPF_OP(insn->code);
11379         bool is_jmp32;
11380         int pred = -1;
11381         int err;
11382
11383         /* Only conditional jumps are expected to reach here. */
11384         if (opcode == BPF_JA || opcode > BPF_JSLE) {
11385                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
11386                 return -EINVAL;
11387         }
11388
11389         if (BPF_SRC(insn->code) == BPF_X) {
11390                 if (insn->imm != 0) {
11391                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11392                         return -EINVAL;
11393                 }
11394
11395                 /* check src1 operand */
11396                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11397                 if (err)
11398                         return err;
11399
11400                 if (is_pointer_value(env, insn->src_reg)) {
11401                         verbose(env, "R%d pointer comparison prohibited\n",
11402                                 insn->src_reg);
11403                         return -EACCES;
11404                 }
11405                 src_reg = &regs[insn->src_reg];
11406         } else {
11407                 if (insn->src_reg != BPF_REG_0) {
11408                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
11409                         return -EINVAL;
11410                 }
11411         }
11412
11413         /* check src2 operand */
11414         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11415         if (err)
11416                 return err;
11417
11418         dst_reg = &regs[insn->dst_reg];
11419         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
11420
11421         if (BPF_SRC(insn->code) == BPF_K) {
11422                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11423         } else if (src_reg->type == SCALAR_VALUE &&
11424                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11425                 pred = is_branch_taken(dst_reg,
11426                                        tnum_subreg(src_reg->var_off).value,
11427                                        opcode,
11428                                        is_jmp32);
11429         } else if (src_reg->type == SCALAR_VALUE &&
11430                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11431                 pred = is_branch_taken(dst_reg,
11432                                        src_reg->var_off.value,
11433                                        opcode,
11434                                        is_jmp32);
11435         } else if (reg_is_pkt_pointer_any(dst_reg) &&
11436                    reg_is_pkt_pointer_any(src_reg) &&
11437                    !is_jmp32) {
11438                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
11439         }
11440
11441         if (pred >= 0) {
11442                 /* If we get here with a dst_reg pointer type it is because
11443                  * above is_branch_taken() special cased the 0 comparison.
11444                  */
11445                 if (!__is_pointer_value(false, dst_reg))
11446                         err = mark_chain_precision(env, insn->dst_reg);
11447                 if (BPF_SRC(insn->code) == BPF_X && !err &&
11448                     !__is_pointer_value(false, src_reg))
11449                         err = mark_chain_precision(env, insn->src_reg);
11450                 if (err)
11451                         return err;
11452         }
11453
11454         if (pred == 1) {
11455                 /* Only follow the goto, ignore fall-through. If needed, push
11456                  * the fall-through branch for simulation under speculative
11457                  * execution.
11458                  */
11459                 if (!env->bypass_spec_v1 &&
11460                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
11461                                                *insn_idx))
11462                         return -EFAULT;
11463                 *insn_idx += insn->off;
11464                 return 0;
11465         } else if (pred == 0) {
11466                 /* Only follow the fall-through branch, since that's where the
11467                  * program will go. If needed, push the goto branch for
11468                  * simulation under speculative execution.
11469                  */
11470                 if (!env->bypass_spec_v1 &&
11471                     !sanitize_speculative_path(env, insn,
11472                                                *insn_idx + insn->off + 1,
11473                                                *insn_idx))
11474                         return -EFAULT;
11475                 return 0;
11476         }
11477
11478         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11479                                   false);
11480         if (!other_branch)
11481                 return -EFAULT;
11482         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
11483
11484         /* detect if we are comparing against a constant value so we can adjust
11485          * our min/max values for our dst register.
11486          * this is only legit if both are scalars (or pointers to the same
11487          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11488          * because otherwise the different base pointers mean the offsets aren't
11489          * comparable.
11490          */
11491         if (BPF_SRC(insn->code) == BPF_X) {
11492                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
11493
11494                 if (dst_reg->type == SCALAR_VALUE &&
11495                     src_reg->type == SCALAR_VALUE) {
11496                         if (tnum_is_const(src_reg->var_off) ||
11497                             (is_jmp32 &&
11498                              tnum_is_const(tnum_subreg(src_reg->var_off))))
11499                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11500                                                 dst_reg,
11501                                                 src_reg->var_off.value,
11502                                                 tnum_subreg(src_reg->var_off).value,
11503                                                 opcode, is_jmp32);
11504                         else if (tnum_is_const(dst_reg->var_off) ||
11505                                  (is_jmp32 &&
11506                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
11507                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
11508                                                     src_reg,
11509                                                     dst_reg->var_off.value,
11510                                                     tnum_subreg(dst_reg->var_off).value,
11511                                                     opcode, is_jmp32);
11512                         else if (!is_jmp32 &&
11513                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
11514                                 /* Comparing for equality, we can combine knowledge */
11515                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
11516                                                     &other_branch_regs[insn->dst_reg],
11517                                                     src_reg, dst_reg, opcode);
11518                         if (src_reg->id &&
11519                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
11520                                 find_equal_scalars(this_branch, src_reg);
11521                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11522                         }
11523
11524                 }
11525         } else if (dst_reg->type == SCALAR_VALUE) {
11526                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
11527                                         dst_reg, insn->imm, (u32)insn->imm,
11528                                         opcode, is_jmp32);
11529         }
11530
11531         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11532             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
11533                 find_equal_scalars(this_branch, dst_reg);
11534                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11535         }
11536
11537         /* if one pointer register is compared to another pointer
11538          * register check if PTR_MAYBE_NULL could be lifted.
11539          * E.g. register A - maybe null
11540          *      register B - not null
11541          * for JNE A, B, ... - A is not null in the false branch;
11542          * for JEQ A, B, ... - A is not null in the true branch.
11543          */
11544         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11545             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11546             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type)) {
11547                 eq_branch_regs = NULL;
11548                 switch (opcode) {
11549                 case BPF_JEQ:
11550                         eq_branch_regs = other_branch_regs;
11551                         break;
11552                 case BPF_JNE:
11553                         eq_branch_regs = regs;
11554                         break;
11555                 default:
11556                         /* do nothing */
11557                         break;
11558                 }
11559                 if (eq_branch_regs) {
11560                         if (type_may_be_null(src_reg->type))
11561                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11562                         else
11563                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11564                 }
11565         }
11566
11567         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11568          * NOTE: these optimizations below are related with pointer comparison
11569          *       which will never be JMP32.
11570          */
11571         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
11572             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
11573             type_may_be_null(dst_reg->type)) {
11574                 /* Mark all identical registers in each branch as either
11575                  * safe or unknown depending R == 0 or R != 0 conditional.
11576                  */
11577                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11578                                       opcode == BPF_JNE);
11579                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11580                                       opcode == BPF_JEQ);
11581         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
11582                                            this_branch, other_branch) &&
11583                    is_pointer_value(env, insn->dst_reg)) {
11584                 verbose(env, "R%d pointer comparison prohibited\n",
11585                         insn->dst_reg);
11586                 return -EACCES;
11587         }
11588         if (env->log.level & BPF_LOG_LEVEL)
11589                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
11590         return 0;
11591 }
11592
11593 /* verify BPF_LD_IMM64 instruction */
11594 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
11595 {
11596         struct bpf_insn_aux_data *aux = cur_aux(env);
11597         struct bpf_reg_state *regs = cur_regs(env);
11598         struct bpf_reg_state *dst_reg;
11599         struct bpf_map *map;
11600         int err;
11601
11602         if (BPF_SIZE(insn->code) != BPF_DW) {
11603                 verbose(env, "invalid BPF_LD_IMM insn\n");
11604                 return -EINVAL;
11605         }
11606         if (insn->off != 0) {
11607                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
11608                 return -EINVAL;
11609         }
11610
11611         err = check_reg_arg(env, insn->dst_reg, DST_OP);
11612         if (err)
11613                 return err;
11614
11615         dst_reg = &regs[insn->dst_reg];
11616         if (insn->src_reg == 0) {
11617                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11618
11619                 dst_reg->type = SCALAR_VALUE;
11620                 __mark_reg_known(&regs[insn->dst_reg], imm);
11621                 return 0;
11622         }
11623
11624         /* All special src_reg cases are listed below. From this point onwards
11625          * we either succeed and assign a corresponding dst_reg->type after
11626          * zeroing the offset, or fail and reject the program.
11627          */
11628         mark_reg_known_zero(env, regs, insn->dst_reg);
11629
11630         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
11631                 dst_reg->type = aux->btf_var.reg_type;
11632                 switch (base_type(dst_reg->type)) {
11633                 case PTR_TO_MEM:
11634                         dst_reg->mem_size = aux->btf_var.mem_size;
11635                         break;
11636                 case PTR_TO_BTF_ID:
11637                         dst_reg->btf = aux->btf_var.btf;
11638                         dst_reg->btf_id = aux->btf_var.btf_id;
11639                         break;
11640                 default:
11641                         verbose(env, "bpf verifier is misconfigured\n");
11642                         return -EFAULT;
11643                 }
11644                 return 0;
11645         }
11646
11647         if (insn->src_reg == BPF_PSEUDO_FUNC) {
11648                 struct bpf_prog_aux *aux = env->prog->aux;
11649                 u32 subprogno = find_subprog(env,
11650                                              env->insn_idx + insn->imm + 1);
11651
11652                 if (!aux->func_info) {
11653                         verbose(env, "missing btf func_info\n");
11654                         return -EINVAL;
11655                 }
11656                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11657                         verbose(env, "callback function not static\n");
11658                         return -EINVAL;
11659                 }
11660
11661                 dst_reg->type = PTR_TO_FUNC;
11662                 dst_reg->subprogno = subprogno;
11663                 return 0;
11664         }
11665
11666         map = env->used_maps[aux->map_index];
11667         dst_reg->map_ptr = map;
11668
11669         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11670             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
11671                 dst_reg->type = PTR_TO_MAP_VALUE;
11672                 dst_reg->off = aux->map_off;
11673                 WARN_ON_ONCE(map->max_entries != 1);
11674                 /* We want reg->id to be same (0) as map_value is not distinct */
11675         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11676                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
11677                 dst_reg->type = CONST_PTR_TO_MAP;
11678         } else {
11679                 verbose(env, "bpf verifier is misconfigured\n");
11680                 return -EINVAL;
11681         }
11682
11683         return 0;
11684 }
11685
11686 static bool may_access_skb(enum bpf_prog_type type)
11687 {
11688         switch (type) {
11689         case BPF_PROG_TYPE_SOCKET_FILTER:
11690         case BPF_PROG_TYPE_SCHED_CLS:
11691         case BPF_PROG_TYPE_SCHED_ACT:
11692                 return true;
11693         default:
11694                 return false;
11695         }
11696 }
11697
11698 /* verify safety of LD_ABS|LD_IND instructions:
11699  * - they can only appear in the programs where ctx == skb
11700  * - since they are wrappers of function calls, they scratch R1-R5 registers,
11701  *   preserve R6-R9, and store return value into R0
11702  *
11703  * Implicit input:
11704  *   ctx == skb == R6 == CTX
11705  *
11706  * Explicit input:
11707  *   SRC == any register
11708  *   IMM == 32-bit immediate
11709  *
11710  * Output:
11711  *   R0 - 8/16/32-bit skb data converted to cpu endianness
11712  */
11713 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
11714 {
11715         struct bpf_reg_state *regs = cur_regs(env);
11716         static const int ctx_reg = BPF_REG_6;
11717         u8 mode = BPF_MODE(insn->code);
11718         int i, err;
11719
11720         if (!may_access_skb(resolve_prog_type(env->prog))) {
11721                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
11722                 return -EINVAL;
11723         }
11724
11725         if (!env->ops->gen_ld_abs) {
11726                 verbose(env, "bpf verifier is misconfigured\n");
11727                 return -EINVAL;
11728         }
11729
11730         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
11731             BPF_SIZE(insn->code) == BPF_DW ||
11732             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
11733                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
11734                 return -EINVAL;
11735         }
11736
11737         /* check whether implicit source operand (register R6) is readable */
11738         err = check_reg_arg(env, ctx_reg, SRC_OP);
11739         if (err)
11740                 return err;
11741
11742         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
11743          * gen_ld_abs() may terminate the program at runtime, leading to
11744          * reference leak.
11745          */
11746         err = check_reference_leak(env);
11747         if (err) {
11748                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
11749                 return err;
11750         }
11751
11752         if (env->cur_state->active_lock.ptr) {
11753                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
11754                 return -EINVAL;
11755         }
11756
11757         if (regs[ctx_reg].type != PTR_TO_CTX) {
11758                 verbose(env,
11759                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
11760                 return -EINVAL;
11761         }
11762
11763         if (mode == BPF_IND) {
11764                 /* check explicit source operand */
11765                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11766                 if (err)
11767                         return err;
11768         }
11769
11770         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
11771         if (err < 0)
11772                 return err;
11773
11774         /* reset caller saved regs to unreadable */
11775         for (i = 0; i < CALLER_SAVED_REGS; i++) {
11776                 mark_reg_not_init(env, regs, caller_saved[i]);
11777                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11778         }
11779
11780         /* mark destination R0 register as readable, since it contains
11781          * the value fetched from the packet.
11782          * Already marked as written above.
11783          */
11784         mark_reg_unknown(env, regs, BPF_REG_0);
11785         /* ld_abs load up to 32-bit skb data. */
11786         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
11787         return 0;
11788 }
11789
11790 static int check_return_code(struct bpf_verifier_env *env)
11791 {
11792         struct tnum enforce_attach_type_range = tnum_unknown;
11793         const struct bpf_prog *prog = env->prog;
11794         struct bpf_reg_state *reg;
11795         struct tnum range = tnum_range(0, 1);
11796         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11797         int err;
11798         struct bpf_func_state *frame = env->cur_state->frame[0];
11799         const bool is_subprog = frame->subprogno;
11800
11801         /* LSM and struct_ops func-ptr's return type could be "void" */
11802         if (!is_subprog) {
11803                 switch (prog_type) {
11804                 case BPF_PROG_TYPE_LSM:
11805                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
11806                                 /* See below, can be 0 or 0-1 depending on hook. */
11807                                 break;
11808                         fallthrough;
11809                 case BPF_PROG_TYPE_STRUCT_OPS:
11810                         if (!prog->aux->attach_func_proto->type)
11811                                 return 0;
11812                         break;
11813                 default:
11814                         break;
11815                 }
11816         }
11817
11818         /* eBPF calling convention is such that R0 is used
11819          * to return the value from eBPF program.
11820          * Make sure that it's readable at this time
11821          * of bpf_exit, which means that program wrote
11822          * something into it earlier
11823          */
11824         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
11825         if (err)
11826                 return err;
11827
11828         if (is_pointer_value(env, BPF_REG_0)) {
11829                 verbose(env, "R0 leaks addr as return value\n");
11830                 return -EACCES;
11831         }
11832
11833         reg = cur_regs(env) + BPF_REG_0;
11834
11835         if (frame->in_async_callback_fn) {
11836                 /* enforce return zero from async callbacks like timer */
11837                 if (reg->type != SCALAR_VALUE) {
11838                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
11839                                 reg_type_str(env, reg->type));
11840                         return -EINVAL;
11841                 }
11842
11843                 if (!tnum_in(tnum_const(0), reg->var_off)) {
11844                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
11845                         return -EINVAL;
11846                 }
11847                 return 0;
11848         }
11849
11850         if (is_subprog) {
11851                 if (reg->type != SCALAR_VALUE) {
11852                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
11853                                 reg_type_str(env, reg->type));
11854                         return -EINVAL;
11855                 }
11856                 return 0;
11857         }
11858
11859         switch (prog_type) {
11860         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
11861                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
11862                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
11863                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
11864                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
11865                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
11866                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
11867                         range = tnum_range(1, 1);
11868                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
11869                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
11870                         range = tnum_range(0, 3);
11871                 break;
11872         case BPF_PROG_TYPE_CGROUP_SKB:
11873                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
11874                         range = tnum_range(0, 3);
11875                         enforce_attach_type_range = tnum_range(2, 3);
11876                 }
11877                 break;
11878         case BPF_PROG_TYPE_CGROUP_SOCK:
11879         case BPF_PROG_TYPE_SOCK_OPS:
11880         case BPF_PROG_TYPE_CGROUP_DEVICE:
11881         case BPF_PROG_TYPE_CGROUP_SYSCTL:
11882         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
11883                 break;
11884         case BPF_PROG_TYPE_RAW_TRACEPOINT:
11885                 if (!env->prog->aux->attach_btf_id)
11886                         return 0;
11887                 range = tnum_const(0);
11888                 break;
11889         case BPF_PROG_TYPE_TRACING:
11890                 switch (env->prog->expected_attach_type) {
11891                 case BPF_TRACE_FENTRY:
11892                 case BPF_TRACE_FEXIT:
11893                         range = tnum_const(0);
11894                         break;
11895                 case BPF_TRACE_RAW_TP:
11896                 case BPF_MODIFY_RETURN:
11897                         return 0;
11898                 case BPF_TRACE_ITER:
11899                         break;
11900                 default:
11901                         return -ENOTSUPP;
11902                 }
11903                 break;
11904         case BPF_PROG_TYPE_SK_LOOKUP:
11905                 range = tnum_range(SK_DROP, SK_PASS);
11906                 break;
11907
11908         case BPF_PROG_TYPE_LSM:
11909                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
11910                         /* Regular BPF_PROG_TYPE_LSM programs can return
11911                          * any value.
11912                          */
11913                         return 0;
11914                 }
11915                 if (!env->prog->aux->attach_func_proto->type) {
11916                         /* Make sure programs that attach to void
11917                          * hooks don't try to modify return value.
11918                          */
11919                         range = tnum_range(1, 1);
11920                 }
11921                 break;
11922
11923         case BPF_PROG_TYPE_EXT:
11924                 /* freplace program can return anything as its return value
11925                  * depends on the to-be-replaced kernel func or bpf program.
11926                  */
11927         default:
11928                 return 0;
11929         }
11930
11931         if (reg->type != SCALAR_VALUE) {
11932                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
11933                         reg_type_str(env, reg->type));
11934                 return -EINVAL;
11935         }
11936
11937         if (!tnum_in(range, reg->var_off)) {
11938                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
11939                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
11940                     prog_type == BPF_PROG_TYPE_LSM &&
11941                     !prog->aux->attach_func_proto->type)
11942                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11943                 return -EINVAL;
11944         }
11945
11946         if (!tnum_is_unknown(enforce_attach_type_range) &&
11947             tnum_in(enforce_attach_type_range, reg->var_off))
11948                 env->prog->enforce_expected_attach_type = 1;
11949         return 0;
11950 }
11951
11952 /* non-recursive DFS pseudo code
11953  * 1  procedure DFS-iterative(G,v):
11954  * 2      label v as discovered
11955  * 3      let S be a stack
11956  * 4      S.push(v)
11957  * 5      while S is not empty
11958  * 6            t <- S.peek()
11959  * 7            if t is what we're looking for:
11960  * 8                return t
11961  * 9            for all edges e in G.adjacentEdges(t) do
11962  * 10               if edge e is already labelled
11963  * 11                   continue with the next edge
11964  * 12               w <- G.adjacentVertex(t,e)
11965  * 13               if vertex w is not discovered and not explored
11966  * 14                   label e as tree-edge
11967  * 15                   label w as discovered
11968  * 16                   S.push(w)
11969  * 17                   continue at 5
11970  * 18               else if vertex w is discovered
11971  * 19                   label e as back-edge
11972  * 20               else
11973  * 21                   // vertex w is explored
11974  * 22                   label e as forward- or cross-edge
11975  * 23           label t as explored
11976  * 24           S.pop()
11977  *
11978  * convention:
11979  * 0x10 - discovered
11980  * 0x11 - discovered and fall-through edge labelled
11981  * 0x12 - discovered and fall-through and branch edges labelled
11982  * 0x20 - explored
11983  */
11984
11985 enum {
11986         DISCOVERED = 0x10,
11987         EXPLORED = 0x20,
11988         FALLTHROUGH = 1,
11989         BRANCH = 2,
11990 };
11991
11992 static u32 state_htab_size(struct bpf_verifier_env *env)
11993 {
11994         return env->prog->len;
11995 }
11996
11997 static struct bpf_verifier_state_list **explored_state(
11998                                         struct bpf_verifier_env *env,
11999                                         int idx)
12000 {
12001         struct bpf_verifier_state *cur = env->cur_state;
12002         struct bpf_func_state *state = cur->frame[cur->curframe];
12003
12004         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
12005 }
12006
12007 static void init_explored_state(struct bpf_verifier_env *env, int idx)
12008 {
12009         env->insn_aux_data[idx].prune_point = true;
12010 }
12011
12012 enum {
12013         DONE_EXPLORING = 0,
12014         KEEP_EXPLORING = 1,
12015 };
12016
12017 /* t, w, e - match pseudo-code above:
12018  * t - index of current instruction
12019  * w - next instruction
12020  * e - edge
12021  */
12022 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12023                      bool loop_ok)
12024 {
12025         int *insn_stack = env->cfg.insn_stack;
12026         int *insn_state = env->cfg.insn_state;
12027
12028         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
12029                 return DONE_EXPLORING;
12030
12031         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
12032                 return DONE_EXPLORING;
12033
12034         if (w < 0 || w >= env->prog->len) {
12035                 verbose_linfo(env, t, "%d: ", t);
12036                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
12037                 return -EINVAL;
12038         }
12039
12040         if (e == BRANCH)
12041                 /* mark branch target for state pruning */
12042                 init_explored_state(env, w);
12043
12044         if (insn_state[w] == 0) {
12045                 /* tree-edge */
12046                 insn_state[t] = DISCOVERED | e;
12047                 insn_state[w] = DISCOVERED;
12048                 if (env->cfg.cur_stack >= env->prog->len)
12049                         return -E2BIG;
12050                 insn_stack[env->cfg.cur_stack++] = w;
12051                 return KEEP_EXPLORING;
12052         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
12053                 if (loop_ok && env->bpf_capable)
12054                         return DONE_EXPLORING;
12055                 verbose_linfo(env, t, "%d: ", t);
12056                 verbose_linfo(env, w, "%d: ", w);
12057                 verbose(env, "back-edge from insn %d to %d\n", t, w);
12058                 return -EINVAL;
12059         } else if (insn_state[w] == EXPLORED) {
12060                 /* forward- or cross-edge */
12061                 insn_state[t] = DISCOVERED | e;
12062         } else {
12063                 verbose(env, "insn state internal bug\n");
12064                 return -EFAULT;
12065         }
12066         return DONE_EXPLORING;
12067 }
12068
12069 static int visit_func_call_insn(int t, int insn_cnt,
12070                                 struct bpf_insn *insns,
12071                                 struct bpf_verifier_env *env,
12072                                 bool visit_callee)
12073 {
12074         int ret;
12075
12076         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12077         if (ret)
12078                 return ret;
12079
12080         if (t + 1 < insn_cnt)
12081                 init_explored_state(env, t + 1);
12082         if (visit_callee) {
12083                 init_explored_state(env, t);
12084                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12085                                 /* It's ok to allow recursion from CFG point of
12086                                  * view. __check_func_call() will do the actual
12087                                  * check.
12088                                  */
12089                                 bpf_pseudo_func(insns + t));
12090         }
12091         return ret;
12092 }
12093
12094 /* Visits the instruction at index t and returns one of the following:
12095  *  < 0 - an error occurred
12096  *  DONE_EXPLORING - the instruction was fully explored
12097  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
12098  */
12099 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
12100 {
12101         struct bpf_insn *insns = env->prog->insnsi;
12102         int ret;
12103
12104         if (bpf_pseudo_func(insns + t))
12105                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
12106
12107         /* All non-branch instructions have a single fall-through edge. */
12108         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12109             BPF_CLASS(insns[t].code) != BPF_JMP32)
12110                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
12111
12112         switch (BPF_OP(insns[t].code)) {
12113         case BPF_EXIT:
12114                 return DONE_EXPLORING;
12115
12116         case BPF_CALL:
12117                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
12118                         /* Mark this call insn to trigger is_state_visited() check
12119                          * before call itself is processed by __check_func_call().
12120                          * Otherwise new async state will be pushed for further
12121                          * exploration.
12122                          */
12123                         init_explored_state(env, t);
12124                 return visit_func_call_insn(t, insn_cnt, insns, env,
12125                                             insns[t].src_reg == BPF_PSEUDO_CALL);
12126
12127         case BPF_JA:
12128                 if (BPF_SRC(insns[t].code) != BPF_K)
12129                         return -EINVAL;
12130
12131                 /* unconditional jump with single edge */
12132                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12133                                 true);
12134                 if (ret)
12135                         return ret;
12136
12137                 /* unconditional jmp is not a good pruning point,
12138                  * but it's marked, since backtracking needs
12139                  * to record jmp history in is_state_visited().
12140                  */
12141                 init_explored_state(env, t + insns[t].off + 1);
12142                 /* tell verifier to check for equivalent states
12143                  * after every call and jump
12144                  */
12145                 if (t + 1 < insn_cnt)
12146                         init_explored_state(env, t + 1);
12147
12148                 return ret;
12149
12150         default:
12151                 /* conditional jump with two edges */
12152                 init_explored_state(env, t);
12153                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12154                 if (ret)
12155                         return ret;
12156
12157                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12158         }
12159 }
12160
12161 /* non-recursive depth-first-search to detect loops in BPF program
12162  * loop == back-edge in directed graph
12163  */
12164 static int check_cfg(struct bpf_verifier_env *env)
12165 {
12166         int insn_cnt = env->prog->len;
12167         int *insn_stack, *insn_state;
12168         int ret = 0;
12169         int i;
12170
12171         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12172         if (!insn_state)
12173                 return -ENOMEM;
12174
12175         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
12176         if (!insn_stack) {
12177                 kvfree(insn_state);
12178                 return -ENOMEM;
12179         }
12180
12181         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12182         insn_stack[0] = 0; /* 0 is the first instruction */
12183         env->cfg.cur_stack = 1;
12184
12185         while (env->cfg.cur_stack > 0) {
12186                 int t = insn_stack[env->cfg.cur_stack - 1];
12187
12188                 ret = visit_insn(t, insn_cnt, env);
12189                 switch (ret) {
12190                 case DONE_EXPLORING:
12191                         insn_state[t] = EXPLORED;
12192                         env->cfg.cur_stack--;
12193                         break;
12194                 case KEEP_EXPLORING:
12195                         break;
12196                 default:
12197                         if (ret > 0) {
12198                                 verbose(env, "visit_insn internal bug\n");
12199                                 ret = -EFAULT;
12200                         }
12201                         goto err_free;
12202                 }
12203         }
12204
12205         if (env->cfg.cur_stack < 0) {
12206                 verbose(env, "pop stack internal bug\n");
12207                 ret = -EFAULT;
12208                 goto err_free;
12209         }
12210
12211         for (i = 0; i < insn_cnt; i++) {
12212                 if (insn_state[i] != EXPLORED) {
12213                         verbose(env, "unreachable insn %d\n", i);
12214                         ret = -EINVAL;
12215                         goto err_free;
12216                 }
12217         }
12218         ret = 0; /* cfg looks good */
12219
12220 err_free:
12221         kvfree(insn_state);
12222         kvfree(insn_stack);
12223         env->cfg.insn_state = env->cfg.insn_stack = NULL;
12224         return ret;
12225 }
12226
12227 static int check_abnormal_return(struct bpf_verifier_env *env)
12228 {
12229         int i;
12230
12231         for (i = 1; i < env->subprog_cnt; i++) {
12232                 if (env->subprog_info[i].has_ld_abs) {
12233                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12234                         return -EINVAL;
12235                 }
12236                 if (env->subprog_info[i].has_tail_call) {
12237                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12238                         return -EINVAL;
12239                 }
12240         }
12241         return 0;
12242 }
12243
12244 /* The minimum supported BTF func info size */
12245 #define MIN_BPF_FUNCINFO_SIZE   8
12246 #define MAX_FUNCINFO_REC_SIZE   252
12247
12248 static int check_btf_func(struct bpf_verifier_env *env,
12249                           const union bpf_attr *attr,
12250                           bpfptr_t uattr)
12251 {
12252         const struct btf_type *type, *func_proto, *ret_type;
12253         u32 i, nfuncs, urec_size, min_size;
12254         u32 krec_size = sizeof(struct bpf_func_info);
12255         struct bpf_func_info *krecord;
12256         struct bpf_func_info_aux *info_aux = NULL;
12257         struct bpf_prog *prog;
12258         const struct btf *btf;
12259         bpfptr_t urecord;
12260         u32 prev_offset = 0;
12261         bool scalar_return;
12262         int ret = -ENOMEM;
12263
12264         nfuncs = attr->func_info_cnt;
12265         if (!nfuncs) {
12266                 if (check_abnormal_return(env))
12267                         return -EINVAL;
12268                 return 0;
12269         }
12270
12271         if (nfuncs != env->subprog_cnt) {
12272                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12273                 return -EINVAL;
12274         }
12275
12276         urec_size = attr->func_info_rec_size;
12277         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12278             urec_size > MAX_FUNCINFO_REC_SIZE ||
12279             urec_size % sizeof(u32)) {
12280                 verbose(env, "invalid func info rec size %u\n", urec_size);
12281                 return -EINVAL;
12282         }
12283
12284         prog = env->prog;
12285         btf = prog->aux->btf;
12286
12287         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
12288         min_size = min_t(u32, krec_size, urec_size);
12289
12290         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
12291         if (!krecord)
12292                 return -ENOMEM;
12293         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12294         if (!info_aux)
12295                 goto err_free;
12296
12297         for (i = 0; i < nfuncs; i++) {
12298                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12299                 if (ret) {
12300                         if (ret == -E2BIG) {
12301                                 verbose(env, "nonzero tailing record in func info");
12302                                 /* set the size kernel expects so loader can zero
12303                                  * out the rest of the record.
12304                                  */
12305                                 if (copy_to_bpfptr_offset(uattr,
12306                                                           offsetof(union bpf_attr, func_info_rec_size),
12307                                                           &min_size, sizeof(min_size)))
12308                                         ret = -EFAULT;
12309                         }
12310                         goto err_free;
12311                 }
12312
12313                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
12314                         ret = -EFAULT;
12315                         goto err_free;
12316                 }
12317
12318                 /* check insn_off */
12319                 ret = -EINVAL;
12320                 if (i == 0) {
12321                         if (krecord[i].insn_off) {
12322                                 verbose(env,
12323                                         "nonzero insn_off %u for the first func info record",
12324                                         krecord[i].insn_off);
12325                                 goto err_free;
12326                         }
12327                 } else if (krecord[i].insn_off <= prev_offset) {
12328                         verbose(env,
12329                                 "same or smaller insn offset (%u) than previous func info record (%u)",
12330                                 krecord[i].insn_off, prev_offset);
12331                         goto err_free;
12332                 }
12333
12334                 if (env->subprog_info[i].start != krecord[i].insn_off) {
12335                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
12336                         goto err_free;
12337                 }
12338
12339                 /* check type_id */
12340                 type = btf_type_by_id(btf, krecord[i].type_id);
12341                 if (!type || !btf_type_is_func(type)) {
12342                         verbose(env, "invalid type id %d in func info",
12343                                 krecord[i].type_id);
12344                         goto err_free;
12345                 }
12346                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
12347
12348                 func_proto = btf_type_by_id(btf, type->type);
12349                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12350                         /* btf_func_check() already verified it during BTF load */
12351                         goto err_free;
12352                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12353                 scalar_return =
12354                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
12355                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12356                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12357                         goto err_free;
12358                 }
12359                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12360                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12361                         goto err_free;
12362                 }
12363
12364                 prev_offset = krecord[i].insn_off;
12365                 bpfptr_add(&urecord, urec_size);
12366         }
12367
12368         prog->aux->func_info = krecord;
12369         prog->aux->func_info_cnt = nfuncs;
12370         prog->aux->func_info_aux = info_aux;
12371         return 0;
12372
12373 err_free:
12374         kvfree(krecord);
12375         kfree(info_aux);
12376         return ret;
12377 }
12378
12379 static void adjust_btf_func(struct bpf_verifier_env *env)
12380 {
12381         struct bpf_prog_aux *aux = env->prog->aux;
12382         int i;
12383
12384         if (!aux->func_info)
12385                 return;
12386
12387         for (i = 0; i < env->subprog_cnt; i++)
12388                 aux->func_info[i].insn_off = env->subprog_info[i].start;
12389 }
12390
12391 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
12392 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
12393
12394 static int check_btf_line(struct bpf_verifier_env *env,
12395                           const union bpf_attr *attr,
12396                           bpfptr_t uattr)
12397 {
12398         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12399         struct bpf_subprog_info *sub;
12400         struct bpf_line_info *linfo;
12401         struct bpf_prog *prog;
12402         const struct btf *btf;
12403         bpfptr_t ulinfo;
12404         int err;
12405
12406         nr_linfo = attr->line_info_cnt;
12407         if (!nr_linfo)
12408                 return 0;
12409         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12410                 return -EINVAL;
12411
12412         rec_size = attr->line_info_rec_size;
12413         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12414             rec_size > MAX_LINEINFO_REC_SIZE ||
12415             rec_size & (sizeof(u32) - 1))
12416                 return -EINVAL;
12417
12418         /* Need to zero it in case the userspace may
12419          * pass in a smaller bpf_line_info object.
12420          */
12421         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12422                          GFP_KERNEL | __GFP_NOWARN);
12423         if (!linfo)
12424                 return -ENOMEM;
12425
12426         prog = env->prog;
12427         btf = prog->aux->btf;
12428
12429         s = 0;
12430         sub = env->subprog_info;
12431         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
12432         expected_size = sizeof(struct bpf_line_info);
12433         ncopy = min_t(u32, expected_size, rec_size);
12434         for (i = 0; i < nr_linfo; i++) {
12435                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12436                 if (err) {
12437                         if (err == -E2BIG) {
12438                                 verbose(env, "nonzero tailing record in line_info");
12439                                 if (copy_to_bpfptr_offset(uattr,
12440                                                           offsetof(union bpf_attr, line_info_rec_size),
12441                                                           &expected_size, sizeof(expected_size)))
12442                                         err = -EFAULT;
12443                         }
12444                         goto err_free;
12445                 }
12446
12447                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
12448                         err = -EFAULT;
12449                         goto err_free;
12450                 }
12451
12452                 /*
12453                  * Check insn_off to ensure
12454                  * 1) strictly increasing AND
12455                  * 2) bounded by prog->len
12456                  *
12457                  * The linfo[0].insn_off == 0 check logically falls into
12458                  * the later "missing bpf_line_info for func..." case
12459                  * because the first linfo[0].insn_off must be the
12460                  * first sub also and the first sub must have
12461                  * subprog_info[0].start == 0.
12462                  */
12463                 if ((i && linfo[i].insn_off <= prev_offset) ||
12464                     linfo[i].insn_off >= prog->len) {
12465                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12466                                 i, linfo[i].insn_off, prev_offset,
12467                                 prog->len);
12468                         err = -EINVAL;
12469                         goto err_free;
12470                 }
12471
12472                 if (!prog->insnsi[linfo[i].insn_off].code) {
12473                         verbose(env,
12474                                 "Invalid insn code at line_info[%u].insn_off\n",
12475                                 i);
12476                         err = -EINVAL;
12477                         goto err_free;
12478                 }
12479
12480                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12481                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
12482                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12483                         err = -EINVAL;
12484                         goto err_free;
12485                 }
12486
12487                 if (s != env->subprog_cnt) {
12488                         if (linfo[i].insn_off == sub[s].start) {
12489                                 sub[s].linfo_idx = i;
12490                                 s++;
12491                         } else if (sub[s].start < linfo[i].insn_off) {
12492                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
12493                                 err = -EINVAL;
12494                                 goto err_free;
12495                         }
12496                 }
12497
12498                 prev_offset = linfo[i].insn_off;
12499                 bpfptr_add(&ulinfo, rec_size);
12500         }
12501
12502         if (s != env->subprog_cnt) {
12503                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12504                         env->subprog_cnt - s, s);
12505                 err = -EINVAL;
12506                 goto err_free;
12507         }
12508
12509         prog->aux->linfo = linfo;
12510         prog->aux->nr_linfo = nr_linfo;
12511
12512         return 0;
12513
12514 err_free:
12515         kvfree(linfo);
12516         return err;
12517 }
12518
12519 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
12520 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
12521
12522 static int check_core_relo(struct bpf_verifier_env *env,
12523                            const union bpf_attr *attr,
12524                            bpfptr_t uattr)
12525 {
12526         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12527         struct bpf_core_relo core_relo = {};
12528         struct bpf_prog *prog = env->prog;
12529         const struct btf *btf = prog->aux->btf;
12530         struct bpf_core_ctx ctx = {
12531                 .log = &env->log,
12532                 .btf = btf,
12533         };
12534         bpfptr_t u_core_relo;
12535         int err;
12536
12537         nr_core_relo = attr->core_relo_cnt;
12538         if (!nr_core_relo)
12539                 return 0;
12540         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12541                 return -EINVAL;
12542
12543         rec_size = attr->core_relo_rec_size;
12544         if (rec_size < MIN_CORE_RELO_SIZE ||
12545             rec_size > MAX_CORE_RELO_SIZE ||
12546             rec_size % sizeof(u32))
12547                 return -EINVAL;
12548
12549         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12550         expected_size = sizeof(struct bpf_core_relo);
12551         ncopy = min_t(u32, expected_size, rec_size);
12552
12553         /* Unlike func_info and line_info, copy and apply each CO-RE
12554          * relocation record one at a time.
12555          */
12556         for (i = 0; i < nr_core_relo; i++) {
12557                 /* future proofing when sizeof(bpf_core_relo) changes */
12558                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12559                 if (err) {
12560                         if (err == -E2BIG) {
12561                                 verbose(env, "nonzero tailing record in core_relo");
12562                                 if (copy_to_bpfptr_offset(uattr,
12563                                                           offsetof(union bpf_attr, core_relo_rec_size),
12564                                                           &expected_size, sizeof(expected_size)))
12565                                         err = -EFAULT;
12566                         }
12567                         break;
12568                 }
12569
12570                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12571                         err = -EFAULT;
12572                         break;
12573                 }
12574
12575                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12576                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12577                                 i, core_relo.insn_off, prog->len);
12578                         err = -EINVAL;
12579                         break;
12580                 }
12581
12582                 err = bpf_core_apply(&ctx, &core_relo, i,
12583                                      &prog->insnsi[core_relo.insn_off / 8]);
12584                 if (err)
12585                         break;
12586                 bpfptr_add(&u_core_relo, rec_size);
12587         }
12588         return err;
12589 }
12590
12591 static int check_btf_info(struct bpf_verifier_env *env,
12592                           const union bpf_attr *attr,
12593                           bpfptr_t uattr)
12594 {
12595         struct btf *btf;
12596         int err;
12597
12598         if (!attr->func_info_cnt && !attr->line_info_cnt) {
12599                 if (check_abnormal_return(env))
12600                         return -EINVAL;
12601                 return 0;
12602         }
12603
12604         btf = btf_get_by_fd(attr->prog_btf_fd);
12605         if (IS_ERR(btf))
12606                 return PTR_ERR(btf);
12607         if (btf_is_kernel(btf)) {
12608                 btf_put(btf);
12609                 return -EACCES;
12610         }
12611         env->prog->aux->btf = btf;
12612
12613         err = check_btf_func(env, attr, uattr);
12614         if (err)
12615                 return err;
12616
12617         err = check_btf_line(env, attr, uattr);
12618         if (err)
12619                 return err;
12620
12621         err = check_core_relo(env, attr, uattr);
12622         if (err)
12623                 return err;
12624
12625         return 0;
12626 }
12627
12628 /* check %cur's range satisfies %old's */
12629 static bool range_within(struct bpf_reg_state *old,
12630                          struct bpf_reg_state *cur)
12631 {
12632         return old->umin_value <= cur->umin_value &&
12633                old->umax_value >= cur->umax_value &&
12634                old->smin_value <= cur->smin_value &&
12635                old->smax_value >= cur->smax_value &&
12636                old->u32_min_value <= cur->u32_min_value &&
12637                old->u32_max_value >= cur->u32_max_value &&
12638                old->s32_min_value <= cur->s32_min_value &&
12639                old->s32_max_value >= cur->s32_max_value;
12640 }
12641
12642 /* If in the old state two registers had the same id, then they need to have
12643  * the same id in the new state as well.  But that id could be different from
12644  * the old state, so we need to track the mapping from old to new ids.
12645  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12646  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
12647  * regs with a different old id could still have new id 9, we don't care about
12648  * that.
12649  * So we look through our idmap to see if this old id has been seen before.  If
12650  * so, we require the new id to match; otherwise, we add the id pair to the map.
12651  */
12652 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
12653 {
12654         unsigned int i;
12655
12656         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
12657                 if (!idmap[i].old) {
12658                         /* Reached an empty slot; haven't seen this id before */
12659                         idmap[i].old = old_id;
12660                         idmap[i].cur = cur_id;
12661                         return true;
12662                 }
12663                 if (idmap[i].old == old_id)
12664                         return idmap[i].cur == cur_id;
12665         }
12666         /* We ran out of idmap slots, which should be impossible */
12667         WARN_ON_ONCE(1);
12668         return false;
12669 }
12670
12671 static void clean_func_state(struct bpf_verifier_env *env,
12672                              struct bpf_func_state *st)
12673 {
12674         enum bpf_reg_liveness live;
12675         int i, j;
12676
12677         for (i = 0; i < BPF_REG_FP; i++) {
12678                 live = st->regs[i].live;
12679                 /* liveness must not touch this register anymore */
12680                 st->regs[i].live |= REG_LIVE_DONE;
12681                 if (!(live & REG_LIVE_READ))
12682                         /* since the register is unused, clear its state
12683                          * to make further comparison simpler
12684                          */
12685                         __mark_reg_not_init(env, &st->regs[i]);
12686         }
12687
12688         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12689                 live = st->stack[i].spilled_ptr.live;
12690                 /* liveness must not touch this stack slot anymore */
12691                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
12692                 if (!(live & REG_LIVE_READ)) {
12693                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
12694                         for (j = 0; j < BPF_REG_SIZE; j++)
12695                                 st->stack[i].slot_type[j] = STACK_INVALID;
12696                 }
12697         }
12698 }
12699
12700 static void clean_verifier_state(struct bpf_verifier_env *env,
12701                                  struct bpf_verifier_state *st)
12702 {
12703         int i;
12704
12705         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
12706                 /* all regs in this state in all frames were already marked */
12707                 return;
12708
12709         for (i = 0; i <= st->curframe; i++)
12710                 clean_func_state(env, st->frame[i]);
12711 }
12712
12713 /* the parentage chains form a tree.
12714  * the verifier states are added to state lists at given insn and
12715  * pushed into state stack for future exploration.
12716  * when the verifier reaches bpf_exit insn some of the verifer states
12717  * stored in the state lists have their final liveness state already,
12718  * but a lot of states will get revised from liveness point of view when
12719  * the verifier explores other branches.
12720  * Example:
12721  * 1: r0 = 1
12722  * 2: if r1 == 100 goto pc+1
12723  * 3: r0 = 2
12724  * 4: exit
12725  * when the verifier reaches exit insn the register r0 in the state list of
12726  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
12727  * of insn 2 and goes exploring further. At the insn 4 it will walk the
12728  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
12729  *
12730  * Since the verifier pushes the branch states as it sees them while exploring
12731  * the program the condition of walking the branch instruction for the second
12732  * time means that all states below this branch were already explored and
12733  * their final liveness marks are already propagated.
12734  * Hence when the verifier completes the search of state list in is_state_visited()
12735  * we can call this clean_live_states() function to mark all liveness states
12736  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
12737  * will not be used.
12738  * This function also clears the registers and stack for states that !READ
12739  * to simplify state merging.
12740  *
12741  * Important note here that walking the same branch instruction in the callee
12742  * doesn't meant that the states are DONE. The verifier has to compare
12743  * the callsites
12744  */
12745 static void clean_live_states(struct bpf_verifier_env *env, int insn,
12746                               struct bpf_verifier_state *cur)
12747 {
12748         struct bpf_verifier_state_list *sl;
12749         int i;
12750
12751         sl = *explored_state(env, insn);
12752         while (sl) {
12753                 if (sl->state.branches)
12754                         goto next;
12755                 if (sl->state.insn_idx != insn ||
12756                     sl->state.curframe != cur->curframe)
12757                         goto next;
12758                 for (i = 0; i <= cur->curframe; i++)
12759                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
12760                                 goto next;
12761                 clean_verifier_state(env, &sl->state);
12762 next:
12763                 sl = sl->next;
12764         }
12765 }
12766
12767 /* Returns true if (rold safe implies rcur safe) */
12768 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
12769                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
12770 {
12771         bool equal;
12772
12773         if (!(rold->live & REG_LIVE_READ))
12774                 /* explored state didn't use this */
12775                 return true;
12776
12777         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
12778
12779         if (rold->type == PTR_TO_STACK)
12780                 /* two stack pointers are equal only if they're pointing to
12781                  * the same stack frame, since fp-8 in foo != fp-8 in bar
12782                  */
12783                 return equal && rold->frameno == rcur->frameno;
12784
12785         if (equal)
12786                 return true;
12787
12788         if (rold->type == NOT_INIT)
12789                 /* explored state can't have used this */
12790                 return true;
12791         if (rcur->type == NOT_INIT)
12792                 return false;
12793         switch (base_type(rold->type)) {
12794         case SCALAR_VALUE:
12795                 if (env->explore_alu_limits)
12796                         return false;
12797                 if (rcur->type == SCALAR_VALUE) {
12798                         if (!rold->precise)
12799                                 return true;
12800                         /* new val must satisfy old val knowledge */
12801                         return range_within(rold, rcur) &&
12802                                tnum_in(rold->var_off, rcur->var_off);
12803                 } else {
12804                         /* We're trying to use a pointer in place of a scalar.
12805                          * Even if the scalar was unbounded, this could lead to
12806                          * pointer leaks because scalars are allowed to leak
12807                          * while pointers are not. We could make this safe in
12808                          * special cases if root is calling us, but it's
12809                          * probably not worth the hassle.
12810                          */
12811                         return false;
12812                 }
12813         case PTR_TO_MAP_KEY:
12814         case PTR_TO_MAP_VALUE:
12815                 /* a PTR_TO_MAP_VALUE could be safe to use as a
12816                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
12817                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
12818                  * checked, doing so could have affected others with the same
12819                  * id, and we can't check for that because we lost the id when
12820                  * we converted to a PTR_TO_MAP_VALUE.
12821                  */
12822                 if (type_may_be_null(rold->type)) {
12823                         if (!type_may_be_null(rcur->type))
12824                                 return false;
12825                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
12826                                 return false;
12827                         /* Check our ids match any regs they're supposed to */
12828                         return check_ids(rold->id, rcur->id, idmap);
12829                 }
12830
12831                 /* If the new min/max/var_off satisfy the old ones and
12832                  * everything else matches, we are OK.
12833                  * 'id' is not compared, since it's only used for maps with
12834                  * bpf_spin_lock inside map element and in such cases if
12835                  * the rest of the prog is valid for one map element then
12836                  * it's valid for all map elements regardless of the key
12837                  * used in bpf_map_lookup()
12838                  */
12839                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
12840                        range_within(rold, rcur) &&
12841                        tnum_in(rold->var_off, rcur->var_off);
12842         case PTR_TO_PACKET_META:
12843         case PTR_TO_PACKET:
12844                 if (rcur->type != rold->type)
12845                         return false;
12846                 /* We must have at least as much range as the old ptr
12847                  * did, so that any accesses which were safe before are
12848                  * still safe.  This is true even if old range < old off,
12849                  * since someone could have accessed through (ptr - k), or
12850                  * even done ptr -= k in a register, to get a safe access.
12851                  */
12852                 if (rold->range > rcur->range)
12853                         return false;
12854                 /* If the offsets don't match, we can't trust our alignment;
12855                  * nor can we be sure that we won't fall out of range.
12856                  */
12857                 if (rold->off != rcur->off)
12858                         return false;
12859                 /* id relations must be preserved */
12860                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
12861                         return false;
12862                 /* new val must satisfy old val knowledge */
12863                 return range_within(rold, rcur) &&
12864                        tnum_in(rold->var_off, rcur->var_off);
12865         case PTR_TO_CTX:
12866         case CONST_PTR_TO_MAP:
12867         case PTR_TO_PACKET_END:
12868         case PTR_TO_FLOW_KEYS:
12869         case PTR_TO_SOCKET:
12870         case PTR_TO_SOCK_COMMON:
12871         case PTR_TO_TCP_SOCK:
12872         case PTR_TO_XDP_SOCK:
12873                 /* Only valid matches are exact, which memcmp() above
12874                  * would have accepted
12875                  */
12876         default:
12877                 /* Don't know what's going on, just say it's not safe */
12878                 return false;
12879         }
12880
12881         /* Shouldn't get here; if we do, say it's not safe */
12882         WARN_ON_ONCE(1);
12883         return false;
12884 }
12885
12886 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
12887                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
12888 {
12889         int i, spi;
12890
12891         /* walk slots of the explored stack and ignore any additional
12892          * slots in the current stack, since explored(safe) state
12893          * didn't use them
12894          */
12895         for (i = 0; i < old->allocated_stack; i++) {
12896                 spi = i / BPF_REG_SIZE;
12897
12898                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
12899                         i += BPF_REG_SIZE - 1;
12900                         /* explored state didn't use this */
12901                         continue;
12902                 }
12903
12904                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
12905                         continue;
12906
12907                 /* explored stack has more populated slots than current stack
12908                  * and these slots were used
12909                  */
12910                 if (i >= cur->allocated_stack)
12911                         return false;
12912
12913                 /* if old state was safe with misc data in the stack
12914                  * it will be safe with zero-initialized stack.
12915                  * The opposite is not true
12916                  */
12917                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
12918                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
12919                         continue;
12920                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
12921                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
12922                         /* Ex: old explored (safe) state has STACK_SPILL in
12923                          * this stack slot, but current has STACK_MISC ->
12924                          * this verifier states are not equivalent,
12925                          * return false to continue verification of this path
12926                          */
12927                         return false;
12928                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
12929                         continue;
12930                 if (!is_spilled_reg(&old->stack[spi]))
12931                         continue;
12932                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
12933                              &cur->stack[spi].spilled_ptr, idmap))
12934                         /* when explored and current stack slot are both storing
12935                          * spilled registers, check that stored pointers types
12936                          * are the same as well.
12937                          * Ex: explored safe path could have stored
12938                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
12939                          * but current path has stored:
12940                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
12941                          * such verifier states are not equivalent.
12942                          * return false to continue verification of this path
12943                          */
12944                         return false;
12945         }
12946         return true;
12947 }
12948
12949 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
12950 {
12951         if (old->acquired_refs != cur->acquired_refs)
12952                 return false;
12953         return !memcmp(old->refs, cur->refs,
12954                        sizeof(*old->refs) * old->acquired_refs);
12955 }
12956
12957 /* compare two verifier states
12958  *
12959  * all states stored in state_list are known to be valid, since
12960  * verifier reached 'bpf_exit' instruction through them
12961  *
12962  * this function is called when verifier exploring different branches of
12963  * execution popped from the state stack. If it sees an old state that has
12964  * more strict register state and more strict stack state then this execution
12965  * branch doesn't need to be explored further, since verifier already
12966  * concluded that more strict state leads to valid finish.
12967  *
12968  * Therefore two states are equivalent if register state is more conservative
12969  * and explored stack state is more conservative than the current one.
12970  * Example:
12971  *       explored                   current
12972  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
12973  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
12974  *
12975  * In other words if current stack state (one being explored) has more
12976  * valid slots than old one that already passed validation, it means
12977  * the verifier can stop exploring and conclude that current state is valid too
12978  *
12979  * Similarly with registers. If explored state has register type as invalid
12980  * whereas register type in current state is meaningful, it means that
12981  * the current state will reach 'bpf_exit' instruction safely
12982  */
12983 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
12984                               struct bpf_func_state *cur)
12985 {
12986         int i;
12987
12988         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
12989         for (i = 0; i < MAX_BPF_REG; i++)
12990                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
12991                              env->idmap_scratch))
12992                         return false;
12993
12994         if (!stacksafe(env, old, cur, env->idmap_scratch))
12995                 return false;
12996
12997         if (!refsafe(old, cur))
12998                 return false;
12999
13000         return true;
13001 }
13002
13003 static bool states_equal(struct bpf_verifier_env *env,
13004                          struct bpf_verifier_state *old,
13005                          struct bpf_verifier_state *cur)
13006 {
13007         int i;
13008
13009         if (old->curframe != cur->curframe)
13010                 return false;
13011
13012         /* Verification state from speculative execution simulation
13013          * must never prune a non-speculative execution one.
13014          */
13015         if (old->speculative && !cur->speculative)
13016                 return false;
13017
13018         if (old->active_lock.ptr != cur->active_lock.ptr ||
13019             old->active_lock.id != cur->active_lock.id)
13020                 return false;
13021
13022         /* for states to be equal callsites have to be the same
13023          * and all frame states need to be equivalent
13024          */
13025         for (i = 0; i <= old->curframe; i++) {
13026                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
13027                         return false;
13028                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
13029                         return false;
13030         }
13031         return true;
13032 }
13033
13034 /* Return 0 if no propagation happened. Return negative error code if error
13035  * happened. Otherwise, return the propagated bit.
13036  */
13037 static int propagate_liveness_reg(struct bpf_verifier_env *env,
13038                                   struct bpf_reg_state *reg,
13039                                   struct bpf_reg_state *parent_reg)
13040 {
13041         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13042         u8 flag = reg->live & REG_LIVE_READ;
13043         int err;
13044
13045         /* When comes here, read flags of PARENT_REG or REG could be any of
13046          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13047          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13048          */
13049         if (parent_flag == REG_LIVE_READ64 ||
13050             /* Or if there is no read flag from REG. */
13051             !flag ||
13052             /* Or if the read flag from REG is the same as PARENT_REG. */
13053             parent_flag == flag)
13054                 return 0;
13055
13056         err = mark_reg_read(env, reg, parent_reg, flag);
13057         if (err)
13058                 return err;
13059
13060         return flag;
13061 }
13062
13063 /* A write screens off any subsequent reads; but write marks come from the
13064  * straight-line code between a state and its parent.  When we arrive at an
13065  * equivalent state (jump target or such) we didn't arrive by the straight-line
13066  * code, so read marks in the state must propagate to the parent regardless
13067  * of the state's write marks. That's what 'parent == state->parent' comparison
13068  * in mark_reg_read() is for.
13069  */
13070 static int propagate_liveness(struct bpf_verifier_env *env,
13071                               const struct bpf_verifier_state *vstate,
13072                               struct bpf_verifier_state *vparent)
13073 {
13074         struct bpf_reg_state *state_reg, *parent_reg;
13075         struct bpf_func_state *state, *parent;
13076         int i, frame, err = 0;
13077
13078         if (vparent->curframe != vstate->curframe) {
13079                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
13080                      vparent->curframe, vstate->curframe);
13081                 return -EFAULT;
13082         }
13083         /* Propagate read liveness of registers... */
13084         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
13085         for (frame = 0; frame <= vstate->curframe; frame++) {
13086                 parent = vparent->frame[frame];
13087                 state = vstate->frame[frame];
13088                 parent_reg = parent->regs;
13089                 state_reg = state->regs;
13090                 /* We don't need to worry about FP liveness, it's read-only */
13091                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
13092                         err = propagate_liveness_reg(env, &state_reg[i],
13093                                                      &parent_reg[i]);
13094                         if (err < 0)
13095                                 return err;
13096                         if (err == REG_LIVE_READ64)
13097                                 mark_insn_zext(env, &parent_reg[i]);
13098                 }
13099
13100                 /* Propagate stack slots. */
13101                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13102                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
13103                         parent_reg = &parent->stack[i].spilled_ptr;
13104                         state_reg = &state->stack[i].spilled_ptr;
13105                         err = propagate_liveness_reg(env, state_reg,
13106                                                      parent_reg);
13107                         if (err < 0)
13108                                 return err;
13109                 }
13110         }
13111         return 0;
13112 }
13113
13114 /* find precise scalars in the previous equivalent state and
13115  * propagate them into the current state
13116  */
13117 static int propagate_precision(struct bpf_verifier_env *env,
13118                                const struct bpf_verifier_state *old)
13119 {
13120         struct bpf_reg_state *state_reg;
13121         struct bpf_func_state *state;
13122         int i, err = 0, fr;
13123
13124         for (fr = old->curframe; fr >= 0; fr--) {
13125                 state = old->frame[fr];
13126                 state_reg = state->regs;
13127                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13128                         if (state_reg->type != SCALAR_VALUE ||
13129                             !state_reg->precise)
13130                                 continue;
13131                         if (env->log.level & BPF_LOG_LEVEL2)
13132                                 verbose(env, "frame %d: propagating r%d\n", i, fr);
13133                         err = mark_chain_precision_frame(env, fr, i);
13134                         if (err < 0)
13135                                 return err;
13136                 }
13137
13138                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13139                         if (!is_spilled_reg(&state->stack[i]))
13140                                 continue;
13141                         state_reg = &state->stack[i].spilled_ptr;
13142                         if (state_reg->type != SCALAR_VALUE ||
13143                             !state_reg->precise)
13144                                 continue;
13145                         if (env->log.level & BPF_LOG_LEVEL2)
13146                                 verbose(env, "frame %d: propagating fp%d\n",
13147                                         (-i - 1) * BPF_REG_SIZE, fr);
13148                         err = mark_chain_precision_stack_frame(env, fr, i);
13149                         if (err < 0)
13150                                 return err;
13151                 }
13152         }
13153         return 0;
13154 }
13155
13156 static bool states_maybe_looping(struct bpf_verifier_state *old,
13157                                  struct bpf_verifier_state *cur)
13158 {
13159         struct bpf_func_state *fold, *fcur;
13160         int i, fr = cur->curframe;
13161
13162         if (old->curframe != fr)
13163                 return false;
13164
13165         fold = old->frame[fr];
13166         fcur = cur->frame[fr];
13167         for (i = 0; i < MAX_BPF_REG; i++)
13168                 if (memcmp(&fold->regs[i], &fcur->regs[i],
13169                            offsetof(struct bpf_reg_state, parent)))
13170                         return false;
13171         return true;
13172 }
13173
13174
13175 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
13176 {
13177         struct bpf_verifier_state_list *new_sl;
13178         struct bpf_verifier_state_list *sl, **pprev;
13179         struct bpf_verifier_state *cur = env->cur_state, *new;
13180         int i, j, err, states_cnt = 0;
13181         bool add_new_state = env->test_state_freq ? true : false;
13182
13183         cur->last_insn_idx = env->prev_insn_idx;
13184         if (!env->insn_aux_data[insn_idx].prune_point)
13185                 /* this 'insn_idx' instruction wasn't marked, so we will not
13186                  * be doing state search here
13187                  */
13188                 return 0;
13189
13190         /* bpf progs typically have pruning point every 4 instructions
13191          * http://vger.kernel.org/bpfconf2019.html#session-1
13192          * Do not add new state for future pruning if the verifier hasn't seen
13193          * at least 2 jumps and at least 8 instructions.
13194          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13195          * In tests that amounts to up to 50% reduction into total verifier
13196          * memory consumption and 20% verifier time speedup.
13197          */
13198         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13199             env->insn_processed - env->prev_insn_processed >= 8)
13200                 add_new_state = true;
13201
13202         pprev = explored_state(env, insn_idx);
13203         sl = *pprev;
13204
13205         clean_live_states(env, insn_idx, cur);
13206
13207         while (sl) {
13208                 states_cnt++;
13209                 if (sl->state.insn_idx != insn_idx)
13210                         goto next;
13211
13212                 if (sl->state.branches) {
13213                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13214
13215                         if (frame->in_async_callback_fn &&
13216                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13217                                 /* Different async_entry_cnt means that the verifier is
13218                                  * processing another entry into async callback.
13219                                  * Seeing the same state is not an indication of infinite
13220                                  * loop or infinite recursion.
13221                                  * But finding the same state doesn't mean that it's safe
13222                                  * to stop processing the current state. The previous state
13223                                  * hasn't yet reached bpf_exit, since state.branches > 0.
13224                                  * Checking in_async_callback_fn alone is not enough either.
13225                                  * Since the verifier still needs to catch infinite loops
13226                                  * inside async callbacks.
13227                                  */
13228                         } else if (states_maybe_looping(&sl->state, cur) &&
13229                                    states_equal(env, &sl->state, cur)) {
13230                                 verbose_linfo(env, insn_idx, "; ");
13231                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13232                                 return -EINVAL;
13233                         }
13234                         /* if the verifier is processing a loop, avoid adding new state
13235                          * too often, since different loop iterations have distinct
13236                          * states and may not help future pruning.
13237                          * This threshold shouldn't be too low to make sure that
13238                          * a loop with large bound will be rejected quickly.
13239                          * The most abusive loop will be:
13240                          * r1 += 1
13241                          * if r1 < 1000000 goto pc-2
13242                          * 1M insn_procssed limit / 100 == 10k peak states.
13243                          * This threshold shouldn't be too high either, since states
13244                          * at the end of the loop are likely to be useful in pruning.
13245                          */
13246                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13247                             env->insn_processed - env->prev_insn_processed < 100)
13248                                 add_new_state = false;
13249                         goto miss;
13250                 }
13251                 if (states_equal(env, &sl->state, cur)) {
13252                         sl->hit_cnt++;
13253                         /* reached equivalent register/stack state,
13254                          * prune the search.
13255                          * Registers read by the continuation are read by us.
13256                          * If we have any write marks in env->cur_state, they
13257                          * will prevent corresponding reads in the continuation
13258                          * from reaching our parent (an explored_state).  Our
13259                          * own state will get the read marks recorded, but
13260                          * they'll be immediately forgotten as we're pruning
13261                          * this state and will pop a new one.
13262                          */
13263                         err = propagate_liveness(env, &sl->state, cur);
13264
13265                         /* if previous state reached the exit with precision and
13266                          * current state is equivalent to it (except precsion marks)
13267                          * the precision needs to be propagated back in
13268                          * the current state.
13269                          */
13270                         err = err ? : push_jmp_history(env, cur);
13271                         err = err ? : propagate_precision(env, &sl->state);
13272                         if (err)
13273                                 return err;
13274                         return 1;
13275                 }
13276 miss:
13277                 /* when new state is not going to be added do not increase miss count.
13278                  * Otherwise several loop iterations will remove the state
13279                  * recorded earlier. The goal of these heuristics is to have
13280                  * states from some iterations of the loop (some in the beginning
13281                  * and some at the end) to help pruning.
13282                  */
13283                 if (add_new_state)
13284                         sl->miss_cnt++;
13285                 /* heuristic to determine whether this state is beneficial
13286                  * to keep checking from state equivalence point of view.
13287                  * Higher numbers increase max_states_per_insn and verification time,
13288                  * but do not meaningfully decrease insn_processed.
13289                  */
13290                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13291                         /* the state is unlikely to be useful. Remove it to
13292                          * speed up verification
13293                          */
13294                         *pprev = sl->next;
13295                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
13296                                 u32 br = sl->state.branches;
13297
13298                                 WARN_ONCE(br,
13299                                           "BUG live_done but branches_to_explore %d\n",
13300                                           br);
13301                                 free_verifier_state(&sl->state, false);
13302                                 kfree(sl);
13303                                 env->peak_states--;
13304                         } else {
13305                                 /* cannot free this state, since parentage chain may
13306                                  * walk it later. Add it for free_list instead to
13307                                  * be freed at the end of verification
13308                                  */
13309                                 sl->next = env->free_list;
13310                                 env->free_list = sl;
13311                         }
13312                         sl = *pprev;
13313                         continue;
13314                 }
13315 next:
13316                 pprev = &sl->next;
13317                 sl = *pprev;
13318         }
13319
13320         if (env->max_states_per_insn < states_cnt)
13321                 env->max_states_per_insn = states_cnt;
13322
13323         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
13324                 return push_jmp_history(env, cur);
13325
13326         if (!add_new_state)
13327                 return push_jmp_history(env, cur);
13328
13329         /* There were no equivalent states, remember the current one.
13330          * Technically the current state is not proven to be safe yet,
13331          * but it will either reach outer most bpf_exit (which means it's safe)
13332          * or it will be rejected. When there are no loops the verifier won't be
13333          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
13334          * again on the way to bpf_exit.
13335          * When looping the sl->state.branches will be > 0 and this state
13336          * will not be considered for equivalence until branches == 0.
13337          */
13338         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
13339         if (!new_sl)
13340                 return -ENOMEM;
13341         env->total_states++;
13342         env->peak_states++;
13343         env->prev_jmps_processed = env->jmps_processed;
13344         env->prev_insn_processed = env->insn_processed;
13345
13346         /* forget precise markings we inherited, see __mark_chain_precision */
13347         if (env->bpf_capable)
13348                 mark_all_scalars_imprecise(env, cur);
13349
13350         /* add new state to the head of linked list */
13351         new = &new_sl->state;
13352         err = copy_verifier_state(new, cur);
13353         if (err) {
13354                 free_verifier_state(new, false);
13355                 kfree(new_sl);
13356                 return err;
13357         }
13358         new->insn_idx = insn_idx;
13359         WARN_ONCE(new->branches != 1,
13360                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
13361
13362         cur->parent = new;
13363         cur->first_insn_idx = insn_idx;
13364         clear_jmp_history(cur);
13365         new_sl->next = *explored_state(env, insn_idx);
13366         *explored_state(env, insn_idx) = new_sl;
13367         /* connect new state to parentage chain. Current frame needs all
13368          * registers connected. Only r6 - r9 of the callers are alive (pushed
13369          * to the stack implicitly by JITs) so in callers' frames connect just
13370          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13371          * the state of the call instruction (with WRITTEN set), and r0 comes
13372          * from callee with its full parentage chain, anyway.
13373          */
13374         /* clear write marks in current state: the writes we did are not writes
13375          * our child did, so they don't screen off its reads from us.
13376          * (There are no read marks in current state, because reads always mark
13377          * their parent and current state never has children yet.  Only
13378          * explored_states can get read marks.)
13379          */
13380         for (j = 0; j <= cur->curframe; j++) {
13381                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13382                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13383                 for (i = 0; i < BPF_REG_FP; i++)
13384                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13385         }
13386
13387         /* all stack frames are accessible from callee, clear them all */
13388         for (j = 0; j <= cur->curframe; j++) {
13389                 struct bpf_func_state *frame = cur->frame[j];
13390                 struct bpf_func_state *newframe = new->frame[j];
13391
13392                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
13393                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
13394                         frame->stack[i].spilled_ptr.parent =
13395                                                 &newframe->stack[i].spilled_ptr;
13396                 }
13397         }
13398         return 0;
13399 }
13400
13401 /* Return true if it's OK to have the same insn return a different type. */
13402 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13403 {
13404         switch (base_type(type)) {
13405         case PTR_TO_CTX:
13406         case PTR_TO_SOCKET:
13407         case PTR_TO_SOCK_COMMON:
13408         case PTR_TO_TCP_SOCK:
13409         case PTR_TO_XDP_SOCK:
13410         case PTR_TO_BTF_ID:
13411                 return false;
13412         default:
13413                 return true;
13414         }
13415 }
13416
13417 /* If an instruction was previously used with particular pointer types, then we
13418  * need to be careful to avoid cases such as the below, where it may be ok
13419  * for one branch accessing the pointer, but not ok for the other branch:
13420  *
13421  * R1 = sock_ptr
13422  * goto X;
13423  * ...
13424  * R1 = some_other_valid_ptr;
13425  * goto X;
13426  * ...
13427  * R2 = *(u32 *)(R1 + 0);
13428  */
13429 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13430 {
13431         return src != prev && (!reg_type_mismatch_ok(src) ||
13432                                !reg_type_mismatch_ok(prev));
13433 }
13434
13435 static int do_check(struct bpf_verifier_env *env)
13436 {
13437         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13438         struct bpf_verifier_state *state = env->cur_state;
13439         struct bpf_insn *insns = env->prog->insnsi;
13440         struct bpf_reg_state *regs;
13441         int insn_cnt = env->prog->len;
13442         bool do_print_state = false;
13443         int prev_insn_idx = -1;
13444
13445         for (;;) {
13446                 struct bpf_insn *insn;
13447                 u8 class;
13448                 int err;
13449
13450                 env->prev_insn_idx = prev_insn_idx;
13451                 if (env->insn_idx >= insn_cnt) {
13452                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
13453                                 env->insn_idx, insn_cnt);
13454                         return -EFAULT;
13455                 }
13456
13457                 insn = &insns[env->insn_idx];
13458                 class = BPF_CLASS(insn->code);
13459
13460                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
13461                         verbose(env,
13462                                 "BPF program is too large. Processed %d insn\n",
13463                                 env->insn_processed);
13464                         return -E2BIG;
13465                 }
13466
13467                 err = is_state_visited(env, env->insn_idx);
13468                 if (err < 0)
13469                         return err;
13470                 if (err == 1) {
13471                         /* found equivalent state, can prune the search */
13472                         if (env->log.level & BPF_LOG_LEVEL) {
13473                                 if (do_print_state)
13474                                         verbose(env, "\nfrom %d to %d%s: safe\n",
13475                                                 env->prev_insn_idx, env->insn_idx,
13476                                                 env->cur_state->speculative ?
13477                                                 " (speculative execution)" : "");
13478                                 else
13479                                         verbose(env, "%d: safe\n", env->insn_idx);
13480                         }
13481                         goto process_bpf_exit;
13482                 }
13483
13484                 if (signal_pending(current))
13485                         return -EAGAIN;
13486
13487                 if (need_resched())
13488                         cond_resched();
13489
13490                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13491                         verbose(env, "\nfrom %d to %d%s:",
13492                                 env->prev_insn_idx, env->insn_idx,
13493                                 env->cur_state->speculative ?
13494                                 " (speculative execution)" : "");
13495                         print_verifier_state(env, state->frame[state->curframe], true);
13496                         do_print_state = false;
13497                 }
13498
13499                 if (env->log.level & BPF_LOG_LEVEL) {
13500                         const struct bpf_insn_cbs cbs = {
13501                                 .cb_call        = disasm_kfunc_name,
13502                                 .cb_print       = verbose,
13503                                 .private_data   = env,
13504                         };
13505
13506                         if (verifier_state_scratched(env))
13507                                 print_insn_state(env, state->frame[state->curframe]);
13508
13509                         verbose_linfo(env, env->insn_idx, "; ");
13510                         env->prev_log_len = env->log.len_used;
13511                         verbose(env, "%d: ", env->insn_idx);
13512                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
13513                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13514                         env->prev_log_len = env->log.len_used;
13515                 }
13516
13517                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13518                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13519                                                            env->prev_insn_idx);
13520                         if (err)
13521                                 return err;
13522                 }
13523
13524                 regs = cur_regs(env);
13525                 sanitize_mark_insn_seen(env);
13526                 prev_insn_idx = env->insn_idx;
13527
13528                 if (class == BPF_ALU || class == BPF_ALU64) {
13529                         err = check_alu_op(env, insn);
13530                         if (err)
13531                                 return err;
13532
13533                 } else if (class == BPF_LDX) {
13534                         enum bpf_reg_type *prev_src_type, src_reg_type;
13535
13536                         /* check for reserved fields is already done */
13537
13538                         /* check src operand */
13539                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13540                         if (err)
13541                                 return err;
13542
13543                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13544                         if (err)
13545                                 return err;
13546
13547                         src_reg_type = regs[insn->src_reg].type;
13548
13549                         /* check that memory (src_reg + off) is readable,
13550                          * the state of dst_reg will be updated by this func
13551                          */
13552                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
13553                                                insn->off, BPF_SIZE(insn->code),
13554                                                BPF_READ, insn->dst_reg, false);
13555                         if (err)
13556                                 return err;
13557
13558                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13559
13560                         if (*prev_src_type == NOT_INIT) {
13561                                 /* saw a valid insn
13562                                  * dst_reg = *(u32 *)(src_reg + off)
13563                                  * save type to validate intersecting paths
13564                                  */
13565                                 *prev_src_type = src_reg_type;
13566
13567                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
13568                                 /* ABuser program is trying to use the same insn
13569                                  * dst_reg = *(u32*) (src_reg + off)
13570                                  * with different pointer types:
13571                                  * src_reg == ctx in one branch and
13572                                  * src_reg == stack|map in some other branch.
13573                                  * Reject it.
13574                                  */
13575                                 verbose(env, "same insn cannot be used with different pointers\n");
13576                                 return -EINVAL;
13577                         }
13578
13579                 } else if (class == BPF_STX) {
13580                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
13581
13582                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13583                                 err = check_atomic(env, env->insn_idx, insn);
13584                                 if (err)
13585                                         return err;
13586                                 env->insn_idx++;
13587                                 continue;
13588                         }
13589
13590                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13591                                 verbose(env, "BPF_STX uses reserved fields\n");
13592                                 return -EINVAL;
13593                         }
13594
13595                         /* check src1 operand */
13596                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13597                         if (err)
13598                                 return err;
13599                         /* check src2 operand */
13600                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13601                         if (err)
13602                                 return err;
13603
13604                         dst_reg_type = regs[insn->dst_reg].type;
13605
13606                         /* check that memory (dst_reg + off) is writeable */
13607                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13608                                                insn->off, BPF_SIZE(insn->code),
13609                                                BPF_WRITE, insn->src_reg, false);
13610                         if (err)
13611                                 return err;
13612
13613                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
13614
13615                         if (*prev_dst_type == NOT_INIT) {
13616                                 *prev_dst_type = dst_reg_type;
13617                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
13618                                 verbose(env, "same insn cannot be used with different pointers\n");
13619                                 return -EINVAL;
13620                         }
13621
13622                 } else if (class == BPF_ST) {
13623                         if (BPF_MODE(insn->code) != BPF_MEM ||
13624                             insn->src_reg != BPF_REG_0) {
13625                                 verbose(env, "BPF_ST uses reserved fields\n");
13626                                 return -EINVAL;
13627                         }
13628                         /* check src operand */
13629                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13630                         if (err)
13631                                 return err;
13632
13633                         if (is_ctx_reg(env, insn->dst_reg)) {
13634                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
13635                                         insn->dst_reg,
13636                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
13637                                 return -EACCES;
13638                         }
13639
13640                         /* check that memory (dst_reg + off) is writeable */
13641                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13642                                                insn->off, BPF_SIZE(insn->code),
13643                                                BPF_WRITE, -1, false);
13644                         if (err)
13645                                 return err;
13646
13647                 } else if (class == BPF_JMP || class == BPF_JMP32) {
13648                         u8 opcode = BPF_OP(insn->code);
13649
13650                         env->jmps_processed++;
13651                         if (opcode == BPF_CALL) {
13652                                 if (BPF_SRC(insn->code) != BPF_K ||
13653                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13654                                      && insn->off != 0) ||
13655                                     (insn->src_reg != BPF_REG_0 &&
13656                                      insn->src_reg != BPF_PSEUDO_CALL &&
13657                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
13658                                     insn->dst_reg != BPF_REG_0 ||
13659                                     class == BPF_JMP32) {
13660                                         verbose(env, "BPF_CALL uses reserved fields\n");
13661                                         return -EINVAL;
13662                                 }
13663
13664                                 if (env->cur_state->active_lock.ptr) {
13665                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13666                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
13667                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13668                                              (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13669                                                 verbose(env, "function calls are not allowed while holding a lock\n");
13670                                                 return -EINVAL;
13671                                         }
13672                                 }
13673                                 if (insn->src_reg == BPF_PSEUDO_CALL)
13674                                         err = check_func_call(env, insn, &env->insn_idx);
13675                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
13676                                         err = check_kfunc_call(env, insn, &env->insn_idx);
13677                                 else
13678                                         err = check_helper_call(env, insn, &env->insn_idx);
13679                                 if (err)
13680                                         return err;
13681                         } else if (opcode == BPF_JA) {
13682                                 if (BPF_SRC(insn->code) != BPF_K ||
13683                                     insn->imm != 0 ||
13684                                     insn->src_reg != BPF_REG_0 ||
13685                                     insn->dst_reg != BPF_REG_0 ||
13686                                     class == BPF_JMP32) {
13687                                         verbose(env, "BPF_JA uses reserved fields\n");
13688                                         return -EINVAL;
13689                                 }
13690
13691                                 env->insn_idx += insn->off + 1;
13692                                 continue;
13693
13694                         } else if (opcode == BPF_EXIT) {
13695                                 if (BPF_SRC(insn->code) != BPF_K ||
13696                                     insn->imm != 0 ||
13697                                     insn->src_reg != BPF_REG_0 ||
13698                                     insn->dst_reg != BPF_REG_0 ||
13699                                     class == BPF_JMP32) {
13700                                         verbose(env, "BPF_EXIT uses reserved fields\n");
13701                                         return -EINVAL;
13702                                 }
13703
13704                                 if (env->cur_state->active_lock.ptr) {
13705                                         verbose(env, "bpf_spin_unlock is missing\n");
13706                                         return -EINVAL;
13707                                 }
13708
13709                                 /* We must do check_reference_leak here before
13710                                  * prepare_func_exit to handle the case when
13711                                  * state->curframe > 0, it may be a callback
13712                                  * function, for which reference_state must
13713                                  * match caller reference state when it exits.
13714                                  */
13715                                 err = check_reference_leak(env);
13716                                 if (err)
13717                                         return err;
13718
13719                                 if (state->curframe) {
13720                                         /* exit from nested function */
13721                                         err = prepare_func_exit(env, &env->insn_idx);
13722                                         if (err)
13723                                                 return err;
13724                                         do_print_state = true;
13725                                         continue;
13726                                 }
13727
13728                                 err = check_return_code(env);
13729                                 if (err)
13730                                         return err;
13731 process_bpf_exit:
13732                                 mark_verifier_state_scratched(env);
13733                                 update_branch_counts(env, env->cur_state);
13734                                 err = pop_stack(env, &prev_insn_idx,
13735                                                 &env->insn_idx, pop_log);
13736                                 if (err < 0) {
13737                                         if (err != -ENOENT)
13738                                                 return err;
13739                                         break;
13740                                 } else {
13741                                         do_print_state = true;
13742                                         continue;
13743                                 }
13744                         } else {
13745                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
13746                                 if (err)
13747                                         return err;
13748                         }
13749                 } else if (class == BPF_LD) {
13750                         u8 mode = BPF_MODE(insn->code);
13751
13752                         if (mode == BPF_ABS || mode == BPF_IND) {
13753                                 err = check_ld_abs(env, insn);
13754                                 if (err)
13755                                         return err;
13756
13757                         } else if (mode == BPF_IMM) {
13758                                 err = check_ld_imm(env, insn);
13759                                 if (err)
13760                                         return err;
13761
13762                                 env->insn_idx++;
13763                                 sanitize_mark_insn_seen(env);
13764                         } else {
13765                                 verbose(env, "invalid BPF_LD mode\n");
13766                                 return -EINVAL;
13767                         }
13768                 } else {
13769                         verbose(env, "unknown insn class %d\n", class);
13770                         return -EINVAL;
13771                 }
13772
13773                 env->insn_idx++;
13774         }
13775
13776         return 0;
13777 }
13778
13779 static int find_btf_percpu_datasec(struct btf *btf)
13780 {
13781         const struct btf_type *t;
13782         const char *tname;
13783         int i, n;
13784
13785         /*
13786          * Both vmlinux and module each have their own ".data..percpu"
13787          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
13788          * types to look at only module's own BTF types.
13789          */
13790         n = btf_nr_types(btf);
13791         if (btf_is_module(btf))
13792                 i = btf_nr_types(btf_vmlinux);
13793         else
13794                 i = 1;
13795
13796         for(; i < n; i++) {
13797                 t = btf_type_by_id(btf, i);
13798                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
13799                         continue;
13800
13801                 tname = btf_name_by_offset(btf, t->name_off);
13802                 if (!strcmp(tname, ".data..percpu"))
13803                         return i;
13804         }
13805
13806         return -ENOENT;
13807 }
13808
13809 /* replace pseudo btf_id with kernel symbol address */
13810 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
13811                                struct bpf_insn *insn,
13812                                struct bpf_insn_aux_data *aux)
13813 {
13814         const struct btf_var_secinfo *vsi;
13815         const struct btf_type *datasec;
13816         struct btf_mod_pair *btf_mod;
13817         const struct btf_type *t;
13818         const char *sym_name;
13819         bool percpu = false;
13820         u32 type, id = insn->imm;
13821         struct btf *btf;
13822         s32 datasec_id;
13823         u64 addr;
13824         int i, btf_fd, err;
13825
13826         btf_fd = insn[1].imm;
13827         if (btf_fd) {
13828                 btf = btf_get_by_fd(btf_fd);
13829                 if (IS_ERR(btf)) {
13830                         verbose(env, "invalid module BTF object FD specified.\n");
13831                         return -EINVAL;
13832                 }
13833         } else {
13834                 if (!btf_vmlinux) {
13835                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
13836                         return -EINVAL;
13837                 }
13838                 btf = btf_vmlinux;
13839                 btf_get(btf);
13840         }
13841
13842         t = btf_type_by_id(btf, id);
13843         if (!t) {
13844                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
13845                 err = -ENOENT;
13846                 goto err_put;
13847         }
13848
13849         if (!btf_type_is_var(t)) {
13850                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
13851                 err = -EINVAL;
13852                 goto err_put;
13853         }
13854
13855         sym_name = btf_name_by_offset(btf, t->name_off);
13856         addr = kallsyms_lookup_name(sym_name);
13857         if (!addr) {
13858                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
13859                         sym_name);
13860                 err = -ENOENT;
13861                 goto err_put;
13862         }
13863
13864         datasec_id = find_btf_percpu_datasec(btf);
13865         if (datasec_id > 0) {
13866                 datasec = btf_type_by_id(btf, datasec_id);
13867                 for_each_vsi(i, datasec, vsi) {
13868                         if (vsi->type == id) {
13869                                 percpu = true;
13870                                 break;
13871                         }
13872                 }
13873         }
13874
13875         insn[0].imm = (u32)addr;
13876         insn[1].imm = addr >> 32;
13877
13878         type = t->type;
13879         t = btf_type_skip_modifiers(btf, type, NULL);
13880         if (percpu) {
13881                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
13882                 aux->btf_var.btf = btf;
13883                 aux->btf_var.btf_id = type;
13884         } else if (!btf_type_is_struct(t)) {
13885                 const struct btf_type *ret;
13886                 const char *tname;
13887                 u32 tsize;
13888
13889                 /* resolve the type size of ksym. */
13890                 ret = btf_resolve_size(btf, t, &tsize);
13891                 if (IS_ERR(ret)) {
13892                         tname = btf_name_by_offset(btf, t->name_off);
13893                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
13894                                 tname, PTR_ERR(ret));
13895                         err = -EINVAL;
13896                         goto err_put;
13897                 }
13898                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
13899                 aux->btf_var.mem_size = tsize;
13900         } else {
13901                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
13902                 aux->btf_var.btf = btf;
13903                 aux->btf_var.btf_id = type;
13904         }
13905
13906         /* check whether we recorded this BTF (and maybe module) already */
13907         for (i = 0; i < env->used_btf_cnt; i++) {
13908                 if (env->used_btfs[i].btf == btf) {
13909                         btf_put(btf);
13910                         return 0;
13911                 }
13912         }
13913
13914         if (env->used_btf_cnt >= MAX_USED_BTFS) {
13915                 err = -E2BIG;
13916                 goto err_put;
13917         }
13918
13919         btf_mod = &env->used_btfs[env->used_btf_cnt];
13920         btf_mod->btf = btf;
13921         btf_mod->module = NULL;
13922
13923         /* if we reference variables from kernel module, bump its refcount */
13924         if (btf_is_module(btf)) {
13925                 btf_mod->module = btf_try_get_module(btf);
13926                 if (!btf_mod->module) {
13927                         err = -ENXIO;
13928                         goto err_put;
13929                 }
13930         }
13931
13932         env->used_btf_cnt++;
13933
13934         return 0;
13935 err_put:
13936         btf_put(btf);
13937         return err;
13938 }
13939
13940 static bool is_tracing_prog_type(enum bpf_prog_type type)
13941 {
13942         switch (type) {
13943         case BPF_PROG_TYPE_KPROBE:
13944         case BPF_PROG_TYPE_TRACEPOINT:
13945         case BPF_PROG_TYPE_PERF_EVENT:
13946         case BPF_PROG_TYPE_RAW_TRACEPOINT:
13947         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
13948                 return true;
13949         default:
13950                 return false;
13951         }
13952 }
13953
13954 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
13955                                         struct bpf_map *map,
13956                                         struct bpf_prog *prog)
13957
13958 {
13959         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13960
13961         if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
13962                 if (is_tracing_prog_type(prog_type)) {
13963                         verbose(env, "tracing progs cannot use bpf_list_head yet\n");
13964                         return -EINVAL;
13965                 }
13966         }
13967
13968         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
13969                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
13970                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
13971                         return -EINVAL;
13972                 }
13973
13974                 if (is_tracing_prog_type(prog_type)) {
13975                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
13976                         return -EINVAL;
13977                 }
13978
13979                 if (prog->aux->sleepable) {
13980                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
13981                         return -EINVAL;
13982                 }
13983         }
13984
13985         if (btf_record_has_field(map->record, BPF_TIMER)) {
13986                 if (is_tracing_prog_type(prog_type)) {
13987                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
13988                         return -EINVAL;
13989                 }
13990         }
13991
13992         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
13993             !bpf_offload_prog_map_match(prog, map)) {
13994                 verbose(env, "offload device mismatch between prog and map\n");
13995                 return -EINVAL;
13996         }
13997
13998         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
13999                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14000                 return -EINVAL;
14001         }
14002
14003         if (prog->aux->sleepable)
14004                 switch (map->map_type) {
14005                 case BPF_MAP_TYPE_HASH:
14006                 case BPF_MAP_TYPE_LRU_HASH:
14007                 case BPF_MAP_TYPE_ARRAY:
14008                 case BPF_MAP_TYPE_PERCPU_HASH:
14009                 case BPF_MAP_TYPE_PERCPU_ARRAY:
14010                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14011                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14012                 case BPF_MAP_TYPE_HASH_OF_MAPS:
14013                 case BPF_MAP_TYPE_RINGBUF:
14014                 case BPF_MAP_TYPE_USER_RINGBUF:
14015                 case BPF_MAP_TYPE_INODE_STORAGE:
14016                 case BPF_MAP_TYPE_SK_STORAGE:
14017                 case BPF_MAP_TYPE_TASK_STORAGE:
14018                         break;
14019                 default:
14020                         verbose(env,
14021                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
14022                         return -EINVAL;
14023                 }
14024
14025         return 0;
14026 }
14027
14028 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14029 {
14030         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14031                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14032 }
14033
14034 /* find and rewrite pseudo imm in ld_imm64 instructions:
14035  *
14036  * 1. if it accesses map FD, replace it with actual map pointer.
14037  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14038  *
14039  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
14040  */
14041 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
14042 {
14043         struct bpf_insn *insn = env->prog->insnsi;
14044         int insn_cnt = env->prog->len;
14045         int i, j, err;
14046
14047         err = bpf_prog_calc_tag(env->prog);
14048         if (err)
14049                 return err;
14050
14051         for (i = 0; i < insn_cnt; i++, insn++) {
14052                 if (BPF_CLASS(insn->code) == BPF_LDX &&
14053                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
14054                         verbose(env, "BPF_LDX uses reserved fields\n");
14055                         return -EINVAL;
14056                 }
14057
14058                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
14059                         struct bpf_insn_aux_data *aux;
14060                         struct bpf_map *map;
14061                         struct fd f;
14062                         u64 addr;
14063                         u32 fd;
14064
14065                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
14066                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14067                             insn[1].off != 0) {
14068                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
14069                                 return -EINVAL;
14070                         }
14071
14072                         if (insn[0].src_reg == 0)
14073                                 /* valid generic load 64-bit imm */
14074                                 goto next_insn;
14075
14076                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14077                                 aux = &env->insn_aux_data[i];
14078                                 err = check_pseudo_btf_id(env, insn, aux);
14079                                 if (err)
14080                                         return err;
14081                                 goto next_insn;
14082                         }
14083
14084                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14085                                 aux = &env->insn_aux_data[i];
14086                                 aux->ptr_type = PTR_TO_FUNC;
14087                                 goto next_insn;
14088                         }
14089
14090                         /* In final convert_pseudo_ld_imm64() step, this is
14091                          * converted into regular 64-bit imm load insn.
14092                          */
14093                         switch (insn[0].src_reg) {
14094                         case BPF_PSEUDO_MAP_VALUE:
14095                         case BPF_PSEUDO_MAP_IDX_VALUE:
14096                                 break;
14097                         case BPF_PSEUDO_MAP_FD:
14098                         case BPF_PSEUDO_MAP_IDX:
14099                                 if (insn[1].imm == 0)
14100                                         break;
14101                                 fallthrough;
14102                         default:
14103                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
14104                                 return -EINVAL;
14105                         }
14106
14107                         switch (insn[0].src_reg) {
14108                         case BPF_PSEUDO_MAP_IDX_VALUE:
14109                         case BPF_PSEUDO_MAP_IDX:
14110                                 if (bpfptr_is_null(env->fd_array)) {
14111                                         verbose(env, "fd_idx without fd_array is invalid\n");
14112                                         return -EPROTO;
14113                                 }
14114                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
14115                                                             insn[0].imm * sizeof(fd),
14116                                                             sizeof(fd)))
14117                                         return -EFAULT;
14118                                 break;
14119                         default:
14120                                 fd = insn[0].imm;
14121                                 break;
14122                         }
14123
14124                         f = fdget(fd);
14125                         map = __bpf_map_get(f);
14126                         if (IS_ERR(map)) {
14127                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
14128                                         insn[0].imm);
14129                                 return PTR_ERR(map);
14130                         }
14131
14132                         err = check_map_prog_compatibility(env, map, env->prog);
14133                         if (err) {
14134                                 fdput(f);
14135                                 return err;
14136                         }
14137
14138                         aux = &env->insn_aux_data[i];
14139                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14140                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
14141                                 addr = (unsigned long)map;
14142                         } else {
14143                                 u32 off = insn[1].imm;
14144
14145                                 if (off >= BPF_MAX_VAR_OFF) {
14146                                         verbose(env, "direct value offset of %u is not allowed\n", off);
14147                                         fdput(f);
14148                                         return -EINVAL;
14149                                 }
14150
14151                                 if (!map->ops->map_direct_value_addr) {
14152                                         verbose(env, "no direct value access support for this map type\n");
14153                                         fdput(f);
14154                                         return -EINVAL;
14155                                 }
14156
14157                                 err = map->ops->map_direct_value_addr(map, &addr, off);
14158                                 if (err) {
14159                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14160                                                 map->value_size, off);
14161                                         fdput(f);
14162                                         return err;
14163                                 }
14164
14165                                 aux->map_off = off;
14166                                 addr += off;
14167                         }
14168
14169                         insn[0].imm = (u32)addr;
14170                         insn[1].imm = addr >> 32;
14171
14172                         /* check whether we recorded this map already */
14173                         for (j = 0; j < env->used_map_cnt; j++) {
14174                                 if (env->used_maps[j] == map) {
14175                                         aux->map_index = j;
14176                                         fdput(f);
14177                                         goto next_insn;
14178                                 }
14179                         }
14180
14181                         if (env->used_map_cnt >= MAX_USED_MAPS) {
14182                                 fdput(f);
14183                                 return -E2BIG;
14184                         }
14185
14186                         /* hold the map. If the program is rejected by verifier,
14187                          * the map will be released by release_maps() or it
14188                          * will be used by the valid program until it's unloaded
14189                          * and all maps are released in free_used_maps()
14190                          */
14191                         bpf_map_inc(map);
14192
14193                         aux->map_index = env->used_map_cnt;
14194                         env->used_maps[env->used_map_cnt++] = map;
14195
14196                         if (bpf_map_is_cgroup_storage(map) &&
14197                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
14198                                 verbose(env, "only one cgroup storage of each type is allowed\n");
14199                                 fdput(f);
14200                                 return -EBUSY;
14201                         }
14202
14203                         fdput(f);
14204 next_insn:
14205                         insn++;
14206                         i++;
14207                         continue;
14208                 }
14209
14210                 /* Basic sanity check before we invest more work here. */
14211                 if (!bpf_opcode_in_insntable(insn->code)) {
14212                         verbose(env, "unknown opcode %02x\n", insn->code);
14213                         return -EINVAL;
14214                 }
14215         }
14216
14217         /* now all pseudo BPF_LD_IMM64 instructions load valid
14218          * 'struct bpf_map *' into a register instead of user map_fd.
14219          * These pointers will be used later by verifier to validate map access.
14220          */
14221         return 0;
14222 }
14223
14224 /* drop refcnt of maps used by the rejected program */
14225 static void release_maps(struct bpf_verifier_env *env)
14226 {
14227         __bpf_free_used_maps(env->prog->aux, env->used_maps,
14228                              env->used_map_cnt);
14229 }
14230
14231 /* drop refcnt of maps used by the rejected program */
14232 static void release_btfs(struct bpf_verifier_env *env)
14233 {
14234         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14235                              env->used_btf_cnt);
14236 }
14237
14238 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
14239 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
14240 {
14241         struct bpf_insn *insn = env->prog->insnsi;
14242         int insn_cnt = env->prog->len;
14243         int i;
14244
14245         for (i = 0; i < insn_cnt; i++, insn++) {
14246                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14247                         continue;
14248                 if (insn->src_reg == BPF_PSEUDO_FUNC)
14249                         continue;
14250                 insn->src_reg = 0;
14251         }
14252 }
14253
14254 /* single env->prog->insni[off] instruction was replaced with the range
14255  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
14256  * [0, off) and [off, end) to new locations, so the patched range stays zero
14257  */
14258 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14259                                  struct bpf_insn_aux_data *new_data,
14260                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
14261 {
14262         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
14263         struct bpf_insn *insn = new_prog->insnsi;
14264         u32 old_seen = old_data[off].seen;
14265         u32 prog_len;
14266         int i;
14267
14268         /* aux info at OFF always needs adjustment, no matter fast path
14269          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14270          * original insn at old prog.
14271          */
14272         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14273
14274         if (cnt == 1)
14275                 return;
14276         prog_len = new_prog->len;
14277
14278         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14279         memcpy(new_data + off + cnt - 1, old_data + off,
14280                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
14281         for (i = off; i < off + cnt - 1; i++) {
14282                 /* Expand insni[off]'s seen count to the patched range. */
14283                 new_data[i].seen = old_seen;
14284                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
14285         }
14286         env->insn_aux_data = new_data;
14287         vfree(old_data);
14288 }
14289
14290 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14291 {
14292         int i;
14293
14294         if (len == 1)
14295                 return;
14296         /* NOTE: fake 'exit' subprog should be updated as well. */
14297         for (i = 0; i <= env->subprog_cnt; i++) {
14298                 if (env->subprog_info[i].start <= off)
14299                         continue;
14300                 env->subprog_info[i].start += len - 1;
14301         }
14302 }
14303
14304 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
14305 {
14306         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14307         int i, sz = prog->aux->size_poke_tab;
14308         struct bpf_jit_poke_descriptor *desc;
14309
14310         for (i = 0; i < sz; i++) {
14311                 desc = &tab[i];
14312                 if (desc->insn_idx <= off)
14313                         continue;
14314                 desc->insn_idx += len - 1;
14315         }
14316 }
14317
14318 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14319                                             const struct bpf_insn *patch, u32 len)
14320 {
14321         struct bpf_prog *new_prog;
14322         struct bpf_insn_aux_data *new_data = NULL;
14323
14324         if (len > 1) {
14325                 new_data = vzalloc(array_size(env->prog->len + len - 1,
14326                                               sizeof(struct bpf_insn_aux_data)));
14327                 if (!new_data)
14328                         return NULL;
14329         }
14330
14331         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
14332         if (IS_ERR(new_prog)) {
14333                 if (PTR_ERR(new_prog) == -ERANGE)
14334                         verbose(env,
14335                                 "insn %d cannot be patched due to 16-bit range\n",
14336                                 env->insn_aux_data[off].orig_idx);
14337                 vfree(new_data);
14338                 return NULL;
14339         }
14340         adjust_insn_aux_data(env, new_data, new_prog, off, len);
14341         adjust_subprog_starts(env, off, len);
14342         adjust_poke_descs(new_prog, off, len);
14343         return new_prog;
14344 }
14345
14346 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14347                                               u32 off, u32 cnt)
14348 {
14349         int i, j;
14350
14351         /* find first prog starting at or after off (first to remove) */
14352         for (i = 0; i < env->subprog_cnt; i++)
14353                 if (env->subprog_info[i].start >= off)
14354                         break;
14355         /* find first prog starting at or after off + cnt (first to stay) */
14356         for (j = i; j < env->subprog_cnt; j++)
14357                 if (env->subprog_info[j].start >= off + cnt)
14358                         break;
14359         /* if j doesn't start exactly at off + cnt, we are just removing
14360          * the front of previous prog
14361          */
14362         if (env->subprog_info[j].start != off + cnt)
14363                 j--;
14364
14365         if (j > i) {
14366                 struct bpf_prog_aux *aux = env->prog->aux;
14367                 int move;
14368
14369                 /* move fake 'exit' subprog as well */
14370                 move = env->subprog_cnt + 1 - j;
14371
14372                 memmove(env->subprog_info + i,
14373                         env->subprog_info + j,
14374                         sizeof(*env->subprog_info) * move);
14375                 env->subprog_cnt -= j - i;
14376
14377                 /* remove func_info */
14378                 if (aux->func_info) {
14379                         move = aux->func_info_cnt - j;
14380
14381                         memmove(aux->func_info + i,
14382                                 aux->func_info + j,
14383                                 sizeof(*aux->func_info) * move);
14384                         aux->func_info_cnt -= j - i;
14385                         /* func_info->insn_off is set after all code rewrites,
14386                          * in adjust_btf_func() - no need to adjust
14387                          */
14388                 }
14389         } else {
14390                 /* convert i from "first prog to remove" to "first to adjust" */
14391                 if (env->subprog_info[i].start == off)
14392                         i++;
14393         }
14394
14395         /* update fake 'exit' subprog as well */
14396         for (; i <= env->subprog_cnt; i++)
14397                 env->subprog_info[i].start -= cnt;
14398
14399         return 0;
14400 }
14401
14402 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14403                                       u32 cnt)
14404 {
14405         struct bpf_prog *prog = env->prog;
14406         u32 i, l_off, l_cnt, nr_linfo;
14407         struct bpf_line_info *linfo;
14408
14409         nr_linfo = prog->aux->nr_linfo;
14410         if (!nr_linfo)
14411                 return 0;
14412
14413         linfo = prog->aux->linfo;
14414
14415         /* find first line info to remove, count lines to be removed */
14416         for (i = 0; i < nr_linfo; i++)
14417                 if (linfo[i].insn_off >= off)
14418                         break;
14419
14420         l_off = i;
14421         l_cnt = 0;
14422         for (; i < nr_linfo; i++)
14423                 if (linfo[i].insn_off < off + cnt)
14424                         l_cnt++;
14425                 else
14426                         break;
14427
14428         /* First live insn doesn't match first live linfo, it needs to "inherit"
14429          * last removed linfo.  prog is already modified, so prog->len == off
14430          * means no live instructions after (tail of the program was removed).
14431          */
14432         if (prog->len != off && l_cnt &&
14433             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14434                 l_cnt--;
14435                 linfo[--i].insn_off = off + cnt;
14436         }
14437
14438         /* remove the line info which refer to the removed instructions */
14439         if (l_cnt) {
14440                 memmove(linfo + l_off, linfo + i,
14441                         sizeof(*linfo) * (nr_linfo - i));
14442
14443                 prog->aux->nr_linfo -= l_cnt;
14444                 nr_linfo = prog->aux->nr_linfo;
14445         }
14446
14447         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
14448         for (i = l_off; i < nr_linfo; i++)
14449                 linfo[i].insn_off -= cnt;
14450
14451         /* fix up all subprogs (incl. 'exit') which start >= off */
14452         for (i = 0; i <= env->subprog_cnt; i++)
14453                 if (env->subprog_info[i].linfo_idx > l_off) {
14454                         /* program may have started in the removed region but
14455                          * may not be fully removed
14456                          */
14457                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14458                                 env->subprog_info[i].linfo_idx -= l_cnt;
14459                         else
14460                                 env->subprog_info[i].linfo_idx = l_off;
14461                 }
14462
14463         return 0;
14464 }
14465
14466 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14467 {
14468         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14469         unsigned int orig_prog_len = env->prog->len;
14470         int err;
14471
14472         if (bpf_prog_is_dev_bound(env->prog->aux))
14473                 bpf_prog_offload_remove_insns(env, off, cnt);
14474
14475         err = bpf_remove_insns(env->prog, off, cnt);
14476         if (err)
14477                 return err;
14478
14479         err = adjust_subprog_starts_after_remove(env, off, cnt);
14480         if (err)
14481                 return err;
14482
14483         err = bpf_adj_linfo_after_remove(env, off, cnt);
14484         if (err)
14485                 return err;
14486
14487         memmove(aux_data + off, aux_data + off + cnt,
14488                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
14489
14490         return 0;
14491 }
14492
14493 /* The verifier does more data flow analysis than llvm and will not
14494  * explore branches that are dead at run time. Malicious programs can
14495  * have dead code too. Therefore replace all dead at-run-time code
14496  * with 'ja -1'.
14497  *
14498  * Just nops are not optimal, e.g. if they would sit at the end of the
14499  * program and through another bug we would manage to jump there, then
14500  * we'd execute beyond program memory otherwise. Returning exception
14501  * code also wouldn't work since we can have subprogs where the dead
14502  * code could be located.
14503  */
14504 static void sanitize_dead_code(struct bpf_verifier_env *env)
14505 {
14506         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14507         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
14508         struct bpf_insn *insn = env->prog->insnsi;
14509         const int insn_cnt = env->prog->len;
14510         int i;
14511
14512         for (i = 0; i < insn_cnt; i++) {
14513                 if (aux_data[i].seen)
14514                         continue;
14515                 memcpy(insn + i, &trap, sizeof(trap));
14516                 aux_data[i].zext_dst = false;
14517         }
14518 }
14519
14520 static bool insn_is_cond_jump(u8 code)
14521 {
14522         u8 op;
14523
14524         if (BPF_CLASS(code) == BPF_JMP32)
14525                 return true;
14526
14527         if (BPF_CLASS(code) != BPF_JMP)
14528                 return false;
14529
14530         op = BPF_OP(code);
14531         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14532 }
14533
14534 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14535 {
14536         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14537         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14538         struct bpf_insn *insn = env->prog->insnsi;
14539         const int insn_cnt = env->prog->len;
14540         int i;
14541
14542         for (i = 0; i < insn_cnt; i++, insn++) {
14543                 if (!insn_is_cond_jump(insn->code))
14544                         continue;
14545
14546                 if (!aux_data[i + 1].seen)
14547                         ja.off = insn->off;
14548                 else if (!aux_data[i + 1 + insn->off].seen)
14549                         ja.off = 0;
14550                 else
14551                         continue;
14552
14553                 if (bpf_prog_is_dev_bound(env->prog->aux))
14554                         bpf_prog_offload_replace_insn(env, i, &ja);
14555
14556                 memcpy(insn, &ja, sizeof(ja));
14557         }
14558 }
14559
14560 static int opt_remove_dead_code(struct bpf_verifier_env *env)
14561 {
14562         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14563         int insn_cnt = env->prog->len;
14564         int i, err;
14565
14566         for (i = 0; i < insn_cnt; i++) {
14567                 int j;
14568
14569                 j = 0;
14570                 while (i + j < insn_cnt && !aux_data[i + j].seen)
14571                         j++;
14572                 if (!j)
14573                         continue;
14574
14575                 err = verifier_remove_insns(env, i, j);
14576                 if (err)
14577                         return err;
14578                 insn_cnt = env->prog->len;
14579         }
14580
14581         return 0;
14582 }
14583
14584 static int opt_remove_nops(struct bpf_verifier_env *env)
14585 {
14586         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14587         struct bpf_insn *insn = env->prog->insnsi;
14588         int insn_cnt = env->prog->len;
14589         int i, err;
14590
14591         for (i = 0; i < insn_cnt; i++) {
14592                 if (memcmp(&insn[i], &ja, sizeof(ja)))
14593                         continue;
14594
14595                 err = verifier_remove_insns(env, i, 1);
14596                 if (err)
14597                         return err;
14598                 insn_cnt--;
14599                 i--;
14600         }
14601
14602         return 0;
14603 }
14604
14605 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14606                                          const union bpf_attr *attr)
14607 {
14608         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
14609         struct bpf_insn_aux_data *aux = env->insn_aux_data;
14610         int i, patch_len, delta = 0, len = env->prog->len;
14611         struct bpf_insn *insns = env->prog->insnsi;
14612         struct bpf_prog *new_prog;
14613         bool rnd_hi32;
14614
14615         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
14616         zext_patch[1] = BPF_ZEXT_REG(0);
14617         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14618         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14619         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
14620         for (i = 0; i < len; i++) {
14621                 int adj_idx = i + delta;
14622                 struct bpf_insn insn;
14623                 int load_reg;
14624
14625                 insn = insns[adj_idx];
14626                 load_reg = insn_def_regno(&insn);
14627                 if (!aux[adj_idx].zext_dst) {
14628                         u8 code, class;
14629                         u32 imm_rnd;
14630
14631                         if (!rnd_hi32)
14632                                 continue;
14633
14634                         code = insn.code;
14635                         class = BPF_CLASS(code);
14636                         if (load_reg == -1)
14637                                 continue;
14638
14639                         /* NOTE: arg "reg" (the fourth one) is only used for
14640                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
14641                          *       here.
14642                          */
14643                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
14644                                 if (class == BPF_LD &&
14645                                     BPF_MODE(code) == BPF_IMM)
14646                                         i++;
14647                                 continue;
14648                         }
14649
14650                         /* ctx load could be transformed into wider load. */
14651                         if (class == BPF_LDX &&
14652                             aux[adj_idx].ptr_type == PTR_TO_CTX)
14653                                 continue;
14654
14655                         imm_rnd = get_random_u32();
14656                         rnd_hi32_patch[0] = insn;
14657                         rnd_hi32_patch[1].imm = imm_rnd;
14658                         rnd_hi32_patch[3].dst_reg = load_reg;
14659                         patch = rnd_hi32_patch;
14660                         patch_len = 4;
14661                         goto apply_patch_buffer;
14662                 }
14663
14664                 /* Add in an zero-extend instruction if a) the JIT has requested
14665                  * it or b) it's a CMPXCHG.
14666                  *
14667                  * The latter is because: BPF_CMPXCHG always loads a value into
14668                  * R0, therefore always zero-extends. However some archs'
14669                  * equivalent instruction only does this load when the
14670                  * comparison is successful. This detail of CMPXCHG is
14671                  * orthogonal to the general zero-extension behaviour of the
14672                  * CPU, so it's treated independently of bpf_jit_needs_zext.
14673                  */
14674                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
14675                         continue;
14676
14677                 if (WARN_ON(load_reg == -1)) {
14678                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
14679                         return -EFAULT;
14680                 }
14681
14682                 zext_patch[0] = insn;
14683                 zext_patch[1].dst_reg = load_reg;
14684                 zext_patch[1].src_reg = load_reg;
14685                 patch = zext_patch;
14686                 patch_len = 2;
14687 apply_patch_buffer:
14688                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
14689                 if (!new_prog)
14690                         return -ENOMEM;
14691                 env->prog = new_prog;
14692                 insns = new_prog->insnsi;
14693                 aux = env->insn_aux_data;
14694                 delta += patch_len - 1;
14695         }
14696
14697         return 0;
14698 }
14699
14700 /* convert load instructions that access fields of a context type into a
14701  * sequence of instructions that access fields of the underlying structure:
14702  *     struct __sk_buff    -> struct sk_buff
14703  *     struct bpf_sock_ops -> struct sock
14704  */
14705 static int convert_ctx_accesses(struct bpf_verifier_env *env)
14706 {
14707         const struct bpf_verifier_ops *ops = env->ops;
14708         int i, cnt, size, ctx_field_size, delta = 0;
14709         const int insn_cnt = env->prog->len;
14710         struct bpf_insn insn_buf[16], *insn;
14711         u32 target_size, size_default, off;
14712         struct bpf_prog *new_prog;
14713         enum bpf_access_type type;
14714         bool is_narrower_load;
14715
14716         if (ops->gen_prologue || env->seen_direct_write) {
14717                 if (!ops->gen_prologue) {
14718                         verbose(env, "bpf verifier is misconfigured\n");
14719                         return -EINVAL;
14720                 }
14721                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
14722                                         env->prog);
14723                 if (cnt >= ARRAY_SIZE(insn_buf)) {
14724                         verbose(env, "bpf verifier is misconfigured\n");
14725                         return -EINVAL;
14726                 } else if (cnt) {
14727                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
14728                         if (!new_prog)
14729                                 return -ENOMEM;
14730
14731                         env->prog = new_prog;
14732                         delta += cnt - 1;
14733                 }
14734         }
14735
14736         if (bpf_prog_is_dev_bound(env->prog->aux))
14737                 return 0;
14738
14739         insn = env->prog->insnsi + delta;
14740
14741         for (i = 0; i < insn_cnt; i++, insn++) {
14742                 bpf_convert_ctx_access_t convert_ctx_access;
14743                 bool ctx_access;
14744
14745                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
14746                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
14747                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
14748                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
14749                         type = BPF_READ;
14750                         ctx_access = true;
14751                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
14752                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
14753                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
14754                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
14755                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
14756                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
14757                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
14758                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
14759                         type = BPF_WRITE;
14760                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
14761                 } else {
14762                         continue;
14763                 }
14764
14765                 if (type == BPF_WRITE &&
14766                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
14767                         struct bpf_insn patch[] = {
14768                                 *insn,
14769                                 BPF_ST_NOSPEC(),
14770                         };
14771
14772                         cnt = ARRAY_SIZE(patch);
14773                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
14774                         if (!new_prog)
14775                                 return -ENOMEM;
14776
14777                         delta    += cnt - 1;
14778                         env->prog = new_prog;
14779                         insn      = new_prog->insnsi + i + delta;
14780                         continue;
14781                 }
14782
14783                 if (!ctx_access)
14784                         continue;
14785
14786                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
14787                 case PTR_TO_CTX:
14788                         if (!ops->convert_ctx_access)
14789                                 continue;
14790                         convert_ctx_access = ops->convert_ctx_access;
14791                         break;
14792                 case PTR_TO_SOCKET:
14793                 case PTR_TO_SOCK_COMMON:
14794                         convert_ctx_access = bpf_sock_convert_ctx_access;
14795                         break;
14796                 case PTR_TO_TCP_SOCK:
14797                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
14798                         break;
14799                 case PTR_TO_XDP_SOCK:
14800                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
14801                         break;
14802                 case PTR_TO_BTF_ID:
14803                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
14804                 case PTR_TO_BTF_ID | PTR_TRUSTED:
14805                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
14806                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
14807                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
14808                  * any faults for loads into such types. BPF_WRITE is disallowed
14809                  * for this case.
14810                  */
14811                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
14812                 case PTR_TO_BTF_ID | PTR_UNTRUSTED | PTR_TRUSTED:
14813                 case PTR_TO_BTF_ID | PTR_UNTRUSTED | MEM_ALLOC | PTR_TRUSTED:
14814                         if (type == BPF_READ) {
14815                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
14816                                         BPF_SIZE((insn)->code);
14817                                 env->prog->aux->num_exentries++;
14818                         }
14819                         continue;
14820                 default:
14821                         continue;
14822                 }
14823
14824                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
14825                 size = BPF_LDST_BYTES(insn);
14826
14827                 /* If the read access is a narrower load of the field,
14828                  * convert to a 4/8-byte load, to minimum program type specific
14829                  * convert_ctx_access changes. If conversion is successful,
14830                  * we will apply proper mask to the result.
14831                  */
14832                 is_narrower_load = size < ctx_field_size;
14833                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
14834                 off = insn->off;
14835                 if (is_narrower_load) {
14836                         u8 size_code;
14837
14838                         if (type == BPF_WRITE) {
14839                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
14840                                 return -EINVAL;
14841                         }
14842
14843                         size_code = BPF_H;
14844                         if (ctx_field_size == 4)
14845                                 size_code = BPF_W;
14846                         else if (ctx_field_size == 8)
14847                                 size_code = BPF_DW;
14848
14849                         insn->off = off & ~(size_default - 1);
14850                         insn->code = BPF_LDX | BPF_MEM | size_code;
14851                 }
14852
14853                 target_size = 0;
14854                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
14855                                          &target_size);
14856                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
14857                     (ctx_field_size && !target_size)) {
14858                         verbose(env, "bpf verifier is misconfigured\n");
14859                         return -EINVAL;
14860                 }
14861
14862                 if (is_narrower_load && size < target_size) {
14863                         u8 shift = bpf_ctx_narrow_access_offset(
14864                                 off, size, size_default) * 8;
14865                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
14866                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
14867                                 return -EINVAL;
14868                         }
14869                         if (ctx_field_size <= 4) {
14870                                 if (shift)
14871                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
14872                                                                         insn->dst_reg,
14873                                                                         shift);
14874                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
14875                                                                 (1 << size * 8) - 1);
14876                         } else {
14877                                 if (shift)
14878                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
14879                                                                         insn->dst_reg,
14880                                                                         shift);
14881                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
14882                                                                 (1ULL << size * 8) - 1);
14883                         }
14884                 }
14885
14886                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14887                 if (!new_prog)
14888                         return -ENOMEM;
14889
14890                 delta += cnt - 1;
14891
14892                 /* keep walking new program and skip insns we just inserted */
14893                 env->prog = new_prog;
14894                 insn      = new_prog->insnsi + i + delta;
14895         }
14896
14897         return 0;
14898 }
14899
14900 static int jit_subprogs(struct bpf_verifier_env *env)
14901 {
14902         struct bpf_prog *prog = env->prog, **func, *tmp;
14903         int i, j, subprog_start, subprog_end = 0, len, subprog;
14904         struct bpf_map *map_ptr;
14905         struct bpf_insn *insn;
14906         void *old_bpf_func;
14907         int err, num_exentries;
14908
14909         if (env->subprog_cnt <= 1)
14910                 return 0;
14911
14912         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
14913                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
14914                         continue;
14915
14916                 /* Upon error here we cannot fall back to interpreter but
14917                  * need a hard reject of the program. Thus -EFAULT is
14918                  * propagated in any case.
14919                  */
14920                 subprog = find_subprog(env, i + insn->imm + 1);
14921                 if (subprog < 0) {
14922                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
14923                                   i + insn->imm + 1);
14924                         return -EFAULT;
14925                 }
14926                 /* temporarily remember subprog id inside insn instead of
14927                  * aux_data, since next loop will split up all insns into funcs
14928                  */
14929                 insn->off = subprog;
14930                 /* remember original imm in case JIT fails and fallback
14931                  * to interpreter will be needed
14932                  */
14933                 env->insn_aux_data[i].call_imm = insn->imm;
14934                 /* point imm to __bpf_call_base+1 from JITs point of view */
14935                 insn->imm = 1;
14936                 if (bpf_pseudo_func(insn))
14937                         /* jit (e.g. x86_64) may emit fewer instructions
14938                          * if it learns a u32 imm is the same as a u64 imm.
14939                          * Force a non zero here.
14940                          */
14941                         insn[1].imm = 1;
14942         }
14943
14944         err = bpf_prog_alloc_jited_linfo(prog);
14945         if (err)
14946                 goto out_undo_insn;
14947
14948         err = -ENOMEM;
14949         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
14950         if (!func)
14951                 goto out_undo_insn;
14952
14953         for (i = 0; i < env->subprog_cnt; i++) {
14954                 subprog_start = subprog_end;
14955                 subprog_end = env->subprog_info[i + 1].start;
14956
14957                 len = subprog_end - subprog_start;
14958                 /* bpf_prog_run() doesn't call subprogs directly,
14959                  * hence main prog stats include the runtime of subprogs.
14960                  * subprogs don't have IDs and not reachable via prog_get_next_id
14961                  * func[i]->stats will never be accessed and stays NULL
14962                  */
14963                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
14964                 if (!func[i])
14965                         goto out_free;
14966                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
14967                        len * sizeof(struct bpf_insn));
14968                 func[i]->type = prog->type;
14969                 func[i]->len = len;
14970                 if (bpf_prog_calc_tag(func[i]))
14971                         goto out_free;
14972                 func[i]->is_func = 1;
14973                 func[i]->aux->func_idx = i;
14974                 /* Below members will be freed only at prog->aux */
14975                 func[i]->aux->btf = prog->aux->btf;
14976                 func[i]->aux->func_info = prog->aux->func_info;
14977                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
14978                 func[i]->aux->poke_tab = prog->aux->poke_tab;
14979                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
14980
14981                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
14982                         struct bpf_jit_poke_descriptor *poke;
14983
14984                         poke = &prog->aux->poke_tab[j];
14985                         if (poke->insn_idx < subprog_end &&
14986                             poke->insn_idx >= subprog_start)
14987                                 poke->aux = func[i]->aux;
14988                 }
14989
14990                 func[i]->aux->name[0] = 'F';
14991                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
14992                 func[i]->jit_requested = 1;
14993                 func[i]->blinding_requested = prog->blinding_requested;
14994                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
14995                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
14996                 func[i]->aux->linfo = prog->aux->linfo;
14997                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
14998                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
14999                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
15000                 num_exentries = 0;
15001                 insn = func[i]->insnsi;
15002                 for (j = 0; j < func[i]->len; j++, insn++) {
15003                         if (BPF_CLASS(insn->code) == BPF_LDX &&
15004                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
15005                                 num_exentries++;
15006                 }
15007                 func[i]->aux->num_exentries = num_exentries;
15008                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
15009                 func[i] = bpf_int_jit_compile(func[i]);
15010                 if (!func[i]->jited) {
15011                         err = -ENOTSUPP;
15012                         goto out_free;
15013                 }
15014                 cond_resched();
15015         }
15016
15017         /* at this point all bpf functions were successfully JITed
15018          * now populate all bpf_calls with correct addresses and
15019          * run last pass of JIT
15020          */
15021         for (i = 0; i < env->subprog_cnt; i++) {
15022                 insn = func[i]->insnsi;
15023                 for (j = 0; j < func[i]->len; j++, insn++) {
15024                         if (bpf_pseudo_func(insn)) {
15025                                 subprog = insn->off;
15026                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15027                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15028                                 continue;
15029                         }
15030                         if (!bpf_pseudo_call(insn))
15031                                 continue;
15032                         subprog = insn->off;
15033                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
15034                 }
15035
15036                 /* we use the aux data to keep a list of the start addresses
15037                  * of the JITed images for each function in the program
15038                  *
15039                  * for some architectures, such as powerpc64, the imm field
15040                  * might not be large enough to hold the offset of the start
15041                  * address of the callee's JITed image from __bpf_call_base
15042                  *
15043                  * in such cases, we can lookup the start address of a callee
15044                  * by using its subprog id, available from the off field of
15045                  * the call instruction, as an index for this list
15046                  */
15047                 func[i]->aux->func = func;
15048                 func[i]->aux->func_cnt = env->subprog_cnt;
15049         }
15050         for (i = 0; i < env->subprog_cnt; i++) {
15051                 old_bpf_func = func[i]->bpf_func;
15052                 tmp = bpf_int_jit_compile(func[i]);
15053                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15054                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
15055                         err = -ENOTSUPP;
15056                         goto out_free;
15057                 }
15058                 cond_resched();
15059         }
15060
15061         /* finally lock prog and jit images for all functions and
15062          * populate kallsysm
15063          */
15064         for (i = 0; i < env->subprog_cnt; i++) {
15065                 bpf_prog_lock_ro(func[i]);
15066                 bpf_prog_kallsyms_add(func[i]);
15067         }
15068
15069         /* Last step: make now unused interpreter insns from main
15070          * prog consistent for later dump requests, so they can
15071          * later look the same as if they were interpreted only.
15072          */
15073         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15074                 if (bpf_pseudo_func(insn)) {
15075                         insn[0].imm = env->insn_aux_data[i].call_imm;
15076                         insn[1].imm = insn->off;
15077                         insn->off = 0;
15078                         continue;
15079                 }
15080                 if (!bpf_pseudo_call(insn))
15081                         continue;
15082                 insn->off = env->insn_aux_data[i].call_imm;
15083                 subprog = find_subprog(env, i + insn->off + 1);
15084                 insn->imm = subprog;
15085         }
15086
15087         prog->jited = 1;
15088         prog->bpf_func = func[0]->bpf_func;
15089         prog->jited_len = func[0]->jited_len;
15090         prog->aux->func = func;
15091         prog->aux->func_cnt = env->subprog_cnt;
15092         bpf_prog_jit_attempt_done(prog);
15093         return 0;
15094 out_free:
15095         /* We failed JIT'ing, so at this point we need to unregister poke
15096          * descriptors from subprogs, so that kernel is not attempting to
15097          * patch it anymore as we're freeing the subprog JIT memory.
15098          */
15099         for (i = 0; i < prog->aux->size_poke_tab; i++) {
15100                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15101                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15102         }
15103         /* At this point we're guaranteed that poke descriptors are not
15104          * live anymore. We can just unlink its descriptor table as it's
15105          * released with the main prog.
15106          */
15107         for (i = 0; i < env->subprog_cnt; i++) {
15108                 if (!func[i])
15109                         continue;
15110                 func[i]->aux->poke_tab = NULL;
15111                 bpf_jit_free(func[i]);
15112         }
15113         kfree(func);
15114 out_undo_insn:
15115         /* cleanup main prog to be interpreted */
15116         prog->jit_requested = 0;
15117         prog->blinding_requested = 0;
15118         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
15119                 if (!bpf_pseudo_call(insn))
15120                         continue;
15121                 insn->off = 0;
15122                 insn->imm = env->insn_aux_data[i].call_imm;
15123         }
15124         bpf_prog_jit_attempt_done(prog);
15125         return err;
15126 }
15127
15128 static int fixup_call_args(struct bpf_verifier_env *env)
15129 {
15130 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15131         struct bpf_prog *prog = env->prog;
15132         struct bpf_insn *insn = prog->insnsi;
15133         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
15134         int i, depth;
15135 #endif
15136         int err = 0;
15137
15138         if (env->prog->jit_requested &&
15139             !bpf_prog_is_dev_bound(env->prog->aux)) {
15140                 err = jit_subprogs(env);
15141                 if (err == 0)
15142                         return 0;
15143                 if (err == -EFAULT)
15144                         return err;
15145         }
15146 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
15147         if (has_kfunc_call) {
15148                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15149                 return -EINVAL;
15150         }
15151         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15152                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
15153                  * have to be rejected, since interpreter doesn't support them yet.
15154                  */
15155                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15156                 return -EINVAL;
15157         }
15158         for (i = 0; i < prog->len; i++, insn++) {
15159                 if (bpf_pseudo_func(insn)) {
15160                         /* When JIT fails the progs with callback calls
15161                          * have to be rejected, since interpreter doesn't support them yet.
15162                          */
15163                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
15164                         return -EINVAL;
15165                 }
15166
15167                 if (!bpf_pseudo_call(insn))
15168                         continue;
15169                 depth = get_callee_stack_depth(env, insn, i);
15170                 if (depth < 0)
15171                         return depth;
15172                 bpf_patch_call_args(insn, depth);
15173         }
15174         err = 0;
15175 #endif
15176         return err;
15177 }
15178
15179 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15180                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
15181 {
15182         const struct bpf_kfunc_desc *desc;
15183
15184         if (!insn->imm) {
15185                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15186                 return -EINVAL;
15187         }
15188
15189         /* insn->imm has the btf func_id. Replace it with
15190          * an address (relative to __bpf_base_call).
15191          */
15192         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15193         if (!desc) {
15194                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15195                         insn->imm);
15196                 return -EFAULT;
15197         }
15198
15199         *cnt = 0;
15200         insn->imm = desc->imm;
15201         if (insn->off)
15202                 return 0;
15203         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15204                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15205                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15206                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
15207
15208                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15209                 insn_buf[1] = addr[0];
15210                 insn_buf[2] = addr[1];
15211                 insn_buf[3] = *insn;
15212                 *cnt = 4;
15213         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15214                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15215                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15216
15217                 insn_buf[0] = addr[0];
15218                 insn_buf[1] = addr[1];
15219                 insn_buf[2] = *insn;
15220                 *cnt = 3;
15221         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15222                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
15223                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15224                 *cnt = 1;
15225         }
15226         return 0;
15227 }
15228
15229 /* Do various post-verification rewrites in a single program pass.
15230  * These rewrites simplify JIT and interpreter implementations.
15231  */
15232 static int do_misc_fixups(struct bpf_verifier_env *env)
15233 {
15234         struct bpf_prog *prog = env->prog;
15235         enum bpf_attach_type eatype = prog->expected_attach_type;
15236         enum bpf_prog_type prog_type = resolve_prog_type(prog);
15237         struct bpf_insn *insn = prog->insnsi;
15238         const struct bpf_func_proto *fn;
15239         const int insn_cnt = prog->len;
15240         const struct bpf_map_ops *ops;
15241         struct bpf_insn_aux_data *aux;
15242         struct bpf_insn insn_buf[16];
15243         struct bpf_prog *new_prog;
15244         struct bpf_map *map_ptr;
15245         int i, ret, cnt, delta = 0;
15246
15247         for (i = 0; i < insn_cnt; i++, insn++) {
15248                 /* Make divide-by-zero exceptions impossible. */
15249                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15250                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15251                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
15252                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
15253                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
15254                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15255                         struct bpf_insn *patchlet;
15256                         struct bpf_insn chk_and_div[] = {
15257                                 /* [R,W]x div 0 -> 0 */
15258                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15259                                              BPF_JNE | BPF_K, insn->src_reg,
15260                                              0, 2, 0),
15261                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15262                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15263                                 *insn,
15264                         };
15265                         struct bpf_insn chk_and_mod[] = {
15266                                 /* [R,W]x mod 0 -> [R,W]x */
15267                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15268                                              BPF_JEQ | BPF_K, insn->src_reg,
15269                                              0, 1 + (is64 ? 0 : 1), 0),
15270                                 *insn,
15271                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15272                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
15273                         };
15274
15275                         patchlet = isdiv ? chk_and_div : chk_and_mod;
15276                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
15277                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
15278
15279                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
15280                         if (!new_prog)
15281                                 return -ENOMEM;
15282
15283                         delta    += cnt - 1;
15284                         env->prog = prog = new_prog;
15285                         insn      = new_prog->insnsi + i + delta;
15286                         continue;
15287                 }
15288
15289                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
15290                 if (BPF_CLASS(insn->code) == BPF_LD &&
15291                     (BPF_MODE(insn->code) == BPF_ABS ||
15292                      BPF_MODE(insn->code) == BPF_IND)) {
15293                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
15294                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15295                                 verbose(env, "bpf verifier is misconfigured\n");
15296                                 return -EINVAL;
15297                         }
15298
15299                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15300                         if (!new_prog)
15301                                 return -ENOMEM;
15302
15303                         delta    += cnt - 1;
15304                         env->prog = prog = new_prog;
15305                         insn      = new_prog->insnsi + i + delta;
15306                         continue;
15307                 }
15308
15309                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
15310                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15311                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15312                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15313                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
15314                         struct bpf_insn *patch = &insn_buf[0];
15315                         bool issrc, isneg, isimm;
15316                         u32 off_reg;
15317
15318                         aux = &env->insn_aux_data[i + delta];
15319                         if (!aux->alu_state ||
15320                             aux->alu_state == BPF_ALU_NON_POINTER)
15321                                 continue;
15322
15323                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15324                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15325                                 BPF_ALU_SANITIZE_SRC;
15326                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
15327
15328                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
15329                         if (isimm) {
15330                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15331                         } else {
15332                                 if (isneg)
15333                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15334                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15335                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15336                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15337                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15338                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15339                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15340                         }
15341                         if (!issrc)
15342                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15343                         insn->src_reg = BPF_REG_AX;
15344                         if (isneg)
15345                                 insn->code = insn->code == code_add ?
15346                                              code_sub : code_add;
15347                         *patch++ = *insn;
15348                         if (issrc && isneg && !isimm)
15349                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15350                         cnt = patch - insn_buf;
15351
15352                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15353                         if (!new_prog)
15354                                 return -ENOMEM;
15355
15356                         delta    += cnt - 1;
15357                         env->prog = prog = new_prog;
15358                         insn      = new_prog->insnsi + i + delta;
15359                         continue;
15360                 }
15361
15362                 if (insn->code != (BPF_JMP | BPF_CALL))
15363                         continue;
15364                 if (insn->src_reg == BPF_PSEUDO_CALL)
15365                         continue;
15366                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15367                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
15368                         if (ret)
15369                                 return ret;
15370                         if (cnt == 0)
15371                                 continue;
15372
15373                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15374                         if (!new_prog)
15375                                 return -ENOMEM;
15376
15377                         delta    += cnt - 1;
15378                         env->prog = prog = new_prog;
15379                         insn      = new_prog->insnsi + i + delta;
15380                         continue;
15381                 }
15382
15383                 if (insn->imm == BPF_FUNC_get_route_realm)
15384                         prog->dst_needed = 1;
15385                 if (insn->imm == BPF_FUNC_get_prandom_u32)
15386                         bpf_user_rnd_init_once();
15387                 if (insn->imm == BPF_FUNC_override_return)
15388                         prog->kprobe_override = 1;
15389                 if (insn->imm == BPF_FUNC_tail_call) {
15390                         /* If we tail call into other programs, we
15391                          * cannot make any assumptions since they can
15392                          * be replaced dynamically during runtime in
15393                          * the program array.
15394                          */
15395                         prog->cb_access = 1;
15396                         if (!allow_tail_call_in_subprogs(env))
15397                                 prog->aux->stack_depth = MAX_BPF_STACK;
15398                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
15399
15400                         /* mark bpf_tail_call as different opcode to avoid
15401                          * conditional branch in the interpreter for every normal
15402                          * call and to prevent accidental JITing by JIT compiler
15403                          * that doesn't support bpf_tail_call yet
15404                          */
15405                         insn->imm = 0;
15406                         insn->code = BPF_JMP | BPF_TAIL_CALL;
15407
15408                         aux = &env->insn_aux_data[i + delta];
15409                         if (env->bpf_capable && !prog->blinding_requested &&
15410                             prog->jit_requested &&
15411                             !bpf_map_key_poisoned(aux) &&
15412                             !bpf_map_ptr_poisoned(aux) &&
15413                             !bpf_map_ptr_unpriv(aux)) {
15414                                 struct bpf_jit_poke_descriptor desc = {
15415                                         .reason = BPF_POKE_REASON_TAIL_CALL,
15416                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15417                                         .tail_call.key = bpf_map_key_immediate(aux),
15418                                         .insn_idx = i + delta,
15419                                 };
15420
15421                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
15422                                 if (ret < 0) {
15423                                         verbose(env, "adding tail call poke descriptor failed\n");
15424                                         return ret;
15425                                 }
15426
15427                                 insn->imm = ret + 1;
15428                                 continue;
15429                         }
15430
15431                         if (!bpf_map_ptr_unpriv(aux))
15432                                 continue;
15433
15434                         /* instead of changing every JIT dealing with tail_call
15435                          * emit two extra insns:
15436                          * if (index >= max_entries) goto out;
15437                          * index &= array->index_mask;
15438                          * to avoid out-of-bounds cpu speculation
15439                          */
15440                         if (bpf_map_ptr_poisoned(aux)) {
15441                                 verbose(env, "tail_call abusing map_ptr\n");
15442                                 return -EINVAL;
15443                         }
15444
15445                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15446                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15447                                                   map_ptr->max_entries, 2);
15448                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15449                                                     container_of(map_ptr,
15450                                                                  struct bpf_array,
15451                                                                  map)->index_mask);
15452                         insn_buf[2] = *insn;
15453                         cnt = 3;
15454                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15455                         if (!new_prog)
15456                                 return -ENOMEM;
15457
15458                         delta    += cnt - 1;
15459                         env->prog = prog = new_prog;
15460                         insn      = new_prog->insnsi + i + delta;
15461                         continue;
15462                 }
15463
15464                 if (insn->imm == BPF_FUNC_timer_set_callback) {
15465                         /* The verifier will process callback_fn as many times as necessary
15466                          * with different maps and the register states prepared by
15467                          * set_timer_callback_state will be accurate.
15468                          *
15469                          * The following use case is valid:
15470                          *   map1 is shared by prog1, prog2, prog3.
15471                          *   prog1 calls bpf_timer_init for some map1 elements
15472                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
15473                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
15474                          *   prog3 calls bpf_timer_start for some map1 elements.
15475                          *     Those that were not both bpf_timer_init-ed and
15476                          *     bpf_timer_set_callback-ed will return -EINVAL.
15477                          */
15478                         struct bpf_insn ld_addrs[2] = {
15479                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15480                         };
15481
15482                         insn_buf[0] = ld_addrs[0];
15483                         insn_buf[1] = ld_addrs[1];
15484                         insn_buf[2] = *insn;
15485                         cnt = 3;
15486
15487                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15488                         if (!new_prog)
15489                                 return -ENOMEM;
15490
15491                         delta    += cnt - 1;
15492                         env->prog = prog = new_prog;
15493                         insn      = new_prog->insnsi + i + delta;
15494                         goto patch_call_imm;
15495                 }
15496
15497                 if (insn->imm == BPF_FUNC_task_storage_get ||
15498                     insn->imm == BPF_FUNC_sk_storage_get ||
15499                     insn->imm == BPF_FUNC_inode_storage_get ||
15500                     insn->imm == BPF_FUNC_cgrp_storage_get) {
15501                         if (env->prog->aux->sleepable)
15502                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
15503                         else
15504                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
15505                         insn_buf[1] = *insn;
15506                         cnt = 2;
15507
15508                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15509                         if (!new_prog)
15510                                 return -ENOMEM;
15511
15512                         delta += cnt - 1;
15513                         env->prog = prog = new_prog;
15514                         insn = new_prog->insnsi + i + delta;
15515                         goto patch_call_imm;
15516                 }
15517
15518                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
15519                  * and other inlining handlers are currently limited to 64 bit
15520                  * only.
15521                  */
15522                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15523                     (insn->imm == BPF_FUNC_map_lookup_elem ||
15524                      insn->imm == BPF_FUNC_map_update_elem ||
15525                      insn->imm == BPF_FUNC_map_delete_elem ||
15526                      insn->imm == BPF_FUNC_map_push_elem   ||
15527                      insn->imm == BPF_FUNC_map_pop_elem    ||
15528                      insn->imm == BPF_FUNC_map_peek_elem   ||
15529                      insn->imm == BPF_FUNC_redirect_map    ||
15530                      insn->imm == BPF_FUNC_for_each_map_elem ||
15531                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
15532                         aux = &env->insn_aux_data[i + delta];
15533                         if (bpf_map_ptr_poisoned(aux))
15534                                 goto patch_call_imm;
15535
15536                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
15537                         ops = map_ptr->ops;
15538                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
15539                             ops->map_gen_lookup) {
15540                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
15541                                 if (cnt == -EOPNOTSUPP)
15542                                         goto patch_map_ops_generic;
15543                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15544                                         verbose(env, "bpf verifier is misconfigured\n");
15545                                         return -EINVAL;
15546                                 }
15547
15548                                 new_prog = bpf_patch_insn_data(env, i + delta,
15549                                                                insn_buf, cnt);
15550                                 if (!new_prog)
15551                                         return -ENOMEM;
15552
15553                                 delta    += cnt - 1;
15554                                 env->prog = prog = new_prog;
15555                                 insn      = new_prog->insnsi + i + delta;
15556                                 continue;
15557                         }
15558
15559                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15560                                      (void *(*)(struct bpf_map *map, void *key))NULL));
15561                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15562                                      (int (*)(struct bpf_map *map, void *key))NULL));
15563                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15564                                      (int (*)(struct bpf_map *map, void *key, void *value,
15565                                               u64 flags))NULL));
15566                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15567                                      (int (*)(struct bpf_map *map, void *value,
15568                                               u64 flags))NULL));
15569                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15570                                      (int (*)(struct bpf_map *map, void *value))NULL));
15571                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15572                                      (int (*)(struct bpf_map *map, void *value))NULL));
15573                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
15574                                      (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
15575                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15576                                      (int (*)(struct bpf_map *map,
15577                                               bpf_callback_t callback_fn,
15578                                               void *callback_ctx,
15579                                               u64 flags))NULL));
15580                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15581                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
15582
15583 patch_map_ops_generic:
15584                         switch (insn->imm) {
15585                         case BPF_FUNC_map_lookup_elem:
15586                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
15587                                 continue;
15588                         case BPF_FUNC_map_update_elem:
15589                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
15590                                 continue;
15591                         case BPF_FUNC_map_delete_elem:
15592                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
15593                                 continue;
15594                         case BPF_FUNC_map_push_elem:
15595                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
15596                                 continue;
15597                         case BPF_FUNC_map_pop_elem:
15598                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
15599                                 continue;
15600                         case BPF_FUNC_map_peek_elem:
15601                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
15602                                 continue;
15603                         case BPF_FUNC_redirect_map:
15604                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
15605                                 continue;
15606                         case BPF_FUNC_for_each_map_elem:
15607                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
15608                                 continue;
15609                         case BPF_FUNC_map_lookup_percpu_elem:
15610                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15611                                 continue;
15612                         }
15613
15614                         goto patch_call_imm;
15615                 }
15616
15617                 /* Implement bpf_jiffies64 inline. */
15618                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15619                     insn->imm == BPF_FUNC_jiffies64) {
15620                         struct bpf_insn ld_jiffies_addr[2] = {
15621                                 BPF_LD_IMM64(BPF_REG_0,
15622                                              (unsigned long)&jiffies),
15623                         };
15624
15625                         insn_buf[0] = ld_jiffies_addr[0];
15626                         insn_buf[1] = ld_jiffies_addr[1];
15627                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15628                                                   BPF_REG_0, 0);
15629                         cnt = 3;
15630
15631                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15632                                                        cnt);
15633                         if (!new_prog)
15634                                 return -ENOMEM;
15635
15636                         delta    += cnt - 1;
15637                         env->prog = prog = new_prog;
15638                         insn      = new_prog->insnsi + i + delta;
15639                         continue;
15640                 }
15641
15642                 /* Implement bpf_get_func_arg inline. */
15643                 if (prog_type == BPF_PROG_TYPE_TRACING &&
15644                     insn->imm == BPF_FUNC_get_func_arg) {
15645                         /* Load nr_args from ctx - 8 */
15646                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15647                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15648                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15649                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15650                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15651                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15652                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15653                         insn_buf[7] = BPF_JMP_A(1);
15654                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15655                         cnt = 9;
15656
15657                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15658                         if (!new_prog)
15659                                 return -ENOMEM;
15660
15661                         delta    += cnt - 1;
15662                         env->prog = prog = new_prog;
15663                         insn      = new_prog->insnsi + i + delta;
15664                         continue;
15665                 }
15666
15667                 /* Implement bpf_get_func_ret inline. */
15668                 if (prog_type == BPF_PROG_TYPE_TRACING &&
15669                     insn->imm == BPF_FUNC_get_func_ret) {
15670                         if (eatype == BPF_TRACE_FEXIT ||
15671                             eatype == BPF_MODIFY_RETURN) {
15672                                 /* Load nr_args from ctx - 8 */
15673                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15674                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15675                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15676                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15677                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15678                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15679                                 cnt = 6;
15680                         } else {
15681                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15682                                 cnt = 1;
15683                         }
15684
15685                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15686                         if (!new_prog)
15687                                 return -ENOMEM;
15688
15689                         delta    += cnt - 1;
15690                         env->prog = prog = new_prog;
15691                         insn      = new_prog->insnsi + i + delta;
15692                         continue;
15693                 }
15694
15695                 /* Implement get_func_arg_cnt inline. */
15696                 if (prog_type == BPF_PROG_TYPE_TRACING &&
15697                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
15698                         /* Load nr_args from ctx - 8 */
15699                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15700
15701                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15702                         if (!new_prog)
15703                                 return -ENOMEM;
15704
15705                         env->prog = prog = new_prog;
15706                         insn      = new_prog->insnsi + i + delta;
15707                         continue;
15708                 }
15709
15710                 /* Implement bpf_get_func_ip inline. */
15711                 if (prog_type == BPF_PROG_TYPE_TRACING &&
15712                     insn->imm == BPF_FUNC_get_func_ip) {
15713                         /* Load IP address from ctx - 16 */
15714                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
15715
15716                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15717                         if (!new_prog)
15718                                 return -ENOMEM;
15719
15720                         env->prog = prog = new_prog;
15721                         insn      = new_prog->insnsi + i + delta;
15722                         continue;
15723                 }
15724
15725 patch_call_imm:
15726                 fn = env->ops->get_func_proto(insn->imm, env->prog);
15727                 /* all functions that have prototype and verifier allowed
15728                  * programs to call them, must be real in-kernel functions
15729                  */
15730                 if (!fn->func) {
15731                         verbose(env,
15732                                 "kernel subsystem misconfigured func %s#%d\n",
15733                                 func_id_name(insn->imm), insn->imm);
15734                         return -EFAULT;
15735                 }
15736                 insn->imm = fn->func - __bpf_call_base;
15737         }
15738
15739         /* Since poke tab is now finalized, publish aux to tracker. */
15740         for (i = 0; i < prog->aux->size_poke_tab; i++) {
15741                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15742                 if (!map_ptr->ops->map_poke_track ||
15743                     !map_ptr->ops->map_poke_untrack ||
15744                     !map_ptr->ops->map_poke_run) {
15745                         verbose(env, "bpf verifier is misconfigured\n");
15746                         return -EINVAL;
15747                 }
15748
15749                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
15750                 if (ret < 0) {
15751                         verbose(env, "tracking tail call prog failed\n");
15752                         return ret;
15753                 }
15754         }
15755
15756         sort_kfunc_descs_by_imm(env->prog);
15757
15758         return 0;
15759 }
15760
15761 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
15762                                         int position,
15763                                         s32 stack_base,
15764                                         u32 callback_subprogno,
15765                                         u32 *cnt)
15766 {
15767         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
15768         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
15769         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
15770         int reg_loop_max = BPF_REG_6;
15771         int reg_loop_cnt = BPF_REG_7;
15772         int reg_loop_ctx = BPF_REG_8;
15773
15774         struct bpf_prog *new_prog;
15775         u32 callback_start;
15776         u32 call_insn_offset;
15777         s32 callback_offset;
15778
15779         /* This represents an inlined version of bpf_iter.c:bpf_loop,
15780          * be careful to modify this code in sync.
15781          */
15782         struct bpf_insn insn_buf[] = {
15783                 /* Return error and jump to the end of the patch if
15784                  * expected number of iterations is too big.
15785                  */
15786                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
15787                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
15788                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
15789                 /* spill R6, R7, R8 to use these as loop vars */
15790                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
15791                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
15792                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
15793                 /* initialize loop vars */
15794                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
15795                 BPF_MOV32_IMM(reg_loop_cnt, 0),
15796                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
15797                 /* loop header,
15798                  * if reg_loop_cnt >= reg_loop_max skip the loop body
15799                  */
15800                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
15801                 /* callback call,
15802                  * correct callback offset would be set after patching
15803                  */
15804                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
15805                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
15806                 BPF_CALL_REL(0),
15807                 /* increment loop counter */
15808                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
15809                 /* jump to loop header if callback returned 0 */
15810                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
15811                 /* return value of bpf_loop,
15812                  * set R0 to the number of iterations
15813                  */
15814                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
15815                 /* restore original values of R6, R7, R8 */
15816                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
15817                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
15818                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
15819         };
15820
15821         *cnt = ARRAY_SIZE(insn_buf);
15822         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
15823         if (!new_prog)
15824                 return new_prog;
15825
15826         /* callback start is known only after patching */
15827         callback_start = env->subprog_info[callback_subprogno].start;
15828         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
15829         call_insn_offset = position + 12;
15830         callback_offset = callback_start - call_insn_offset - 1;
15831         new_prog->insnsi[call_insn_offset].imm = callback_offset;
15832
15833         return new_prog;
15834 }
15835
15836 static bool is_bpf_loop_call(struct bpf_insn *insn)
15837 {
15838         return insn->code == (BPF_JMP | BPF_CALL) &&
15839                 insn->src_reg == 0 &&
15840                 insn->imm == BPF_FUNC_loop;
15841 }
15842
15843 /* For all sub-programs in the program (including main) check
15844  * insn_aux_data to see if there are bpf_loop calls that require
15845  * inlining. If such calls are found the calls are replaced with a
15846  * sequence of instructions produced by `inline_bpf_loop` function and
15847  * subprog stack_depth is increased by the size of 3 registers.
15848  * This stack space is used to spill values of the R6, R7, R8.  These
15849  * registers are used to store the loop bound, counter and context
15850  * variables.
15851  */
15852 static int optimize_bpf_loop(struct bpf_verifier_env *env)
15853 {
15854         struct bpf_subprog_info *subprogs = env->subprog_info;
15855         int i, cur_subprog = 0, cnt, delta = 0;
15856         struct bpf_insn *insn = env->prog->insnsi;
15857         int insn_cnt = env->prog->len;
15858         u16 stack_depth = subprogs[cur_subprog].stack_depth;
15859         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15860         u16 stack_depth_extra = 0;
15861
15862         for (i = 0; i < insn_cnt; i++, insn++) {
15863                 struct bpf_loop_inline_state *inline_state =
15864                         &env->insn_aux_data[i + delta].loop_inline_state;
15865
15866                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
15867                         struct bpf_prog *new_prog;
15868
15869                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
15870                         new_prog = inline_bpf_loop(env,
15871                                                    i + delta,
15872                                                    -(stack_depth + stack_depth_extra),
15873                                                    inline_state->callback_subprogno,
15874                                                    &cnt);
15875                         if (!new_prog)
15876                                 return -ENOMEM;
15877
15878                         delta     += cnt - 1;
15879                         env->prog  = new_prog;
15880                         insn       = new_prog->insnsi + i + delta;
15881                 }
15882
15883                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
15884                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
15885                         cur_subprog++;
15886                         stack_depth = subprogs[cur_subprog].stack_depth;
15887                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15888                         stack_depth_extra = 0;
15889                 }
15890         }
15891
15892         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
15893
15894         return 0;
15895 }
15896
15897 static void free_states(struct bpf_verifier_env *env)
15898 {
15899         struct bpf_verifier_state_list *sl, *sln;
15900         int i;
15901
15902         sl = env->free_list;
15903         while (sl) {
15904                 sln = sl->next;
15905                 free_verifier_state(&sl->state, false);
15906                 kfree(sl);
15907                 sl = sln;
15908         }
15909         env->free_list = NULL;
15910
15911         if (!env->explored_states)
15912                 return;
15913
15914         for (i = 0; i < state_htab_size(env); i++) {
15915                 sl = env->explored_states[i];
15916
15917                 while (sl) {
15918                         sln = sl->next;
15919                         free_verifier_state(&sl->state, false);
15920                         kfree(sl);
15921                         sl = sln;
15922                 }
15923                 env->explored_states[i] = NULL;
15924         }
15925 }
15926
15927 static int do_check_common(struct bpf_verifier_env *env, int subprog)
15928 {
15929         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15930         struct bpf_verifier_state *state;
15931         struct bpf_reg_state *regs;
15932         int ret, i;
15933
15934         env->prev_linfo = NULL;
15935         env->pass_cnt++;
15936
15937         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
15938         if (!state)
15939                 return -ENOMEM;
15940         state->curframe = 0;
15941         state->speculative = false;
15942         state->branches = 1;
15943         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
15944         if (!state->frame[0]) {
15945                 kfree(state);
15946                 return -ENOMEM;
15947         }
15948         env->cur_state = state;
15949         init_func_state(env, state->frame[0],
15950                         BPF_MAIN_FUNC /* callsite */,
15951                         0 /* frameno */,
15952                         subprog);
15953         state->first_insn_idx = env->subprog_info[subprog].start;
15954         state->last_insn_idx = -1;
15955
15956         regs = state->frame[state->curframe]->regs;
15957         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
15958                 ret = btf_prepare_func_args(env, subprog, regs);
15959                 if (ret)
15960                         goto out;
15961                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
15962                         if (regs[i].type == PTR_TO_CTX)
15963                                 mark_reg_known_zero(env, regs, i);
15964                         else if (regs[i].type == SCALAR_VALUE)
15965                                 mark_reg_unknown(env, regs, i);
15966                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
15967                                 const u32 mem_size = regs[i].mem_size;
15968
15969                                 mark_reg_known_zero(env, regs, i);
15970                                 regs[i].mem_size = mem_size;
15971                                 regs[i].id = ++env->id_gen;
15972                         }
15973                 }
15974         } else {
15975                 /* 1st arg to a function */
15976                 regs[BPF_REG_1].type = PTR_TO_CTX;
15977                 mark_reg_known_zero(env, regs, BPF_REG_1);
15978                 ret = btf_check_subprog_arg_match(env, subprog, regs);
15979                 if (ret == -EFAULT)
15980                         /* unlikely verifier bug. abort.
15981                          * ret == 0 and ret < 0 are sadly acceptable for
15982                          * main() function due to backward compatibility.
15983                          * Like socket filter program may be written as:
15984                          * int bpf_prog(struct pt_regs *ctx)
15985                          * and never dereference that ctx in the program.
15986                          * 'struct pt_regs' is a type mismatch for socket
15987                          * filter that should be using 'struct __sk_buff'.
15988                          */
15989                         goto out;
15990         }
15991
15992         ret = do_check(env);
15993 out:
15994         /* check for NULL is necessary, since cur_state can be freed inside
15995          * do_check() under memory pressure.
15996          */
15997         if (env->cur_state) {
15998                 free_verifier_state(env->cur_state, true);
15999                 env->cur_state = NULL;
16000         }
16001         while (!pop_stack(env, NULL, NULL, false));
16002         if (!ret && pop_log)
16003                 bpf_vlog_reset(&env->log, 0);
16004         free_states(env);
16005         return ret;
16006 }
16007
16008 /* Verify all global functions in a BPF program one by one based on their BTF.
16009  * All global functions must pass verification. Otherwise the whole program is rejected.
16010  * Consider:
16011  * int bar(int);
16012  * int foo(int f)
16013  * {
16014  *    return bar(f);
16015  * }
16016  * int bar(int b)
16017  * {
16018  *    ...
16019  * }
16020  * foo() will be verified first for R1=any_scalar_value. During verification it
16021  * will be assumed that bar() already verified successfully and call to bar()
16022  * from foo() will be checked for type match only. Later bar() will be verified
16023  * independently to check that it's safe for R1=any_scalar_value.
16024  */
16025 static int do_check_subprogs(struct bpf_verifier_env *env)
16026 {
16027         struct bpf_prog_aux *aux = env->prog->aux;
16028         int i, ret;
16029
16030         if (!aux->func_info)
16031                 return 0;
16032
16033         for (i = 1; i < env->subprog_cnt; i++) {
16034                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16035                         continue;
16036                 env->insn_idx = env->subprog_info[i].start;
16037                 WARN_ON_ONCE(env->insn_idx == 0);
16038                 ret = do_check_common(env, i);
16039                 if (ret) {
16040                         return ret;
16041                 } else if (env->log.level & BPF_LOG_LEVEL) {
16042                         verbose(env,
16043                                 "Func#%d is safe for any args that match its prototype\n",
16044                                 i);
16045                 }
16046         }
16047         return 0;
16048 }
16049
16050 static int do_check_main(struct bpf_verifier_env *env)
16051 {
16052         int ret;
16053
16054         env->insn_idx = 0;
16055         ret = do_check_common(env, 0);
16056         if (!ret)
16057                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16058         return ret;
16059 }
16060
16061
16062 static void print_verification_stats(struct bpf_verifier_env *env)
16063 {
16064         int i;
16065
16066         if (env->log.level & BPF_LOG_STATS) {
16067                 verbose(env, "verification time %lld usec\n",
16068                         div_u64(env->verification_time, 1000));
16069                 verbose(env, "stack depth ");
16070                 for (i = 0; i < env->subprog_cnt; i++) {
16071                         u32 depth = env->subprog_info[i].stack_depth;
16072
16073                         verbose(env, "%d", depth);
16074                         if (i + 1 < env->subprog_cnt)
16075                                 verbose(env, "+");
16076                 }
16077                 verbose(env, "\n");
16078         }
16079         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16080                 "total_states %d peak_states %d mark_read %d\n",
16081                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16082                 env->max_states_per_insn, env->total_states,
16083                 env->peak_states, env->longest_mark_read_walk);
16084 }
16085
16086 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16087 {
16088         const struct btf_type *t, *func_proto;
16089         const struct bpf_struct_ops *st_ops;
16090         const struct btf_member *member;
16091         struct bpf_prog *prog = env->prog;
16092         u32 btf_id, member_idx;
16093         const char *mname;
16094
16095         if (!prog->gpl_compatible) {
16096                 verbose(env, "struct ops programs must have a GPL compatible license\n");
16097                 return -EINVAL;
16098         }
16099
16100         btf_id = prog->aux->attach_btf_id;
16101         st_ops = bpf_struct_ops_find(btf_id);
16102         if (!st_ops) {
16103                 verbose(env, "attach_btf_id %u is not a supported struct\n",
16104                         btf_id);
16105                 return -ENOTSUPP;
16106         }
16107
16108         t = st_ops->type;
16109         member_idx = prog->expected_attach_type;
16110         if (member_idx >= btf_type_vlen(t)) {
16111                 verbose(env, "attach to invalid member idx %u of struct %s\n",
16112                         member_idx, st_ops->name);
16113                 return -EINVAL;
16114         }
16115
16116         member = &btf_type_member(t)[member_idx];
16117         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16118         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16119                                                NULL);
16120         if (!func_proto) {
16121                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16122                         mname, member_idx, st_ops->name);
16123                 return -EINVAL;
16124         }
16125
16126         if (st_ops->check_member) {
16127                 int err = st_ops->check_member(t, member);
16128
16129                 if (err) {
16130                         verbose(env, "attach to unsupported member %s of struct %s\n",
16131                                 mname, st_ops->name);
16132                         return err;
16133                 }
16134         }
16135
16136         prog->aux->attach_func_proto = func_proto;
16137         prog->aux->attach_func_name = mname;
16138         env->ops = st_ops->verifier_ops;
16139
16140         return 0;
16141 }
16142 #define SECURITY_PREFIX "security_"
16143
16144 static int check_attach_modify_return(unsigned long addr, const char *func_name)
16145 {
16146         if (within_error_injection_list(addr) ||
16147             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
16148                 return 0;
16149
16150         return -EINVAL;
16151 }
16152
16153 /* list of non-sleepable functions that are otherwise on
16154  * ALLOW_ERROR_INJECTION list
16155  */
16156 BTF_SET_START(btf_non_sleepable_error_inject)
16157 /* Three functions below can be called from sleepable and non-sleepable context.
16158  * Assume non-sleepable from bpf safety point of view.
16159  */
16160 BTF_ID(func, __filemap_add_folio)
16161 BTF_ID(func, should_fail_alloc_page)
16162 BTF_ID(func, should_failslab)
16163 BTF_SET_END(btf_non_sleepable_error_inject)
16164
16165 static int check_non_sleepable_error_inject(u32 btf_id)
16166 {
16167         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16168 }
16169
16170 int bpf_check_attach_target(struct bpf_verifier_log *log,
16171                             const struct bpf_prog *prog,
16172                             const struct bpf_prog *tgt_prog,
16173                             u32 btf_id,
16174                             struct bpf_attach_target_info *tgt_info)
16175 {
16176         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
16177         const char prefix[] = "btf_trace_";
16178         int ret = 0, subprog = -1, i;
16179         const struct btf_type *t;
16180         bool conservative = true;
16181         const char *tname;
16182         struct btf *btf;
16183         long addr = 0;
16184
16185         if (!btf_id) {
16186                 bpf_log(log, "Tracing programs must provide btf_id\n");
16187                 return -EINVAL;
16188         }
16189         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
16190         if (!btf) {
16191                 bpf_log(log,
16192                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16193                 return -EINVAL;
16194         }
16195         t = btf_type_by_id(btf, btf_id);
16196         if (!t) {
16197                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
16198                 return -EINVAL;
16199         }
16200         tname = btf_name_by_offset(btf, t->name_off);
16201         if (!tname) {
16202                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
16203                 return -EINVAL;
16204         }
16205         if (tgt_prog) {
16206                 struct bpf_prog_aux *aux = tgt_prog->aux;
16207
16208                 for (i = 0; i < aux->func_info_cnt; i++)
16209                         if (aux->func_info[i].type_id == btf_id) {
16210                                 subprog = i;
16211                                 break;
16212                         }
16213                 if (subprog == -1) {
16214                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
16215                         return -EINVAL;
16216                 }
16217                 conservative = aux->func_info_aux[subprog].unreliable;
16218                 if (prog_extension) {
16219                         if (conservative) {
16220                                 bpf_log(log,
16221                                         "Cannot replace static functions\n");
16222                                 return -EINVAL;
16223                         }
16224                         if (!prog->jit_requested) {
16225                                 bpf_log(log,
16226                                         "Extension programs should be JITed\n");
16227                                 return -EINVAL;
16228                         }
16229                 }
16230                 if (!tgt_prog->jited) {
16231                         bpf_log(log, "Can attach to only JITed progs\n");
16232                         return -EINVAL;
16233                 }
16234                 if (tgt_prog->type == prog->type) {
16235                         /* Cannot fentry/fexit another fentry/fexit program.
16236                          * Cannot attach program extension to another extension.
16237                          * It's ok to attach fentry/fexit to extension program.
16238                          */
16239                         bpf_log(log, "Cannot recursively attach\n");
16240                         return -EINVAL;
16241                 }
16242                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16243                     prog_extension &&
16244                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16245                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16246                         /* Program extensions can extend all program types
16247                          * except fentry/fexit. The reason is the following.
16248                          * The fentry/fexit programs are used for performance
16249                          * analysis, stats and can be attached to any program
16250                          * type except themselves. When extension program is
16251                          * replacing XDP function it is necessary to allow
16252                          * performance analysis of all functions. Both original
16253                          * XDP program and its program extension. Hence
16254                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16255                          * allowed. If extending of fentry/fexit was allowed it
16256                          * would be possible to create long call chain
16257                          * fentry->extension->fentry->extension beyond
16258                          * reasonable stack size. Hence extending fentry is not
16259                          * allowed.
16260                          */
16261                         bpf_log(log, "Cannot extend fentry/fexit\n");
16262                         return -EINVAL;
16263                 }
16264         } else {
16265                 if (prog_extension) {
16266                         bpf_log(log, "Cannot replace kernel functions\n");
16267                         return -EINVAL;
16268                 }
16269         }
16270
16271         switch (prog->expected_attach_type) {
16272         case BPF_TRACE_RAW_TP:
16273                 if (tgt_prog) {
16274                         bpf_log(log,
16275                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16276                         return -EINVAL;
16277                 }
16278                 if (!btf_type_is_typedef(t)) {
16279                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
16280                                 btf_id);
16281                         return -EINVAL;
16282                 }
16283                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
16284                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
16285                                 btf_id, tname);
16286                         return -EINVAL;
16287                 }
16288                 tname += sizeof(prefix) - 1;
16289                 t = btf_type_by_id(btf, t->type);
16290                 if (!btf_type_is_ptr(t))
16291                         /* should never happen in valid vmlinux build */
16292                         return -EINVAL;
16293                 t = btf_type_by_id(btf, t->type);
16294                 if (!btf_type_is_func_proto(t))
16295                         /* should never happen in valid vmlinux build */
16296                         return -EINVAL;
16297
16298                 break;
16299         case BPF_TRACE_ITER:
16300                 if (!btf_type_is_func(t)) {
16301                         bpf_log(log, "attach_btf_id %u is not a function\n",
16302                                 btf_id);
16303                         return -EINVAL;
16304                 }
16305                 t = btf_type_by_id(btf, t->type);
16306                 if (!btf_type_is_func_proto(t))
16307                         return -EINVAL;
16308                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16309                 if (ret)
16310                         return ret;
16311                 break;
16312         default:
16313                 if (!prog_extension)
16314                         return -EINVAL;
16315                 fallthrough;
16316         case BPF_MODIFY_RETURN:
16317         case BPF_LSM_MAC:
16318         case BPF_LSM_CGROUP:
16319         case BPF_TRACE_FENTRY:
16320         case BPF_TRACE_FEXIT:
16321                 if (!btf_type_is_func(t)) {
16322                         bpf_log(log, "attach_btf_id %u is not a function\n",
16323                                 btf_id);
16324                         return -EINVAL;
16325                 }
16326                 if (prog_extension &&
16327                     btf_check_type_match(log, prog, btf, t))
16328                         return -EINVAL;
16329                 t = btf_type_by_id(btf, t->type);
16330                 if (!btf_type_is_func_proto(t))
16331                         return -EINVAL;
16332
16333                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16334                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16335                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16336                         return -EINVAL;
16337
16338                 if (tgt_prog && conservative)
16339                         t = NULL;
16340
16341                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16342                 if (ret < 0)
16343                         return ret;
16344
16345                 if (tgt_prog) {
16346                         if (subprog == 0)
16347                                 addr = (long) tgt_prog->bpf_func;
16348                         else
16349                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
16350                 } else {
16351                         addr = kallsyms_lookup_name(tname);
16352                         if (!addr) {
16353                                 bpf_log(log,
16354                                         "The address of function %s cannot be found\n",
16355                                         tname);
16356                                 return -ENOENT;
16357                         }
16358                 }
16359
16360                 if (prog->aux->sleepable) {
16361                         ret = -EINVAL;
16362                         switch (prog->type) {
16363                         case BPF_PROG_TYPE_TRACING:
16364                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
16365                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16366                                  */
16367                                 if (!check_non_sleepable_error_inject(btf_id) &&
16368                                     within_error_injection_list(addr))
16369                                         ret = 0;
16370                                 break;
16371                         case BPF_PROG_TYPE_LSM:
16372                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
16373                                  * Only some of them are sleepable.
16374                                  */
16375                                 if (bpf_lsm_is_sleepable_hook(btf_id))
16376                                         ret = 0;
16377                                 break;
16378                         default:
16379                                 break;
16380                         }
16381                         if (ret) {
16382                                 bpf_log(log, "%s is not sleepable\n", tname);
16383                                 return ret;
16384                         }
16385                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
16386                         if (tgt_prog) {
16387                                 bpf_log(log, "can't modify return codes of BPF programs\n");
16388                                 return -EINVAL;
16389                         }
16390                         ret = check_attach_modify_return(addr, tname);
16391                         if (ret) {
16392                                 bpf_log(log, "%s() is not modifiable\n", tname);
16393                                 return ret;
16394                         }
16395                 }
16396
16397                 break;
16398         }
16399         tgt_info->tgt_addr = addr;
16400         tgt_info->tgt_name = tname;
16401         tgt_info->tgt_type = t;
16402         return 0;
16403 }
16404
16405 BTF_SET_START(btf_id_deny)
16406 BTF_ID_UNUSED
16407 #ifdef CONFIG_SMP
16408 BTF_ID(func, migrate_disable)
16409 BTF_ID(func, migrate_enable)
16410 #endif
16411 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16412 BTF_ID(func, rcu_read_unlock_strict)
16413 #endif
16414 BTF_SET_END(btf_id_deny)
16415
16416 static int check_attach_btf_id(struct bpf_verifier_env *env)
16417 {
16418         struct bpf_prog *prog = env->prog;
16419         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
16420         struct bpf_attach_target_info tgt_info = {};
16421         u32 btf_id = prog->aux->attach_btf_id;
16422         struct bpf_trampoline *tr;
16423         int ret;
16424         u64 key;
16425
16426         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16427                 if (prog->aux->sleepable)
16428                         /* attach_btf_id checked to be zero already */
16429                         return 0;
16430                 verbose(env, "Syscall programs can only be sleepable\n");
16431                 return -EINVAL;
16432         }
16433
16434         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
16435             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16436                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
16437                 return -EINVAL;
16438         }
16439
16440         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16441                 return check_struct_ops_btf_id(env);
16442
16443         if (prog->type != BPF_PROG_TYPE_TRACING &&
16444             prog->type != BPF_PROG_TYPE_LSM &&
16445             prog->type != BPF_PROG_TYPE_EXT)
16446                 return 0;
16447
16448         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16449         if (ret)
16450                 return ret;
16451
16452         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
16453                 /* to make freplace equivalent to their targets, they need to
16454                  * inherit env->ops and expected_attach_type for the rest of the
16455                  * verification
16456                  */
16457                 env->ops = bpf_verifier_ops[tgt_prog->type];
16458                 prog->expected_attach_type = tgt_prog->expected_attach_type;
16459         }
16460
16461         /* store info about the attachment target that will be used later */
16462         prog->aux->attach_func_proto = tgt_info.tgt_type;
16463         prog->aux->attach_func_name = tgt_info.tgt_name;
16464
16465         if (tgt_prog) {
16466                 prog->aux->saved_dst_prog_type = tgt_prog->type;
16467                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16468         }
16469
16470         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16471                 prog->aux->attach_btf_trace = true;
16472                 return 0;
16473         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16474                 if (!bpf_iter_prog_supported(prog))
16475                         return -EINVAL;
16476                 return 0;
16477         }
16478
16479         if (prog->type == BPF_PROG_TYPE_LSM) {
16480                 ret = bpf_lsm_verify_prog(&env->log, prog);
16481                 if (ret < 0)
16482                         return ret;
16483         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
16484                    btf_id_set_contains(&btf_id_deny, btf_id)) {
16485                 return -EINVAL;
16486         }
16487
16488         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
16489         tr = bpf_trampoline_get(key, &tgt_info);
16490         if (!tr)
16491                 return -ENOMEM;
16492
16493         prog->aux->dst_trampoline = tr;
16494         return 0;
16495 }
16496
16497 struct btf *bpf_get_btf_vmlinux(void)
16498 {
16499         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16500                 mutex_lock(&bpf_verifier_lock);
16501                 if (!btf_vmlinux)
16502                         btf_vmlinux = btf_parse_vmlinux();
16503                 mutex_unlock(&bpf_verifier_lock);
16504         }
16505         return btf_vmlinux;
16506 }
16507
16508 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
16509 {
16510         u64 start_time = ktime_get_ns();
16511         struct bpf_verifier_env *env;
16512         struct bpf_verifier_log *log;
16513         int i, len, ret = -EINVAL;
16514         bool is_priv;
16515
16516         /* no program is valid */
16517         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16518                 return -EINVAL;
16519
16520         /* 'struct bpf_verifier_env' can be global, but since it's not small,
16521          * allocate/free it every time bpf_check() is called
16522          */
16523         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
16524         if (!env)
16525                 return -ENOMEM;
16526         log = &env->log;
16527
16528         len = (*prog)->len;
16529         env->insn_aux_data =
16530                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
16531         ret = -ENOMEM;
16532         if (!env->insn_aux_data)
16533                 goto err_free_env;
16534         for (i = 0; i < len; i++)
16535                 env->insn_aux_data[i].orig_idx = i;
16536         env->prog = *prog;
16537         env->ops = bpf_verifier_ops[env->prog->type];
16538         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
16539         is_priv = bpf_capable();
16540
16541         bpf_get_btf_vmlinux();
16542
16543         /* grab the mutex to protect few globals used by verifier */
16544         if (!is_priv)
16545                 mutex_lock(&bpf_verifier_lock);
16546
16547         if (attr->log_level || attr->log_buf || attr->log_size) {
16548                 /* user requested verbose verifier output
16549                  * and supplied buffer to store the verification trace
16550                  */
16551                 log->level = attr->log_level;
16552                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16553                 log->len_total = attr->log_size;
16554
16555                 /* log attributes have to be sane */
16556                 if (!bpf_verifier_log_attr_valid(log)) {
16557                         ret = -EINVAL;
16558                         goto err_unlock;
16559                 }
16560         }
16561
16562         mark_verifier_state_clean(env);
16563
16564         if (IS_ERR(btf_vmlinux)) {
16565                 /* Either gcc or pahole or kernel are broken. */
16566                 verbose(env, "in-kernel BTF is malformed\n");
16567                 ret = PTR_ERR(btf_vmlinux);
16568                 goto skip_full_check;
16569         }
16570
16571         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16572         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
16573                 env->strict_alignment = true;
16574         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16575                 env->strict_alignment = false;
16576
16577         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
16578         env->allow_uninit_stack = bpf_allow_uninit_stack();
16579         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
16580         env->bypass_spec_v1 = bpf_bypass_spec_v1();
16581         env->bypass_spec_v4 = bpf_bypass_spec_v4();
16582         env->bpf_capable = bpf_capable();
16583
16584         if (is_priv)
16585                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16586
16587         env->explored_states = kvcalloc(state_htab_size(env),
16588                                        sizeof(struct bpf_verifier_state_list *),
16589                                        GFP_USER);
16590         ret = -ENOMEM;
16591         if (!env->explored_states)
16592                 goto skip_full_check;
16593
16594         ret = add_subprog_and_kfunc(env);
16595         if (ret < 0)
16596                 goto skip_full_check;
16597
16598         ret = check_subprogs(env);
16599         if (ret < 0)
16600                 goto skip_full_check;
16601
16602         ret = check_btf_info(env, attr, uattr);
16603         if (ret < 0)
16604                 goto skip_full_check;
16605
16606         ret = check_attach_btf_id(env);
16607         if (ret)
16608                 goto skip_full_check;
16609
16610         ret = resolve_pseudo_ldimm64(env);
16611         if (ret < 0)
16612                 goto skip_full_check;
16613
16614         if (bpf_prog_is_dev_bound(env->prog->aux)) {
16615                 ret = bpf_prog_offload_verifier_prep(env->prog);
16616                 if (ret)
16617                         goto skip_full_check;
16618         }
16619
16620         ret = check_cfg(env);
16621         if (ret < 0)
16622                 goto skip_full_check;
16623
16624         ret = do_check_subprogs(env);
16625         ret = ret ?: do_check_main(env);
16626
16627         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16628                 ret = bpf_prog_offload_finalize(env);
16629
16630 skip_full_check:
16631         kvfree(env->explored_states);
16632
16633         if (ret == 0)
16634                 ret = check_max_stack_depth(env);
16635
16636         /* instruction rewrites happen after this point */
16637         if (ret == 0)
16638                 ret = optimize_bpf_loop(env);
16639
16640         if (is_priv) {
16641                 if (ret == 0)
16642                         opt_hard_wire_dead_code_branches(env);
16643                 if (ret == 0)
16644                         ret = opt_remove_dead_code(env);
16645                 if (ret == 0)
16646                         ret = opt_remove_nops(env);
16647         } else {
16648                 if (ret == 0)
16649                         sanitize_dead_code(env);
16650         }
16651
16652         if (ret == 0)
16653                 /* program is valid, convert *(u32*)(ctx + off) accesses */
16654                 ret = convert_ctx_accesses(env);
16655
16656         if (ret == 0)
16657                 ret = do_misc_fixups(env);
16658
16659         /* do 32-bit optimization after insn patching has done so those patched
16660          * insns could be handled correctly.
16661          */
16662         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16663                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16664                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16665                                                                      : false;
16666         }
16667
16668         if (ret == 0)
16669                 ret = fixup_call_args(env);
16670
16671         env->verification_time = ktime_get_ns() - start_time;
16672         print_verification_stats(env);
16673         env->prog->aux->verified_insns = env->insn_processed;
16674
16675         if (log->level && bpf_verifier_log_full(log))
16676                 ret = -ENOSPC;
16677         if (log->level && !log->ubuf) {
16678                 ret = -EFAULT;
16679                 goto err_release_maps;
16680         }
16681
16682         if (ret)
16683                 goto err_release_maps;
16684
16685         if (env->used_map_cnt) {
16686                 /* if program passed verifier, update used_maps in bpf_prog_info */
16687                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
16688                                                           sizeof(env->used_maps[0]),
16689                                                           GFP_KERNEL);
16690
16691                 if (!env->prog->aux->used_maps) {
16692                         ret = -ENOMEM;
16693                         goto err_release_maps;
16694                 }
16695
16696                 memcpy(env->prog->aux->used_maps, env->used_maps,
16697                        sizeof(env->used_maps[0]) * env->used_map_cnt);
16698                 env->prog->aux->used_map_cnt = env->used_map_cnt;
16699         }
16700         if (env->used_btf_cnt) {
16701                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
16702                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
16703                                                           sizeof(env->used_btfs[0]),
16704                                                           GFP_KERNEL);
16705                 if (!env->prog->aux->used_btfs) {
16706                         ret = -ENOMEM;
16707                         goto err_release_maps;
16708                 }
16709
16710                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
16711                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
16712                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
16713         }
16714         if (env->used_map_cnt || env->used_btf_cnt) {
16715                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
16716                  * bpf_ld_imm64 instructions
16717                  */
16718                 convert_pseudo_ld_imm64(env);
16719         }
16720
16721         adjust_btf_func(env);
16722
16723 err_release_maps:
16724         if (!env->prog->aux->used_maps)
16725                 /* if we didn't copy map pointers into bpf_prog_info, release
16726                  * them now. Otherwise free_used_maps() will release them.
16727                  */
16728                 release_maps(env);
16729         if (!env->prog->aux->used_btfs)
16730                 release_btfs(env);
16731
16732         /* extension progs temporarily inherit the attach_type of their targets
16733            for verification purposes, so set it back to zero before returning
16734          */
16735         if (env->prog->type == BPF_PROG_TYPE_EXT)
16736                 env->prog->expected_attach_type = 0;
16737
16738         *prog = env->prog;
16739 err_unlock:
16740         if (!is_priv)
16741                 mutex_unlock(&bpf_verifier_lock);
16742         vfree(env->insn_aux_data);
16743 err_free_env:
16744         kfree(env);
16745         return ret;
16746 }