1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Linux Socket Filter - Kernel level socket filtering
5 * Based on the design of the Berkeley Packet Filter. The new
6 * internal format has been designed by PLUMgrid:
8 * Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
12 * Jay Schulist <jschlst@samba.org>
13 * Alexei Starovoitov <ast@plumgrid.com>
14 * Daniel Borkmann <dborkman@redhat.com>
16 * Andi Kleen - Fix a few bad bugs and races.
17 * Kris Katterjohn - Added many additional checks in bpf_check_classic()
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/objtool.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/extable.h>
34 #include <linux/log2.h>
35 #include <linux/bpf_verifier.h>
36 #include <linux/nodemask.h>
38 #include <asm/barrier.h>
39 #include <asm/unaligned.h>
42 #define BPF_R0 regs[BPF_REG_0]
43 #define BPF_R1 regs[BPF_REG_1]
44 #define BPF_R2 regs[BPF_REG_2]
45 #define BPF_R3 regs[BPF_REG_3]
46 #define BPF_R4 regs[BPF_REG_4]
47 #define BPF_R5 regs[BPF_REG_5]
48 #define BPF_R6 regs[BPF_REG_6]
49 #define BPF_R7 regs[BPF_REG_7]
50 #define BPF_R8 regs[BPF_REG_8]
51 #define BPF_R9 regs[BPF_REG_9]
52 #define BPF_R10 regs[BPF_REG_10]
55 #define DST regs[insn->dst_reg]
56 #define SRC regs[insn->src_reg]
57 #define FP regs[BPF_REG_FP]
58 #define AX regs[BPF_REG_AX]
59 #define ARG1 regs[BPF_REG_ARG1]
60 #define CTX regs[BPF_REG_CTX]
63 /* No hurry in this branch
65 * Exported for the bpf jit load helper.
67 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
72 ptr = skb_network_header(skb) + k - SKF_NET_OFF;
73 else if (k >= SKF_LL_OFF)
74 ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
76 if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
82 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
84 gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
85 struct bpf_prog_aux *aux;
88 size = round_up(size, PAGE_SIZE);
89 fp = __vmalloc(size, gfp_flags);
93 aux = kzalloc(sizeof(*aux), GFP_KERNEL_ACCOUNT | gfp_extra_flags);
98 fp->active = alloc_percpu_gfp(int, GFP_KERNEL_ACCOUNT | gfp_extra_flags);
105 fp->pages = size / PAGE_SIZE;
108 fp->jit_requested = ebpf_jit_enabled();
109 fp->blinding_requested = bpf_jit_blinding_enabled(fp);
111 INIT_LIST_HEAD_RCU(&fp->aux->ksym.lnode);
112 mutex_init(&fp->aux->used_maps_mutex);
113 mutex_init(&fp->aux->dst_mutex);
118 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
120 gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
121 struct bpf_prog *prog;
124 prog = bpf_prog_alloc_no_stats(size, gfp_extra_flags);
128 prog->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags);
130 free_percpu(prog->active);
136 for_each_possible_cpu(cpu) {
137 struct bpf_prog_stats *pstats;
139 pstats = per_cpu_ptr(prog->stats, cpu);
140 u64_stats_init(&pstats->syncp);
144 EXPORT_SYMBOL_GPL(bpf_prog_alloc);
146 int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog)
148 if (!prog->aux->nr_linfo || !prog->jit_requested)
151 prog->aux->jited_linfo = kvcalloc(prog->aux->nr_linfo,
152 sizeof(*prog->aux->jited_linfo),
153 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
154 if (!prog->aux->jited_linfo)
160 void bpf_prog_jit_attempt_done(struct bpf_prog *prog)
162 if (prog->aux->jited_linfo &&
163 (!prog->jited || !prog->aux->jited_linfo[0])) {
164 kvfree(prog->aux->jited_linfo);
165 prog->aux->jited_linfo = NULL;
168 kfree(prog->aux->kfunc_tab);
169 prog->aux->kfunc_tab = NULL;
172 /* The jit engine is responsible to provide an array
173 * for insn_off to the jited_off mapping (insn_to_jit_off).
175 * The idx to this array is the insn_off. Hence, the insn_off
176 * here is relative to the prog itself instead of the main prog.
177 * This array has one entry for each xlated bpf insn.
179 * jited_off is the byte off to the last byte of the jited insn.
183 * The first bpf insn off of the prog. The insn off
184 * here is relative to the main prog.
185 * e.g. if prog is a subprog, insn_start > 0
187 * The prog's idx to prog->aux->linfo and jited_linfo
189 * jited_linfo[linfo_idx] = prog->bpf_func
193 * jited_linfo[i] = prog->bpf_func +
194 * insn_to_jit_off[linfo[i].insn_off - insn_start - 1]
196 void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
197 const u32 *insn_to_jit_off)
199 u32 linfo_idx, insn_start, insn_end, nr_linfo, i;
200 const struct bpf_line_info *linfo;
203 if (!prog->aux->jited_linfo)
204 /* Userspace did not provide linfo */
207 linfo_idx = prog->aux->linfo_idx;
208 linfo = &prog->aux->linfo[linfo_idx];
209 insn_start = linfo[0].insn_off;
210 insn_end = insn_start + prog->len;
212 jited_linfo = &prog->aux->jited_linfo[linfo_idx];
213 jited_linfo[0] = prog->bpf_func;
215 nr_linfo = prog->aux->nr_linfo - linfo_idx;
217 for (i = 1; i < nr_linfo && linfo[i].insn_off < insn_end; i++)
218 /* The verifier ensures that linfo[i].insn_off is
219 * strictly increasing
221 jited_linfo[i] = prog->bpf_func +
222 insn_to_jit_off[linfo[i].insn_off - insn_start - 1];
225 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
226 gfp_t gfp_extra_flags)
228 gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
232 size = round_up(size, PAGE_SIZE);
233 pages = size / PAGE_SIZE;
234 if (pages <= fp_old->pages)
237 fp = __vmalloc(size, gfp_flags);
239 memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
243 /* We keep fp->aux from fp_old around in the new
244 * reallocated structure.
247 fp_old->stats = NULL;
248 fp_old->active = NULL;
249 __bpf_prog_free(fp_old);
255 void __bpf_prog_free(struct bpf_prog *fp)
258 mutex_destroy(&fp->aux->used_maps_mutex);
259 mutex_destroy(&fp->aux->dst_mutex);
260 kfree(fp->aux->poke_tab);
263 free_percpu(fp->stats);
264 free_percpu(fp->active);
268 int bpf_prog_calc_tag(struct bpf_prog *fp)
270 const u32 bits_offset = SHA1_BLOCK_SIZE - sizeof(__be64);
271 u32 raw_size = bpf_prog_tag_scratch_size(fp);
272 u32 digest[SHA1_DIGEST_WORDS];
273 u32 ws[SHA1_WORKSPACE_WORDS];
274 u32 i, bsize, psize, blocks;
275 struct bpf_insn *dst;
281 raw = vmalloc(raw_size);
286 memset(ws, 0, sizeof(ws));
288 /* We need to take out the map fd for the digest calculation
289 * since they are unstable from user space side.
292 for (i = 0, was_ld_map = false; i < fp->len; i++) {
293 dst[i] = fp->insnsi[i];
295 dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
296 (dst[i].src_reg == BPF_PSEUDO_MAP_FD ||
297 dst[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
300 } else if (was_ld_map &&
302 dst[i].dst_reg == 0 &&
303 dst[i].src_reg == 0 &&
312 psize = bpf_prog_insn_size(fp);
313 memset(&raw[psize], 0, raw_size - psize);
316 bsize = round_up(psize, SHA1_BLOCK_SIZE);
317 blocks = bsize / SHA1_BLOCK_SIZE;
319 if (bsize - psize >= sizeof(__be64)) {
320 bits = (__be64 *)(todo + bsize - sizeof(__be64));
322 bits = (__be64 *)(todo + bsize + bits_offset);
325 *bits = cpu_to_be64((psize - 1) << 3);
328 sha1_transform(digest, todo, ws);
329 todo += SHA1_BLOCK_SIZE;
332 result = (__force __be32 *)digest;
333 for (i = 0; i < SHA1_DIGEST_WORDS; i++)
334 result[i] = cpu_to_be32(digest[i]);
335 memcpy(fp->tag, result, sizeof(fp->tag));
341 static int bpf_adj_delta_to_imm(struct bpf_insn *insn, u32 pos, s32 end_old,
342 s32 end_new, s32 curr, const bool probe_pass)
344 const s64 imm_min = S32_MIN, imm_max = S32_MAX;
345 s32 delta = end_new - end_old;
348 if (curr < pos && curr + imm + 1 >= end_old)
350 else if (curr >= end_new && curr + imm + 1 < end_new)
352 if (imm < imm_min || imm > imm_max)
359 static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old,
360 s32 end_new, s32 curr, const bool probe_pass)
362 const s32 off_min = S16_MIN, off_max = S16_MAX;
363 s32 delta = end_new - end_old;
366 if (curr < pos && curr + off + 1 >= end_old)
368 else if (curr >= end_new && curr + off + 1 < end_new)
370 if (off < off_min || off > off_max)
377 static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, s32 end_old,
378 s32 end_new, const bool probe_pass)
380 u32 i, insn_cnt = prog->len + (probe_pass ? end_new - end_old : 0);
381 struct bpf_insn *insn = prog->insnsi;
384 for (i = 0; i < insn_cnt; i++, insn++) {
387 /* In the probing pass we still operate on the original,
388 * unpatched image in order to check overflows before we
389 * do any other adjustments. Therefore skip the patchlet.
391 if (probe_pass && i == pos) {
393 insn = prog->insnsi + end_old;
395 if (bpf_pseudo_func(insn)) {
396 ret = bpf_adj_delta_to_imm(insn, pos, end_old,
397 end_new, i, probe_pass);
403 if ((BPF_CLASS(code) != BPF_JMP &&
404 BPF_CLASS(code) != BPF_JMP32) ||
405 BPF_OP(code) == BPF_EXIT)
407 /* Adjust offset of jmps if we cross patch boundaries. */
408 if (BPF_OP(code) == BPF_CALL) {
409 if (insn->src_reg != BPF_PSEUDO_CALL)
411 ret = bpf_adj_delta_to_imm(insn, pos, end_old,
412 end_new, i, probe_pass);
414 ret = bpf_adj_delta_to_off(insn, pos, end_old,
415 end_new, i, probe_pass);
424 static void bpf_adj_linfo(struct bpf_prog *prog, u32 off, u32 delta)
426 struct bpf_line_info *linfo;
429 nr_linfo = prog->aux->nr_linfo;
430 if (!nr_linfo || !delta)
433 linfo = prog->aux->linfo;
435 for (i = 0; i < nr_linfo; i++)
436 if (off < linfo[i].insn_off)
439 /* Push all off < linfo[i].insn_off by delta */
440 for (; i < nr_linfo; i++)
441 linfo[i].insn_off += delta;
444 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
445 const struct bpf_insn *patch, u32 len)
447 u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
448 const u32 cnt_max = S16_MAX;
449 struct bpf_prog *prog_adj;
452 /* Since our patchlet doesn't expand the image, we're done. */
453 if (insn_delta == 0) {
454 memcpy(prog->insnsi + off, patch, sizeof(*patch));
458 insn_adj_cnt = prog->len + insn_delta;
460 /* Reject anything that would potentially let the insn->off
461 * target overflow when we have excessive program expansions.
462 * We need to probe here before we do any reallocation where
463 * we afterwards may not fail anymore.
465 if (insn_adj_cnt > cnt_max &&
466 (err = bpf_adj_branches(prog, off, off + 1, off + len, true)))
469 /* Several new instructions need to be inserted. Make room
470 * for them. Likely, there's no need for a new allocation as
471 * last page could have large enough tailroom.
473 prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
476 return ERR_PTR(-ENOMEM);
478 prog_adj->len = insn_adj_cnt;
480 /* Patching happens in 3 steps:
482 * 1) Move over tail of insnsi from next instruction onwards,
483 * so we can patch the single target insn with one or more
484 * new ones (patching is always from 1 to n insns, n > 0).
485 * 2) Inject new instructions at the target location.
486 * 3) Adjust branch offsets if necessary.
488 insn_rest = insn_adj_cnt - off - len;
490 memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
491 sizeof(*patch) * insn_rest);
492 memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
494 /* We are guaranteed to not fail at this point, otherwise
495 * the ship has sailed to reverse to the original state. An
496 * overflow cannot happen at this point.
498 BUG_ON(bpf_adj_branches(prog_adj, off, off + 1, off + len, false));
500 bpf_adj_linfo(prog_adj, off, insn_delta);
505 int bpf_remove_insns(struct bpf_prog *prog, u32 off, u32 cnt)
507 /* Branch offsets can't overflow when program is shrinking, no need
508 * to call bpf_adj_branches(..., true) here
510 memmove(prog->insnsi + off, prog->insnsi + off + cnt,
511 sizeof(struct bpf_insn) * (prog->len - off - cnt));
514 return WARN_ON_ONCE(bpf_adj_branches(prog, off, off + cnt, off, false));
517 static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp)
521 for (i = 0; i < fp->aux->func_cnt; i++)
522 bpf_prog_kallsyms_del(fp->aux->func[i]);
525 void bpf_prog_kallsyms_del_all(struct bpf_prog *fp)
527 bpf_prog_kallsyms_del_subprogs(fp);
528 bpf_prog_kallsyms_del(fp);
531 #ifdef CONFIG_BPF_JIT
532 /* All BPF JIT sysctl knobs here. */
533 int bpf_jit_enable __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
534 int bpf_jit_kallsyms __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
535 int bpf_jit_harden __read_mostly;
536 long bpf_jit_limit __read_mostly;
537 long bpf_jit_limit_max __read_mostly;
540 bpf_prog_ksym_set_addr(struct bpf_prog *prog)
542 WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
544 prog->aux->ksym.start = (unsigned long) prog->bpf_func;
545 prog->aux->ksym.end = prog->aux->ksym.start + prog->jited_len;
549 bpf_prog_ksym_set_name(struct bpf_prog *prog)
551 char *sym = prog->aux->ksym.name;
552 const char *end = sym + KSYM_NAME_LEN;
553 const struct btf_type *type;
554 const char *func_name;
556 BUILD_BUG_ON(sizeof("bpf_prog_") +
557 sizeof(prog->tag) * 2 +
558 /* name has been null terminated.
559 * We should need +1 for the '_' preceding
560 * the name. However, the null character
561 * is double counted between the name and the
562 * sizeof("bpf_prog_") above, so we omit
565 sizeof(prog->aux->name) > KSYM_NAME_LEN);
567 sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
568 sym = bin2hex(sym, prog->tag, sizeof(prog->tag));
570 /* prog->aux->name will be ignored if full btf name is available */
571 if (prog->aux->func_info_cnt) {
572 type = btf_type_by_id(prog->aux->btf,
573 prog->aux->func_info[prog->aux->func_idx].type_id);
574 func_name = btf_name_by_offset(prog->aux->btf, type->name_off);
575 snprintf(sym, (size_t)(end - sym), "_%s", func_name);
579 if (prog->aux->name[0])
580 snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
585 static unsigned long bpf_get_ksym_start(struct latch_tree_node *n)
587 return container_of(n, struct bpf_ksym, tnode)->start;
590 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
591 struct latch_tree_node *b)
593 return bpf_get_ksym_start(a) < bpf_get_ksym_start(b);
596 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
598 unsigned long val = (unsigned long)key;
599 const struct bpf_ksym *ksym;
601 ksym = container_of(n, struct bpf_ksym, tnode);
603 if (val < ksym->start)
605 if (val >= ksym->end)
611 static const struct latch_tree_ops bpf_tree_ops = {
612 .less = bpf_tree_less,
613 .comp = bpf_tree_comp,
616 static DEFINE_SPINLOCK(bpf_lock);
617 static LIST_HEAD(bpf_kallsyms);
618 static struct latch_tree_root bpf_tree __cacheline_aligned;
620 void bpf_ksym_add(struct bpf_ksym *ksym)
622 spin_lock_bh(&bpf_lock);
623 WARN_ON_ONCE(!list_empty(&ksym->lnode));
624 list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms);
625 latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
626 spin_unlock_bh(&bpf_lock);
629 static void __bpf_ksym_del(struct bpf_ksym *ksym)
631 if (list_empty(&ksym->lnode))
634 latch_tree_erase(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
635 list_del_rcu(&ksym->lnode);
638 void bpf_ksym_del(struct bpf_ksym *ksym)
640 spin_lock_bh(&bpf_lock);
641 __bpf_ksym_del(ksym);
642 spin_unlock_bh(&bpf_lock);
645 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
647 return fp->jited && !bpf_prog_was_classic(fp);
650 static bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
652 return list_empty(&fp->aux->ksym.lnode) ||
653 fp->aux->ksym.lnode.prev == LIST_POISON2;
656 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
658 if (!bpf_prog_kallsyms_candidate(fp) ||
662 bpf_prog_ksym_set_addr(fp);
663 bpf_prog_ksym_set_name(fp);
664 fp->aux->ksym.prog = true;
666 bpf_ksym_add(&fp->aux->ksym);
669 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
671 if (!bpf_prog_kallsyms_candidate(fp))
674 bpf_ksym_del(&fp->aux->ksym);
677 static struct bpf_ksym *bpf_ksym_find(unsigned long addr)
679 struct latch_tree_node *n;
681 n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
682 return n ? container_of(n, struct bpf_ksym, tnode) : NULL;
685 const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
686 unsigned long *off, char *sym)
688 struct bpf_ksym *ksym;
692 ksym = bpf_ksym_find(addr);
694 unsigned long symbol_start = ksym->start;
695 unsigned long symbol_end = ksym->end;
697 strncpy(sym, ksym->name, KSYM_NAME_LEN);
701 *size = symbol_end - symbol_start;
703 *off = addr - symbol_start;
710 bool is_bpf_text_address(unsigned long addr)
715 ret = bpf_ksym_find(addr) != NULL;
721 static struct bpf_prog *bpf_prog_ksym_find(unsigned long addr)
723 struct bpf_ksym *ksym = bpf_ksym_find(addr);
725 return ksym && ksym->prog ?
726 container_of(ksym, struct bpf_prog_aux, ksym)->prog :
730 const struct exception_table_entry *search_bpf_extables(unsigned long addr)
732 const struct exception_table_entry *e = NULL;
733 struct bpf_prog *prog;
736 prog = bpf_prog_ksym_find(addr);
739 if (!prog->aux->num_exentries)
742 e = search_extable(prog->aux->extable, prog->aux->num_exentries, addr);
748 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
751 struct bpf_ksym *ksym;
755 if (!bpf_jit_kallsyms_enabled())
759 list_for_each_entry_rcu(ksym, &bpf_kallsyms, lnode) {
763 strncpy(sym, ksym->name, KSYM_NAME_LEN);
765 *value = ksym->start;
766 *type = BPF_SYM_ELF_TYPE;
776 int bpf_jit_add_poke_descriptor(struct bpf_prog *prog,
777 struct bpf_jit_poke_descriptor *poke)
779 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
780 static const u32 poke_tab_max = 1024;
781 u32 slot = prog->aux->size_poke_tab;
784 if (size > poke_tab_max)
786 if (poke->tailcall_target || poke->tailcall_target_stable ||
787 poke->tailcall_bypass || poke->adj_off || poke->bypass_addr)
790 switch (poke->reason) {
791 case BPF_POKE_REASON_TAIL_CALL:
792 if (!poke->tail_call.map)
799 tab = krealloc(tab, size * sizeof(*poke), GFP_KERNEL);
803 memcpy(&tab[slot], poke, sizeof(*poke));
804 prog->aux->size_poke_tab = size;
805 prog->aux->poke_tab = tab;
811 * BPF program pack allocator.
813 * Most BPF programs are pretty small. Allocating a hole page for each
814 * program is sometime a waste. Many small bpf program also adds pressure
815 * to instruction TLB. To solve this issue, we introduce a BPF program pack
816 * allocator. The prog_pack allocator uses HPAGE_PMD_SIZE page (2MB on x86)
817 * to host BPF programs.
819 #define BPF_PROG_CHUNK_SHIFT 6
820 #define BPF_PROG_CHUNK_SIZE (1 << BPF_PROG_CHUNK_SHIFT)
821 #define BPF_PROG_CHUNK_MASK (~(BPF_PROG_CHUNK_SIZE - 1))
823 struct bpf_prog_pack {
824 struct list_head list;
826 unsigned long bitmap[];
829 #define BPF_PROG_SIZE_TO_NBITS(size) (round_up(size, BPF_PROG_CHUNK_SIZE) / BPF_PROG_CHUNK_SIZE)
831 static size_t bpf_prog_pack_size = -1;
832 static size_t bpf_prog_pack_mask = -1;
834 static int bpf_prog_chunk_count(void)
836 WARN_ON_ONCE(bpf_prog_pack_size == -1);
837 return bpf_prog_pack_size / BPF_PROG_CHUNK_SIZE;
840 static DEFINE_MUTEX(pack_mutex);
841 static LIST_HEAD(pack_list);
843 /* PMD_SIZE is not available in some special config, e.g. ARCH=arm with
844 * CONFIG_MMU=n. Use PAGE_SIZE in these cases.
847 #define BPF_HPAGE_SIZE PMD_SIZE
848 #define BPF_HPAGE_MASK PMD_MASK
850 #define BPF_HPAGE_SIZE PAGE_SIZE
851 #define BPF_HPAGE_MASK PAGE_MASK
854 static size_t select_bpf_prog_pack_size(void)
859 size = BPF_HPAGE_SIZE * num_online_nodes();
860 ptr = module_alloc(size);
862 /* Test whether we can get huge pages. If not just use PAGE_SIZE
865 if (!ptr || !is_vm_area_hugepages(ptr)) {
867 bpf_prog_pack_mask = PAGE_MASK;
869 bpf_prog_pack_mask = BPF_HPAGE_MASK;
876 static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_insns)
878 struct bpf_prog_pack *pack;
880 pack = kzalloc(struct_size(pack, bitmap, BITS_TO_LONGS(bpf_prog_chunk_count())),
884 pack->ptr = module_alloc(bpf_prog_pack_size);
889 bpf_fill_ill_insns(pack->ptr, bpf_prog_pack_size);
890 bitmap_zero(pack->bitmap, bpf_prog_pack_size / BPF_PROG_CHUNK_SIZE);
891 list_add_tail(&pack->list, &pack_list);
893 set_vm_flush_reset_perms(pack->ptr);
894 set_memory_ro((unsigned long)pack->ptr, bpf_prog_pack_size / PAGE_SIZE);
895 set_memory_x((unsigned long)pack->ptr, bpf_prog_pack_size / PAGE_SIZE);
899 static void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns)
901 unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size);
902 struct bpf_prog_pack *pack;
906 mutex_lock(&pack_mutex);
907 if (bpf_prog_pack_size == -1)
908 bpf_prog_pack_size = select_bpf_prog_pack_size();
910 if (size > bpf_prog_pack_size) {
911 size = round_up(size, PAGE_SIZE);
912 ptr = module_alloc(size);
914 bpf_fill_ill_insns(ptr, size);
915 set_vm_flush_reset_perms(ptr);
916 set_memory_ro((unsigned long)ptr, size / PAGE_SIZE);
917 set_memory_x((unsigned long)ptr, size / PAGE_SIZE);
921 list_for_each_entry(pack, &pack_list, list) {
922 pos = bitmap_find_next_zero_area(pack->bitmap, bpf_prog_chunk_count(), 0,
924 if (pos < bpf_prog_chunk_count())
925 goto found_free_area;
928 pack = alloc_new_pack(bpf_fill_ill_insns);
935 bitmap_set(pack->bitmap, pos, nbits);
936 ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
939 mutex_unlock(&pack_mutex);
943 static void bpf_prog_pack_free(struct bpf_binary_header *hdr)
945 struct bpf_prog_pack *pack = NULL, *tmp;
950 mutex_lock(&pack_mutex);
951 if (hdr->size > bpf_prog_pack_size) {
956 pack_ptr = (void *)((unsigned long)hdr & bpf_prog_pack_mask);
958 list_for_each_entry(tmp, &pack_list, list) {
959 if (tmp->ptr == pack_ptr) {
965 if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
968 nbits = BPF_PROG_SIZE_TO_NBITS(hdr->size);
969 pos = ((unsigned long)hdr - (unsigned long)pack_ptr) >> BPF_PROG_CHUNK_SHIFT;
971 WARN_ONCE(bpf_arch_text_invalidate(hdr, hdr->size),
972 "bpf_prog_pack bug: missing bpf_arch_text_invalidate?\n");
974 bitmap_clear(pack->bitmap, pos, nbits);
975 if (bitmap_find_next_zero_area(pack->bitmap, bpf_prog_chunk_count(), 0,
976 bpf_prog_chunk_count(), 0) == 0) {
977 list_del(&pack->list);
978 module_memfree(pack->ptr);
982 mutex_unlock(&pack_mutex);
985 static atomic_long_t bpf_jit_current;
987 /* Can be overridden by an arch's JIT compiler if it has a custom,
988 * dedicated BPF backend memory area, or if neither of the two
991 u64 __weak bpf_jit_alloc_exec_limit(void)
993 #if defined(MODULES_VADDR)
994 return MODULES_END - MODULES_VADDR;
996 return VMALLOC_END - VMALLOC_START;
1000 static int __init bpf_jit_charge_init(void)
1002 /* Only used as heuristic here to derive limit. */
1003 bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
1004 bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 2,
1005 PAGE_SIZE), LONG_MAX);
1008 pure_initcall(bpf_jit_charge_init);
1010 int bpf_jit_charge_modmem(u32 size)
1012 if (atomic_long_add_return(size, &bpf_jit_current) > bpf_jit_limit) {
1013 if (!bpf_capable()) {
1014 atomic_long_sub(size, &bpf_jit_current);
1022 void bpf_jit_uncharge_modmem(u32 size)
1024 atomic_long_sub(size, &bpf_jit_current);
1027 void *__weak bpf_jit_alloc_exec(unsigned long size)
1029 return module_alloc(size);
1032 void __weak bpf_jit_free_exec(void *addr)
1034 module_memfree(addr);
1037 struct bpf_binary_header *
1038 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
1039 unsigned int alignment,
1040 bpf_jit_fill_hole_t bpf_fill_ill_insns)
1042 struct bpf_binary_header *hdr;
1043 u32 size, hole, start;
1045 WARN_ON_ONCE(!is_power_of_2(alignment) ||
1046 alignment > BPF_IMAGE_ALIGNMENT);
1048 /* Most of BPF filters are really small, but if some of them
1049 * fill a page, allow at least 128 extra bytes to insert a
1050 * random section of illegal instructions.
1052 size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
1054 if (bpf_jit_charge_modmem(size))
1056 hdr = bpf_jit_alloc_exec(size);
1058 bpf_jit_uncharge_modmem(size);
1062 /* Fill space with illegal/arch-dep instructions. */
1063 bpf_fill_ill_insns(hdr, size);
1066 hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
1067 PAGE_SIZE - sizeof(*hdr));
1068 start = (get_random_int() % hole) & ~(alignment - 1);
1070 /* Leave a random number of instructions before BPF code. */
1071 *image_ptr = &hdr->image[start];
1076 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
1078 u32 size = hdr->size;
1080 bpf_jit_free_exec(hdr);
1081 bpf_jit_uncharge_modmem(size);
1084 /* Allocate jit binary from bpf_prog_pack allocator.
1085 * Since the allocated memory is RO+X, the JIT engine cannot write directly
1086 * to the memory. To solve this problem, a RW buffer is also allocated at
1087 * as the same time. The JIT engine should calculate offsets based on the
1088 * RO memory address, but write JITed program to the RW buffer. Once the
1089 * JIT engine finishes, it calls bpf_jit_binary_pack_finalize, which copies
1090 * the JITed program to the RO memory.
1092 struct bpf_binary_header *
1093 bpf_jit_binary_pack_alloc(unsigned int proglen, u8 **image_ptr,
1094 unsigned int alignment,
1095 struct bpf_binary_header **rw_header,
1097 bpf_jit_fill_hole_t bpf_fill_ill_insns)
1099 struct bpf_binary_header *ro_header;
1100 u32 size, hole, start;
1102 WARN_ON_ONCE(!is_power_of_2(alignment) ||
1103 alignment > BPF_IMAGE_ALIGNMENT);
1105 /* add 16 bytes for a random section of illegal instructions */
1106 size = round_up(proglen + sizeof(*ro_header) + 16, BPF_PROG_CHUNK_SIZE);
1108 if (bpf_jit_charge_modmem(size))
1110 ro_header = bpf_prog_pack_alloc(size, bpf_fill_ill_insns);
1112 bpf_jit_uncharge_modmem(size);
1116 *rw_header = kvmalloc(size, GFP_KERNEL);
1118 bpf_arch_text_copy(&ro_header->size, &size, sizeof(size));
1119 bpf_prog_pack_free(ro_header);
1120 bpf_jit_uncharge_modmem(size);
1124 /* Fill space with illegal/arch-dep instructions. */
1125 bpf_fill_ill_insns(*rw_header, size);
1126 (*rw_header)->size = size;
1128 hole = min_t(unsigned int, size - (proglen + sizeof(*ro_header)),
1129 BPF_PROG_CHUNK_SIZE - sizeof(*ro_header));
1130 start = (get_random_int() % hole) & ~(alignment - 1);
1132 *image_ptr = &ro_header->image[start];
1133 *rw_image = &(*rw_header)->image[start];
1138 /* Copy JITed text from rw_header to its final location, the ro_header. */
1139 int bpf_jit_binary_pack_finalize(struct bpf_prog *prog,
1140 struct bpf_binary_header *ro_header,
1141 struct bpf_binary_header *rw_header)
1145 ptr = bpf_arch_text_copy(ro_header, rw_header, rw_header->size);
1150 bpf_prog_pack_free(ro_header);
1151 return PTR_ERR(ptr);
1153 prog->aux->use_bpf_prog_pack = true;
1157 /* bpf_jit_binary_pack_free is called in two different scenarios:
1158 * 1) when the program is freed after;
1159 * 2) when the JIT engine fails (before bpf_jit_binary_pack_finalize).
1160 * For case 2), we need to free both the RO memory and the RW buffer.
1162 * bpf_jit_binary_pack_free requires proper ro_header->size. However,
1163 * bpf_jit_binary_pack_alloc does not set it. Therefore, ro_header->size
1164 * must be set with either bpf_jit_binary_pack_finalize (normal path) or
1165 * bpf_arch_text_copy (when jit fails).
1167 void bpf_jit_binary_pack_free(struct bpf_binary_header *ro_header,
1168 struct bpf_binary_header *rw_header)
1170 u32 size = ro_header->size;
1172 bpf_prog_pack_free(ro_header);
1174 bpf_jit_uncharge_modmem(size);
1177 static inline struct bpf_binary_header *
1178 bpf_jit_binary_hdr(const struct bpf_prog *fp)
1180 unsigned long real_start = (unsigned long)fp->bpf_func;
1183 if (fp->aux->use_bpf_prog_pack)
1184 addr = real_start & BPF_PROG_CHUNK_MASK;
1186 addr = real_start & PAGE_MASK;
1188 return (void *)addr;
1191 /* This symbol is only overridden by archs that have different
1192 * requirements than the usual eBPF JITs, f.e. when they only
1193 * implement cBPF JIT, do not set images read-only, etc.
1195 void __weak bpf_jit_free(struct bpf_prog *fp)
1198 struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
1200 if (fp->aux->use_bpf_prog_pack)
1201 bpf_jit_binary_pack_free(hdr, NULL /* rw_buffer */);
1203 bpf_jit_binary_free(hdr);
1205 WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
1208 bpf_prog_unlock_free(fp);
1211 int bpf_jit_get_func_addr(const struct bpf_prog *prog,
1212 const struct bpf_insn *insn, bool extra_pass,
1213 u64 *func_addr, bool *func_addr_fixed)
1215 s16 off = insn->off;
1216 s32 imm = insn->imm;
1219 *func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL;
1220 if (!*func_addr_fixed) {
1221 /* Place-holder address till the last pass has collected
1222 * all addresses for JITed subprograms in which case we
1223 * can pick them up from prog->aux.
1227 else if (prog->aux->func &&
1228 off >= 0 && off < prog->aux->func_cnt)
1229 addr = (u8 *)prog->aux->func[off]->bpf_func;
1233 /* Address of a BPF helper call. Since part of the core
1234 * kernel, it's always at a fixed location. __bpf_call_base
1235 * and the helper with imm relative to it are both in core
1238 addr = (u8 *)__bpf_call_base + imm;
1241 *func_addr = (unsigned long)addr;
1245 static int bpf_jit_blind_insn(const struct bpf_insn *from,
1246 const struct bpf_insn *aux,
1247 struct bpf_insn *to_buff,
1250 struct bpf_insn *to = to_buff;
1251 u32 imm_rnd = get_random_int();
1254 BUILD_BUG_ON(BPF_REG_AX + 1 != MAX_BPF_JIT_REG);
1255 BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
1257 /* Constraints on AX register:
1259 * AX register is inaccessible from user space. It is mapped in
1260 * all JITs, and used here for constant blinding rewrites. It is
1261 * typically "stateless" meaning its contents are only valid within
1262 * the executed instruction, but not across several instructions.
1263 * There are a few exceptions however which are further detailed
1266 * Constant blinding is only used by JITs, not in the interpreter.
1267 * The interpreter uses AX in some occasions as a local temporary
1268 * register e.g. in DIV or MOD instructions.
1270 * In restricted circumstances, the verifier can also use the AX
1271 * register for rewrites as long as they do not interfere with
1274 if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
1277 if (from->imm == 0 &&
1278 (from->code == (BPF_ALU | BPF_MOV | BPF_K) ||
1279 from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
1280 *to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
1284 switch (from->code) {
1285 case BPF_ALU | BPF_ADD | BPF_K:
1286 case BPF_ALU | BPF_SUB | BPF_K:
1287 case BPF_ALU | BPF_AND | BPF_K:
1288 case BPF_ALU | BPF_OR | BPF_K:
1289 case BPF_ALU | BPF_XOR | BPF_K:
1290 case BPF_ALU | BPF_MUL | BPF_K:
1291 case BPF_ALU | BPF_MOV | BPF_K:
1292 case BPF_ALU | BPF_DIV | BPF_K:
1293 case BPF_ALU | BPF_MOD | BPF_K:
1294 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1295 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1296 *to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
1299 case BPF_ALU64 | BPF_ADD | BPF_K:
1300 case BPF_ALU64 | BPF_SUB | BPF_K:
1301 case BPF_ALU64 | BPF_AND | BPF_K:
1302 case BPF_ALU64 | BPF_OR | BPF_K:
1303 case BPF_ALU64 | BPF_XOR | BPF_K:
1304 case BPF_ALU64 | BPF_MUL | BPF_K:
1305 case BPF_ALU64 | BPF_MOV | BPF_K:
1306 case BPF_ALU64 | BPF_DIV | BPF_K:
1307 case BPF_ALU64 | BPF_MOD | BPF_K:
1308 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1309 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1310 *to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
1313 case BPF_JMP | BPF_JEQ | BPF_K:
1314 case BPF_JMP | BPF_JNE | BPF_K:
1315 case BPF_JMP | BPF_JGT | BPF_K:
1316 case BPF_JMP | BPF_JLT | BPF_K:
1317 case BPF_JMP | BPF_JGE | BPF_K:
1318 case BPF_JMP | BPF_JLE | BPF_K:
1319 case BPF_JMP | BPF_JSGT | BPF_K:
1320 case BPF_JMP | BPF_JSLT | BPF_K:
1321 case BPF_JMP | BPF_JSGE | BPF_K:
1322 case BPF_JMP | BPF_JSLE | BPF_K:
1323 case BPF_JMP | BPF_JSET | BPF_K:
1324 /* Accommodate for extra offset in case of a backjump. */
1328 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1329 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1330 *to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
1333 case BPF_JMP32 | BPF_JEQ | BPF_K:
1334 case BPF_JMP32 | BPF_JNE | BPF_K:
1335 case BPF_JMP32 | BPF_JGT | BPF_K:
1336 case BPF_JMP32 | BPF_JLT | BPF_K:
1337 case BPF_JMP32 | BPF_JGE | BPF_K:
1338 case BPF_JMP32 | BPF_JLE | BPF_K:
1339 case BPF_JMP32 | BPF_JSGT | BPF_K:
1340 case BPF_JMP32 | BPF_JSLT | BPF_K:
1341 case BPF_JMP32 | BPF_JSGE | BPF_K:
1342 case BPF_JMP32 | BPF_JSLE | BPF_K:
1343 case BPF_JMP32 | BPF_JSET | BPF_K:
1344 /* Accommodate for extra offset in case of a backjump. */
1348 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1349 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1350 *to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX,
1354 case BPF_LD | BPF_IMM | BPF_DW:
1355 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
1356 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1357 *to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
1358 *to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
1360 case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
1361 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
1362 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1364 *to++ = BPF_ZEXT_REG(BPF_REG_AX);
1365 *to++ = BPF_ALU64_REG(BPF_OR, aux[0].dst_reg, BPF_REG_AX);
1368 case BPF_ST | BPF_MEM | BPF_DW:
1369 case BPF_ST | BPF_MEM | BPF_W:
1370 case BPF_ST | BPF_MEM | BPF_H:
1371 case BPF_ST | BPF_MEM | BPF_B:
1372 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1373 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1374 *to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
1378 return to - to_buff;
1381 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
1382 gfp_t gfp_extra_flags)
1384 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
1385 struct bpf_prog *fp;
1387 fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags);
1389 /* aux->prog still points to the fp_other one, so
1390 * when promoting the clone to the real program,
1391 * this still needs to be adapted.
1393 memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
1399 static void bpf_prog_clone_free(struct bpf_prog *fp)
1401 /* aux was stolen by the other clone, so we cannot free
1402 * it from this path! It will be freed eventually by the
1403 * other program on release.
1405 * At this point, we don't need a deferred release since
1406 * clone is guaranteed to not be locked.
1411 __bpf_prog_free(fp);
1414 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
1416 /* We have to repoint aux->prog to self, as we don't
1417 * know whether fp here is the clone or the original.
1420 bpf_prog_clone_free(fp_other);
1423 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
1425 struct bpf_insn insn_buff[16], aux[2];
1426 struct bpf_prog *clone, *tmp;
1427 int insn_delta, insn_cnt;
1428 struct bpf_insn *insn;
1431 if (!prog->blinding_requested || prog->blinded)
1434 clone = bpf_prog_clone_create(prog, GFP_USER);
1436 return ERR_PTR(-ENOMEM);
1438 insn_cnt = clone->len;
1439 insn = clone->insnsi;
1441 for (i = 0; i < insn_cnt; i++, insn++) {
1442 if (bpf_pseudo_func(insn)) {
1443 /* ld_imm64 with an address of bpf subprog is not
1444 * a user controlled constant. Don't randomize it,
1445 * since it will conflict with jit_subprogs() logic.
1452 /* We temporarily need to hold the original ld64 insn
1453 * so that we can still access the first part in the
1454 * second blinding run.
1456 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
1458 memcpy(aux, insn, sizeof(aux));
1460 rewritten = bpf_jit_blind_insn(insn, aux, insn_buff,
1461 clone->aux->verifier_zext);
1465 tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
1467 /* Patching may have repointed aux->prog during
1468 * realloc from the original one, so we need to
1469 * fix it up here on error.
1471 bpf_jit_prog_release_other(prog, clone);
1476 insn_delta = rewritten - 1;
1478 /* Walk new program and skip insns we just inserted. */
1479 insn = clone->insnsi + i + insn_delta;
1480 insn_cnt += insn_delta;
1487 #endif /* CONFIG_BPF_JIT */
1489 /* Base function for offset calculation. Needs to go into .text section,
1490 * therefore keeping it non-static as well; will also be used by JITs
1491 * anyway later on, so do not let the compiler omit it. This also needs
1492 * to go into kallsyms for correlation from e.g. bpftool, so naming
1495 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
1499 EXPORT_SYMBOL_GPL(__bpf_call_base);
1501 /* All UAPI available opcodes. */
1502 #define BPF_INSN_MAP(INSN_2, INSN_3) \
1503 /* 32 bit ALU operations. */ \
1504 /* Register based. */ \
1505 INSN_3(ALU, ADD, X), \
1506 INSN_3(ALU, SUB, X), \
1507 INSN_3(ALU, AND, X), \
1508 INSN_3(ALU, OR, X), \
1509 INSN_3(ALU, LSH, X), \
1510 INSN_3(ALU, RSH, X), \
1511 INSN_3(ALU, XOR, X), \
1512 INSN_3(ALU, MUL, X), \
1513 INSN_3(ALU, MOV, X), \
1514 INSN_3(ALU, ARSH, X), \
1515 INSN_3(ALU, DIV, X), \
1516 INSN_3(ALU, MOD, X), \
1518 INSN_3(ALU, END, TO_BE), \
1519 INSN_3(ALU, END, TO_LE), \
1520 /* Immediate based. */ \
1521 INSN_3(ALU, ADD, K), \
1522 INSN_3(ALU, SUB, K), \
1523 INSN_3(ALU, AND, K), \
1524 INSN_3(ALU, OR, K), \
1525 INSN_3(ALU, LSH, K), \
1526 INSN_3(ALU, RSH, K), \
1527 INSN_3(ALU, XOR, K), \
1528 INSN_3(ALU, MUL, K), \
1529 INSN_3(ALU, MOV, K), \
1530 INSN_3(ALU, ARSH, K), \
1531 INSN_3(ALU, DIV, K), \
1532 INSN_3(ALU, MOD, K), \
1533 /* 64 bit ALU operations. */ \
1534 /* Register based. */ \
1535 INSN_3(ALU64, ADD, X), \
1536 INSN_3(ALU64, SUB, X), \
1537 INSN_3(ALU64, AND, X), \
1538 INSN_3(ALU64, OR, X), \
1539 INSN_3(ALU64, LSH, X), \
1540 INSN_3(ALU64, RSH, X), \
1541 INSN_3(ALU64, XOR, X), \
1542 INSN_3(ALU64, MUL, X), \
1543 INSN_3(ALU64, MOV, X), \
1544 INSN_3(ALU64, ARSH, X), \
1545 INSN_3(ALU64, DIV, X), \
1546 INSN_3(ALU64, MOD, X), \
1547 INSN_2(ALU64, NEG), \
1548 /* Immediate based. */ \
1549 INSN_3(ALU64, ADD, K), \
1550 INSN_3(ALU64, SUB, K), \
1551 INSN_3(ALU64, AND, K), \
1552 INSN_3(ALU64, OR, K), \
1553 INSN_3(ALU64, LSH, K), \
1554 INSN_3(ALU64, RSH, K), \
1555 INSN_3(ALU64, XOR, K), \
1556 INSN_3(ALU64, MUL, K), \
1557 INSN_3(ALU64, MOV, K), \
1558 INSN_3(ALU64, ARSH, K), \
1559 INSN_3(ALU64, DIV, K), \
1560 INSN_3(ALU64, MOD, K), \
1561 /* Call instruction. */ \
1562 INSN_2(JMP, CALL), \
1563 /* Exit instruction. */ \
1564 INSN_2(JMP, EXIT), \
1565 /* 32-bit Jump instructions. */ \
1566 /* Register based. */ \
1567 INSN_3(JMP32, JEQ, X), \
1568 INSN_3(JMP32, JNE, X), \
1569 INSN_3(JMP32, JGT, X), \
1570 INSN_3(JMP32, JLT, X), \
1571 INSN_3(JMP32, JGE, X), \
1572 INSN_3(JMP32, JLE, X), \
1573 INSN_3(JMP32, JSGT, X), \
1574 INSN_3(JMP32, JSLT, X), \
1575 INSN_3(JMP32, JSGE, X), \
1576 INSN_3(JMP32, JSLE, X), \
1577 INSN_3(JMP32, JSET, X), \
1578 /* Immediate based. */ \
1579 INSN_3(JMP32, JEQ, K), \
1580 INSN_3(JMP32, JNE, K), \
1581 INSN_3(JMP32, JGT, K), \
1582 INSN_3(JMP32, JLT, K), \
1583 INSN_3(JMP32, JGE, K), \
1584 INSN_3(JMP32, JLE, K), \
1585 INSN_3(JMP32, JSGT, K), \
1586 INSN_3(JMP32, JSLT, K), \
1587 INSN_3(JMP32, JSGE, K), \
1588 INSN_3(JMP32, JSLE, K), \
1589 INSN_3(JMP32, JSET, K), \
1590 /* Jump instructions. */ \
1591 /* Register based. */ \
1592 INSN_3(JMP, JEQ, X), \
1593 INSN_3(JMP, JNE, X), \
1594 INSN_3(JMP, JGT, X), \
1595 INSN_3(JMP, JLT, X), \
1596 INSN_3(JMP, JGE, X), \
1597 INSN_3(JMP, JLE, X), \
1598 INSN_3(JMP, JSGT, X), \
1599 INSN_3(JMP, JSLT, X), \
1600 INSN_3(JMP, JSGE, X), \
1601 INSN_3(JMP, JSLE, X), \
1602 INSN_3(JMP, JSET, X), \
1603 /* Immediate based. */ \
1604 INSN_3(JMP, JEQ, K), \
1605 INSN_3(JMP, JNE, K), \
1606 INSN_3(JMP, JGT, K), \
1607 INSN_3(JMP, JLT, K), \
1608 INSN_3(JMP, JGE, K), \
1609 INSN_3(JMP, JLE, K), \
1610 INSN_3(JMP, JSGT, K), \
1611 INSN_3(JMP, JSLT, K), \
1612 INSN_3(JMP, JSGE, K), \
1613 INSN_3(JMP, JSLE, K), \
1614 INSN_3(JMP, JSET, K), \
1616 /* Store instructions. */ \
1617 /* Register based. */ \
1618 INSN_3(STX, MEM, B), \
1619 INSN_3(STX, MEM, H), \
1620 INSN_3(STX, MEM, W), \
1621 INSN_3(STX, MEM, DW), \
1622 INSN_3(STX, ATOMIC, W), \
1623 INSN_3(STX, ATOMIC, DW), \
1624 /* Immediate based. */ \
1625 INSN_3(ST, MEM, B), \
1626 INSN_3(ST, MEM, H), \
1627 INSN_3(ST, MEM, W), \
1628 INSN_3(ST, MEM, DW), \
1629 /* Load instructions. */ \
1630 /* Register based. */ \
1631 INSN_3(LDX, MEM, B), \
1632 INSN_3(LDX, MEM, H), \
1633 INSN_3(LDX, MEM, W), \
1634 INSN_3(LDX, MEM, DW), \
1635 /* Immediate based. */ \
1638 bool bpf_opcode_in_insntable(u8 code)
1640 #define BPF_INSN_2_TBL(x, y) [BPF_##x | BPF_##y] = true
1641 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
1642 static const bool public_insntable[256] = {
1643 [0 ... 255] = false,
1644 /* Now overwrite non-defaults ... */
1645 BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
1646 /* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
1647 [BPF_LD | BPF_ABS | BPF_B] = true,
1648 [BPF_LD | BPF_ABS | BPF_H] = true,
1649 [BPF_LD | BPF_ABS | BPF_W] = true,
1650 [BPF_LD | BPF_IND | BPF_B] = true,
1651 [BPF_LD | BPF_IND | BPF_H] = true,
1652 [BPF_LD | BPF_IND | BPF_W] = true,
1654 #undef BPF_INSN_3_TBL
1655 #undef BPF_INSN_2_TBL
1656 return public_insntable[code];
1659 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1660 u64 __weak bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr)
1662 memset(dst, 0, size);
1667 * ___bpf_prog_run - run eBPF program on a given context
1668 * @regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers
1669 * @insn: is the array of eBPF instructions
1671 * Decode and execute eBPF instructions.
1673 * Return: whatever value is in %BPF_R0 at program exit
1675 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn)
1677 #define BPF_INSN_2_LBL(x, y) [BPF_##x | BPF_##y] = &&x##_##y
1678 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
1679 static const void * const jumptable[256] __annotate_jump_table = {
1680 [0 ... 255] = &&default_label,
1681 /* Now overwrite non-defaults ... */
1682 BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
1683 /* Non-UAPI available opcodes. */
1684 [BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
1685 [BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
1686 [BPF_ST | BPF_NOSPEC] = &&ST_NOSPEC,
1687 [BPF_LDX | BPF_PROBE_MEM | BPF_B] = &&LDX_PROBE_MEM_B,
1688 [BPF_LDX | BPF_PROBE_MEM | BPF_H] = &&LDX_PROBE_MEM_H,
1689 [BPF_LDX | BPF_PROBE_MEM | BPF_W] = &&LDX_PROBE_MEM_W,
1690 [BPF_LDX | BPF_PROBE_MEM | BPF_DW] = &&LDX_PROBE_MEM_DW,
1692 #undef BPF_INSN_3_LBL
1693 #undef BPF_INSN_2_LBL
1694 u32 tail_call_cnt = 0;
1696 #define CONT ({ insn++; goto select_insn; })
1697 #define CONT_JMP ({ insn++; goto select_insn; })
1700 goto *jumptable[insn->code];
1702 /* Explicitly mask the register-based shift amounts with 63 or 31
1703 * to avoid undefined behavior. Normally this won't affect the
1704 * generated code, for example, in case of native 64 bit archs such
1705 * as x86-64 or arm64, the compiler is optimizing the AND away for
1706 * the interpreter. In case of JITs, each of the JIT backends compiles
1707 * the BPF shift operations to machine instructions which produce
1708 * implementation-defined results in such a case; the resulting
1709 * contents of the register may be arbitrary, but program behaviour
1710 * as a whole remains defined. In other words, in case of JIT backends,
1711 * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation.
1714 #define SHT(OPCODE, OP) \
1715 ALU64_##OPCODE##_X: \
1716 DST = DST OP (SRC & 63); \
1719 DST = (u32) DST OP ((u32) SRC & 31); \
1721 ALU64_##OPCODE##_K: \
1725 DST = (u32) DST OP (u32) IMM; \
1728 #define ALU(OPCODE, OP) \
1729 ALU64_##OPCODE##_X: \
1733 DST = (u32) DST OP (u32) SRC; \
1735 ALU64_##OPCODE##_K: \
1739 DST = (u32) DST OP (u32) IMM; \
1770 DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1774 DST = (u64) (u32) (((s32) DST) >> (SRC & 31));
1777 DST = (u64) (u32) (((s32) DST) >> IMM);
1780 (*(s64 *) &DST) >>= (SRC & 63);
1783 (*(s64 *) &DST) >>= IMM;
1786 div64_u64_rem(DST, SRC, &AX);
1791 DST = do_div(AX, (u32) SRC);
1794 div64_u64_rem(DST, IMM, &AX);
1799 DST = do_div(AX, (u32) IMM);
1802 DST = div64_u64(DST, SRC);
1806 do_div(AX, (u32) SRC);
1810 DST = div64_u64(DST, IMM);
1814 do_div(AX, (u32) IMM);
1820 DST = (__force u16) cpu_to_be16(DST);
1823 DST = (__force u32) cpu_to_be32(DST);
1826 DST = (__force u64) cpu_to_be64(DST);
1833 DST = (__force u16) cpu_to_le16(DST);
1836 DST = (__force u32) cpu_to_le32(DST);
1839 DST = (__force u64) cpu_to_le64(DST);
1846 /* Function call scratches BPF_R1-BPF_R5 registers,
1847 * preserves BPF_R6-BPF_R9, and stores return value
1850 BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1855 BPF_R0 = (__bpf_call_base_args + insn->imm)(BPF_R1, BPF_R2,
1858 insn + insn->off + 1);
1862 struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1863 struct bpf_array *array = container_of(map, struct bpf_array, map);
1864 struct bpf_prog *prog;
1867 if (unlikely(index >= array->map.max_entries))
1870 if (unlikely(tail_call_cnt >= MAX_TAIL_CALL_CNT))
1875 prog = READ_ONCE(array->ptrs[index]);
1879 /* ARG1 at this point is guaranteed to point to CTX from
1880 * the verifier side due to the fact that the tail call is
1881 * handled like a helper, that is, bpf_tail_call_proto,
1882 * where arg1_type is ARG_PTR_TO_CTX.
1884 insn = prog->insnsi;
1895 #define COND_JMP(SIGN, OPCODE, CMP_OP) \
1897 if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) { \
1898 insn += insn->off; \
1902 JMP32_##OPCODE##_X: \
1903 if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) { \
1904 insn += insn->off; \
1909 if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) { \
1910 insn += insn->off; \
1914 JMP32_##OPCODE##_K: \
1915 if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) { \
1916 insn += insn->off; \
1920 COND_JMP(u, JEQ, ==)
1921 COND_JMP(u, JNE, !=)
1924 COND_JMP(u, JGE, >=)
1925 COND_JMP(u, JLE, <=)
1926 COND_JMP(u, JSET, &)
1927 COND_JMP(s, JSGT, >)
1928 COND_JMP(s, JSLT, <)
1929 COND_JMP(s, JSGE, >=)
1930 COND_JMP(s, JSLE, <=)
1932 /* ST, STX and LDX*/
1934 /* Speculation barrier for mitigating Speculative Store Bypass.
1935 * In case of arm64, we rely on the firmware mitigation as
1936 * controlled via the ssbd kernel parameter. Whenever the
1937 * mitigation is enabled, it works for all of the kernel code
1938 * with no need to provide any additional instructions here.
1939 * In case of x86, we use 'lfence' insn for mitigation. We
1940 * reuse preexisting logic from Spectre v1 mitigation that
1941 * happens to produce the required code on x86 for v4 as well.
1947 #define LDST(SIZEOP, SIZE) \
1949 *(SIZE *)(unsigned long) (DST + insn->off) = SRC; \
1952 *(SIZE *)(unsigned long) (DST + insn->off) = IMM; \
1955 DST = *(SIZE *)(unsigned long) (SRC + insn->off); \
1963 #define LDX_PROBE(SIZEOP, SIZE) \
1964 LDX_PROBE_MEM_##SIZEOP: \
1965 bpf_probe_read_kernel(&DST, SIZE, (const void *)(long) (SRC + insn->off)); \
1973 #define ATOMIC_ALU_OP(BOP, KOP) \
1975 if (BPF_SIZE(insn->code) == BPF_W) \
1976 atomic_##KOP((u32) SRC, (atomic_t *)(unsigned long) \
1977 (DST + insn->off)); \
1979 atomic64_##KOP((u64) SRC, (atomic64_t *)(unsigned long) \
1980 (DST + insn->off)); \
1982 case BOP | BPF_FETCH: \
1983 if (BPF_SIZE(insn->code) == BPF_W) \
1984 SRC = (u32) atomic_fetch_##KOP( \
1986 (atomic_t *)(unsigned long) (DST + insn->off)); \
1988 SRC = (u64) atomic64_fetch_##KOP( \
1990 (atomic64_t *)(unsigned long) (DST + insn->off)); \
1996 ATOMIC_ALU_OP(BPF_ADD, add)
1997 ATOMIC_ALU_OP(BPF_AND, and)
1998 ATOMIC_ALU_OP(BPF_OR, or)
1999 ATOMIC_ALU_OP(BPF_XOR, xor)
2000 #undef ATOMIC_ALU_OP
2003 if (BPF_SIZE(insn->code) == BPF_W)
2004 SRC = (u32) atomic_xchg(
2005 (atomic_t *)(unsigned long) (DST + insn->off),
2008 SRC = (u64) atomic64_xchg(
2009 (atomic64_t *)(unsigned long) (DST + insn->off),
2013 if (BPF_SIZE(insn->code) == BPF_W)
2014 BPF_R0 = (u32) atomic_cmpxchg(
2015 (atomic_t *)(unsigned long) (DST + insn->off),
2016 (u32) BPF_R0, (u32) SRC);
2018 BPF_R0 = (u64) atomic64_cmpxchg(
2019 (atomic64_t *)(unsigned long) (DST + insn->off),
2020 (u64) BPF_R0, (u64) SRC);
2029 /* If we ever reach this, we have a bug somewhere. Die hard here
2030 * instead of just returning 0; we could be somewhere in a subprog,
2031 * so execution could continue otherwise which we do /not/ want.
2033 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
2035 pr_warn("BPF interpreter: unknown opcode %02x (imm: 0x%x)\n",
2036 insn->code, insn->imm);
2041 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
2042 #define DEFINE_BPF_PROG_RUN(stack_size) \
2043 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
2045 u64 stack[stack_size / sizeof(u64)]; \
2046 u64 regs[MAX_BPF_EXT_REG]; \
2048 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2049 ARG1 = (u64) (unsigned long) ctx; \
2050 return ___bpf_prog_run(regs, insn); \
2053 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
2054 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
2055 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
2056 const struct bpf_insn *insn) \
2058 u64 stack[stack_size / sizeof(u64)]; \
2059 u64 regs[MAX_BPF_EXT_REG]; \
2061 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2067 return ___bpf_prog_run(regs, insn); \
2070 #define EVAL1(FN, X) FN(X)
2071 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
2072 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
2073 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
2074 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
2075 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
2077 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
2078 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
2079 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
2081 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
2082 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
2083 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
2085 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
2087 static unsigned int (*interpreters[])(const void *ctx,
2088 const struct bpf_insn *insn) = {
2089 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2090 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2091 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2093 #undef PROG_NAME_LIST
2094 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
2095 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
2096 const struct bpf_insn *insn) = {
2097 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2098 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2099 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2101 #undef PROG_NAME_LIST
2103 void bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
2105 stack_depth = max_t(u32, stack_depth, 1);
2106 insn->off = (s16) insn->imm;
2107 insn->imm = interpreters_args[(round_up(stack_depth, 32) / 32) - 1] -
2108 __bpf_call_base_args;
2109 insn->code = BPF_JMP | BPF_CALL_ARGS;
2113 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
2114 const struct bpf_insn *insn)
2116 /* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
2117 * is not working properly, so warn about it!
2124 bool bpf_prog_map_compatible(struct bpf_map *map,
2125 const struct bpf_prog *fp)
2129 if (fp->kprobe_override)
2132 spin_lock(&map->owner.lock);
2133 if (!map->owner.type) {
2134 /* There's no owner yet where we could check for
2137 map->owner.type = fp->type;
2138 map->owner.jited = fp->jited;
2139 map->owner.xdp_has_frags = fp->aux->xdp_has_frags;
2142 ret = map->owner.type == fp->type &&
2143 map->owner.jited == fp->jited &&
2144 map->owner.xdp_has_frags == fp->aux->xdp_has_frags;
2146 spin_unlock(&map->owner.lock);
2151 static int bpf_check_tail_call(const struct bpf_prog *fp)
2153 struct bpf_prog_aux *aux = fp->aux;
2156 mutex_lock(&aux->used_maps_mutex);
2157 for (i = 0; i < aux->used_map_cnt; i++) {
2158 struct bpf_map *map = aux->used_maps[i];
2160 if (!map_type_contains_progs(map))
2163 if (!bpf_prog_map_compatible(map, fp)) {
2170 mutex_unlock(&aux->used_maps_mutex);
2174 static void bpf_prog_select_func(struct bpf_prog *fp)
2176 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2177 u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
2179 fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
2181 fp->bpf_func = __bpf_prog_ret0_warn;
2186 * bpf_prog_select_runtime - select exec runtime for BPF program
2187 * @fp: bpf_prog populated with BPF program
2188 * @err: pointer to error variable
2190 * Try to JIT eBPF program, if JIT is not available, use interpreter.
2191 * The BPF program will be executed via bpf_prog_run() function.
2193 * Return: the &fp argument along with &err set to 0 for success or
2194 * a negative errno code on failure
2196 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
2198 /* In case of BPF to BPF calls, verifier did all the prep
2199 * work with regards to JITing, etc.
2201 bool jit_needed = false;
2206 if (IS_ENABLED(CONFIG_BPF_JIT_ALWAYS_ON) ||
2207 bpf_prog_has_kfunc_call(fp))
2210 bpf_prog_select_func(fp);
2212 /* eBPF JITs can rewrite the program in case constant
2213 * blinding is active. However, in case of error during
2214 * blinding, bpf_int_jit_compile() must always return a
2215 * valid program, which in this case would simply not
2216 * be JITed, but falls back to the interpreter.
2218 if (!bpf_prog_is_dev_bound(fp->aux)) {
2219 *err = bpf_prog_alloc_jited_linfo(fp);
2223 fp = bpf_int_jit_compile(fp);
2224 bpf_prog_jit_attempt_done(fp);
2225 if (!fp->jited && jit_needed) {
2230 *err = bpf_prog_offload_compile(fp);
2236 bpf_prog_lock_ro(fp);
2238 /* The tail call compatibility check can only be done at
2239 * this late stage as we need to determine, if we deal
2240 * with JITed or non JITed program concatenations and not
2241 * all eBPF JITs might immediately support all features.
2243 *err = bpf_check_tail_call(fp);
2247 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
2249 static unsigned int __bpf_prog_ret1(const void *ctx,
2250 const struct bpf_insn *insn)
2255 static struct bpf_prog_dummy {
2256 struct bpf_prog prog;
2257 } dummy_bpf_prog = {
2259 .bpf_func = __bpf_prog_ret1,
2263 struct bpf_empty_prog_array bpf_empty_prog_array = {
2266 EXPORT_SYMBOL(bpf_empty_prog_array);
2268 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
2271 return kzalloc(sizeof(struct bpf_prog_array) +
2272 sizeof(struct bpf_prog_array_item) *
2276 return &bpf_empty_prog_array.hdr;
2279 void bpf_prog_array_free(struct bpf_prog_array *progs)
2281 if (!progs || progs == &bpf_empty_prog_array.hdr)
2283 kfree_rcu(progs, rcu);
2286 int bpf_prog_array_length(struct bpf_prog_array *array)
2288 struct bpf_prog_array_item *item;
2291 for (item = array->items; item->prog; item++)
2292 if (item->prog != &dummy_bpf_prog.prog)
2297 bool bpf_prog_array_is_empty(struct bpf_prog_array *array)
2299 struct bpf_prog_array_item *item;
2301 for (item = array->items; item->prog; item++)
2302 if (item->prog != &dummy_bpf_prog.prog)
2307 static bool bpf_prog_array_copy_core(struct bpf_prog_array *array,
2311 struct bpf_prog_array_item *item;
2314 for (item = array->items; item->prog; item++) {
2315 if (item->prog == &dummy_bpf_prog.prog)
2317 prog_ids[i] = item->prog->aux->id;
2318 if (++i == request_cnt) {
2324 return !!(item->prog);
2327 int bpf_prog_array_copy_to_user(struct bpf_prog_array *array,
2328 __u32 __user *prog_ids, u32 cnt)
2330 unsigned long err = 0;
2334 /* users of this function are doing:
2335 * cnt = bpf_prog_array_length();
2337 * bpf_prog_array_copy_to_user(..., cnt);
2338 * so below kcalloc doesn't need extra cnt > 0 check.
2340 ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
2343 nospc = bpf_prog_array_copy_core(array, ids, cnt);
2344 err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
2353 void bpf_prog_array_delete_safe(struct bpf_prog_array *array,
2354 struct bpf_prog *old_prog)
2356 struct bpf_prog_array_item *item;
2358 for (item = array->items; item->prog; item++)
2359 if (item->prog == old_prog) {
2360 WRITE_ONCE(item->prog, &dummy_bpf_prog.prog);
2366 * bpf_prog_array_delete_safe_at() - Replaces the program at the given
2367 * index into the program array with
2368 * a dummy no-op program.
2369 * @array: a bpf_prog_array
2370 * @index: the index of the program to replace
2372 * Skips over dummy programs, by not counting them, when calculating
2373 * the position of the program to replace.
2377 * * -EINVAL - Invalid index value. Must be a non-negative integer.
2378 * * -ENOENT - Index out of range
2380 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index)
2382 return bpf_prog_array_update_at(array, index, &dummy_bpf_prog.prog);
2386 * bpf_prog_array_update_at() - Updates the program at the given index
2387 * into the program array.
2388 * @array: a bpf_prog_array
2389 * @index: the index of the program to update
2390 * @prog: the program to insert into the array
2392 * Skips over dummy programs, by not counting them, when calculating
2393 * the position of the program to update.
2397 * * -EINVAL - Invalid index value. Must be a non-negative integer.
2398 * * -ENOENT - Index out of range
2400 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index,
2401 struct bpf_prog *prog)
2403 struct bpf_prog_array_item *item;
2405 if (unlikely(index < 0))
2408 for (item = array->items; item->prog; item++) {
2409 if (item->prog == &dummy_bpf_prog.prog)
2412 WRITE_ONCE(item->prog, prog);
2420 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
2421 struct bpf_prog *exclude_prog,
2422 struct bpf_prog *include_prog,
2424 struct bpf_prog_array **new_array)
2426 int new_prog_cnt, carry_prog_cnt = 0;
2427 struct bpf_prog_array_item *existing, *new;
2428 struct bpf_prog_array *array;
2429 bool found_exclude = false;
2431 /* Figure out how many existing progs we need to carry over to
2435 existing = old_array->items;
2436 for (; existing->prog; existing++) {
2437 if (existing->prog == exclude_prog) {
2438 found_exclude = true;
2441 if (existing->prog != &dummy_bpf_prog.prog)
2443 if (existing->prog == include_prog)
2448 if (exclude_prog && !found_exclude)
2451 /* How many progs (not NULL) will be in the new array? */
2452 new_prog_cnt = carry_prog_cnt;
2456 /* Do we have any prog (not NULL) in the new array? */
2457 if (!new_prog_cnt) {
2462 /* +1 as the end of prog_array is marked with NULL */
2463 array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
2468 /* Fill in the new prog array */
2469 if (carry_prog_cnt) {
2470 existing = old_array->items;
2471 for (; existing->prog; existing++) {
2472 if (existing->prog == exclude_prog ||
2473 existing->prog == &dummy_bpf_prog.prog)
2476 new->prog = existing->prog;
2477 new->bpf_cookie = existing->bpf_cookie;
2482 new->prog = include_prog;
2483 new->bpf_cookie = bpf_cookie;
2491 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
2492 u32 *prog_ids, u32 request_cnt,
2498 cnt = bpf_prog_array_length(array);
2502 /* return early if user requested only program count or nothing to copy */
2503 if (!request_cnt || !cnt)
2506 /* this function is called under trace/bpf_trace.c: bpf_event_mutex */
2507 return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC
2511 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
2512 struct bpf_map **used_maps, u32 len)
2514 struct bpf_map *map;
2517 for (i = 0; i < len; i++) {
2519 if (map->ops->map_poke_untrack)
2520 map->ops->map_poke_untrack(map, aux);
2525 static void bpf_free_used_maps(struct bpf_prog_aux *aux)
2527 __bpf_free_used_maps(aux, aux->used_maps, aux->used_map_cnt);
2528 kfree(aux->used_maps);
2531 void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
2532 struct btf_mod_pair *used_btfs, u32 len)
2534 #ifdef CONFIG_BPF_SYSCALL
2535 struct btf_mod_pair *btf_mod;
2538 for (i = 0; i < len; i++) {
2539 btf_mod = &used_btfs[i];
2540 if (btf_mod->module)
2541 module_put(btf_mod->module);
2542 btf_put(btf_mod->btf);
2547 static void bpf_free_used_btfs(struct bpf_prog_aux *aux)
2549 __bpf_free_used_btfs(aux, aux->used_btfs, aux->used_btf_cnt);
2550 kfree(aux->used_btfs);
2553 static void bpf_prog_free_deferred(struct work_struct *work)
2555 struct bpf_prog_aux *aux;
2558 aux = container_of(work, struct bpf_prog_aux, work);
2559 #ifdef CONFIG_BPF_SYSCALL
2560 bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab);
2562 bpf_free_used_maps(aux);
2563 bpf_free_used_btfs(aux);
2564 if (bpf_prog_is_dev_bound(aux))
2565 bpf_prog_offload_destroy(aux->prog);
2566 #ifdef CONFIG_PERF_EVENTS
2567 if (aux->prog->has_callchain_buf)
2568 put_callchain_buffers();
2570 if (aux->dst_trampoline)
2571 bpf_trampoline_put(aux->dst_trampoline);
2572 for (i = 0; i < aux->func_cnt; i++) {
2573 /* We can just unlink the subprog poke descriptor table as
2574 * it was originally linked to the main program and is also
2575 * released along with it.
2577 aux->func[i]->aux->poke_tab = NULL;
2578 bpf_jit_free(aux->func[i]);
2580 if (aux->func_cnt) {
2582 bpf_prog_unlock_free(aux->prog);
2584 bpf_jit_free(aux->prog);
2588 void bpf_prog_free(struct bpf_prog *fp)
2590 struct bpf_prog_aux *aux = fp->aux;
2593 bpf_prog_put(aux->dst_prog);
2594 INIT_WORK(&aux->work, bpf_prog_free_deferred);
2595 schedule_work(&aux->work);
2597 EXPORT_SYMBOL_GPL(bpf_prog_free);
2599 /* RNG for unpriviledged user space with separated state from prandom_u32(). */
2600 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
2602 void bpf_user_rnd_init_once(void)
2604 prandom_init_once(&bpf_user_rnd_state);
2607 BPF_CALL_0(bpf_user_rnd_u32)
2609 /* Should someone ever have the rather unwise idea to use some
2610 * of the registers passed into this function, then note that
2611 * this function is called from native eBPF and classic-to-eBPF
2612 * transformations. Register assignments from both sides are
2613 * different, f.e. classic always sets fn(ctx, A, X) here.
2615 struct rnd_state *state;
2618 state = &get_cpu_var(bpf_user_rnd_state);
2619 res = prandom_u32_state(state);
2620 put_cpu_var(bpf_user_rnd_state);
2625 BPF_CALL_0(bpf_get_raw_cpu_id)
2627 return raw_smp_processor_id();
2630 /* Weak definitions of helper functions in case we don't have bpf syscall. */
2631 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
2632 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
2633 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
2634 const struct bpf_func_proto bpf_map_push_elem_proto __weak;
2635 const struct bpf_func_proto bpf_map_pop_elem_proto __weak;
2636 const struct bpf_func_proto bpf_map_peek_elem_proto __weak;
2637 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto __weak;
2638 const struct bpf_func_proto bpf_spin_lock_proto __weak;
2639 const struct bpf_func_proto bpf_spin_unlock_proto __weak;
2640 const struct bpf_func_proto bpf_jiffies64_proto __weak;
2642 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
2643 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
2644 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
2645 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
2646 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto __weak;
2647 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto __weak;
2649 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
2650 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
2651 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
2652 const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak;
2653 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto __weak;
2654 const struct bpf_func_proto bpf_get_local_storage_proto __weak;
2655 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto __weak;
2656 const struct bpf_func_proto bpf_snprintf_btf_proto __weak;
2657 const struct bpf_func_proto bpf_seq_printf_btf_proto __weak;
2659 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
2664 const struct bpf_func_proto * __weak bpf_get_trace_vprintk_proto(void)
2670 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2671 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
2675 EXPORT_SYMBOL_GPL(bpf_event_output);
2677 /* Always built-in helper functions. */
2678 const struct bpf_func_proto bpf_tail_call_proto = {
2681 .ret_type = RET_VOID,
2682 .arg1_type = ARG_PTR_TO_CTX,
2683 .arg2_type = ARG_CONST_MAP_PTR,
2684 .arg3_type = ARG_ANYTHING,
2687 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
2688 * It is encouraged to implement bpf_int_jit_compile() instead, so that
2689 * eBPF and implicitly also cBPF can get JITed!
2691 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
2696 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
2697 * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
2699 void __weak bpf_jit_compile(struct bpf_prog *prog)
2703 bool __weak bpf_helper_changes_pkt_data(void *func)
2708 /* Return TRUE if the JIT backend wants verifier to enable sub-register usage
2709 * analysis code and wants explicit zero extension inserted by verifier.
2710 * Otherwise, return FALSE.
2712 * The verifier inserts an explicit zero extension after BPF_CMPXCHGs even if
2713 * you don't override this. JITs that don't want these extra insns can detect
2714 * them using insn_is_zext.
2716 bool __weak bpf_jit_needs_zext(void)
2721 bool __weak bpf_jit_supports_kfunc_call(void)
2726 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
2727 * skb_copy_bits(), so provide a weak definition of it for NET-less config.
2729 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
2735 int __weak bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
2736 void *addr1, void *addr2)
2741 void * __weak bpf_arch_text_copy(void *dst, void *src, size_t len)
2743 return ERR_PTR(-ENOTSUPP);
2746 int __weak bpf_arch_text_invalidate(void *dst, size_t len)
2751 DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key);
2752 EXPORT_SYMBOL(bpf_stats_enabled_key);
2754 /* All definitions of tracepoints related to BPF. */
2755 #define CREATE_TRACE_POINTS
2756 #include <linux/bpf_trace.h>
2758 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
2759 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);