GNU Linux-libre 4.14.313-gnu1
[releases.git] / kernel / bpf / core.c
1 /*
2  * Linux Socket Filter - Kernel level socket filtering
3  *
4  * Based on the design of the Berkeley Packet Filter. The new
5  * internal format has been designed by PLUMgrid:
6  *
7  *      Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
8  *
9  * Authors:
10  *
11  *      Jay Schulist <jschlst@samba.org>
12  *      Alexei Starovoitov <ast@plumgrid.com>
13  *      Daniel Borkmann <dborkman@redhat.com>
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version
18  * 2 of the License, or (at your option) any later version.
19  *
20  * Andi Kleen - Fix a few bad bugs and races.
21  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
22  */
23
24 #include <linux/filter.h>
25 #include <linux/skbuff.h>
26 #include <linux/vmalloc.h>
27 #include <linux/random.h>
28 #include <linux/moduleloader.h>
29 #include <linux/bpf.h>
30 #include <linux/frame.h>
31 #include <linux/rbtree_latch.h>
32 #include <linux/kallsyms.h>
33 #include <linux/rcupdate.h>
34
35 #include <asm/unaligned.h>
36
37 /* Registers */
38 #define BPF_R0  regs[BPF_REG_0]
39 #define BPF_R1  regs[BPF_REG_1]
40 #define BPF_R2  regs[BPF_REG_2]
41 #define BPF_R3  regs[BPF_REG_3]
42 #define BPF_R4  regs[BPF_REG_4]
43 #define BPF_R5  regs[BPF_REG_5]
44 #define BPF_R6  regs[BPF_REG_6]
45 #define BPF_R7  regs[BPF_REG_7]
46 #define BPF_R8  regs[BPF_REG_8]
47 #define BPF_R9  regs[BPF_REG_9]
48 #define BPF_R10 regs[BPF_REG_10]
49
50 /* Named registers */
51 #define DST     regs[insn->dst_reg]
52 #define SRC     regs[insn->src_reg]
53 #define FP      regs[BPF_REG_FP]
54 #define AX      regs[BPF_REG_AX]
55 #define ARG1    regs[BPF_REG_ARG1]
56 #define CTX     regs[BPF_REG_CTX]
57 #define IMM     insn->imm
58
59 /* No hurry in this branch
60  *
61  * Exported for the bpf jit load helper.
62  */
63 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
64 {
65         u8 *ptr = NULL;
66
67         if (k >= SKF_NET_OFF) {
68                 ptr = skb_network_header(skb) + k - SKF_NET_OFF;
69         } else if (k >= SKF_LL_OFF) {
70                 if (unlikely(!skb_mac_header_was_set(skb)))
71                         return NULL;
72                 ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
73         }
74         if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
75                 return ptr;
76
77         return NULL;
78 }
79
80 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
81 {
82         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
83         struct bpf_prog_aux *aux;
84         struct bpf_prog *fp;
85
86         size = round_up(size, PAGE_SIZE);
87         fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
88         if (fp == NULL)
89                 return NULL;
90
91         aux = kzalloc(sizeof(*aux), GFP_KERNEL | gfp_extra_flags);
92         if (aux == NULL) {
93                 vfree(fp);
94                 return NULL;
95         }
96
97         fp->pages = size / PAGE_SIZE;
98         fp->aux = aux;
99         fp->aux->prog = fp;
100
101         INIT_LIST_HEAD_RCU(&fp->aux->ksym_lnode);
102
103         return fp;
104 }
105 EXPORT_SYMBOL_GPL(bpf_prog_alloc);
106
107 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
108                                   gfp_t gfp_extra_flags)
109 {
110         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
111         struct bpf_prog *fp;
112         u32 pages, delta;
113         int ret;
114
115         BUG_ON(fp_old == NULL);
116
117         size = round_up(size, PAGE_SIZE);
118         pages = size / PAGE_SIZE;
119         if (pages <= fp_old->pages)
120                 return fp_old;
121
122         delta = pages - fp_old->pages;
123         ret = __bpf_prog_charge(fp_old->aux->user, delta);
124         if (ret)
125                 return NULL;
126
127         fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
128         if (fp == NULL) {
129                 __bpf_prog_uncharge(fp_old->aux->user, delta);
130         } else {
131                 memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
132                 fp->pages = pages;
133                 fp->aux->prog = fp;
134
135                 /* We keep fp->aux from fp_old around in the new
136                  * reallocated structure.
137                  */
138                 fp_old->aux = NULL;
139                 __bpf_prog_free(fp_old);
140         }
141
142         return fp;
143 }
144
145 void __bpf_prog_free(struct bpf_prog *fp)
146 {
147         kfree(fp->aux);
148         vfree(fp);
149 }
150
151 int bpf_prog_calc_tag(struct bpf_prog *fp)
152 {
153         const u32 bits_offset = SHA_MESSAGE_BYTES - sizeof(__be64);
154         u32 raw_size = bpf_prog_tag_scratch_size(fp);
155         u32 digest[SHA_DIGEST_WORDS];
156         u32 ws[SHA_WORKSPACE_WORDS];
157         u32 i, bsize, psize, blocks;
158         struct bpf_insn *dst;
159         bool was_ld_map;
160         u8 *raw, *todo;
161         __be32 *result;
162         __be64 *bits;
163
164         raw = vmalloc(raw_size);
165         if (!raw)
166                 return -ENOMEM;
167
168         sha_init(digest);
169         memset(ws, 0, sizeof(ws));
170
171         /* We need to take out the map fd for the digest calculation
172          * since they are unstable from user space side.
173          */
174         dst = (void *)raw;
175         for (i = 0, was_ld_map = false; i < fp->len; i++) {
176                 dst[i] = fp->insnsi[i];
177                 if (!was_ld_map &&
178                     dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
179                     dst[i].src_reg == BPF_PSEUDO_MAP_FD) {
180                         was_ld_map = true;
181                         dst[i].imm = 0;
182                 } else if (was_ld_map &&
183                            dst[i].code == 0 &&
184                            dst[i].dst_reg == 0 &&
185                            dst[i].src_reg == 0 &&
186                            dst[i].off == 0) {
187                         was_ld_map = false;
188                         dst[i].imm = 0;
189                 } else {
190                         was_ld_map = false;
191                 }
192         }
193
194         psize = bpf_prog_insn_size(fp);
195         memset(&raw[psize], 0, raw_size - psize);
196         raw[psize++] = 0x80;
197
198         bsize  = round_up(psize, SHA_MESSAGE_BYTES);
199         blocks = bsize / SHA_MESSAGE_BYTES;
200         todo   = raw;
201         if (bsize - psize >= sizeof(__be64)) {
202                 bits = (__be64 *)(todo + bsize - sizeof(__be64));
203         } else {
204                 bits = (__be64 *)(todo + bsize + bits_offset);
205                 blocks++;
206         }
207         *bits = cpu_to_be64((psize - 1) << 3);
208
209         while (blocks--) {
210                 sha_transform(digest, todo, ws);
211                 todo += SHA_MESSAGE_BYTES;
212         }
213
214         result = (__force __be32 *)digest;
215         for (i = 0; i < SHA_DIGEST_WORDS; i++)
216                 result[i] = cpu_to_be32(digest[i]);
217         memcpy(fp->tag, result, sizeof(fp->tag));
218
219         vfree(raw);
220         return 0;
221 }
222
223 static bool bpf_is_jmp_and_has_target(const struct bpf_insn *insn)
224 {
225         return BPF_CLASS(insn->code) == BPF_JMP  &&
226                /* Call and Exit are both special jumps with no
227                 * target inside the BPF instruction image.
228                 */
229                BPF_OP(insn->code) != BPF_CALL &&
230                BPF_OP(insn->code) != BPF_EXIT;
231 }
232
233 static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, u32 delta,
234                                 u32 curr, const bool probe_pass)
235 {
236         const s32 off_min = S16_MIN, off_max = S16_MAX;
237         s32 off = insn->off;
238
239         if (curr < pos && curr + off + 1 > pos)
240                 off += delta;
241         else if (curr > pos + delta && curr + off + 1 <= pos + delta)
242                 off -= delta;
243         if (off < off_min || off > off_max)
244                 return -ERANGE;
245         if (!probe_pass)
246                 insn->off = off;
247         return 0;
248 }
249
250 static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, u32 delta,
251                             const bool probe_pass)
252 {
253         u32 i, insn_cnt = prog->len + (probe_pass ? delta : 0);
254         struct bpf_insn *insn = prog->insnsi;
255         int ret = 0;
256
257         for (i = 0; i < insn_cnt; i++, insn++) {
258                 /* In the probing pass we still operate on the original,
259                  * unpatched image in order to check overflows before we
260                  * do any other adjustments. Therefore skip the patchlet.
261                  */
262                 if (probe_pass && i == pos) {
263                         i += delta + 1;
264                         insn++;
265                 }
266
267                 if (!bpf_is_jmp_and_has_target(insn))
268                         continue;
269
270                 /* Adjust offset of jmps if we cross patch boundaries. */
271                 ret = bpf_adj_delta_to_off(insn, pos, delta, i, probe_pass);
272                 if (ret)
273                         break;
274         }
275
276         return ret;
277 }
278
279 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
280                                        const struct bpf_insn *patch, u32 len)
281 {
282         u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
283         const u32 cnt_max = S16_MAX;
284         struct bpf_prog *prog_adj;
285
286         /* Since our patchlet doesn't expand the image, we're done. */
287         if (insn_delta == 0) {
288                 memcpy(prog->insnsi + off, patch, sizeof(*patch));
289                 return prog;
290         }
291
292         insn_adj_cnt = prog->len + insn_delta;
293
294         /* Reject anything that would potentially let the insn->off
295          * target overflow when we have excessive program expansions.
296          * We need to probe here before we do any reallocation where
297          * we afterwards may not fail anymore.
298          */
299         if (insn_adj_cnt > cnt_max &&
300             bpf_adj_branches(prog, off, insn_delta, true))
301                 return NULL;
302
303         /* Several new instructions need to be inserted. Make room
304          * for them. Likely, there's no need for a new allocation as
305          * last page could have large enough tailroom.
306          */
307         prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
308                                     GFP_USER);
309         if (!prog_adj)
310                 return NULL;
311
312         prog_adj->len = insn_adj_cnt;
313
314         /* Patching happens in 3 steps:
315          *
316          * 1) Move over tail of insnsi from next instruction onwards,
317          *    so we can patch the single target insn with one or more
318          *    new ones (patching is always from 1 to n insns, n > 0).
319          * 2) Inject new instructions at the target location.
320          * 3) Adjust branch offsets if necessary.
321          */
322         insn_rest = insn_adj_cnt - off - len;
323
324         memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
325                 sizeof(*patch) * insn_rest);
326         memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
327
328         /* We are guaranteed to not fail at this point, otherwise
329          * the ship has sailed to reverse to the original state. An
330          * overflow cannot happen at this point.
331          */
332         BUG_ON(bpf_adj_branches(prog_adj, off, insn_delta, false));
333
334         return prog_adj;
335 }
336
337 #ifdef CONFIG_BPF_JIT
338 /* All BPF JIT sysctl knobs here. */
339 int bpf_jit_enable   __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_ALWAYS_ON);
340 int bpf_jit_harden   __read_mostly;
341 int bpf_jit_kallsyms __read_mostly;
342 long bpf_jit_limit   __read_mostly;
343 long bpf_jit_limit_max __read_mostly;
344
345 static __always_inline void
346 bpf_get_prog_addr_region(const struct bpf_prog *prog,
347                          unsigned long *symbol_start,
348                          unsigned long *symbol_end)
349 {
350         const struct bpf_binary_header *hdr = bpf_jit_binary_hdr(prog);
351         unsigned long addr = (unsigned long)hdr;
352
353         WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
354
355         *symbol_start = addr;
356         *symbol_end   = addr + hdr->pages * PAGE_SIZE;
357 }
358
359 static void bpf_get_prog_name(const struct bpf_prog *prog, char *sym)
360 {
361         BUILD_BUG_ON(sizeof("bpf_prog_") +
362                      sizeof(prog->tag) * 2 + 1 > KSYM_NAME_LEN);
363
364         sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
365         sym  = bin2hex(sym, prog->tag, sizeof(prog->tag));
366         *sym = 0;
367 }
368
369 static __always_inline unsigned long
370 bpf_get_prog_addr_start(struct latch_tree_node *n)
371 {
372         unsigned long symbol_start, symbol_end;
373         const struct bpf_prog_aux *aux;
374
375         aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
376         bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
377
378         return symbol_start;
379 }
380
381 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
382                                           struct latch_tree_node *b)
383 {
384         return bpf_get_prog_addr_start(a) < bpf_get_prog_addr_start(b);
385 }
386
387 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
388 {
389         unsigned long val = (unsigned long)key;
390         unsigned long symbol_start, symbol_end;
391         const struct bpf_prog_aux *aux;
392
393         aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
394         bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
395
396         if (val < symbol_start)
397                 return -1;
398         if (val >= symbol_end)
399                 return  1;
400
401         return 0;
402 }
403
404 static const struct latch_tree_ops bpf_tree_ops = {
405         .less   = bpf_tree_less,
406         .comp   = bpf_tree_comp,
407 };
408
409 static DEFINE_SPINLOCK(bpf_lock);
410 static LIST_HEAD(bpf_kallsyms);
411 static struct latch_tree_root bpf_tree __cacheline_aligned;
412
413 static void bpf_prog_ksym_node_add(struct bpf_prog_aux *aux)
414 {
415         WARN_ON_ONCE(!list_empty(&aux->ksym_lnode));
416         list_add_tail_rcu(&aux->ksym_lnode, &bpf_kallsyms);
417         latch_tree_insert(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
418 }
419
420 static void bpf_prog_ksym_node_del(struct bpf_prog_aux *aux)
421 {
422         if (list_empty(&aux->ksym_lnode))
423                 return;
424
425         latch_tree_erase(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
426         list_del_rcu(&aux->ksym_lnode);
427 }
428
429 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
430 {
431         return fp->jited && !bpf_prog_was_classic(fp);
432 }
433
434 static bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
435 {
436         return list_empty(&fp->aux->ksym_lnode) ||
437                fp->aux->ksym_lnode.prev == LIST_POISON2;
438 }
439
440 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
441 {
442         if (!bpf_prog_kallsyms_candidate(fp) ||
443             !capable(CAP_SYS_ADMIN))
444                 return;
445
446         spin_lock_bh(&bpf_lock);
447         bpf_prog_ksym_node_add(fp->aux);
448         spin_unlock_bh(&bpf_lock);
449 }
450
451 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
452 {
453         if (!bpf_prog_kallsyms_candidate(fp))
454                 return;
455
456         spin_lock_bh(&bpf_lock);
457         bpf_prog_ksym_node_del(fp->aux);
458         spin_unlock_bh(&bpf_lock);
459 }
460
461 static struct bpf_prog *bpf_prog_kallsyms_find(unsigned long addr)
462 {
463         struct latch_tree_node *n;
464
465         if (!bpf_jit_kallsyms_enabled())
466                 return NULL;
467
468         n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
469         return n ?
470                container_of(n, struct bpf_prog_aux, ksym_tnode)->prog :
471                NULL;
472 }
473
474 const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
475                                  unsigned long *off, char *sym)
476 {
477         unsigned long symbol_start, symbol_end;
478         struct bpf_prog *prog;
479         char *ret = NULL;
480
481         rcu_read_lock();
482         prog = bpf_prog_kallsyms_find(addr);
483         if (prog) {
484                 bpf_get_prog_addr_region(prog, &symbol_start, &symbol_end);
485                 bpf_get_prog_name(prog, sym);
486
487                 ret = sym;
488                 if (size)
489                         *size = symbol_end - symbol_start;
490                 if (off)
491                         *off  = addr - symbol_start;
492         }
493         rcu_read_unlock();
494
495         return ret;
496 }
497
498 bool is_bpf_text_address(unsigned long addr)
499 {
500         bool ret;
501
502         rcu_read_lock();
503         ret = bpf_prog_kallsyms_find(addr) != NULL;
504         rcu_read_unlock();
505
506         return ret;
507 }
508
509 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
510                     char *sym)
511 {
512         unsigned long symbol_start, symbol_end;
513         struct bpf_prog_aux *aux;
514         unsigned int it = 0;
515         int ret = -ERANGE;
516
517         if (!bpf_jit_kallsyms_enabled())
518                 return ret;
519
520         rcu_read_lock();
521         list_for_each_entry_rcu(aux, &bpf_kallsyms, ksym_lnode) {
522                 if (it++ != symnum)
523                         continue;
524
525                 bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
526                 bpf_get_prog_name(aux->prog, sym);
527
528                 *value = symbol_start;
529                 *type  = BPF_SYM_ELF_TYPE;
530
531                 ret = 0;
532                 break;
533         }
534         rcu_read_unlock();
535
536         return ret;
537 }
538
539 static atomic_long_t bpf_jit_current;
540
541 /* Can be overridden by an arch's JIT compiler if it has a custom,
542  * dedicated BPF backend memory area, or if neither of the two
543  * below apply.
544  */
545 u64 __weak bpf_jit_alloc_exec_limit(void)
546 {
547 #if defined(MODULES_VADDR)
548         return MODULES_END - MODULES_VADDR;
549 #else
550         return VMALLOC_END - VMALLOC_START;
551 #endif
552 }
553
554 static int __init bpf_jit_charge_init(void)
555 {
556         /* Only used as heuristic here to derive limit. */
557         bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
558         bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 1,
559                                             PAGE_SIZE), LONG_MAX);
560         return 0;
561 }
562 pure_initcall(bpf_jit_charge_init);
563
564 static int bpf_jit_charge_modmem(u32 pages)
565 {
566         if (atomic_long_add_return(pages, &bpf_jit_current) >
567             (bpf_jit_limit >> PAGE_SHIFT)) {
568                 if (!capable(CAP_SYS_ADMIN)) {
569                         atomic_long_sub(pages, &bpf_jit_current);
570                         return -EPERM;
571                 }
572         }
573
574         return 0;
575 }
576
577 static void bpf_jit_uncharge_modmem(u32 pages)
578 {
579         atomic_long_sub(pages, &bpf_jit_current);
580 }
581
582 struct bpf_binary_header *
583 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
584                      unsigned int alignment,
585                      bpf_jit_fill_hole_t bpf_fill_ill_insns)
586 {
587         struct bpf_binary_header *hdr;
588         u32 size, hole, start, pages;
589
590         /* Most of BPF filters are really small, but if some of them
591          * fill a page, allow at least 128 extra bytes to insert a
592          * random section of illegal instructions.
593          */
594         size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
595         pages = size / PAGE_SIZE;
596
597         if (bpf_jit_charge_modmem(pages))
598                 return NULL;
599         hdr = module_alloc(size);
600         if (!hdr) {
601                 bpf_jit_uncharge_modmem(pages);
602                 return NULL;
603         }
604
605         /* Fill space with illegal/arch-dep instructions. */
606         bpf_fill_ill_insns(hdr, size);
607
608         hdr->pages = pages;
609         hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
610                      PAGE_SIZE - sizeof(*hdr));
611         start = (get_random_int() % hole) & ~(alignment - 1);
612
613         /* Leave a random number of instructions before BPF code. */
614         *image_ptr = &hdr->image[start];
615
616         return hdr;
617 }
618
619 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
620 {
621         u32 pages = hdr->pages;
622
623         module_memfree(hdr);
624         bpf_jit_uncharge_modmem(pages);
625 }
626
627 /* This symbol is only overridden by archs that have different
628  * requirements than the usual eBPF JITs, f.e. when they only
629  * implement cBPF JIT, do not set images read-only, etc.
630  */
631 void __weak bpf_jit_free(struct bpf_prog *fp)
632 {
633         if (fp->jited) {
634                 struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
635
636                 bpf_jit_binary_unlock_ro(hdr);
637                 bpf_jit_binary_free(hdr);
638
639                 WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
640         }
641
642         bpf_prog_unlock_free(fp);
643 }
644
645 static int bpf_jit_blind_insn(const struct bpf_insn *from,
646                               const struct bpf_insn *aux,
647                               struct bpf_insn *to_buff)
648 {
649         struct bpf_insn *to = to_buff;
650         u32 imm_rnd = get_random_int();
651         s16 off;
652
653         BUILD_BUG_ON(BPF_REG_AX  + 1 != MAX_BPF_JIT_REG);
654         BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
655
656         /* Constraints on AX register:
657          *
658          * AX register is inaccessible from user space. It is mapped in
659          * all JITs, and used here for constant blinding rewrites. It is
660          * typically "stateless" meaning its contents are only valid within
661          * the executed instruction, but not across several instructions.
662          * There are a few exceptions however which are further detailed
663          * below.
664          *
665          * Constant blinding is only used by JITs, not in the interpreter.
666          * In restricted circumstances, the verifier can also use the AX
667          * register for rewrites as long as they do not interfere with
668          * the above cases!
669          */
670         if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
671                 goto out;
672
673         if (from->imm == 0 &&
674             (from->code == (BPF_ALU   | BPF_MOV | BPF_K) ||
675              from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
676                 *to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
677                 goto out;
678         }
679
680         switch (from->code) {
681         case BPF_ALU | BPF_ADD | BPF_K:
682         case BPF_ALU | BPF_SUB | BPF_K:
683         case BPF_ALU | BPF_AND | BPF_K:
684         case BPF_ALU | BPF_OR  | BPF_K:
685         case BPF_ALU | BPF_XOR | BPF_K:
686         case BPF_ALU | BPF_MUL | BPF_K:
687         case BPF_ALU | BPF_MOV | BPF_K:
688         case BPF_ALU | BPF_DIV | BPF_K:
689         case BPF_ALU | BPF_MOD | BPF_K:
690                 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
691                 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
692                 *to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
693                 break;
694
695         case BPF_ALU64 | BPF_ADD | BPF_K:
696         case BPF_ALU64 | BPF_SUB | BPF_K:
697         case BPF_ALU64 | BPF_AND | BPF_K:
698         case BPF_ALU64 | BPF_OR  | BPF_K:
699         case BPF_ALU64 | BPF_XOR | BPF_K:
700         case BPF_ALU64 | BPF_MUL | BPF_K:
701         case BPF_ALU64 | BPF_MOV | BPF_K:
702         case BPF_ALU64 | BPF_DIV | BPF_K:
703         case BPF_ALU64 | BPF_MOD | BPF_K:
704                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
705                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
706                 *to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
707                 break;
708
709         case BPF_JMP | BPF_JEQ  | BPF_K:
710         case BPF_JMP | BPF_JNE  | BPF_K:
711         case BPF_JMP | BPF_JGT  | BPF_K:
712         case BPF_JMP | BPF_JLT  | BPF_K:
713         case BPF_JMP | BPF_JGE  | BPF_K:
714         case BPF_JMP | BPF_JLE  | BPF_K:
715         case BPF_JMP | BPF_JSGT | BPF_K:
716         case BPF_JMP | BPF_JSLT | BPF_K:
717         case BPF_JMP | BPF_JSGE | BPF_K:
718         case BPF_JMP | BPF_JSLE | BPF_K:
719         case BPF_JMP | BPF_JSET | BPF_K:
720                 /* Accommodate for extra offset in case of a backjump. */
721                 off = from->off;
722                 if (off < 0)
723                         off -= 2;
724                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
725                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
726                 *to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
727                 break;
728
729         case BPF_LD | BPF_ABS | BPF_W:
730         case BPF_LD | BPF_ABS | BPF_H:
731         case BPF_LD | BPF_ABS | BPF_B:
732                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
733                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
734                 *to++ = BPF_LD_IND(from->code, BPF_REG_AX, 0);
735                 break;
736
737         case BPF_LD | BPF_IND | BPF_W:
738         case BPF_LD | BPF_IND | BPF_H:
739         case BPF_LD | BPF_IND | BPF_B:
740                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
741                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
742                 *to++ = BPF_ALU32_REG(BPF_ADD, BPF_REG_AX, from->src_reg);
743                 *to++ = BPF_LD_IND(from->code, BPF_REG_AX, 0);
744                 break;
745
746         case BPF_LD | BPF_IMM | BPF_DW:
747                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
748                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
749                 *to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
750                 *to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
751                 break;
752         case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
753                 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
754                 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
755                 *to++ = BPF_ALU64_REG(BPF_OR,  aux[0].dst_reg, BPF_REG_AX);
756                 break;
757
758         case BPF_ST | BPF_MEM | BPF_DW:
759         case BPF_ST | BPF_MEM | BPF_W:
760         case BPF_ST | BPF_MEM | BPF_H:
761         case BPF_ST | BPF_MEM | BPF_B:
762                 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
763                 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
764                 *to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
765                 break;
766         }
767 out:
768         return to - to_buff;
769 }
770
771 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
772                                               gfp_t gfp_extra_flags)
773 {
774         gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
775         struct bpf_prog *fp;
776
777         fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags, PAGE_KERNEL);
778         if (fp != NULL) {
779                 /* aux->prog still points to the fp_other one, so
780                  * when promoting the clone to the real program,
781                  * this still needs to be adapted.
782                  */
783                 memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
784         }
785
786         return fp;
787 }
788
789 static void bpf_prog_clone_free(struct bpf_prog *fp)
790 {
791         /* aux was stolen by the other clone, so we cannot free
792          * it from this path! It will be freed eventually by the
793          * other program on release.
794          *
795          * At this point, we don't need a deferred release since
796          * clone is guaranteed to not be locked.
797          */
798         fp->aux = NULL;
799         __bpf_prog_free(fp);
800 }
801
802 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
803 {
804         /* We have to repoint aux->prog to self, as we don't
805          * know whether fp here is the clone or the original.
806          */
807         fp->aux->prog = fp;
808         bpf_prog_clone_free(fp_other);
809 }
810
811 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
812 {
813         struct bpf_insn insn_buff[16], aux[2];
814         struct bpf_prog *clone, *tmp;
815         int insn_delta, insn_cnt;
816         struct bpf_insn *insn;
817         int i, rewritten;
818
819         if (!bpf_jit_blinding_enabled())
820                 return prog;
821
822         clone = bpf_prog_clone_create(prog, GFP_USER);
823         if (!clone)
824                 return ERR_PTR(-ENOMEM);
825
826         insn_cnt = clone->len;
827         insn = clone->insnsi;
828
829         for (i = 0; i < insn_cnt; i++, insn++) {
830                 /* We temporarily need to hold the original ld64 insn
831                  * so that we can still access the first part in the
832                  * second blinding run.
833                  */
834                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
835                     insn[1].code == 0)
836                         memcpy(aux, insn, sizeof(aux));
837
838                 rewritten = bpf_jit_blind_insn(insn, aux, insn_buff);
839                 if (!rewritten)
840                         continue;
841
842                 tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
843                 if (!tmp) {
844                         /* Patching may have repointed aux->prog during
845                          * realloc from the original one, so we need to
846                          * fix it up here on error.
847                          */
848                         bpf_jit_prog_release_other(prog, clone);
849                         return ERR_PTR(-ENOMEM);
850                 }
851
852                 clone = tmp;
853                 insn_delta = rewritten - 1;
854
855                 /* Walk new program and skip insns we just inserted. */
856                 insn = clone->insnsi + i + insn_delta;
857                 insn_cnt += insn_delta;
858                 i        += insn_delta;
859         }
860
861         return clone;
862 }
863 #endif /* CONFIG_BPF_JIT */
864
865 /* Base function for offset calculation. Needs to go into .text section,
866  * therefore keeping it non-static as well; will also be used by JITs
867  * anyway later on, so do not let the compiler omit it.
868  */
869 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
870 {
871         return 0;
872 }
873 EXPORT_SYMBOL_GPL(__bpf_call_base);
874
875 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
876 /**
877  *      __bpf_prog_run - run eBPF program on a given context
878  *      @ctx: is the data we are operating on
879  *      @insn: is the array of eBPF instructions
880  *
881  * Decode and execute eBPF instructions.
882  */
883 static unsigned int ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn,
884                                     u64 *stack)
885 {
886         u64 tmp;
887         static const void *jumptable[256] = {
888                 [0 ... 255] = &&default_label,
889                 /* Now overwrite non-defaults ... */
890                 /* 32 bit ALU operations */
891                 [BPF_ALU | BPF_ADD | BPF_X] = &&ALU_ADD_X,
892                 [BPF_ALU | BPF_ADD | BPF_K] = &&ALU_ADD_K,
893                 [BPF_ALU | BPF_SUB | BPF_X] = &&ALU_SUB_X,
894                 [BPF_ALU | BPF_SUB | BPF_K] = &&ALU_SUB_K,
895                 [BPF_ALU | BPF_AND | BPF_X] = &&ALU_AND_X,
896                 [BPF_ALU | BPF_AND | BPF_K] = &&ALU_AND_K,
897                 [BPF_ALU | BPF_OR | BPF_X]  = &&ALU_OR_X,
898                 [BPF_ALU | BPF_OR | BPF_K]  = &&ALU_OR_K,
899                 [BPF_ALU | BPF_LSH | BPF_X] = &&ALU_LSH_X,
900                 [BPF_ALU | BPF_LSH | BPF_K] = &&ALU_LSH_K,
901                 [BPF_ALU | BPF_RSH | BPF_X] = &&ALU_RSH_X,
902                 [BPF_ALU | BPF_RSH | BPF_K] = &&ALU_RSH_K,
903                 [BPF_ALU | BPF_XOR | BPF_X] = &&ALU_XOR_X,
904                 [BPF_ALU | BPF_XOR | BPF_K] = &&ALU_XOR_K,
905                 [BPF_ALU | BPF_MUL | BPF_X] = &&ALU_MUL_X,
906                 [BPF_ALU | BPF_MUL | BPF_K] = &&ALU_MUL_K,
907                 [BPF_ALU | BPF_MOV | BPF_X] = &&ALU_MOV_X,
908                 [BPF_ALU | BPF_MOV | BPF_K] = &&ALU_MOV_K,
909                 [BPF_ALU | BPF_DIV | BPF_X] = &&ALU_DIV_X,
910                 [BPF_ALU | BPF_DIV | BPF_K] = &&ALU_DIV_K,
911                 [BPF_ALU | BPF_MOD | BPF_X] = &&ALU_MOD_X,
912                 [BPF_ALU | BPF_MOD | BPF_K] = &&ALU_MOD_K,
913                 [BPF_ALU | BPF_NEG] = &&ALU_NEG,
914                 [BPF_ALU | BPF_END | BPF_TO_BE] = &&ALU_END_TO_BE,
915                 [BPF_ALU | BPF_END | BPF_TO_LE] = &&ALU_END_TO_LE,
916                 /* 64 bit ALU operations */
917                 [BPF_ALU64 | BPF_ADD | BPF_X] = &&ALU64_ADD_X,
918                 [BPF_ALU64 | BPF_ADD | BPF_K] = &&ALU64_ADD_K,
919                 [BPF_ALU64 | BPF_SUB | BPF_X] = &&ALU64_SUB_X,
920                 [BPF_ALU64 | BPF_SUB | BPF_K] = &&ALU64_SUB_K,
921                 [BPF_ALU64 | BPF_AND | BPF_X] = &&ALU64_AND_X,
922                 [BPF_ALU64 | BPF_AND | BPF_K] = &&ALU64_AND_K,
923                 [BPF_ALU64 | BPF_OR | BPF_X] = &&ALU64_OR_X,
924                 [BPF_ALU64 | BPF_OR | BPF_K] = &&ALU64_OR_K,
925                 [BPF_ALU64 | BPF_LSH | BPF_X] = &&ALU64_LSH_X,
926                 [BPF_ALU64 | BPF_LSH | BPF_K] = &&ALU64_LSH_K,
927                 [BPF_ALU64 | BPF_RSH | BPF_X] = &&ALU64_RSH_X,
928                 [BPF_ALU64 | BPF_RSH | BPF_K] = &&ALU64_RSH_K,
929                 [BPF_ALU64 | BPF_XOR | BPF_X] = &&ALU64_XOR_X,
930                 [BPF_ALU64 | BPF_XOR | BPF_K] = &&ALU64_XOR_K,
931                 [BPF_ALU64 | BPF_MUL | BPF_X] = &&ALU64_MUL_X,
932                 [BPF_ALU64 | BPF_MUL | BPF_K] = &&ALU64_MUL_K,
933                 [BPF_ALU64 | BPF_MOV | BPF_X] = &&ALU64_MOV_X,
934                 [BPF_ALU64 | BPF_MOV | BPF_K] = &&ALU64_MOV_K,
935                 [BPF_ALU64 | BPF_ARSH | BPF_X] = &&ALU64_ARSH_X,
936                 [BPF_ALU64 | BPF_ARSH | BPF_K] = &&ALU64_ARSH_K,
937                 [BPF_ALU64 | BPF_DIV | BPF_X] = &&ALU64_DIV_X,
938                 [BPF_ALU64 | BPF_DIV | BPF_K] = &&ALU64_DIV_K,
939                 [BPF_ALU64 | BPF_MOD | BPF_X] = &&ALU64_MOD_X,
940                 [BPF_ALU64 | BPF_MOD | BPF_K] = &&ALU64_MOD_K,
941                 [BPF_ALU64 | BPF_NEG] = &&ALU64_NEG,
942                 /* Call instruction */
943                 [BPF_JMP | BPF_CALL] = &&JMP_CALL,
944                 [BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
945                 /* Jumps */
946                 [BPF_JMP | BPF_JA] = &&JMP_JA,
947                 [BPF_JMP | BPF_JEQ | BPF_X] = &&JMP_JEQ_X,
948                 [BPF_JMP | BPF_JEQ | BPF_K] = &&JMP_JEQ_K,
949                 [BPF_JMP | BPF_JNE | BPF_X] = &&JMP_JNE_X,
950                 [BPF_JMP | BPF_JNE | BPF_K] = &&JMP_JNE_K,
951                 [BPF_JMP | BPF_JGT | BPF_X] = &&JMP_JGT_X,
952                 [BPF_JMP | BPF_JGT | BPF_K] = &&JMP_JGT_K,
953                 [BPF_JMP | BPF_JLT | BPF_X] = &&JMP_JLT_X,
954                 [BPF_JMP | BPF_JLT | BPF_K] = &&JMP_JLT_K,
955                 [BPF_JMP | BPF_JGE | BPF_X] = &&JMP_JGE_X,
956                 [BPF_JMP | BPF_JGE | BPF_K] = &&JMP_JGE_K,
957                 [BPF_JMP | BPF_JLE | BPF_X] = &&JMP_JLE_X,
958                 [BPF_JMP | BPF_JLE | BPF_K] = &&JMP_JLE_K,
959                 [BPF_JMP | BPF_JSGT | BPF_X] = &&JMP_JSGT_X,
960                 [BPF_JMP | BPF_JSGT | BPF_K] = &&JMP_JSGT_K,
961                 [BPF_JMP | BPF_JSLT | BPF_X] = &&JMP_JSLT_X,
962                 [BPF_JMP | BPF_JSLT | BPF_K] = &&JMP_JSLT_K,
963                 [BPF_JMP | BPF_JSGE | BPF_X] = &&JMP_JSGE_X,
964                 [BPF_JMP | BPF_JSGE | BPF_K] = &&JMP_JSGE_K,
965                 [BPF_JMP | BPF_JSLE | BPF_X] = &&JMP_JSLE_X,
966                 [BPF_JMP | BPF_JSLE | BPF_K] = &&JMP_JSLE_K,
967                 [BPF_JMP | BPF_JSET | BPF_X] = &&JMP_JSET_X,
968                 [BPF_JMP | BPF_JSET | BPF_K] = &&JMP_JSET_K,
969                 /* Program return */
970                 [BPF_JMP | BPF_EXIT] = &&JMP_EXIT,
971                 /* Store instructions */
972                 [BPF_STX | BPF_MEM | BPF_B] = &&STX_MEM_B,
973                 [BPF_STX | BPF_MEM | BPF_H] = &&STX_MEM_H,
974                 [BPF_STX | BPF_MEM | BPF_W] = &&STX_MEM_W,
975                 [BPF_STX | BPF_MEM | BPF_DW] = &&STX_MEM_DW,
976                 [BPF_STX | BPF_XADD | BPF_W] = &&STX_XADD_W,
977                 [BPF_STX | BPF_XADD | BPF_DW] = &&STX_XADD_DW,
978                 [BPF_ST | BPF_MEM | BPF_B] = &&ST_MEM_B,
979                 [BPF_ST | BPF_MEM | BPF_H] = &&ST_MEM_H,
980                 [BPF_ST | BPF_MEM | BPF_W] = &&ST_MEM_W,
981                 [BPF_ST | BPF_MEM | BPF_DW] = &&ST_MEM_DW,
982                 /* Load instructions */
983                 [BPF_LDX | BPF_MEM | BPF_B] = &&LDX_MEM_B,
984                 [BPF_LDX | BPF_MEM | BPF_H] = &&LDX_MEM_H,
985                 [BPF_LDX | BPF_MEM | BPF_W] = &&LDX_MEM_W,
986                 [BPF_LDX | BPF_MEM | BPF_DW] = &&LDX_MEM_DW,
987                 [BPF_LD | BPF_ABS | BPF_W] = &&LD_ABS_W,
988                 [BPF_LD | BPF_ABS | BPF_H] = &&LD_ABS_H,
989                 [BPF_LD | BPF_ABS | BPF_B] = &&LD_ABS_B,
990                 [BPF_LD | BPF_IND | BPF_W] = &&LD_IND_W,
991                 [BPF_LD | BPF_IND | BPF_H] = &&LD_IND_H,
992                 [BPF_LD | BPF_IND | BPF_B] = &&LD_IND_B,
993                 [BPF_LD | BPF_IMM | BPF_DW] = &&LD_IMM_DW,
994         };
995         u32 tail_call_cnt = 0;
996         void *ptr;
997         int off;
998
999 #define CONT     ({ insn++; goto select_insn; })
1000 #define CONT_JMP ({ insn++; goto select_insn; })
1001
1002 select_insn:
1003         goto *jumptable[insn->code];
1004
1005         /* ALU */
1006 #define ALU(OPCODE, OP)                 \
1007         ALU64_##OPCODE##_X:             \
1008                 DST = DST OP SRC;       \
1009                 CONT;                   \
1010         ALU_##OPCODE##_X:               \
1011                 DST = (u32) DST OP (u32) SRC;   \
1012                 CONT;                   \
1013         ALU64_##OPCODE##_K:             \
1014                 DST = DST OP IMM;               \
1015                 CONT;                   \
1016         ALU_##OPCODE##_K:               \
1017                 DST = (u32) DST OP (u32) IMM;   \
1018                 CONT;
1019
1020         ALU(ADD,  +)
1021         ALU(SUB,  -)
1022         ALU(AND,  &)
1023         ALU(OR,   |)
1024         ALU(LSH, <<)
1025         ALU(RSH, >>)
1026         ALU(XOR,  ^)
1027         ALU(MUL,  *)
1028 #undef ALU
1029         ALU_NEG:
1030                 DST = (u32) -DST;
1031                 CONT;
1032         ALU64_NEG:
1033                 DST = -DST;
1034                 CONT;
1035         ALU_MOV_X:
1036                 DST = (u32) SRC;
1037                 CONT;
1038         ALU_MOV_K:
1039                 DST = (u32) IMM;
1040                 CONT;
1041         ALU64_MOV_X:
1042                 DST = SRC;
1043                 CONT;
1044         ALU64_MOV_K:
1045                 DST = IMM;
1046                 CONT;
1047         LD_IMM_DW:
1048                 DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1049                 insn++;
1050                 CONT;
1051         ALU64_ARSH_X:
1052                 (*(s64 *) &DST) >>= SRC;
1053                 CONT;
1054         ALU64_ARSH_K:
1055                 (*(s64 *) &DST) >>= IMM;
1056                 CONT;
1057         ALU64_MOD_X:
1058                 div64_u64_rem(DST, SRC, &tmp);
1059                 DST = tmp;
1060                 CONT;
1061         ALU_MOD_X:
1062                 tmp = (u32) DST;
1063                 DST = do_div(tmp, (u32) SRC);
1064                 CONT;
1065         ALU64_MOD_K:
1066                 div64_u64_rem(DST, IMM, &tmp);
1067                 DST = tmp;
1068                 CONT;
1069         ALU_MOD_K:
1070                 tmp = (u32) DST;
1071                 DST = do_div(tmp, (u32) IMM);
1072                 CONT;
1073         ALU64_DIV_X:
1074                 DST = div64_u64(DST, SRC);
1075                 CONT;
1076         ALU_DIV_X:
1077                 tmp = (u32) DST;
1078                 do_div(tmp, (u32) SRC);
1079                 DST = (u32) tmp;
1080                 CONT;
1081         ALU64_DIV_K:
1082                 DST = div64_u64(DST, IMM);
1083                 CONT;
1084         ALU_DIV_K:
1085                 tmp = (u32) DST;
1086                 do_div(tmp, (u32) IMM);
1087                 DST = (u32) tmp;
1088                 CONT;
1089         ALU_END_TO_BE:
1090                 switch (IMM) {
1091                 case 16:
1092                         DST = (__force u16) cpu_to_be16(DST);
1093                         break;
1094                 case 32:
1095                         DST = (__force u32) cpu_to_be32(DST);
1096                         break;
1097                 case 64:
1098                         DST = (__force u64) cpu_to_be64(DST);
1099                         break;
1100                 }
1101                 CONT;
1102         ALU_END_TO_LE:
1103                 switch (IMM) {
1104                 case 16:
1105                         DST = (__force u16) cpu_to_le16(DST);
1106                         break;
1107                 case 32:
1108                         DST = (__force u32) cpu_to_le32(DST);
1109                         break;
1110                 case 64:
1111                         DST = (__force u64) cpu_to_le64(DST);
1112                         break;
1113                 }
1114                 CONT;
1115
1116         /* CALL */
1117         JMP_CALL:
1118                 /* Function call scratches BPF_R1-BPF_R5 registers,
1119                  * preserves BPF_R6-BPF_R9, and stores return value
1120                  * into BPF_R0.
1121                  */
1122                 BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1123                                                        BPF_R4, BPF_R5);
1124                 CONT;
1125
1126         JMP_TAIL_CALL: {
1127                 struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1128                 struct bpf_array *array = container_of(map, struct bpf_array, map);
1129                 struct bpf_prog *prog;
1130                 u32 index = BPF_R3;
1131
1132                 if (unlikely(index >= array->map.max_entries))
1133                         goto out;
1134                 if (unlikely(tail_call_cnt > MAX_TAIL_CALL_CNT))
1135                         goto out;
1136
1137                 tail_call_cnt++;
1138
1139                 prog = READ_ONCE(array->ptrs[index]);
1140                 if (!prog)
1141                         goto out;
1142
1143                 /* ARG1 at this point is guaranteed to point to CTX from
1144                  * the verifier side due to the fact that the tail call is
1145                  * handeled like a helper, that is, bpf_tail_call_proto,
1146                  * where arg1_type is ARG_PTR_TO_CTX.
1147                  */
1148                 insn = prog->insnsi;
1149                 goto select_insn;
1150 out:
1151                 CONT;
1152         }
1153         /* JMP */
1154         JMP_JA:
1155                 insn += insn->off;
1156                 CONT;
1157         JMP_JEQ_X:
1158                 if (DST == SRC) {
1159                         insn += insn->off;
1160                         CONT_JMP;
1161                 }
1162                 CONT;
1163         JMP_JEQ_K:
1164                 if (DST == IMM) {
1165                         insn += insn->off;
1166                         CONT_JMP;
1167                 }
1168                 CONT;
1169         JMP_JNE_X:
1170                 if (DST != SRC) {
1171                         insn += insn->off;
1172                         CONT_JMP;
1173                 }
1174                 CONT;
1175         JMP_JNE_K:
1176                 if (DST != IMM) {
1177                         insn += insn->off;
1178                         CONT_JMP;
1179                 }
1180                 CONT;
1181         JMP_JGT_X:
1182                 if (DST > SRC) {
1183                         insn += insn->off;
1184                         CONT_JMP;
1185                 }
1186                 CONT;
1187         JMP_JGT_K:
1188                 if (DST > IMM) {
1189                         insn += insn->off;
1190                         CONT_JMP;
1191                 }
1192                 CONT;
1193         JMP_JLT_X:
1194                 if (DST < SRC) {
1195                         insn += insn->off;
1196                         CONT_JMP;
1197                 }
1198                 CONT;
1199         JMP_JLT_K:
1200                 if (DST < IMM) {
1201                         insn += insn->off;
1202                         CONT_JMP;
1203                 }
1204                 CONT;
1205         JMP_JGE_X:
1206                 if (DST >= SRC) {
1207                         insn += insn->off;
1208                         CONT_JMP;
1209                 }
1210                 CONT;
1211         JMP_JGE_K:
1212                 if (DST >= IMM) {
1213                         insn += insn->off;
1214                         CONT_JMP;
1215                 }
1216                 CONT;
1217         JMP_JLE_X:
1218                 if (DST <= SRC) {
1219                         insn += insn->off;
1220                         CONT_JMP;
1221                 }
1222                 CONT;
1223         JMP_JLE_K:
1224                 if (DST <= IMM) {
1225                         insn += insn->off;
1226                         CONT_JMP;
1227                 }
1228                 CONT;
1229         JMP_JSGT_X:
1230                 if (((s64) DST) > ((s64) SRC)) {
1231                         insn += insn->off;
1232                         CONT_JMP;
1233                 }
1234                 CONT;
1235         JMP_JSGT_K:
1236                 if (((s64) DST) > ((s64) IMM)) {
1237                         insn += insn->off;
1238                         CONT_JMP;
1239                 }
1240                 CONT;
1241         JMP_JSLT_X:
1242                 if (((s64) DST) < ((s64) SRC)) {
1243                         insn += insn->off;
1244                         CONT_JMP;
1245                 }
1246                 CONT;
1247         JMP_JSLT_K:
1248                 if (((s64) DST) < ((s64) IMM)) {
1249                         insn += insn->off;
1250                         CONT_JMP;
1251                 }
1252                 CONT;
1253         JMP_JSGE_X:
1254                 if (((s64) DST) >= ((s64) SRC)) {
1255                         insn += insn->off;
1256                         CONT_JMP;
1257                 }
1258                 CONT;
1259         JMP_JSGE_K:
1260                 if (((s64) DST) >= ((s64) IMM)) {
1261                         insn += insn->off;
1262                         CONT_JMP;
1263                 }
1264                 CONT;
1265         JMP_JSLE_X:
1266                 if (((s64) DST) <= ((s64) SRC)) {
1267                         insn += insn->off;
1268                         CONT_JMP;
1269                 }
1270                 CONT;
1271         JMP_JSLE_K:
1272                 if (((s64) DST) <= ((s64) IMM)) {
1273                         insn += insn->off;
1274                         CONT_JMP;
1275                 }
1276                 CONT;
1277         JMP_JSET_X:
1278                 if (DST & SRC) {
1279                         insn += insn->off;
1280                         CONT_JMP;
1281                 }
1282                 CONT;
1283         JMP_JSET_K:
1284                 if (DST & IMM) {
1285                         insn += insn->off;
1286                         CONT_JMP;
1287                 }
1288                 CONT;
1289         JMP_EXIT:
1290                 return BPF_R0;
1291
1292         /* STX and ST and LDX*/
1293 #define LDST(SIZEOP, SIZE)                                              \
1294         STX_MEM_##SIZEOP:                                               \
1295                 *(SIZE *)(unsigned long) (DST + insn->off) = SRC;       \
1296                 CONT;                                                   \
1297         ST_MEM_##SIZEOP:                                                \
1298                 *(SIZE *)(unsigned long) (DST + insn->off) = IMM;       \
1299                 CONT;                                                   \
1300         LDX_MEM_##SIZEOP:                                               \
1301                 DST = *(SIZE *)(unsigned long) (SRC + insn->off);       \
1302                 CONT;
1303
1304         LDST(B,   u8)
1305         LDST(H,  u16)
1306         LDST(W,  u32)
1307         LDST(DW, u64)
1308 #undef LDST
1309         STX_XADD_W: /* lock xadd *(u32 *)(dst_reg + off16) += src_reg */
1310                 atomic_add((u32) SRC, (atomic_t *)(unsigned long)
1311                            (DST + insn->off));
1312                 CONT;
1313         STX_XADD_DW: /* lock xadd *(u64 *)(dst_reg + off16) += src_reg */
1314                 atomic64_add((u64) SRC, (atomic64_t *)(unsigned long)
1315                              (DST + insn->off));
1316                 CONT;
1317         LD_ABS_W: /* BPF_R0 = ntohl(*(u32 *) (skb->data + imm32)) */
1318                 off = IMM;
1319 load_word:
1320                 /* BPF_LD + BPD_ABS and BPF_LD + BPF_IND insns are only
1321                  * appearing in the programs where ctx == skb
1322                  * (see may_access_skb() in the verifier). All programs
1323                  * keep 'ctx' in regs[BPF_REG_CTX] == BPF_R6,
1324                  * bpf_convert_filter() saves it in BPF_R6, internal BPF
1325                  * verifier will check that BPF_R6 == ctx.
1326                  *
1327                  * BPF_ABS and BPF_IND are wrappers of function calls,
1328                  * so they scratch BPF_R1-BPF_R5 registers, preserve
1329                  * BPF_R6-BPF_R9, and store return value into BPF_R0.
1330                  *
1331                  * Implicit input:
1332                  *   ctx == skb == BPF_R6 == CTX
1333                  *
1334                  * Explicit input:
1335                  *   SRC == any register
1336                  *   IMM == 32-bit immediate
1337                  *
1338                  * Output:
1339                  *   BPF_R0 - 8/16/32-bit skb data converted to cpu endianness
1340                  */
1341
1342                 ptr = bpf_load_pointer((struct sk_buff *) (unsigned long) CTX, off, 4, &tmp);
1343                 if (likely(ptr != NULL)) {
1344                         BPF_R0 = get_unaligned_be32(ptr);
1345                         CONT;
1346                 }
1347
1348                 return 0;
1349         LD_ABS_H: /* BPF_R0 = ntohs(*(u16 *) (skb->data + imm32)) */
1350                 off = IMM;
1351 load_half:
1352                 ptr = bpf_load_pointer((struct sk_buff *) (unsigned long) CTX, off, 2, &tmp);
1353                 if (likely(ptr != NULL)) {
1354                         BPF_R0 = get_unaligned_be16(ptr);
1355                         CONT;
1356                 }
1357
1358                 return 0;
1359         LD_ABS_B: /* BPF_R0 = *(u8 *) (skb->data + imm32) */
1360                 off = IMM;
1361 load_byte:
1362                 ptr = bpf_load_pointer((struct sk_buff *) (unsigned long) CTX, off, 1, &tmp);
1363                 if (likely(ptr != NULL)) {
1364                         BPF_R0 = *(u8 *)ptr;
1365                         CONT;
1366                 }
1367
1368                 return 0;
1369         LD_IND_W: /* BPF_R0 = ntohl(*(u32 *) (skb->data + src_reg + imm32)) */
1370                 off = IMM + SRC;
1371                 goto load_word;
1372         LD_IND_H: /* BPF_R0 = ntohs(*(u16 *) (skb->data + src_reg + imm32)) */
1373                 off = IMM + SRC;
1374                 goto load_half;
1375         LD_IND_B: /* BPF_R0 = *(u8 *) (skb->data + src_reg + imm32) */
1376                 off = IMM + SRC;
1377                 goto load_byte;
1378
1379         default_label:
1380                 /* If we ever reach this, we have a bug somewhere. */
1381                 WARN_RATELIMIT(1, "unknown opcode %02x\n", insn->code);
1382                 return 0;
1383 }
1384 STACK_FRAME_NON_STANDARD(___bpf_prog_run); /* jump table */
1385
1386 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
1387 #define DEFINE_BPF_PROG_RUN(stack_size) \
1388 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
1389 { \
1390         u64 stack[stack_size / sizeof(u64)]; \
1391         u64 regs[MAX_BPF_EXT_REG]; \
1392 \
1393         FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1394         ARG1 = (u64) (unsigned long) ctx; \
1395         return ___bpf_prog_run(regs, insn, stack); \
1396 }
1397
1398 #define EVAL1(FN, X) FN(X)
1399 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
1400 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
1401 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
1402 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
1403 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
1404
1405 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
1406 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
1407 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
1408
1409 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
1410
1411 static unsigned int (*interpreters[])(const void *ctx,
1412                                       const struct bpf_insn *insn) = {
1413 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1414 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1415 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1416 };
1417
1418 #else
1419 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
1420                                          const struct bpf_insn *insn)
1421 {
1422         /* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
1423          * is not working properly, so warn about it!
1424          */
1425         WARN_ON_ONCE(1);
1426         return 0;
1427 }
1428 #endif
1429
1430 bool bpf_prog_array_compatible(struct bpf_array *array,
1431                                const struct bpf_prog *fp)
1432 {
1433         if (!array->owner_prog_type) {
1434                 /* There's no owner yet where we could check for
1435                  * compatibility.
1436                  */
1437                 array->owner_prog_type = fp->type;
1438                 array->owner_jited = fp->jited;
1439
1440                 return true;
1441         }
1442
1443         return array->owner_prog_type == fp->type &&
1444                array->owner_jited == fp->jited;
1445 }
1446
1447 static int bpf_check_tail_call(const struct bpf_prog *fp)
1448 {
1449         struct bpf_prog_aux *aux = fp->aux;
1450         int i;
1451
1452         for (i = 0; i < aux->used_map_cnt; i++) {
1453                 struct bpf_map *map = aux->used_maps[i];
1454                 struct bpf_array *array;
1455
1456                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1457                         continue;
1458
1459                 array = container_of(map, struct bpf_array, map);
1460                 if (!bpf_prog_array_compatible(array, fp))
1461                         return -EINVAL;
1462         }
1463
1464         return 0;
1465 }
1466
1467 /**
1468  *      bpf_prog_select_runtime - select exec runtime for BPF program
1469  *      @fp: bpf_prog populated with internal BPF program
1470  *      @err: pointer to error variable
1471  *
1472  * Try to JIT eBPF program, if JIT is not available, use interpreter.
1473  * The BPF program will be executed via BPF_PROG_RUN() macro.
1474  */
1475 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
1476 {
1477 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1478         u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
1479
1480         fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
1481 #else
1482         fp->bpf_func = __bpf_prog_ret0_warn;
1483 #endif
1484
1485         /* eBPF JITs can rewrite the program in case constant
1486          * blinding is active. However, in case of error during
1487          * blinding, bpf_int_jit_compile() must always return a
1488          * valid program, which in this case would simply not
1489          * be JITed, but falls back to the interpreter.
1490          */
1491         fp = bpf_int_jit_compile(fp);
1492 #ifdef CONFIG_BPF_JIT_ALWAYS_ON
1493         if (!fp->jited) {
1494                 *err = -ENOTSUPP;
1495                 return fp;
1496         }
1497 #endif
1498         bpf_prog_lock_ro(fp);
1499
1500         /* The tail call compatibility check can only be done at
1501          * this late stage as we need to determine, if we deal
1502          * with JITed or non JITed program concatenations and not
1503          * all eBPF JITs might immediately support all features.
1504          */
1505         *err = bpf_check_tail_call(fp);
1506
1507         return fp;
1508 }
1509 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
1510
1511 static void bpf_prog_free_deferred(struct work_struct *work)
1512 {
1513         struct bpf_prog_aux *aux;
1514
1515         aux = container_of(work, struct bpf_prog_aux, work);
1516         bpf_jit_free(aux->prog);
1517 }
1518
1519 /* Free internal BPF program */
1520 void bpf_prog_free(struct bpf_prog *fp)
1521 {
1522         struct bpf_prog_aux *aux = fp->aux;
1523
1524         INIT_WORK(&aux->work, bpf_prog_free_deferred);
1525         schedule_work(&aux->work);
1526 }
1527 EXPORT_SYMBOL_GPL(bpf_prog_free);
1528
1529 /* RNG for unpriviledged user space with separated state from prandom_u32(). */
1530 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
1531
1532 void bpf_user_rnd_init_once(void)
1533 {
1534         prandom_init_once(&bpf_user_rnd_state);
1535 }
1536
1537 BPF_CALL_0(bpf_user_rnd_u32)
1538 {
1539         /* Should someone ever have the rather unwise idea to use some
1540          * of the registers passed into this function, then note that
1541          * this function is called from native eBPF and classic-to-eBPF
1542          * transformations. Register assignments from both sides are
1543          * different, f.e. classic always sets fn(ctx, A, X) here.
1544          */
1545         struct rnd_state *state;
1546         u32 res;
1547
1548         state = &get_cpu_var(bpf_user_rnd_state);
1549         res = prandom_u32_state(state);
1550         put_cpu_var(bpf_user_rnd_state);
1551
1552         return res;
1553 }
1554
1555 /* Weak definitions of helper functions in case we don't have bpf syscall. */
1556 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
1557 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
1558 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
1559
1560 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
1561 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
1562 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
1563 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
1564
1565 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
1566 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
1567 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
1568 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
1569
1570 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
1571 {
1572         return NULL;
1573 }
1574
1575 u64 __weak
1576 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
1577                  void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
1578 {
1579         return -ENOTSUPP;
1580 }
1581
1582 /* Always built-in helper functions. */
1583 const struct bpf_func_proto bpf_tail_call_proto = {
1584         .func           = NULL,
1585         .gpl_only       = false,
1586         .ret_type       = RET_VOID,
1587         .arg1_type      = ARG_PTR_TO_CTX,
1588         .arg2_type      = ARG_CONST_MAP_PTR,
1589         .arg3_type      = ARG_ANYTHING,
1590 };
1591
1592 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
1593  * It is encouraged to implement bpf_int_jit_compile() instead, so that
1594  * eBPF and implicitly also cBPF can get JITed!
1595  */
1596 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
1597 {
1598         return prog;
1599 }
1600
1601 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
1602  * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
1603  */
1604 void __weak bpf_jit_compile(struct bpf_prog *prog)
1605 {
1606 }
1607
1608 bool __weak bpf_helper_changes_pkt_data(void *func)
1609 {
1610         return false;
1611 }
1612
1613 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
1614  * skb_copy_bits(), so provide a weak definition of it for NET-less config.
1615  */
1616 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
1617                          int len)
1618 {
1619         return -EFAULT;
1620 }
1621
1622 /* All definitions of tracepoints related to BPF. */
1623 #define CREATE_TRACE_POINTS
1624 #include <linux/bpf_trace.h>
1625
1626 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
1627
1628 EXPORT_TRACEPOINT_SYMBOL_GPL(bpf_prog_get_type);
1629 EXPORT_TRACEPOINT_SYMBOL_GPL(bpf_prog_put_rcu);