GNU Linux-libre 5.4.257-gnu1
[releases.git] / kernel / bpf / core.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Linux Socket Filter - Kernel level socket filtering
4  *
5  * Based on the design of the Berkeley Packet Filter. The new
6  * internal format has been designed by PLUMgrid:
7  *
8  *      Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
9  *
10  * Authors:
11  *
12  *      Jay Schulist <jschlst@samba.org>
13  *      Alexei Starovoitov <ast@plumgrid.com>
14  *      Daniel Borkmann <dborkman@redhat.com>
15  *
16  * Andi Kleen - Fix a few bad bugs and races.
17  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
18  */
19
20 #include <uapi/linux/btf.h>
21 #include <linux/filter.h>
22 #include <linux/skbuff.h>
23 #include <linux/vmalloc.h>
24 #include <linux/random.h>
25 #include <linux/moduleloader.h>
26 #include <linux/bpf.h>
27 #include <linux/btf.h>
28 #include <linux/frame.h>
29 #include <linux/rbtree_latch.h>
30 #include <linux/kallsyms.h>
31 #include <linux/rcupdate.h>
32 #include <linux/perf_event.h>
33 #include <linux/nospec.h>
34
35 #include <asm/barrier.h>
36 #include <asm/unaligned.h>
37
38 /* Registers */
39 #define BPF_R0  regs[BPF_REG_0]
40 #define BPF_R1  regs[BPF_REG_1]
41 #define BPF_R2  regs[BPF_REG_2]
42 #define BPF_R3  regs[BPF_REG_3]
43 #define BPF_R4  regs[BPF_REG_4]
44 #define BPF_R5  regs[BPF_REG_5]
45 #define BPF_R6  regs[BPF_REG_6]
46 #define BPF_R7  regs[BPF_REG_7]
47 #define BPF_R8  regs[BPF_REG_8]
48 #define BPF_R9  regs[BPF_REG_9]
49 #define BPF_R10 regs[BPF_REG_10]
50
51 /* Named registers */
52 #define DST     regs[insn->dst_reg]
53 #define SRC     regs[insn->src_reg]
54 #define FP      regs[BPF_REG_FP]
55 #define AX      regs[BPF_REG_AX]
56 #define ARG1    regs[BPF_REG_ARG1]
57 #define CTX     regs[BPF_REG_CTX]
58 #define IMM     insn->imm
59
60 /* No hurry in this branch
61  *
62  * Exported for the bpf jit load helper.
63  */
64 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
65 {
66         u8 *ptr = NULL;
67
68         if (k >= SKF_NET_OFF) {
69                 ptr = skb_network_header(skb) + k - SKF_NET_OFF;
70         } else if (k >= SKF_LL_OFF) {
71                 if (unlikely(!skb_mac_header_was_set(skb)))
72                         return NULL;
73                 ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
74         }
75         if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
76                 return ptr;
77
78         return NULL;
79 }
80
81 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
82 {
83         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
84         struct bpf_prog_aux *aux;
85         struct bpf_prog *fp;
86
87         size = round_up(size, PAGE_SIZE);
88         fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
89         if (fp == NULL)
90                 return NULL;
91
92         aux = kzalloc(sizeof(*aux), GFP_KERNEL | gfp_extra_flags);
93         if (aux == NULL) {
94                 vfree(fp);
95                 return NULL;
96         }
97
98         fp->pages = size / PAGE_SIZE;
99         fp->aux = aux;
100         fp->aux->prog = fp;
101         fp->jit_requested = ebpf_jit_enabled();
102
103         INIT_LIST_HEAD_RCU(&fp->aux->ksym_lnode);
104
105         return fp;
106 }
107
108 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
109 {
110         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
111         struct bpf_prog *prog;
112         int cpu;
113
114         prog = bpf_prog_alloc_no_stats(size, gfp_extra_flags);
115         if (!prog)
116                 return NULL;
117
118         prog->aux->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags);
119         if (!prog->aux->stats) {
120                 kfree(prog->aux);
121                 vfree(prog);
122                 return NULL;
123         }
124
125         for_each_possible_cpu(cpu) {
126                 struct bpf_prog_stats *pstats;
127
128                 pstats = per_cpu_ptr(prog->aux->stats, cpu);
129                 u64_stats_init(&pstats->syncp);
130         }
131         return prog;
132 }
133 EXPORT_SYMBOL_GPL(bpf_prog_alloc);
134
135 int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog)
136 {
137         if (!prog->aux->nr_linfo || !prog->jit_requested)
138                 return 0;
139
140         prog->aux->jited_linfo = kcalloc(prog->aux->nr_linfo,
141                                          sizeof(*prog->aux->jited_linfo),
142                                          GFP_KERNEL | __GFP_NOWARN);
143         if (!prog->aux->jited_linfo)
144                 return -ENOMEM;
145
146         return 0;
147 }
148
149 void bpf_prog_free_jited_linfo(struct bpf_prog *prog)
150 {
151         kfree(prog->aux->jited_linfo);
152         prog->aux->jited_linfo = NULL;
153 }
154
155 void bpf_prog_free_unused_jited_linfo(struct bpf_prog *prog)
156 {
157         if (prog->aux->jited_linfo && !prog->aux->jited_linfo[0])
158                 bpf_prog_free_jited_linfo(prog);
159 }
160
161 /* The jit engine is responsible to provide an array
162  * for insn_off to the jited_off mapping (insn_to_jit_off).
163  *
164  * The idx to this array is the insn_off.  Hence, the insn_off
165  * here is relative to the prog itself instead of the main prog.
166  * This array has one entry for each xlated bpf insn.
167  *
168  * jited_off is the byte off to the last byte of the jited insn.
169  *
170  * Hence, with
171  * insn_start:
172  *      The first bpf insn off of the prog.  The insn off
173  *      here is relative to the main prog.
174  *      e.g. if prog is a subprog, insn_start > 0
175  * linfo_idx:
176  *      The prog's idx to prog->aux->linfo and jited_linfo
177  *
178  * jited_linfo[linfo_idx] = prog->bpf_func
179  *
180  * For i > linfo_idx,
181  *
182  * jited_linfo[i] = prog->bpf_func +
183  *      insn_to_jit_off[linfo[i].insn_off - insn_start - 1]
184  */
185 void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
186                                const u32 *insn_to_jit_off)
187 {
188         u32 linfo_idx, insn_start, insn_end, nr_linfo, i;
189         const struct bpf_line_info *linfo;
190         void **jited_linfo;
191
192         if (!prog->aux->jited_linfo)
193                 /* Userspace did not provide linfo */
194                 return;
195
196         linfo_idx = prog->aux->linfo_idx;
197         linfo = &prog->aux->linfo[linfo_idx];
198         insn_start = linfo[0].insn_off;
199         insn_end = insn_start + prog->len;
200
201         jited_linfo = &prog->aux->jited_linfo[linfo_idx];
202         jited_linfo[0] = prog->bpf_func;
203
204         nr_linfo = prog->aux->nr_linfo - linfo_idx;
205
206         for (i = 1; i < nr_linfo && linfo[i].insn_off < insn_end; i++)
207                 /* The verifier ensures that linfo[i].insn_off is
208                  * strictly increasing
209                  */
210                 jited_linfo[i] = prog->bpf_func +
211                         insn_to_jit_off[linfo[i].insn_off - insn_start - 1];
212 }
213
214 void bpf_prog_free_linfo(struct bpf_prog *prog)
215 {
216         bpf_prog_free_jited_linfo(prog);
217         kvfree(prog->aux->linfo);
218 }
219
220 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
221                                   gfp_t gfp_extra_flags)
222 {
223         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
224         struct bpf_prog *fp;
225         u32 pages, delta;
226         int ret;
227
228         BUG_ON(fp_old == NULL);
229
230         size = round_up(size, PAGE_SIZE);
231         pages = size / PAGE_SIZE;
232         if (pages <= fp_old->pages)
233                 return fp_old;
234
235         delta = pages - fp_old->pages;
236         ret = __bpf_prog_charge(fp_old->aux->user, delta);
237         if (ret)
238                 return NULL;
239
240         fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
241         if (fp == NULL) {
242                 __bpf_prog_uncharge(fp_old->aux->user, delta);
243         } else {
244                 memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
245                 fp->pages = pages;
246                 fp->aux->prog = fp;
247
248                 /* We keep fp->aux from fp_old around in the new
249                  * reallocated structure.
250                  */
251                 fp_old->aux = NULL;
252                 __bpf_prog_free(fp_old);
253         }
254
255         return fp;
256 }
257
258 void __bpf_prog_free(struct bpf_prog *fp)
259 {
260         if (fp->aux) {
261                 free_percpu(fp->aux->stats);
262                 kfree(fp->aux);
263         }
264         vfree(fp);
265 }
266
267 int bpf_prog_calc_tag(struct bpf_prog *fp)
268 {
269         const u32 bits_offset = SHA_MESSAGE_BYTES - sizeof(__be64);
270         u32 raw_size = bpf_prog_tag_scratch_size(fp);
271         u32 digest[SHA_DIGEST_WORDS];
272         u32 ws[SHA_WORKSPACE_WORDS];
273         u32 i, bsize, psize, blocks;
274         struct bpf_insn *dst;
275         bool was_ld_map;
276         u8 *raw, *todo;
277         __be32 *result;
278         __be64 *bits;
279
280         raw = vmalloc(raw_size);
281         if (!raw)
282                 return -ENOMEM;
283
284         sha_init(digest);
285         memset(ws, 0, sizeof(ws));
286
287         /* We need to take out the map fd for the digest calculation
288          * since they are unstable from user space side.
289          */
290         dst = (void *)raw;
291         for (i = 0, was_ld_map = false; i < fp->len; i++) {
292                 dst[i] = fp->insnsi[i];
293                 if (!was_ld_map &&
294                     dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
295                     (dst[i].src_reg == BPF_PSEUDO_MAP_FD ||
296                      dst[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
297                         was_ld_map = true;
298                         dst[i].imm = 0;
299                 } else if (was_ld_map &&
300                            dst[i].code == 0 &&
301                            dst[i].dst_reg == 0 &&
302                            dst[i].src_reg == 0 &&
303                            dst[i].off == 0) {
304                         was_ld_map = false;
305                         dst[i].imm = 0;
306                 } else {
307                         was_ld_map = false;
308                 }
309         }
310
311         psize = bpf_prog_insn_size(fp);
312         memset(&raw[psize], 0, raw_size - psize);
313         raw[psize++] = 0x80;
314
315         bsize  = round_up(psize, SHA_MESSAGE_BYTES);
316         blocks = bsize / SHA_MESSAGE_BYTES;
317         todo   = raw;
318         if (bsize - psize >= sizeof(__be64)) {
319                 bits = (__be64 *)(todo + bsize - sizeof(__be64));
320         } else {
321                 bits = (__be64 *)(todo + bsize + bits_offset);
322                 blocks++;
323         }
324         *bits = cpu_to_be64((psize - 1) << 3);
325
326         while (blocks--) {
327                 sha_transform(digest, todo, ws);
328                 todo += SHA_MESSAGE_BYTES;
329         }
330
331         result = (__force __be32 *)digest;
332         for (i = 0; i < SHA_DIGEST_WORDS; i++)
333                 result[i] = cpu_to_be32(digest[i]);
334         memcpy(fp->tag, result, sizeof(fp->tag));
335
336         vfree(raw);
337         return 0;
338 }
339
340 static int bpf_adj_delta_to_imm(struct bpf_insn *insn, u32 pos, s32 end_old,
341                                 s32 end_new, s32 curr, const bool probe_pass)
342 {
343         const s64 imm_min = S32_MIN, imm_max = S32_MAX;
344         s32 delta = end_new - end_old;
345         s64 imm = insn->imm;
346
347         if (curr < pos && curr + imm + 1 >= end_old)
348                 imm += delta;
349         else if (curr >= end_new && curr + imm + 1 < end_new)
350                 imm -= delta;
351         if (imm < imm_min || imm > imm_max)
352                 return -ERANGE;
353         if (!probe_pass)
354                 insn->imm = imm;
355         return 0;
356 }
357
358 static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old,
359                                 s32 end_new, s32 curr, const bool probe_pass)
360 {
361         const s32 off_min = S16_MIN, off_max = S16_MAX;
362         s32 delta = end_new - end_old;
363         s32 off = insn->off;
364
365         if (curr < pos && curr + off + 1 >= end_old)
366                 off += delta;
367         else if (curr >= end_new && curr + off + 1 < end_new)
368                 off -= delta;
369         if (off < off_min || off > off_max)
370                 return -ERANGE;
371         if (!probe_pass)
372                 insn->off = off;
373         return 0;
374 }
375
376 static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, s32 end_old,
377                             s32 end_new, const bool probe_pass)
378 {
379         u32 i, insn_cnt = prog->len + (probe_pass ? end_new - end_old : 0);
380         struct bpf_insn *insn = prog->insnsi;
381         int ret = 0;
382
383         for (i = 0; i < insn_cnt; i++, insn++) {
384                 u8 code;
385
386                 /* In the probing pass we still operate on the original,
387                  * unpatched image in order to check overflows before we
388                  * do any other adjustments. Therefore skip the patchlet.
389                  */
390                 if (probe_pass && i == pos) {
391                         i = end_new;
392                         insn = prog->insnsi + end_old;
393                 }
394                 code = insn->code;
395                 if ((BPF_CLASS(code) != BPF_JMP &&
396                      BPF_CLASS(code) != BPF_JMP32) ||
397                     BPF_OP(code) == BPF_EXIT)
398                         continue;
399                 /* Adjust offset of jmps if we cross patch boundaries. */
400                 if (BPF_OP(code) == BPF_CALL) {
401                         if (insn->src_reg != BPF_PSEUDO_CALL)
402                                 continue;
403                         ret = bpf_adj_delta_to_imm(insn, pos, end_old,
404                                                    end_new, i, probe_pass);
405                 } else {
406                         ret = bpf_adj_delta_to_off(insn, pos, end_old,
407                                                    end_new, i, probe_pass);
408                 }
409                 if (ret)
410                         break;
411         }
412
413         return ret;
414 }
415
416 static void bpf_adj_linfo(struct bpf_prog *prog, u32 off, u32 delta)
417 {
418         struct bpf_line_info *linfo;
419         u32 i, nr_linfo;
420
421         nr_linfo = prog->aux->nr_linfo;
422         if (!nr_linfo || !delta)
423                 return;
424
425         linfo = prog->aux->linfo;
426
427         for (i = 0; i < nr_linfo; i++)
428                 if (off < linfo[i].insn_off)
429                         break;
430
431         /* Push all off < linfo[i].insn_off by delta */
432         for (; i < nr_linfo; i++)
433                 linfo[i].insn_off += delta;
434 }
435
436 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
437                                        const struct bpf_insn *patch, u32 len)
438 {
439         u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
440         const u32 cnt_max = S16_MAX;
441         struct bpf_prog *prog_adj;
442         int err;
443
444         /* Since our patchlet doesn't expand the image, we're done. */
445         if (insn_delta == 0) {
446                 memcpy(prog->insnsi + off, patch, sizeof(*patch));
447                 return prog;
448         }
449
450         insn_adj_cnt = prog->len + insn_delta;
451
452         /* Reject anything that would potentially let the insn->off
453          * target overflow when we have excessive program expansions.
454          * We need to probe here before we do any reallocation where
455          * we afterwards may not fail anymore.
456          */
457         if (insn_adj_cnt > cnt_max &&
458             (err = bpf_adj_branches(prog, off, off + 1, off + len, true)))
459                 return ERR_PTR(err);
460
461         /* Several new instructions need to be inserted. Make room
462          * for them. Likely, there's no need for a new allocation as
463          * last page could have large enough tailroom.
464          */
465         prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
466                                     GFP_USER);
467         if (!prog_adj)
468                 return ERR_PTR(-ENOMEM);
469
470         prog_adj->len = insn_adj_cnt;
471
472         /* Patching happens in 3 steps:
473          *
474          * 1) Move over tail of insnsi from next instruction onwards,
475          *    so we can patch the single target insn with one or more
476          *    new ones (patching is always from 1 to n insns, n > 0).
477          * 2) Inject new instructions at the target location.
478          * 3) Adjust branch offsets if necessary.
479          */
480         insn_rest = insn_adj_cnt - off - len;
481
482         memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
483                 sizeof(*patch) * insn_rest);
484         memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
485
486         /* We are guaranteed to not fail at this point, otherwise
487          * the ship has sailed to reverse to the original state. An
488          * overflow cannot happen at this point.
489          */
490         BUG_ON(bpf_adj_branches(prog_adj, off, off + 1, off + len, false));
491
492         bpf_adj_linfo(prog_adj, off, insn_delta);
493
494         return prog_adj;
495 }
496
497 int bpf_remove_insns(struct bpf_prog *prog, u32 off, u32 cnt)
498 {
499         /* Branch offsets can't overflow when program is shrinking, no need
500          * to call bpf_adj_branches(..., true) here
501          */
502         memmove(prog->insnsi + off, prog->insnsi + off + cnt,
503                 sizeof(struct bpf_insn) * (prog->len - off - cnt));
504         prog->len -= cnt;
505
506         return WARN_ON_ONCE(bpf_adj_branches(prog, off, off + cnt, off, false));
507 }
508
509 static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp)
510 {
511         int i;
512
513         for (i = 0; i < fp->aux->func_cnt; i++)
514                 bpf_prog_kallsyms_del(fp->aux->func[i]);
515 }
516
517 void bpf_prog_kallsyms_del_all(struct bpf_prog *fp)
518 {
519         bpf_prog_kallsyms_del_subprogs(fp);
520         bpf_prog_kallsyms_del(fp);
521 }
522
523 #ifdef CONFIG_BPF_JIT
524 /* All BPF JIT sysctl knobs here. */
525 int bpf_jit_enable   __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_ALWAYS_ON);
526 int bpf_jit_harden   __read_mostly;
527 int bpf_jit_kallsyms __read_mostly;
528 long bpf_jit_limit   __read_mostly;
529 long bpf_jit_limit_max __read_mostly;
530
531 static __always_inline void
532 bpf_get_prog_addr_region(const struct bpf_prog *prog,
533                          unsigned long *symbol_start,
534                          unsigned long *symbol_end)
535 {
536         const struct bpf_binary_header *hdr = bpf_jit_binary_hdr(prog);
537         unsigned long addr = (unsigned long)hdr;
538
539         WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
540
541         *symbol_start = addr;
542         *symbol_end   = addr + hdr->pages * PAGE_SIZE;
543 }
544
545 void bpf_get_prog_name(const struct bpf_prog *prog, char *sym)
546 {
547         const char *end = sym + KSYM_NAME_LEN;
548         const struct btf_type *type;
549         const char *func_name;
550
551         BUILD_BUG_ON(sizeof("bpf_prog_") +
552                      sizeof(prog->tag) * 2 +
553                      /* name has been null terminated.
554                       * We should need +1 for the '_' preceding
555                       * the name.  However, the null character
556                       * is double counted between the name and the
557                       * sizeof("bpf_prog_") above, so we omit
558                       * the +1 here.
559                       */
560                      sizeof(prog->aux->name) > KSYM_NAME_LEN);
561
562         sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
563         sym  = bin2hex(sym, prog->tag, sizeof(prog->tag));
564
565         /* prog->aux->name will be ignored if full btf name is available */
566         if (prog->aux->func_info_cnt) {
567                 type = btf_type_by_id(prog->aux->btf,
568                                       prog->aux->func_info[prog->aux->func_idx].type_id);
569                 func_name = btf_name_by_offset(prog->aux->btf, type->name_off);
570                 snprintf(sym, (size_t)(end - sym), "_%s", func_name);
571                 return;
572         }
573
574         if (prog->aux->name[0])
575                 snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
576         else
577                 *sym = 0;
578 }
579
580 static __always_inline unsigned long
581 bpf_get_prog_addr_start(struct latch_tree_node *n)
582 {
583         unsigned long symbol_start, symbol_end;
584         const struct bpf_prog_aux *aux;
585
586         aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
587         bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
588
589         return symbol_start;
590 }
591
592 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
593                                           struct latch_tree_node *b)
594 {
595         return bpf_get_prog_addr_start(a) < bpf_get_prog_addr_start(b);
596 }
597
598 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
599 {
600         unsigned long val = (unsigned long)key;
601         unsigned long symbol_start, symbol_end;
602         const struct bpf_prog_aux *aux;
603
604         aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
605         bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
606
607         if (val < symbol_start)
608                 return -1;
609         if (val >= symbol_end)
610                 return  1;
611
612         return 0;
613 }
614
615 static const struct latch_tree_ops bpf_tree_ops = {
616         .less   = bpf_tree_less,
617         .comp   = bpf_tree_comp,
618 };
619
620 static DEFINE_SPINLOCK(bpf_lock);
621 static LIST_HEAD(bpf_kallsyms);
622 static struct latch_tree_root bpf_tree __cacheline_aligned;
623
624 static void bpf_prog_ksym_node_add(struct bpf_prog_aux *aux)
625 {
626         WARN_ON_ONCE(!list_empty(&aux->ksym_lnode));
627         list_add_tail_rcu(&aux->ksym_lnode, &bpf_kallsyms);
628         latch_tree_insert(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
629 }
630
631 static void bpf_prog_ksym_node_del(struct bpf_prog_aux *aux)
632 {
633         if (list_empty(&aux->ksym_lnode))
634                 return;
635
636         latch_tree_erase(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
637         list_del_rcu(&aux->ksym_lnode);
638 }
639
640 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
641 {
642         return fp->jited && !bpf_prog_was_classic(fp);
643 }
644
645 static bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
646 {
647         return list_empty(&fp->aux->ksym_lnode) ||
648                fp->aux->ksym_lnode.prev == LIST_POISON2;
649 }
650
651 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
652 {
653         if (!bpf_prog_kallsyms_candidate(fp) ||
654             !capable(CAP_SYS_ADMIN))
655                 return;
656
657         spin_lock_bh(&bpf_lock);
658         bpf_prog_ksym_node_add(fp->aux);
659         spin_unlock_bh(&bpf_lock);
660 }
661
662 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
663 {
664         if (!bpf_prog_kallsyms_candidate(fp))
665                 return;
666
667         spin_lock_bh(&bpf_lock);
668         bpf_prog_ksym_node_del(fp->aux);
669         spin_unlock_bh(&bpf_lock);
670 }
671
672 static struct bpf_prog *bpf_prog_kallsyms_find(unsigned long addr)
673 {
674         struct latch_tree_node *n;
675
676         if (!bpf_jit_kallsyms_enabled())
677                 return NULL;
678
679         n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
680         return n ?
681                container_of(n, struct bpf_prog_aux, ksym_tnode)->prog :
682                NULL;
683 }
684
685 const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
686                                  unsigned long *off, char *sym)
687 {
688         unsigned long symbol_start, symbol_end;
689         struct bpf_prog *prog;
690         char *ret = NULL;
691
692         rcu_read_lock();
693         prog = bpf_prog_kallsyms_find(addr);
694         if (prog) {
695                 bpf_get_prog_addr_region(prog, &symbol_start, &symbol_end);
696                 bpf_get_prog_name(prog, sym);
697
698                 ret = sym;
699                 if (size)
700                         *size = symbol_end - symbol_start;
701                 if (off)
702                         *off  = addr - symbol_start;
703         }
704         rcu_read_unlock();
705
706         return ret;
707 }
708
709 bool is_bpf_text_address(unsigned long addr)
710 {
711         bool ret;
712
713         rcu_read_lock();
714         ret = bpf_prog_kallsyms_find(addr) != NULL;
715         rcu_read_unlock();
716
717         return ret;
718 }
719
720 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
721                     char *sym)
722 {
723         struct bpf_prog_aux *aux;
724         unsigned int it = 0;
725         int ret = -ERANGE;
726
727         if (!bpf_jit_kallsyms_enabled())
728                 return ret;
729
730         rcu_read_lock();
731         list_for_each_entry_rcu(aux, &bpf_kallsyms, ksym_lnode) {
732                 if (it++ != symnum)
733                         continue;
734
735                 bpf_get_prog_name(aux->prog, sym);
736
737                 *value = (unsigned long)aux->prog->bpf_func;
738                 *type  = BPF_SYM_ELF_TYPE;
739
740                 ret = 0;
741                 break;
742         }
743         rcu_read_unlock();
744
745         return ret;
746 }
747
748 static atomic_long_t bpf_jit_current;
749
750 /* Can be overridden by an arch's JIT compiler if it has a custom,
751  * dedicated BPF backend memory area, or if neither of the two
752  * below apply.
753  */
754 u64 __weak bpf_jit_alloc_exec_limit(void)
755 {
756 #if defined(MODULES_VADDR)
757         return MODULES_END - MODULES_VADDR;
758 #else
759         return VMALLOC_END - VMALLOC_START;
760 #endif
761 }
762
763 static int __init bpf_jit_charge_init(void)
764 {
765         /* Only used as heuristic here to derive limit. */
766         bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
767         bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 1,
768                                             PAGE_SIZE), LONG_MAX);
769         return 0;
770 }
771 pure_initcall(bpf_jit_charge_init);
772
773 static int bpf_jit_charge_modmem(u32 pages)
774 {
775         if (atomic_long_add_return(pages, &bpf_jit_current) >
776             (bpf_jit_limit >> PAGE_SHIFT)) {
777                 if (!capable(CAP_SYS_ADMIN)) {
778                         atomic_long_sub(pages, &bpf_jit_current);
779                         return -EPERM;
780                 }
781         }
782
783         return 0;
784 }
785
786 static void bpf_jit_uncharge_modmem(u32 pages)
787 {
788         atomic_long_sub(pages, &bpf_jit_current);
789 }
790
791 void *__weak bpf_jit_alloc_exec(unsigned long size)
792 {
793         return module_alloc(size);
794 }
795
796 void __weak bpf_jit_free_exec(void *addr)
797 {
798         module_memfree(addr);
799 }
800
801 struct bpf_binary_header *
802 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
803                      unsigned int alignment,
804                      bpf_jit_fill_hole_t bpf_fill_ill_insns)
805 {
806         struct bpf_binary_header *hdr;
807         u32 size, hole, start, pages;
808
809         /* Most of BPF filters are really small, but if some of them
810          * fill a page, allow at least 128 extra bytes to insert a
811          * random section of illegal instructions.
812          */
813         size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
814         pages = size / PAGE_SIZE;
815
816         if (bpf_jit_charge_modmem(pages))
817                 return NULL;
818         hdr = bpf_jit_alloc_exec(size);
819         if (!hdr) {
820                 bpf_jit_uncharge_modmem(pages);
821                 return NULL;
822         }
823
824         /* Fill space with illegal/arch-dep instructions. */
825         bpf_fill_ill_insns(hdr, size);
826
827         hdr->pages = pages;
828         hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
829                      PAGE_SIZE - sizeof(*hdr));
830         start = (get_random_int() % hole) & ~(alignment - 1);
831
832         /* Leave a random number of instructions before BPF code. */
833         *image_ptr = &hdr->image[start];
834
835         return hdr;
836 }
837
838 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
839 {
840         u32 pages = hdr->pages;
841
842         bpf_jit_free_exec(hdr);
843         bpf_jit_uncharge_modmem(pages);
844 }
845
846 /* This symbol is only overridden by archs that have different
847  * requirements than the usual eBPF JITs, f.e. when they only
848  * implement cBPF JIT, do not set images read-only, etc.
849  */
850 void __weak bpf_jit_free(struct bpf_prog *fp)
851 {
852         if (fp->jited) {
853                 struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
854
855                 bpf_jit_binary_free(hdr);
856
857                 WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
858         }
859
860         bpf_prog_unlock_free(fp);
861 }
862
863 int bpf_jit_get_func_addr(const struct bpf_prog *prog,
864                           const struct bpf_insn *insn, bool extra_pass,
865                           u64 *func_addr, bool *func_addr_fixed)
866 {
867         s16 off = insn->off;
868         s32 imm = insn->imm;
869         u8 *addr;
870
871         *func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL;
872         if (!*func_addr_fixed) {
873                 /* Place-holder address till the last pass has collected
874                  * all addresses for JITed subprograms in which case we
875                  * can pick them up from prog->aux.
876                  */
877                 if (!extra_pass)
878                         addr = NULL;
879                 else if (prog->aux->func &&
880                          off >= 0 && off < prog->aux->func_cnt)
881                         addr = (u8 *)prog->aux->func[off]->bpf_func;
882                 else
883                         return -EINVAL;
884         } else {
885                 /* Address of a BPF helper call. Since part of the core
886                  * kernel, it's always at a fixed location. __bpf_call_base
887                  * and the helper with imm relative to it are both in core
888                  * kernel.
889                  */
890                 addr = (u8 *)__bpf_call_base + imm;
891         }
892
893         *func_addr = (unsigned long)addr;
894         return 0;
895 }
896
897 static int bpf_jit_blind_insn(const struct bpf_insn *from,
898                               const struct bpf_insn *aux,
899                               struct bpf_insn *to_buff,
900                               bool emit_zext)
901 {
902         struct bpf_insn *to = to_buff;
903         u32 imm_rnd = get_random_int();
904         s16 off;
905
906         BUILD_BUG_ON(BPF_REG_AX  + 1 != MAX_BPF_JIT_REG);
907         BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
908
909         /* Constraints on AX register:
910          *
911          * AX register is inaccessible from user space. It is mapped in
912          * all JITs, and used here for constant blinding rewrites. It is
913          * typically "stateless" meaning its contents are only valid within
914          * the executed instruction, but not across several instructions.
915          * There are a few exceptions however which are further detailed
916          * below.
917          *
918          * Constant blinding is only used by JITs, not in the interpreter.
919          * The interpreter uses AX in some occasions as a local temporary
920          * register e.g. in DIV or MOD instructions.
921          *
922          * In restricted circumstances, the verifier can also use the AX
923          * register for rewrites as long as they do not interfere with
924          * the above cases!
925          */
926         if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
927                 goto out;
928
929         if (from->imm == 0 &&
930             (from->code == (BPF_ALU   | BPF_MOV | BPF_K) ||
931              from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
932                 *to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
933                 goto out;
934         }
935
936         switch (from->code) {
937         case BPF_ALU | BPF_ADD | BPF_K:
938         case BPF_ALU | BPF_SUB | BPF_K:
939         case BPF_ALU | BPF_AND | BPF_K:
940         case BPF_ALU | BPF_OR  | BPF_K:
941         case BPF_ALU | BPF_XOR | BPF_K:
942         case BPF_ALU | BPF_MUL | BPF_K:
943         case BPF_ALU | BPF_MOV | BPF_K:
944         case BPF_ALU | BPF_DIV | BPF_K:
945         case BPF_ALU | BPF_MOD | BPF_K:
946                 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
947                 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
948                 *to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
949                 break;
950
951         case BPF_ALU64 | BPF_ADD | BPF_K:
952         case BPF_ALU64 | BPF_SUB | BPF_K:
953         case BPF_ALU64 | BPF_AND | BPF_K:
954         case BPF_ALU64 | BPF_OR  | BPF_K:
955         case BPF_ALU64 | BPF_XOR | BPF_K:
956         case BPF_ALU64 | BPF_MUL | BPF_K:
957         case BPF_ALU64 | BPF_MOV | BPF_K:
958         case BPF_ALU64 | BPF_DIV | BPF_K:
959         case BPF_ALU64 | BPF_MOD | BPF_K:
960                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
961                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
962                 *to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
963                 break;
964
965         case BPF_JMP | BPF_JEQ  | BPF_K:
966         case BPF_JMP | BPF_JNE  | BPF_K:
967         case BPF_JMP | BPF_JGT  | BPF_K:
968         case BPF_JMP | BPF_JLT  | BPF_K:
969         case BPF_JMP | BPF_JGE  | BPF_K:
970         case BPF_JMP | BPF_JLE  | BPF_K:
971         case BPF_JMP | BPF_JSGT | BPF_K:
972         case BPF_JMP | BPF_JSLT | BPF_K:
973         case BPF_JMP | BPF_JSGE | BPF_K:
974         case BPF_JMP | BPF_JSLE | BPF_K:
975         case BPF_JMP | BPF_JSET | BPF_K:
976                 /* Accommodate for extra offset in case of a backjump. */
977                 off = from->off;
978                 if (off < 0)
979                         off -= 2;
980                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
981                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
982                 *to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
983                 break;
984
985         case BPF_JMP32 | BPF_JEQ  | BPF_K:
986         case BPF_JMP32 | BPF_JNE  | BPF_K:
987         case BPF_JMP32 | BPF_JGT  | BPF_K:
988         case BPF_JMP32 | BPF_JLT  | BPF_K:
989         case BPF_JMP32 | BPF_JGE  | BPF_K:
990         case BPF_JMP32 | BPF_JLE  | BPF_K:
991         case BPF_JMP32 | BPF_JSGT | BPF_K:
992         case BPF_JMP32 | BPF_JSLT | BPF_K:
993         case BPF_JMP32 | BPF_JSGE | BPF_K:
994         case BPF_JMP32 | BPF_JSLE | BPF_K:
995         case BPF_JMP32 | BPF_JSET | BPF_K:
996                 /* Accommodate for extra offset in case of a backjump. */
997                 off = from->off;
998                 if (off < 0)
999                         off -= 2;
1000                 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1001                 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1002                 *to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX,
1003                                       off);
1004                 break;
1005
1006         case BPF_LD | BPF_IMM | BPF_DW:
1007                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
1008                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1009                 *to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
1010                 *to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
1011                 break;
1012         case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
1013                 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
1014                 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1015                 if (emit_zext)
1016                         *to++ = BPF_ZEXT_REG(BPF_REG_AX);
1017                 *to++ = BPF_ALU64_REG(BPF_OR,  aux[0].dst_reg, BPF_REG_AX);
1018                 break;
1019
1020         case BPF_ST | BPF_MEM | BPF_DW:
1021         case BPF_ST | BPF_MEM | BPF_W:
1022         case BPF_ST | BPF_MEM | BPF_H:
1023         case BPF_ST | BPF_MEM | BPF_B:
1024                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1025                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1026                 *to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
1027                 break;
1028         }
1029 out:
1030         return to - to_buff;
1031 }
1032
1033 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
1034                                               gfp_t gfp_extra_flags)
1035 {
1036         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
1037         struct bpf_prog *fp;
1038
1039         fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags, PAGE_KERNEL);
1040         if (fp != NULL) {
1041                 /* aux->prog still points to the fp_other one, so
1042                  * when promoting the clone to the real program,
1043                  * this still needs to be adapted.
1044                  */
1045                 memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
1046         }
1047
1048         return fp;
1049 }
1050
1051 static void bpf_prog_clone_free(struct bpf_prog *fp)
1052 {
1053         /* aux was stolen by the other clone, so we cannot free
1054          * it from this path! It will be freed eventually by the
1055          * other program on release.
1056          *
1057          * At this point, we don't need a deferred release since
1058          * clone is guaranteed to not be locked.
1059          */
1060         fp->aux = NULL;
1061         __bpf_prog_free(fp);
1062 }
1063
1064 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
1065 {
1066         /* We have to repoint aux->prog to self, as we don't
1067          * know whether fp here is the clone or the original.
1068          */
1069         fp->aux->prog = fp;
1070         bpf_prog_clone_free(fp_other);
1071 }
1072
1073 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
1074 {
1075         struct bpf_insn insn_buff[16], aux[2];
1076         struct bpf_prog *clone, *tmp;
1077         int insn_delta, insn_cnt;
1078         struct bpf_insn *insn;
1079         int i, rewritten;
1080
1081         if (!bpf_jit_blinding_enabled(prog) || prog->blinded)
1082                 return prog;
1083
1084         clone = bpf_prog_clone_create(prog, GFP_USER);
1085         if (!clone)
1086                 return ERR_PTR(-ENOMEM);
1087
1088         insn_cnt = clone->len;
1089         insn = clone->insnsi;
1090
1091         for (i = 0; i < insn_cnt; i++, insn++) {
1092                 /* We temporarily need to hold the original ld64 insn
1093                  * so that we can still access the first part in the
1094                  * second blinding run.
1095                  */
1096                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
1097                     insn[1].code == 0)
1098                         memcpy(aux, insn, sizeof(aux));
1099
1100                 rewritten = bpf_jit_blind_insn(insn, aux, insn_buff,
1101                                                 clone->aux->verifier_zext);
1102                 if (!rewritten)
1103                         continue;
1104
1105                 tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
1106                 if (IS_ERR(tmp)) {
1107                         /* Patching may have repointed aux->prog during
1108                          * realloc from the original one, so we need to
1109                          * fix it up here on error.
1110                          */
1111                         bpf_jit_prog_release_other(prog, clone);
1112                         return tmp;
1113                 }
1114
1115                 clone = tmp;
1116                 insn_delta = rewritten - 1;
1117
1118                 /* Walk new program and skip insns we just inserted. */
1119                 insn = clone->insnsi + i + insn_delta;
1120                 insn_cnt += insn_delta;
1121                 i        += insn_delta;
1122         }
1123
1124         clone->blinded = 1;
1125         return clone;
1126 }
1127 #endif /* CONFIG_BPF_JIT */
1128
1129 /* Base function for offset calculation. Needs to go into .text section,
1130  * therefore keeping it non-static as well; will also be used by JITs
1131  * anyway later on, so do not let the compiler omit it. This also needs
1132  * to go into kallsyms for correlation from e.g. bpftool, so naming
1133  * must not change.
1134  */
1135 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
1136 {
1137         return 0;
1138 }
1139 EXPORT_SYMBOL_GPL(__bpf_call_base);
1140
1141 /* All UAPI available opcodes. */
1142 #define BPF_INSN_MAP(INSN_2, INSN_3)            \
1143         /* 32 bit ALU operations. */            \
1144         /*   Register based. */                 \
1145         INSN_3(ALU, ADD,  X),                   \
1146         INSN_3(ALU, SUB,  X),                   \
1147         INSN_3(ALU, AND,  X),                   \
1148         INSN_3(ALU, OR,   X),                   \
1149         INSN_3(ALU, LSH,  X),                   \
1150         INSN_3(ALU, RSH,  X),                   \
1151         INSN_3(ALU, XOR,  X),                   \
1152         INSN_3(ALU, MUL,  X),                   \
1153         INSN_3(ALU, MOV,  X),                   \
1154         INSN_3(ALU, ARSH, X),                   \
1155         INSN_3(ALU, DIV,  X),                   \
1156         INSN_3(ALU, MOD,  X),                   \
1157         INSN_2(ALU, NEG),                       \
1158         INSN_3(ALU, END, TO_BE),                \
1159         INSN_3(ALU, END, TO_LE),                \
1160         /*   Immediate based. */                \
1161         INSN_3(ALU, ADD,  K),                   \
1162         INSN_3(ALU, SUB,  K),                   \
1163         INSN_3(ALU, AND,  K),                   \
1164         INSN_3(ALU, OR,   K),                   \
1165         INSN_3(ALU, LSH,  K),                   \
1166         INSN_3(ALU, RSH,  K),                   \
1167         INSN_3(ALU, XOR,  K),                   \
1168         INSN_3(ALU, MUL,  K),                   \
1169         INSN_3(ALU, MOV,  K),                   \
1170         INSN_3(ALU, ARSH, K),                   \
1171         INSN_3(ALU, DIV,  K),                   \
1172         INSN_3(ALU, MOD,  K),                   \
1173         /* 64 bit ALU operations. */            \
1174         /*   Register based. */                 \
1175         INSN_3(ALU64, ADD,  X),                 \
1176         INSN_3(ALU64, SUB,  X),                 \
1177         INSN_3(ALU64, AND,  X),                 \
1178         INSN_3(ALU64, OR,   X),                 \
1179         INSN_3(ALU64, LSH,  X),                 \
1180         INSN_3(ALU64, RSH,  X),                 \
1181         INSN_3(ALU64, XOR,  X),                 \
1182         INSN_3(ALU64, MUL,  X),                 \
1183         INSN_3(ALU64, MOV,  X),                 \
1184         INSN_3(ALU64, ARSH, X),                 \
1185         INSN_3(ALU64, DIV,  X),                 \
1186         INSN_3(ALU64, MOD,  X),                 \
1187         INSN_2(ALU64, NEG),                     \
1188         /*   Immediate based. */                \
1189         INSN_3(ALU64, ADD,  K),                 \
1190         INSN_3(ALU64, SUB,  K),                 \
1191         INSN_3(ALU64, AND,  K),                 \
1192         INSN_3(ALU64, OR,   K),                 \
1193         INSN_3(ALU64, LSH,  K),                 \
1194         INSN_3(ALU64, RSH,  K),                 \
1195         INSN_3(ALU64, XOR,  K),                 \
1196         INSN_3(ALU64, MUL,  K),                 \
1197         INSN_3(ALU64, MOV,  K),                 \
1198         INSN_3(ALU64, ARSH, K),                 \
1199         INSN_3(ALU64, DIV,  K),                 \
1200         INSN_3(ALU64, MOD,  K),                 \
1201         /* Call instruction. */                 \
1202         INSN_2(JMP, CALL),                      \
1203         /* Exit instruction. */                 \
1204         INSN_2(JMP, EXIT),                      \
1205         /* 32-bit Jump instructions. */         \
1206         /*   Register based. */                 \
1207         INSN_3(JMP32, JEQ,  X),                 \
1208         INSN_3(JMP32, JNE,  X),                 \
1209         INSN_3(JMP32, JGT,  X),                 \
1210         INSN_3(JMP32, JLT,  X),                 \
1211         INSN_3(JMP32, JGE,  X),                 \
1212         INSN_3(JMP32, JLE,  X),                 \
1213         INSN_3(JMP32, JSGT, X),                 \
1214         INSN_3(JMP32, JSLT, X),                 \
1215         INSN_3(JMP32, JSGE, X),                 \
1216         INSN_3(JMP32, JSLE, X),                 \
1217         INSN_3(JMP32, JSET, X),                 \
1218         /*   Immediate based. */                \
1219         INSN_3(JMP32, JEQ,  K),                 \
1220         INSN_3(JMP32, JNE,  K),                 \
1221         INSN_3(JMP32, JGT,  K),                 \
1222         INSN_3(JMP32, JLT,  K),                 \
1223         INSN_3(JMP32, JGE,  K),                 \
1224         INSN_3(JMP32, JLE,  K),                 \
1225         INSN_3(JMP32, JSGT, K),                 \
1226         INSN_3(JMP32, JSLT, K),                 \
1227         INSN_3(JMP32, JSGE, K),                 \
1228         INSN_3(JMP32, JSLE, K),                 \
1229         INSN_3(JMP32, JSET, K),                 \
1230         /* Jump instructions. */                \
1231         /*   Register based. */                 \
1232         INSN_3(JMP, JEQ,  X),                   \
1233         INSN_3(JMP, JNE,  X),                   \
1234         INSN_3(JMP, JGT,  X),                   \
1235         INSN_3(JMP, JLT,  X),                   \
1236         INSN_3(JMP, JGE,  X),                   \
1237         INSN_3(JMP, JLE,  X),                   \
1238         INSN_3(JMP, JSGT, X),                   \
1239         INSN_3(JMP, JSLT, X),                   \
1240         INSN_3(JMP, JSGE, X),                   \
1241         INSN_3(JMP, JSLE, X),                   \
1242         INSN_3(JMP, JSET, X),                   \
1243         /*   Immediate based. */                \
1244         INSN_3(JMP, JEQ,  K),                   \
1245         INSN_3(JMP, JNE,  K),                   \
1246         INSN_3(JMP, JGT,  K),                   \
1247         INSN_3(JMP, JLT,  K),                   \
1248         INSN_3(JMP, JGE,  K),                   \
1249         INSN_3(JMP, JLE,  K),                   \
1250         INSN_3(JMP, JSGT, K),                   \
1251         INSN_3(JMP, JSLT, K),                   \
1252         INSN_3(JMP, JSGE, K),                   \
1253         INSN_3(JMP, JSLE, K),                   \
1254         INSN_3(JMP, JSET, K),                   \
1255         INSN_2(JMP, JA),                        \
1256         /* Store instructions. */               \
1257         /*   Register based. */                 \
1258         INSN_3(STX, MEM,  B),                   \
1259         INSN_3(STX, MEM,  H),                   \
1260         INSN_3(STX, MEM,  W),                   \
1261         INSN_3(STX, MEM,  DW),                  \
1262         INSN_3(STX, XADD, W),                   \
1263         INSN_3(STX, XADD, DW),                  \
1264         /*   Immediate based. */                \
1265         INSN_3(ST, MEM, B),                     \
1266         INSN_3(ST, MEM, H),                     \
1267         INSN_3(ST, MEM, W),                     \
1268         INSN_3(ST, MEM, DW),                    \
1269         /* Load instructions. */                \
1270         /*   Register based. */                 \
1271         INSN_3(LDX, MEM, B),                    \
1272         INSN_3(LDX, MEM, H),                    \
1273         INSN_3(LDX, MEM, W),                    \
1274         INSN_3(LDX, MEM, DW),                   \
1275         /*   Immediate based. */                \
1276         INSN_3(LD, IMM, DW)
1277
1278 bool bpf_opcode_in_insntable(u8 code)
1279 {
1280 #define BPF_INSN_2_TBL(x, y)    [BPF_##x | BPF_##y] = true
1281 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
1282         static const bool public_insntable[256] = {
1283                 [0 ... 255] = false,
1284                 /* Now overwrite non-defaults ... */
1285                 BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
1286                 /* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
1287                 [BPF_LD | BPF_ABS | BPF_B] = true,
1288                 [BPF_LD | BPF_ABS | BPF_H] = true,
1289                 [BPF_LD | BPF_ABS | BPF_W] = true,
1290                 [BPF_LD | BPF_IND | BPF_B] = true,
1291                 [BPF_LD | BPF_IND | BPF_H] = true,
1292                 [BPF_LD | BPF_IND | BPF_W] = true,
1293         };
1294 #undef BPF_INSN_3_TBL
1295 #undef BPF_INSN_2_TBL
1296         return public_insntable[code];
1297 }
1298
1299 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1300 /**
1301  *      __bpf_prog_run - run eBPF program on a given context
1302  *      @regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers
1303  *      @insn: is the array of eBPF instructions
1304  *      @stack: is the eBPF storage stack
1305  *
1306  * Decode and execute eBPF instructions.
1307  */
1308 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn, u64 *stack)
1309 {
1310 #define BPF_INSN_2_LBL(x, y)    [BPF_##x | BPF_##y] = &&x##_##y
1311 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
1312         static const void * const jumptable[256] __annotate_jump_table = {
1313                 [0 ... 255] = &&default_label,
1314                 /* Now overwrite non-defaults ... */
1315                 BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
1316                 /* Non-UAPI available opcodes. */
1317                 [BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
1318                 [BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
1319                 [BPF_ST  | BPF_NOSPEC] = &&ST_NOSPEC,
1320         };
1321 #undef BPF_INSN_3_LBL
1322 #undef BPF_INSN_2_LBL
1323         u32 tail_call_cnt = 0;
1324
1325 #define CONT     ({ insn++; goto select_insn; })
1326 #define CONT_JMP ({ insn++; goto select_insn; })
1327
1328 select_insn:
1329         goto *jumptable[insn->code];
1330
1331         /* Explicitly mask the register-based shift amounts with 63 or 31
1332          * to avoid undefined behavior. Normally this won't affect the
1333          * generated code, for example, in case of native 64 bit archs such
1334          * as x86-64 or arm64, the compiler is optimizing the AND away for
1335          * the interpreter. In case of JITs, each of the JIT backends compiles
1336          * the BPF shift operations to machine instructions which produce
1337          * implementation-defined results in such a case; the resulting
1338          * contents of the register may be arbitrary, but program behaviour
1339          * as a whole remains defined. In other words, in case of JIT backends,
1340          * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation.
1341          */
1342         /* ALU (shifts) */
1343 #define SHT(OPCODE, OP)                                 \
1344         ALU64_##OPCODE##_X:                             \
1345                 DST = DST OP (SRC & 63);                \
1346                 CONT;                                   \
1347         ALU_##OPCODE##_X:                               \
1348                 DST = (u32) DST OP ((u32) SRC & 31);    \
1349                 CONT;                                   \
1350         ALU64_##OPCODE##_K:                             \
1351                 DST = DST OP IMM;                       \
1352                 CONT;                                   \
1353         ALU_##OPCODE##_K:                               \
1354                 DST = (u32) DST OP (u32) IMM;           \
1355                 CONT;
1356         /* ALU (rest) */
1357 #define ALU(OPCODE, OP)                                 \
1358         ALU64_##OPCODE##_X:                             \
1359                 DST = DST OP SRC;                       \
1360                 CONT;                                   \
1361         ALU_##OPCODE##_X:                               \
1362                 DST = (u32) DST OP (u32) SRC;           \
1363                 CONT;                                   \
1364         ALU64_##OPCODE##_K:                             \
1365                 DST = DST OP IMM;                       \
1366                 CONT;                                   \
1367         ALU_##OPCODE##_K:                               \
1368                 DST = (u32) DST OP (u32) IMM;           \
1369                 CONT;
1370         ALU(ADD,  +)
1371         ALU(SUB,  -)
1372         ALU(AND,  &)
1373         ALU(OR,   |)
1374         ALU(XOR,  ^)
1375         ALU(MUL,  *)
1376         SHT(LSH, <<)
1377         SHT(RSH, >>)
1378 #undef SHT
1379 #undef ALU
1380         ALU_NEG:
1381                 DST = (u32) -DST;
1382                 CONT;
1383         ALU64_NEG:
1384                 DST = -DST;
1385                 CONT;
1386         ALU_MOV_X:
1387                 DST = (u32) SRC;
1388                 CONT;
1389         ALU_MOV_K:
1390                 DST = (u32) IMM;
1391                 CONT;
1392         ALU64_MOV_X:
1393                 DST = SRC;
1394                 CONT;
1395         ALU64_MOV_K:
1396                 DST = IMM;
1397                 CONT;
1398         LD_IMM_DW:
1399                 DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1400                 insn++;
1401                 CONT;
1402         ALU_ARSH_X:
1403                 DST = (u64) (u32) (((s32) DST) >> (SRC & 31));
1404                 CONT;
1405         ALU_ARSH_K:
1406                 DST = (u64) (u32) (((s32) DST) >> IMM);
1407                 CONT;
1408         ALU64_ARSH_X:
1409                 (*(s64 *) &DST) >>= (SRC & 63);
1410                 CONT;
1411         ALU64_ARSH_K:
1412                 (*(s64 *) &DST) >>= IMM;
1413                 CONT;
1414         ALU64_MOD_X:
1415                 div64_u64_rem(DST, SRC, &AX);
1416                 DST = AX;
1417                 CONT;
1418         ALU_MOD_X:
1419                 AX = (u32) DST;
1420                 DST = do_div(AX, (u32) SRC);
1421                 CONT;
1422         ALU64_MOD_K:
1423                 div64_u64_rem(DST, IMM, &AX);
1424                 DST = AX;
1425                 CONT;
1426         ALU_MOD_K:
1427                 AX = (u32) DST;
1428                 DST = do_div(AX, (u32) IMM);
1429                 CONT;
1430         ALU64_DIV_X:
1431                 DST = div64_u64(DST, SRC);
1432                 CONT;
1433         ALU_DIV_X:
1434                 AX = (u32) DST;
1435                 do_div(AX, (u32) SRC);
1436                 DST = (u32) AX;
1437                 CONT;
1438         ALU64_DIV_K:
1439                 DST = div64_u64(DST, IMM);
1440                 CONT;
1441         ALU_DIV_K:
1442                 AX = (u32) DST;
1443                 do_div(AX, (u32) IMM);
1444                 DST = (u32) AX;
1445                 CONT;
1446         ALU_END_TO_BE:
1447                 switch (IMM) {
1448                 case 16:
1449                         DST = (__force u16) cpu_to_be16(DST);
1450                         break;
1451                 case 32:
1452                         DST = (__force u32) cpu_to_be32(DST);
1453                         break;
1454                 case 64:
1455                         DST = (__force u64) cpu_to_be64(DST);
1456                         break;
1457                 }
1458                 CONT;
1459         ALU_END_TO_LE:
1460                 switch (IMM) {
1461                 case 16:
1462                         DST = (__force u16) cpu_to_le16(DST);
1463                         break;
1464                 case 32:
1465                         DST = (__force u32) cpu_to_le32(DST);
1466                         break;
1467                 case 64:
1468                         DST = (__force u64) cpu_to_le64(DST);
1469                         break;
1470                 }
1471                 CONT;
1472
1473         /* CALL */
1474         JMP_CALL:
1475                 /* Function call scratches BPF_R1-BPF_R5 registers,
1476                  * preserves BPF_R6-BPF_R9, and stores return value
1477                  * into BPF_R0.
1478                  */
1479                 BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1480                                                        BPF_R4, BPF_R5);
1481                 CONT;
1482
1483         JMP_CALL_ARGS:
1484                 BPF_R0 = (__bpf_call_base_args + insn->imm)(BPF_R1, BPF_R2,
1485                                                             BPF_R3, BPF_R4,
1486                                                             BPF_R5,
1487                                                             insn + insn->off + 1);
1488                 CONT;
1489
1490         JMP_TAIL_CALL: {
1491                 struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1492                 struct bpf_array *array = container_of(map, struct bpf_array, map);
1493                 struct bpf_prog *prog;
1494                 u32 index = BPF_R3;
1495
1496                 if (unlikely(index >= array->map.max_entries))
1497                         goto out;
1498                 if (unlikely(tail_call_cnt > MAX_TAIL_CALL_CNT))
1499                         goto out;
1500
1501                 tail_call_cnt++;
1502
1503                 prog = READ_ONCE(array->ptrs[index]);
1504                 if (!prog)
1505                         goto out;
1506
1507                 /* ARG1 at this point is guaranteed to point to CTX from
1508                  * the verifier side due to the fact that the tail call is
1509                  * handeled like a helper, that is, bpf_tail_call_proto,
1510                  * where arg1_type is ARG_PTR_TO_CTX.
1511                  */
1512                 insn = prog->insnsi;
1513                 goto select_insn;
1514 out:
1515                 CONT;
1516         }
1517         JMP_JA:
1518                 insn += insn->off;
1519                 CONT;
1520         JMP_EXIT:
1521                 return BPF_R0;
1522         /* JMP */
1523 #define COND_JMP(SIGN, OPCODE, CMP_OP)                          \
1524         JMP_##OPCODE##_X:                                       \
1525                 if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) {     \
1526                         insn += insn->off;                      \
1527                         CONT_JMP;                               \
1528                 }                                               \
1529                 CONT;                                           \
1530         JMP32_##OPCODE##_X:                                     \
1531                 if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) {     \
1532                         insn += insn->off;                      \
1533                         CONT_JMP;                               \
1534                 }                                               \
1535                 CONT;                                           \
1536         JMP_##OPCODE##_K:                                       \
1537                 if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) {     \
1538                         insn += insn->off;                      \
1539                         CONT_JMP;                               \
1540                 }                                               \
1541                 CONT;                                           \
1542         JMP32_##OPCODE##_K:                                     \
1543                 if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) {     \
1544                         insn += insn->off;                      \
1545                         CONT_JMP;                               \
1546                 }                                               \
1547                 CONT;
1548         COND_JMP(u, JEQ, ==)
1549         COND_JMP(u, JNE, !=)
1550         COND_JMP(u, JGT, >)
1551         COND_JMP(u, JLT, <)
1552         COND_JMP(u, JGE, >=)
1553         COND_JMP(u, JLE, <=)
1554         COND_JMP(u, JSET, &)
1555         COND_JMP(s, JSGT, >)
1556         COND_JMP(s, JSLT, <)
1557         COND_JMP(s, JSGE, >=)
1558         COND_JMP(s, JSLE, <=)
1559 #undef COND_JMP
1560         /* ST, STX and LDX*/
1561         ST_NOSPEC:
1562                 /* Speculation barrier for mitigating Speculative Store Bypass.
1563                  * In case of arm64, we rely on the firmware mitigation as
1564                  * controlled via the ssbd kernel parameter. Whenever the
1565                  * mitigation is enabled, it works for all of the kernel code
1566                  * with no need to provide any additional instructions here.
1567                  * In case of x86, we use 'lfence' insn for mitigation. We
1568                  * reuse preexisting logic from Spectre v1 mitigation that
1569                  * happens to produce the required code on x86 for v4 as well.
1570                  */
1571                 barrier_nospec();
1572                 CONT;
1573 #define LDST(SIZEOP, SIZE)                                              \
1574         STX_MEM_##SIZEOP:                                               \
1575                 *(SIZE *)(unsigned long) (DST + insn->off) = SRC;       \
1576                 CONT;                                                   \
1577         ST_MEM_##SIZEOP:                                                \
1578                 *(SIZE *)(unsigned long) (DST + insn->off) = IMM;       \
1579                 CONT;                                                   \
1580         LDX_MEM_##SIZEOP:                                               \
1581                 DST = *(SIZE *)(unsigned long) (SRC + insn->off);       \
1582                 CONT;
1583
1584         LDST(B,   u8)
1585         LDST(H,  u16)
1586         LDST(W,  u32)
1587         LDST(DW, u64)
1588 #undef LDST
1589         STX_XADD_W: /* lock xadd *(u32 *)(dst_reg + off16) += src_reg */
1590                 atomic_add((u32) SRC, (atomic_t *)(unsigned long)
1591                            (DST + insn->off));
1592                 CONT;
1593         STX_XADD_DW: /* lock xadd *(u64 *)(dst_reg + off16) += src_reg */
1594                 atomic64_add((u64) SRC, (atomic64_t *)(unsigned long)
1595                              (DST + insn->off));
1596                 CONT;
1597
1598         default_label:
1599                 /* If we ever reach this, we have a bug somewhere. Die hard here
1600                  * instead of just returning 0; we could be somewhere in a subprog,
1601                  * so execution could continue otherwise which we do /not/ want.
1602                  *
1603                  * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
1604                  */
1605                 pr_warn("BPF interpreter: unknown opcode %02x\n", insn->code);
1606                 BUG_ON(1);
1607                 return 0;
1608 }
1609
1610 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
1611 #define DEFINE_BPF_PROG_RUN(stack_size) \
1612 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
1613 { \
1614         u64 stack[stack_size / sizeof(u64)]; \
1615         u64 regs[MAX_BPF_EXT_REG]; \
1616 \
1617         FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1618         ARG1 = (u64) (unsigned long) ctx; \
1619         return ___bpf_prog_run(regs, insn, stack); \
1620 }
1621
1622 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
1623 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
1624 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
1625                                       const struct bpf_insn *insn) \
1626 { \
1627         u64 stack[stack_size / sizeof(u64)]; \
1628         u64 regs[MAX_BPF_EXT_REG]; \
1629 \
1630         FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1631         BPF_R1 = r1; \
1632         BPF_R2 = r2; \
1633         BPF_R3 = r3; \
1634         BPF_R4 = r4; \
1635         BPF_R5 = r5; \
1636         return ___bpf_prog_run(regs, insn, stack); \
1637 }
1638
1639 #define EVAL1(FN, X) FN(X)
1640 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
1641 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
1642 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
1643 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
1644 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
1645
1646 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
1647 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
1648 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
1649
1650 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
1651 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
1652 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
1653
1654 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
1655
1656 static unsigned int (*interpreters[])(const void *ctx,
1657                                       const struct bpf_insn *insn) = {
1658 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1659 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1660 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1661 };
1662 #undef PROG_NAME_LIST
1663 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
1664 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
1665                                   const struct bpf_insn *insn) = {
1666 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1667 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1668 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1669 };
1670 #undef PROG_NAME_LIST
1671
1672 void bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
1673 {
1674         stack_depth = max_t(u32, stack_depth, 1);
1675         insn->off = (s16) insn->imm;
1676         insn->imm = interpreters_args[(round_up(stack_depth, 32) / 32) - 1] -
1677                 __bpf_call_base_args;
1678         insn->code = BPF_JMP | BPF_CALL_ARGS;
1679 }
1680
1681 #else
1682 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
1683                                          const struct bpf_insn *insn)
1684 {
1685         /* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
1686          * is not working properly, so warn about it!
1687          */
1688         WARN_ON_ONCE(1);
1689         return 0;
1690 }
1691 #endif
1692
1693 bool bpf_prog_array_compatible(struct bpf_array *array,
1694                                const struct bpf_prog *fp)
1695 {
1696         if (fp->kprobe_override)
1697                 return false;
1698
1699         if (!array->owner_prog_type) {
1700                 /* There's no owner yet where we could check for
1701                  * compatibility.
1702                  */
1703                 array->owner_prog_type = fp->type;
1704                 array->owner_jited = fp->jited;
1705
1706                 return true;
1707         }
1708
1709         return array->owner_prog_type == fp->type &&
1710                array->owner_jited == fp->jited;
1711 }
1712
1713 static int bpf_check_tail_call(const struct bpf_prog *fp)
1714 {
1715         struct bpf_prog_aux *aux = fp->aux;
1716         int i;
1717
1718         for (i = 0; i < aux->used_map_cnt; i++) {
1719                 struct bpf_map *map = aux->used_maps[i];
1720                 struct bpf_array *array;
1721
1722                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1723                         continue;
1724
1725                 array = container_of(map, struct bpf_array, map);
1726                 if (!bpf_prog_array_compatible(array, fp))
1727                         return -EINVAL;
1728         }
1729
1730         return 0;
1731 }
1732
1733 static void bpf_prog_select_func(struct bpf_prog *fp)
1734 {
1735 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1736         u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
1737
1738         fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
1739 #else
1740         fp->bpf_func = __bpf_prog_ret0_warn;
1741 #endif
1742 }
1743
1744 /**
1745  *      bpf_prog_select_runtime - select exec runtime for BPF program
1746  *      @fp: bpf_prog populated with internal BPF program
1747  *      @err: pointer to error variable
1748  *
1749  * Try to JIT eBPF program, if JIT is not available, use interpreter.
1750  * The BPF program will be executed via BPF_PROG_RUN() macro.
1751  */
1752 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
1753 {
1754         /* In case of BPF to BPF calls, verifier did all the prep
1755          * work with regards to JITing, etc.
1756          */
1757         if (fp->bpf_func)
1758                 goto finalize;
1759
1760         bpf_prog_select_func(fp);
1761
1762         /* eBPF JITs can rewrite the program in case constant
1763          * blinding is active. However, in case of error during
1764          * blinding, bpf_int_jit_compile() must always return a
1765          * valid program, which in this case would simply not
1766          * be JITed, but falls back to the interpreter.
1767          */
1768         if (!bpf_prog_is_dev_bound(fp->aux)) {
1769                 *err = bpf_prog_alloc_jited_linfo(fp);
1770                 if (*err)
1771                         return fp;
1772
1773                 fp = bpf_int_jit_compile(fp);
1774                 if (!fp->jited) {
1775                         bpf_prog_free_jited_linfo(fp);
1776 #ifdef CONFIG_BPF_JIT_ALWAYS_ON
1777                         *err = -ENOTSUPP;
1778                         return fp;
1779 #endif
1780                 } else {
1781                         bpf_prog_free_unused_jited_linfo(fp);
1782                 }
1783         } else {
1784                 *err = bpf_prog_offload_compile(fp);
1785                 if (*err)
1786                         return fp;
1787         }
1788
1789 finalize:
1790         bpf_prog_lock_ro(fp);
1791
1792         /* The tail call compatibility check can only be done at
1793          * this late stage as we need to determine, if we deal
1794          * with JITed or non JITed program concatenations and not
1795          * all eBPF JITs might immediately support all features.
1796          */
1797         *err = bpf_check_tail_call(fp);
1798
1799         return fp;
1800 }
1801 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
1802
1803 static unsigned int __bpf_prog_ret1(const void *ctx,
1804                                     const struct bpf_insn *insn)
1805 {
1806         return 1;
1807 }
1808
1809 static struct bpf_prog_dummy {
1810         struct bpf_prog prog;
1811 } dummy_bpf_prog = {
1812         .prog = {
1813                 .bpf_func = __bpf_prog_ret1,
1814         },
1815 };
1816
1817 /* to avoid allocating empty bpf_prog_array for cgroups that
1818  * don't have bpf program attached use one global 'empty_prog_array'
1819  * It will not be modified the caller of bpf_prog_array_alloc()
1820  * (since caller requested prog_cnt == 0)
1821  * that pointer should be 'freed' by bpf_prog_array_free()
1822  */
1823 static struct {
1824         struct bpf_prog_array hdr;
1825         struct bpf_prog *null_prog;
1826 } empty_prog_array = {
1827         .null_prog = NULL,
1828 };
1829
1830 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
1831 {
1832         if (prog_cnt)
1833                 return kzalloc(sizeof(struct bpf_prog_array) +
1834                                sizeof(struct bpf_prog_array_item) *
1835                                (prog_cnt + 1),
1836                                flags);
1837
1838         return &empty_prog_array.hdr;
1839 }
1840
1841 void bpf_prog_array_free(struct bpf_prog_array *progs)
1842 {
1843         if (!progs || progs == &empty_prog_array.hdr)
1844                 return;
1845         kfree_rcu(progs, rcu);
1846 }
1847
1848 int bpf_prog_array_length(struct bpf_prog_array *array)
1849 {
1850         struct bpf_prog_array_item *item;
1851         u32 cnt = 0;
1852
1853         for (item = array->items; item->prog; item++)
1854                 if (item->prog != &dummy_bpf_prog.prog)
1855                         cnt++;
1856         return cnt;
1857 }
1858
1859 bool bpf_prog_array_is_empty(struct bpf_prog_array *array)
1860 {
1861         struct bpf_prog_array_item *item;
1862
1863         for (item = array->items; item->prog; item++)
1864                 if (item->prog != &dummy_bpf_prog.prog)
1865                         return false;
1866         return true;
1867 }
1868
1869 static bool bpf_prog_array_copy_core(struct bpf_prog_array *array,
1870                                      u32 *prog_ids,
1871                                      u32 request_cnt)
1872 {
1873         struct bpf_prog_array_item *item;
1874         int i = 0;
1875
1876         for (item = array->items; item->prog; item++) {
1877                 if (item->prog == &dummy_bpf_prog.prog)
1878                         continue;
1879                 prog_ids[i] = item->prog->aux->id;
1880                 if (++i == request_cnt) {
1881                         item++;
1882                         break;
1883                 }
1884         }
1885
1886         return !!(item->prog);
1887 }
1888
1889 int bpf_prog_array_copy_to_user(struct bpf_prog_array *array,
1890                                 __u32 __user *prog_ids, u32 cnt)
1891 {
1892         unsigned long err = 0;
1893         bool nospc;
1894         u32 *ids;
1895
1896         /* users of this function are doing:
1897          * cnt = bpf_prog_array_length();
1898          * if (cnt > 0)
1899          *     bpf_prog_array_copy_to_user(..., cnt);
1900          * so below kcalloc doesn't need extra cnt > 0 check.
1901          */
1902         ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
1903         if (!ids)
1904                 return -ENOMEM;
1905         nospc = bpf_prog_array_copy_core(array, ids, cnt);
1906         err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
1907         kfree(ids);
1908         if (err)
1909                 return -EFAULT;
1910         if (nospc)
1911                 return -ENOSPC;
1912         return 0;
1913 }
1914
1915 void bpf_prog_array_delete_safe(struct bpf_prog_array *array,
1916                                 struct bpf_prog *old_prog)
1917 {
1918         struct bpf_prog_array_item *item;
1919
1920         for (item = array->items; item->prog; item++)
1921                 if (item->prog == old_prog) {
1922                         WRITE_ONCE(item->prog, &dummy_bpf_prog.prog);
1923                         break;
1924                 }
1925 }
1926
1927 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
1928                         struct bpf_prog *exclude_prog,
1929                         struct bpf_prog *include_prog,
1930                         struct bpf_prog_array **new_array)
1931 {
1932         int new_prog_cnt, carry_prog_cnt = 0;
1933         struct bpf_prog_array_item *existing;
1934         struct bpf_prog_array *array;
1935         bool found_exclude = false;
1936         int new_prog_idx = 0;
1937
1938         /* Figure out how many existing progs we need to carry over to
1939          * the new array.
1940          */
1941         if (old_array) {
1942                 existing = old_array->items;
1943                 for (; existing->prog; existing++) {
1944                         if (existing->prog == exclude_prog) {
1945                                 found_exclude = true;
1946                                 continue;
1947                         }
1948                         if (existing->prog != &dummy_bpf_prog.prog)
1949                                 carry_prog_cnt++;
1950                         if (existing->prog == include_prog)
1951                                 return -EEXIST;
1952                 }
1953         }
1954
1955         if (exclude_prog && !found_exclude)
1956                 return -ENOENT;
1957
1958         /* How many progs (not NULL) will be in the new array? */
1959         new_prog_cnt = carry_prog_cnt;
1960         if (include_prog)
1961                 new_prog_cnt += 1;
1962
1963         /* Do we have any prog (not NULL) in the new array? */
1964         if (!new_prog_cnt) {
1965                 *new_array = NULL;
1966                 return 0;
1967         }
1968
1969         /* +1 as the end of prog_array is marked with NULL */
1970         array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
1971         if (!array)
1972                 return -ENOMEM;
1973
1974         /* Fill in the new prog array */
1975         if (carry_prog_cnt) {
1976                 existing = old_array->items;
1977                 for (; existing->prog; existing++)
1978                         if (existing->prog != exclude_prog &&
1979                             existing->prog != &dummy_bpf_prog.prog) {
1980                                 array->items[new_prog_idx++].prog =
1981                                         existing->prog;
1982                         }
1983         }
1984         if (include_prog)
1985                 array->items[new_prog_idx++].prog = include_prog;
1986         array->items[new_prog_idx].prog = NULL;
1987         *new_array = array;
1988         return 0;
1989 }
1990
1991 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
1992                              u32 *prog_ids, u32 request_cnt,
1993                              u32 *prog_cnt)
1994 {
1995         u32 cnt = 0;
1996
1997         if (array)
1998                 cnt = bpf_prog_array_length(array);
1999
2000         *prog_cnt = cnt;
2001
2002         /* return early if user requested only program count or nothing to copy */
2003         if (!request_cnt || !cnt)
2004                 return 0;
2005
2006         /* this function is called under trace/bpf_trace.c: bpf_event_mutex */
2007         return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC
2008                                                                      : 0;
2009 }
2010
2011 static void bpf_prog_free_deferred(struct work_struct *work)
2012 {
2013         struct bpf_prog_aux *aux;
2014         int i;
2015
2016         aux = container_of(work, struct bpf_prog_aux, work);
2017         if (bpf_prog_is_dev_bound(aux))
2018                 bpf_prog_offload_destroy(aux->prog);
2019 #ifdef CONFIG_PERF_EVENTS
2020         if (aux->prog->has_callchain_buf)
2021                 put_callchain_buffers();
2022 #endif
2023         for (i = 0; i < aux->func_cnt; i++)
2024                 bpf_jit_free(aux->func[i]);
2025         if (aux->func_cnt) {
2026                 kfree(aux->func);
2027                 bpf_prog_unlock_free(aux->prog);
2028         } else {
2029                 bpf_jit_free(aux->prog);
2030         }
2031 }
2032
2033 /* Free internal BPF program */
2034 void bpf_prog_free(struct bpf_prog *fp)
2035 {
2036         struct bpf_prog_aux *aux = fp->aux;
2037
2038         INIT_WORK(&aux->work, bpf_prog_free_deferred);
2039         schedule_work(&aux->work);
2040 }
2041 EXPORT_SYMBOL_GPL(bpf_prog_free);
2042
2043 /* RNG for unpriviledged user space with separated state from prandom_u32(). */
2044 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
2045
2046 void bpf_user_rnd_init_once(void)
2047 {
2048         prandom_init_once(&bpf_user_rnd_state);
2049 }
2050
2051 BPF_CALL_0(bpf_user_rnd_u32)
2052 {
2053         /* Should someone ever have the rather unwise idea to use some
2054          * of the registers passed into this function, then note that
2055          * this function is called from native eBPF and classic-to-eBPF
2056          * transformations. Register assignments from both sides are
2057          * different, f.e. classic always sets fn(ctx, A, X) here.
2058          */
2059         struct rnd_state *state;
2060         u32 res;
2061
2062         state = &get_cpu_var(bpf_user_rnd_state);
2063         res = prandom_u32_state(state);
2064         put_cpu_var(bpf_user_rnd_state);
2065
2066         return res;
2067 }
2068
2069 /* Weak definitions of helper functions in case we don't have bpf syscall. */
2070 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
2071 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
2072 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
2073 const struct bpf_func_proto bpf_map_push_elem_proto __weak;
2074 const struct bpf_func_proto bpf_map_pop_elem_proto __weak;
2075 const struct bpf_func_proto bpf_map_peek_elem_proto __weak;
2076 const struct bpf_func_proto bpf_spin_lock_proto __weak;
2077 const struct bpf_func_proto bpf_spin_unlock_proto __weak;
2078
2079 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
2080 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
2081 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
2082 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
2083
2084 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
2085 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
2086 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
2087 const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak;
2088 const struct bpf_func_proto bpf_get_local_storage_proto __weak;
2089
2090 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
2091 {
2092         return NULL;
2093 }
2094
2095 u64 __weak
2096 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2097                  void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
2098 {
2099         return -ENOTSUPP;
2100 }
2101 EXPORT_SYMBOL_GPL(bpf_event_output);
2102
2103 /* Always built-in helper functions. */
2104 const struct bpf_func_proto bpf_tail_call_proto = {
2105         .func           = NULL,
2106         .gpl_only       = false,
2107         .ret_type       = RET_VOID,
2108         .arg1_type      = ARG_PTR_TO_CTX,
2109         .arg2_type      = ARG_CONST_MAP_PTR,
2110         .arg3_type      = ARG_ANYTHING,
2111 };
2112
2113 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
2114  * It is encouraged to implement bpf_int_jit_compile() instead, so that
2115  * eBPF and implicitly also cBPF can get JITed!
2116  */
2117 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
2118 {
2119         return prog;
2120 }
2121
2122 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
2123  * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
2124  */
2125 void __weak bpf_jit_compile(struct bpf_prog *prog)
2126 {
2127 }
2128
2129 bool __weak bpf_helper_changes_pkt_data(void *func)
2130 {
2131         return false;
2132 }
2133
2134 /* Return TRUE if the JIT backend wants verifier to enable sub-register usage
2135  * analysis code and wants explicit zero extension inserted by verifier.
2136  * Otherwise, return FALSE.
2137  */
2138 bool __weak bpf_jit_needs_zext(void)
2139 {
2140         return false;
2141 }
2142
2143 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
2144  * skb_copy_bits(), so provide a weak definition of it for NET-less config.
2145  */
2146 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
2147                          int len)
2148 {
2149         return -EFAULT;
2150 }
2151
2152 DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key);
2153 EXPORT_SYMBOL(bpf_stats_enabled_key);
2154
2155 /* All definitions of tracepoints related to BPF. */
2156 #define CREATE_TRACE_POINTS
2157 #include <linux/bpf_trace.h>
2158
2159 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
2160 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);