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)
71 if (k >= SKF_NET_OFF) {
72 ptr = skb_network_header(skb) + k - SKF_NET_OFF;
73 } else if (k >= SKF_LL_OFF) {
74 if (unlikely(!skb_mac_header_was_set(skb)))
76 ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
78 if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
84 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
86 gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
87 struct bpf_prog_aux *aux;
90 size = round_up(size, PAGE_SIZE);
91 fp = __vmalloc(size, gfp_flags);
95 aux = kzalloc(sizeof(*aux), GFP_KERNEL_ACCOUNT | gfp_extra_flags);
100 fp->active = alloc_percpu_gfp(int, GFP_KERNEL_ACCOUNT | gfp_extra_flags);
107 fp->pages = size / PAGE_SIZE;
110 fp->jit_requested = ebpf_jit_enabled();
111 fp->blinding_requested = bpf_jit_blinding_enabled(fp);
113 INIT_LIST_HEAD_RCU(&fp->aux->ksym.lnode);
114 mutex_init(&fp->aux->used_maps_mutex);
115 mutex_init(&fp->aux->dst_mutex);
120 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
122 gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
123 struct bpf_prog *prog;
126 prog = bpf_prog_alloc_no_stats(size, gfp_extra_flags);
130 prog->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags);
132 free_percpu(prog->active);
138 for_each_possible_cpu(cpu) {
139 struct bpf_prog_stats *pstats;
141 pstats = per_cpu_ptr(prog->stats, cpu);
142 u64_stats_init(&pstats->syncp);
146 EXPORT_SYMBOL_GPL(bpf_prog_alloc);
148 int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog)
150 if (!prog->aux->nr_linfo || !prog->jit_requested)
153 prog->aux->jited_linfo = kvcalloc(prog->aux->nr_linfo,
154 sizeof(*prog->aux->jited_linfo),
155 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
156 if (!prog->aux->jited_linfo)
162 void bpf_prog_jit_attempt_done(struct bpf_prog *prog)
164 if (prog->aux->jited_linfo &&
165 (!prog->jited || !prog->aux->jited_linfo[0])) {
166 kvfree(prog->aux->jited_linfo);
167 prog->aux->jited_linfo = NULL;
170 kfree(prog->aux->kfunc_tab);
171 prog->aux->kfunc_tab = NULL;
174 /* The jit engine is responsible to provide an array
175 * for insn_off to the jited_off mapping (insn_to_jit_off).
177 * The idx to this array is the insn_off. Hence, the insn_off
178 * here is relative to the prog itself instead of the main prog.
179 * This array has one entry for each xlated bpf insn.
181 * jited_off is the byte off to the last byte of the jited insn.
185 * The first bpf insn off of the prog. The insn off
186 * here is relative to the main prog.
187 * e.g. if prog is a subprog, insn_start > 0
189 * The prog's idx to prog->aux->linfo and jited_linfo
191 * jited_linfo[linfo_idx] = prog->bpf_func
195 * jited_linfo[i] = prog->bpf_func +
196 * insn_to_jit_off[linfo[i].insn_off - insn_start - 1]
198 void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
199 const u32 *insn_to_jit_off)
201 u32 linfo_idx, insn_start, insn_end, nr_linfo, i;
202 const struct bpf_line_info *linfo;
205 if (!prog->aux->jited_linfo)
206 /* Userspace did not provide linfo */
209 linfo_idx = prog->aux->linfo_idx;
210 linfo = &prog->aux->linfo[linfo_idx];
211 insn_start = linfo[0].insn_off;
212 insn_end = insn_start + prog->len;
214 jited_linfo = &prog->aux->jited_linfo[linfo_idx];
215 jited_linfo[0] = prog->bpf_func;
217 nr_linfo = prog->aux->nr_linfo - linfo_idx;
219 for (i = 1; i < nr_linfo && linfo[i].insn_off < insn_end; i++)
220 /* The verifier ensures that linfo[i].insn_off is
221 * strictly increasing
223 jited_linfo[i] = prog->bpf_func +
224 insn_to_jit_off[linfo[i].insn_off - insn_start - 1];
227 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
228 gfp_t gfp_extra_flags)
230 gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
234 size = round_up(size, PAGE_SIZE);
235 pages = size / PAGE_SIZE;
236 if (pages <= fp_old->pages)
239 fp = __vmalloc(size, gfp_flags);
241 memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
245 /* We keep fp->aux from fp_old around in the new
246 * reallocated structure.
249 fp_old->stats = NULL;
250 fp_old->active = NULL;
251 __bpf_prog_free(fp_old);
257 void __bpf_prog_free(struct bpf_prog *fp)
260 mutex_destroy(&fp->aux->used_maps_mutex);
261 mutex_destroy(&fp->aux->dst_mutex);
262 kfree(fp->aux->poke_tab);
265 free_percpu(fp->stats);
266 free_percpu(fp->active);
270 int bpf_prog_calc_tag(struct bpf_prog *fp)
272 const u32 bits_offset = SHA1_BLOCK_SIZE - sizeof(__be64);
273 u32 raw_size = bpf_prog_tag_scratch_size(fp);
274 u32 digest[SHA1_DIGEST_WORDS];
275 u32 ws[SHA1_WORKSPACE_WORDS];
276 u32 i, bsize, psize, blocks;
277 struct bpf_insn *dst;
283 raw = vmalloc(raw_size);
288 memset(ws, 0, sizeof(ws));
290 /* We need to take out the map fd for the digest calculation
291 * since they are unstable from user space side.
294 for (i = 0, was_ld_map = false; i < fp->len; i++) {
295 dst[i] = fp->insnsi[i];
297 dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
298 (dst[i].src_reg == BPF_PSEUDO_MAP_FD ||
299 dst[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
302 } else if (was_ld_map &&
304 dst[i].dst_reg == 0 &&
305 dst[i].src_reg == 0 &&
314 psize = bpf_prog_insn_size(fp);
315 memset(&raw[psize], 0, raw_size - psize);
318 bsize = round_up(psize, SHA1_BLOCK_SIZE);
319 blocks = bsize / SHA1_BLOCK_SIZE;
321 if (bsize - psize >= sizeof(__be64)) {
322 bits = (__be64 *)(todo + bsize - sizeof(__be64));
324 bits = (__be64 *)(todo + bsize + bits_offset);
327 *bits = cpu_to_be64((psize - 1) << 3);
330 sha1_transform(digest, todo, ws);
331 todo += SHA1_BLOCK_SIZE;
334 result = (__force __be32 *)digest;
335 for (i = 0; i < SHA1_DIGEST_WORDS; i++)
336 result[i] = cpu_to_be32(digest[i]);
337 memcpy(fp->tag, result, sizeof(fp->tag));
343 static int bpf_adj_delta_to_imm(struct bpf_insn *insn, u32 pos, s32 end_old,
344 s32 end_new, s32 curr, const bool probe_pass)
346 const s64 imm_min = S32_MIN, imm_max = S32_MAX;
347 s32 delta = end_new - end_old;
350 if (curr < pos && curr + imm + 1 >= end_old)
352 else if (curr >= end_new && curr + imm + 1 < end_new)
354 if (imm < imm_min || imm > imm_max)
361 static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old,
362 s32 end_new, s32 curr, const bool probe_pass)
364 const s32 off_min = S16_MIN, off_max = S16_MAX;
365 s32 delta = end_new - end_old;
368 if (curr < pos && curr + off + 1 >= end_old)
370 else if (curr >= end_new && curr + off + 1 < end_new)
372 if (off < off_min || off > off_max)
379 static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, s32 end_old,
380 s32 end_new, const bool probe_pass)
382 u32 i, insn_cnt = prog->len + (probe_pass ? end_new - end_old : 0);
383 struct bpf_insn *insn = prog->insnsi;
386 for (i = 0; i < insn_cnt; i++, insn++) {
389 /* In the probing pass we still operate on the original,
390 * unpatched image in order to check overflows before we
391 * do any other adjustments. Therefore skip the patchlet.
393 if (probe_pass && i == pos) {
395 insn = prog->insnsi + end_old;
397 if (bpf_pseudo_func(insn)) {
398 ret = bpf_adj_delta_to_imm(insn, pos, end_old,
399 end_new, i, probe_pass);
405 if ((BPF_CLASS(code) != BPF_JMP &&
406 BPF_CLASS(code) != BPF_JMP32) ||
407 BPF_OP(code) == BPF_EXIT)
409 /* Adjust offset of jmps if we cross patch boundaries. */
410 if (BPF_OP(code) == BPF_CALL) {
411 if (insn->src_reg != BPF_PSEUDO_CALL)
413 ret = bpf_adj_delta_to_imm(insn, pos, end_old,
414 end_new, i, probe_pass);
416 ret = bpf_adj_delta_to_off(insn, pos, end_old,
417 end_new, i, probe_pass);
426 static void bpf_adj_linfo(struct bpf_prog *prog, u32 off, u32 delta)
428 struct bpf_line_info *linfo;
431 nr_linfo = prog->aux->nr_linfo;
432 if (!nr_linfo || !delta)
435 linfo = prog->aux->linfo;
437 for (i = 0; i < nr_linfo; i++)
438 if (off < linfo[i].insn_off)
441 /* Push all off < linfo[i].insn_off by delta */
442 for (; i < nr_linfo; i++)
443 linfo[i].insn_off += delta;
446 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
447 const struct bpf_insn *patch, u32 len)
449 u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
450 const u32 cnt_max = S16_MAX;
451 struct bpf_prog *prog_adj;
454 /* Since our patchlet doesn't expand the image, we're done. */
455 if (insn_delta == 0) {
456 memcpy(prog->insnsi + off, patch, sizeof(*patch));
460 insn_adj_cnt = prog->len + insn_delta;
462 /* Reject anything that would potentially let the insn->off
463 * target overflow when we have excessive program expansions.
464 * We need to probe here before we do any reallocation where
465 * we afterwards may not fail anymore.
467 if (insn_adj_cnt > cnt_max &&
468 (err = bpf_adj_branches(prog, off, off + 1, off + len, true)))
471 /* Several new instructions need to be inserted. Make room
472 * for them. Likely, there's no need for a new allocation as
473 * last page could have large enough tailroom.
475 prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
478 return ERR_PTR(-ENOMEM);
480 prog_adj->len = insn_adj_cnt;
482 /* Patching happens in 3 steps:
484 * 1) Move over tail of insnsi from next instruction onwards,
485 * so we can patch the single target insn with one or more
486 * new ones (patching is always from 1 to n insns, n > 0).
487 * 2) Inject new instructions at the target location.
488 * 3) Adjust branch offsets if necessary.
490 insn_rest = insn_adj_cnt - off - len;
492 memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
493 sizeof(*patch) * insn_rest);
494 memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
496 /* We are guaranteed to not fail at this point, otherwise
497 * the ship has sailed to reverse to the original state. An
498 * overflow cannot happen at this point.
500 BUG_ON(bpf_adj_branches(prog_adj, off, off + 1, off + len, false));
502 bpf_adj_linfo(prog_adj, off, insn_delta);
507 int bpf_remove_insns(struct bpf_prog *prog, u32 off, u32 cnt)
509 /* Branch offsets can't overflow when program is shrinking, no need
510 * to call bpf_adj_branches(..., true) here
512 memmove(prog->insnsi + off, prog->insnsi + off + cnt,
513 sizeof(struct bpf_insn) * (prog->len - off - cnt));
516 return WARN_ON_ONCE(bpf_adj_branches(prog, off, off + cnt, off, false));
519 static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp)
523 for (i = 0; i < fp->aux->func_cnt; i++)
524 bpf_prog_kallsyms_del(fp->aux->func[i]);
527 void bpf_prog_kallsyms_del_all(struct bpf_prog *fp)
529 bpf_prog_kallsyms_del_subprogs(fp);
530 bpf_prog_kallsyms_del(fp);
533 #ifdef CONFIG_BPF_JIT
534 /* All BPF JIT sysctl knobs here. */
535 int bpf_jit_enable __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
536 int bpf_jit_kallsyms __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
537 int bpf_jit_harden __read_mostly;
538 long bpf_jit_limit __read_mostly;
539 long bpf_jit_limit_max __read_mostly;
542 bpf_prog_ksym_set_addr(struct bpf_prog *prog)
544 WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
546 prog->aux->ksym.start = (unsigned long) prog->bpf_func;
547 prog->aux->ksym.end = prog->aux->ksym.start + prog->jited_len;
551 bpf_prog_ksym_set_name(struct bpf_prog *prog)
553 char *sym = prog->aux->ksym.name;
554 const char *end = sym + KSYM_NAME_LEN;
555 const struct btf_type *type;
556 const char *func_name;
558 BUILD_BUG_ON(sizeof("bpf_prog_") +
559 sizeof(prog->tag) * 2 +
560 /* name has been null terminated.
561 * We should need +1 for the '_' preceding
562 * the name. However, the null character
563 * is double counted between the name and the
564 * sizeof("bpf_prog_") above, so we omit
567 sizeof(prog->aux->name) > KSYM_NAME_LEN);
569 sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
570 sym = bin2hex(sym, prog->tag, sizeof(prog->tag));
572 /* prog->aux->name will be ignored if full btf name is available */
573 if (prog->aux->func_info_cnt) {
574 type = btf_type_by_id(prog->aux->btf,
575 prog->aux->func_info[prog->aux->func_idx].type_id);
576 func_name = btf_name_by_offset(prog->aux->btf, type->name_off);
577 snprintf(sym, (size_t)(end - sym), "_%s", func_name);
581 if (prog->aux->name[0])
582 snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
587 static unsigned long bpf_get_ksym_start(struct latch_tree_node *n)
589 return container_of(n, struct bpf_ksym, tnode)->start;
592 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
593 struct latch_tree_node *b)
595 return bpf_get_ksym_start(a) < bpf_get_ksym_start(b);
598 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
600 unsigned long val = (unsigned long)key;
601 const struct bpf_ksym *ksym;
603 ksym = container_of(n, struct bpf_ksym, tnode);
605 if (val < ksym->start)
607 if (val >= ksym->end)
613 static const struct latch_tree_ops bpf_tree_ops = {
614 .less = bpf_tree_less,
615 .comp = bpf_tree_comp,
618 static DEFINE_SPINLOCK(bpf_lock);
619 static LIST_HEAD(bpf_kallsyms);
620 static struct latch_tree_root bpf_tree __cacheline_aligned;
622 void bpf_ksym_add(struct bpf_ksym *ksym)
624 spin_lock_bh(&bpf_lock);
625 WARN_ON_ONCE(!list_empty(&ksym->lnode));
626 list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms);
627 latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
628 spin_unlock_bh(&bpf_lock);
631 static void __bpf_ksym_del(struct bpf_ksym *ksym)
633 if (list_empty(&ksym->lnode))
636 latch_tree_erase(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
637 list_del_rcu(&ksym->lnode);
640 void bpf_ksym_del(struct bpf_ksym *ksym)
642 spin_lock_bh(&bpf_lock);
643 __bpf_ksym_del(ksym);
644 spin_unlock_bh(&bpf_lock);
647 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
649 return fp->jited && !bpf_prog_was_classic(fp);
652 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
654 if (!bpf_prog_kallsyms_candidate(fp) ||
658 bpf_prog_ksym_set_addr(fp);
659 bpf_prog_ksym_set_name(fp);
660 fp->aux->ksym.prog = true;
662 bpf_ksym_add(&fp->aux->ksym);
665 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
667 if (!bpf_prog_kallsyms_candidate(fp))
670 bpf_ksym_del(&fp->aux->ksym);
673 static struct bpf_ksym *bpf_ksym_find(unsigned long addr)
675 struct latch_tree_node *n;
677 n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
678 return n ? container_of(n, struct bpf_ksym, tnode) : NULL;
681 const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
682 unsigned long *off, char *sym)
684 struct bpf_ksym *ksym;
688 ksym = bpf_ksym_find(addr);
690 unsigned long symbol_start = ksym->start;
691 unsigned long symbol_end = ksym->end;
693 strncpy(sym, ksym->name, KSYM_NAME_LEN);
697 *size = symbol_end - symbol_start;
699 *off = addr - symbol_start;
706 bool is_bpf_text_address(unsigned long addr)
711 ret = bpf_ksym_find(addr) != NULL;
717 static struct bpf_prog *bpf_prog_ksym_find(unsigned long addr)
719 struct bpf_ksym *ksym = bpf_ksym_find(addr);
721 return ksym && ksym->prog ?
722 container_of(ksym, struct bpf_prog_aux, ksym)->prog :
726 const struct exception_table_entry *search_bpf_extables(unsigned long addr)
728 const struct exception_table_entry *e = NULL;
729 struct bpf_prog *prog;
732 prog = bpf_prog_ksym_find(addr);
735 if (!prog->aux->num_exentries)
738 e = search_extable(prog->aux->extable, prog->aux->num_exentries, addr);
744 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
747 struct bpf_ksym *ksym;
751 if (!bpf_jit_kallsyms_enabled())
755 list_for_each_entry_rcu(ksym, &bpf_kallsyms, lnode) {
759 strncpy(sym, ksym->name, KSYM_NAME_LEN);
761 *value = ksym->start;
762 *type = BPF_SYM_ELF_TYPE;
772 int bpf_jit_add_poke_descriptor(struct bpf_prog *prog,
773 struct bpf_jit_poke_descriptor *poke)
775 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
776 static const u32 poke_tab_max = 1024;
777 u32 slot = prog->aux->size_poke_tab;
780 if (size > poke_tab_max)
782 if (poke->tailcall_target || poke->tailcall_target_stable ||
783 poke->tailcall_bypass || poke->adj_off || poke->bypass_addr)
786 switch (poke->reason) {
787 case BPF_POKE_REASON_TAIL_CALL:
788 if (!poke->tail_call.map)
795 tab = krealloc(tab, size * sizeof(*poke), GFP_KERNEL);
799 memcpy(&tab[slot], poke, sizeof(*poke));
800 prog->aux->size_poke_tab = size;
801 prog->aux->poke_tab = tab;
807 * BPF program pack allocator.
809 * Most BPF programs are pretty small. Allocating a hole page for each
810 * program is sometime a waste. Many small bpf program also adds pressure
811 * to instruction TLB. To solve this issue, we introduce a BPF program pack
812 * allocator. The prog_pack allocator uses HPAGE_PMD_SIZE page (2MB on x86)
813 * to host BPF programs.
815 #define BPF_PROG_CHUNK_SHIFT 6
816 #define BPF_PROG_CHUNK_SIZE (1 << BPF_PROG_CHUNK_SHIFT)
817 #define BPF_PROG_CHUNK_MASK (~(BPF_PROG_CHUNK_SIZE - 1))
819 struct bpf_prog_pack {
820 struct list_head list;
822 unsigned long bitmap[];
825 #define BPF_PROG_SIZE_TO_NBITS(size) (round_up(size, BPF_PROG_CHUNK_SIZE) / BPF_PROG_CHUNK_SIZE)
827 static size_t bpf_prog_pack_size = -1;
828 static size_t bpf_prog_pack_mask = -1;
830 static int bpf_prog_chunk_count(void)
832 WARN_ON_ONCE(bpf_prog_pack_size == -1);
833 return bpf_prog_pack_size / BPF_PROG_CHUNK_SIZE;
836 static DEFINE_MUTEX(pack_mutex);
837 static LIST_HEAD(pack_list);
839 /* PMD_SIZE is not available in some special config, e.g. ARCH=arm with
840 * CONFIG_MMU=n. Use PAGE_SIZE in these cases.
843 #define BPF_HPAGE_SIZE PMD_SIZE
844 #define BPF_HPAGE_MASK PMD_MASK
846 #define BPF_HPAGE_SIZE PAGE_SIZE
847 #define BPF_HPAGE_MASK PAGE_MASK
850 static size_t select_bpf_prog_pack_size(void)
855 size = BPF_HPAGE_SIZE * num_online_nodes();
856 ptr = module_alloc(size);
858 /* Test whether we can get huge pages. If not just use PAGE_SIZE
861 if (!ptr || !is_vm_area_hugepages(ptr)) {
863 bpf_prog_pack_mask = PAGE_MASK;
865 bpf_prog_pack_mask = BPF_HPAGE_MASK;
872 static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_insns)
874 struct bpf_prog_pack *pack;
876 pack = kzalloc(struct_size(pack, bitmap, BITS_TO_LONGS(bpf_prog_chunk_count())),
880 pack->ptr = module_alloc(bpf_prog_pack_size);
885 bpf_fill_ill_insns(pack->ptr, bpf_prog_pack_size);
886 bitmap_zero(pack->bitmap, bpf_prog_pack_size / BPF_PROG_CHUNK_SIZE);
887 list_add_tail(&pack->list, &pack_list);
889 set_vm_flush_reset_perms(pack->ptr);
890 set_memory_ro((unsigned long)pack->ptr, bpf_prog_pack_size / PAGE_SIZE);
891 set_memory_x((unsigned long)pack->ptr, bpf_prog_pack_size / PAGE_SIZE);
895 static void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns)
897 unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size);
898 struct bpf_prog_pack *pack;
902 mutex_lock(&pack_mutex);
903 if (bpf_prog_pack_size == -1)
904 bpf_prog_pack_size = select_bpf_prog_pack_size();
906 if (size > bpf_prog_pack_size) {
907 size = round_up(size, PAGE_SIZE);
908 ptr = module_alloc(size);
910 bpf_fill_ill_insns(ptr, size);
911 set_vm_flush_reset_perms(ptr);
912 set_memory_ro((unsigned long)ptr, size / PAGE_SIZE);
913 set_memory_x((unsigned long)ptr, size / PAGE_SIZE);
917 list_for_each_entry(pack, &pack_list, list) {
918 pos = bitmap_find_next_zero_area(pack->bitmap, bpf_prog_chunk_count(), 0,
920 if (pos < bpf_prog_chunk_count())
921 goto found_free_area;
924 pack = alloc_new_pack(bpf_fill_ill_insns);
931 bitmap_set(pack->bitmap, pos, nbits);
932 ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
935 mutex_unlock(&pack_mutex);
939 static void bpf_prog_pack_free(struct bpf_binary_header *hdr)
941 struct bpf_prog_pack *pack = NULL, *tmp;
946 mutex_lock(&pack_mutex);
947 if (hdr->size > bpf_prog_pack_size) {
952 pack_ptr = (void *)((unsigned long)hdr & bpf_prog_pack_mask);
954 list_for_each_entry(tmp, &pack_list, list) {
955 if (tmp->ptr == pack_ptr) {
961 if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
964 nbits = BPF_PROG_SIZE_TO_NBITS(hdr->size);
965 pos = ((unsigned long)hdr - (unsigned long)pack_ptr) >> BPF_PROG_CHUNK_SHIFT;
967 WARN_ONCE(bpf_arch_text_invalidate(hdr, hdr->size),
968 "bpf_prog_pack bug: missing bpf_arch_text_invalidate?\n");
970 bitmap_clear(pack->bitmap, pos, nbits);
971 if (bitmap_find_next_zero_area(pack->bitmap, bpf_prog_chunk_count(), 0,
972 bpf_prog_chunk_count(), 0) == 0) {
973 list_del(&pack->list);
974 module_memfree(pack->ptr);
978 mutex_unlock(&pack_mutex);
981 static atomic_long_t bpf_jit_current;
983 /* Can be overridden by an arch's JIT compiler if it has a custom,
984 * dedicated BPF backend memory area, or if neither of the two
987 u64 __weak bpf_jit_alloc_exec_limit(void)
989 #if defined(MODULES_VADDR)
990 return MODULES_END - MODULES_VADDR;
992 return VMALLOC_END - VMALLOC_START;
996 static int __init bpf_jit_charge_init(void)
998 /* Only used as heuristic here to derive limit. */
999 bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
1000 bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 2,
1001 PAGE_SIZE), LONG_MAX);
1004 pure_initcall(bpf_jit_charge_init);
1006 int bpf_jit_charge_modmem(u32 size)
1008 if (atomic_long_add_return(size, &bpf_jit_current) > READ_ONCE(bpf_jit_limit)) {
1009 if (!bpf_capable()) {
1010 atomic_long_sub(size, &bpf_jit_current);
1018 void bpf_jit_uncharge_modmem(u32 size)
1020 atomic_long_sub(size, &bpf_jit_current);
1023 void *__weak bpf_jit_alloc_exec(unsigned long size)
1025 return module_alloc(size);
1028 void __weak bpf_jit_free_exec(void *addr)
1030 module_memfree(addr);
1033 struct bpf_binary_header *
1034 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
1035 unsigned int alignment,
1036 bpf_jit_fill_hole_t bpf_fill_ill_insns)
1038 struct bpf_binary_header *hdr;
1039 u32 size, hole, start;
1041 WARN_ON_ONCE(!is_power_of_2(alignment) ||
1042 alignment > BPF_IMAGE_ALIGNMENT);
1044 /* Most of BPF filters are really small, but if some of them
1045 * fill a page, allow at least 128 extra bytes to insert a
1046 * random section of illegal instructions.
1048 size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
1050 if (bpf_jit_charge_modmem(size))
1052 hdr = bpf_jit_alloc_exec(size);
1054 bpf_jit_uncharge_modmem(size);
1058 /* Fill space with illegal/arch-dep instructions. */
1059 bpf_fill_ill_insns(hdr, size);
1062 hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
1063 PAGE_SIZE - sizeof(*hdr));
1064 start = (get_random_int() % hole) & ~(alignment - 1);
1066 /* Leave a random number of instructions before BPF code. */
1067 *image_ptr = &hdr->image[start];
1072 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
1074 u32 size = hdr->size;
1076 bpf_jit_free_exec(hdr);
1077 bpf_jit_uncharge_modmem(size);
1080 /* Allocate jit binary from bpf_prog_pack allocator.
1081 * Since the allocated memory is RO+X, the JIT engine cannot write directly
1082 * to the memory. To solve this problem, a RW buffer is also allocated at
1083 * as the same time. The JIT engine should calculate offsets based on the
1084 * RO memory address, but write JITed program to the RW buffer. Once the
1085 * JIT engine finishes, it calls bpf_jit_binary_pack_finalize, which copies
1086 * the JITed program to the RO memory.
1088 struct bpf_binary_header *
1089 bpf_jit_binary_pack_alloc(unsigned int proglen, u8 **image_ptr,
1090 unsigned int alignment,
1091 struct bpf_binary_header **rw_header,
1093 bpf_jit_fill_hole_t bpf_fill_ill_insns)
1095 struct bpf_binary_header *ro_header;
1096 u32 size, hole, start;
1098 WARN_ON_ONCE(!is_power_of_2(alignment) ||
1099 alignment > BPF_IMAGE_ALIGNMENT);
1101 /* add 16 bytes for a random section of illegal instructions */
1102 size = round_up(proglen + sizeof(*ro_header) + 16, BPF_PROG_CHUNK_SIZE);
1104 if (bpf_jit_charge_modmem(size))
1106 ro_header = bpf_prog_pack_alloc(size, bpf_fill_ill_insns);
1108 bpf_jit_uncharge_modmem(size);
1112 *rw_header = kvmalloc(size, GFP_KERNEL);
1114 bpf_arch_text_copy(&ro_header->size, &size, sizeof(size));
1115 bpf_prog_pack_free(ro_header);
1116 bpf_jit_uncharge_modmem(size);
1120 /* Fill space with illegal/arch-dep instructions. */
1121 bpf_fill_ill_insns(*rw_header, size);
1122 (*rw_header)->size = size;
1124 hole = min_t(unsigned int, size - (proglen + sizeof(*ro_header)),
1125 BPF_PROG_CHUNK_SIZE - sizeof(*ro_header));
1126 start = (get_random_int() % hole) & ~(alignment - 1);
1128 *image_ptr = &ro_header->image[start];
1129 *rw_image = &(*rw_header)->image[start];
1134 /* Copy JITed text from rw_header to its final location, the ro_header. */
1135 int bpf_jit_binary_pack_finalize(struct bpf_prog *prog,
1136 struct bpf_binary_header *ro_header,
1137 struct bpf_binary_header *rw_header)
1141 ptr = bpf_arch_text_copy(ro_header, rw_header, rw_header->size);
1146 bpf_prog_pack_free(ro_header);
1147 return PTR_ERR(ptr);
1152 /* bpf_jit_binary_pack_free is called in two different scenarios:
1153 * 1) when the program is freed after;
1154 * 2) when the JIT engine fails (before bpf_jit_binary_pack_finalize).
1155 * For case 2), we need to free both the RO memory and the RW buffer.
1157 * bpf_jit_binary_pack_free requires proper ro_header->size. However,
1158 * bpf_jit_binary_pack_alloc does not set it. Therefore, ro_header->size
1159 * must be set with either bpf_jit_binary_pack_finalize (normal path) or
1160 * bpf_arch_text_copy (when jit fails).
1162 void bpf_jit_binary_pack_free(struct bpf_binary_header *ro_header,
1163 struct bpf_binary_header *rw_header)
1165 u32 size = ro_header->size;
1167 bpf_prog_pack_free(ro_header);
1169 bpf_jit_uncharge_modmem(size);
1172 struct bpf_binary_header *
1173 bpf_jit_binary_pack_hdr(const struct bpf_prog *fp)
1175 unsigned long real_start = (unsigned long)fp->bpf_func;
1178 addr = real_start & BPF_PROG_CHUNK_MASK;
1179 return (void *)addr;
1182 static inline struct bpf_binary_header *
1183 bpf_jit_binary_hdr(const struct bpf_prog *fp)
1185 unsigned long real_start = (unsigned long)fp->bpf_func;
1188 addr = real_start & PAGE_MASK;
1189 return (void *)addr;
1192 /* This symbol is only overridden by archs that have different
1193 * requirements than the usual eBPF JITs, f.e. when they only
1194 * implement cBPF JIT, do not set images read-only, etc.
1196 void __weak bpf_jit_free(struct bpf_prog *fp)
1199 struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
1201 bpf_jit_binary_free(hdr);
1202 WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
1205 bpf_prog_unlock_free(fp);
1208 int bpf_jit_get_func_addr(const struct bpf_prog *prog,
1209 const struct bpf_insn *insn, bool extra_pass,
1210 u64 *func_addr, bool *func_addr_fixed)
1212 s16 off = insn->off;
1213 s32 imm = insn->imm;
1216 *func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL;
1217 if (!*func_addr_fixed) {
1218 /* Place-holder address till the last pass has collected
1219 * all addresses for JITed subprograms in which case we
1220 * can pick them up from prog->aux.
1224 else if (prog->aux->func &&
1225 off >= 0 && off < prog->aux->func_cnt)
1226 addr = (u8 *)prog->aux->func[off]->bpf_func;
1230 /* Address of a BPF helper call. Since part of the core
1231 * kernel, it's always at a fixed location. __bpf_call_base
1232 * and the helper with imm relative to it are both in core
1235 addr = (u8 *)__bpf_call_base + imm;
1238 *func_addr = (unsigned long)addr;
1242 static int bpf_jit_blind_insn(const struct bpf_insn *from,
1243 const struct bpf_insn *aux,
1244 struct bpf_insn *to_buff,
1247 struct bpf_insn *to = to_buff;
1248 u32 imm_rnd = get_random_int();
1251 BUILD_BUG_ON(BPF_REG_AX + 1 != MAX_BPF_JIT_REG);
1252 BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
1254 /* Constraints on AX register:
1256 * AX register is inaccessible from user space. It is mapped in
1257 * all JITs, and used here for constant blinding rewrites. It is
1258 * typically "stateless" meaning its contents are only valid within
1259 * the executed instruction, but not across several instructions.
1260 * There are a few exceptions however which are further detailed
1263 * Constant blinding is only used by JITs, not in the interpreter.
1264 * The interpreter uses AX in some occasions as a local temporary
1265 * register e.g. in DIV or MOD instructions.
1267 * In restricted circumstances, the verifier can also use the AX
1268 * register for rewrites as long as they do not interfere with
1271 if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
1274 if (from->imm == 0 &&
1275 (from->code == (BPF_ALU | BPF_MOV | BPF_K) ||
1276 from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
1277 *to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
1281 switch (from->code) {
1282 case BPF_ALU | BPF_ADD | BPF_K:
1283 case BPF_ALU | BPF_SUB | BPF_K:
1284 case BPF_ALU | BPF_AND | BPF_K:
1285 case BPF_ALU | BPF_OR | BPF_K:
1286 case BPF_ALU | BPF_XOR | BPF_K:
1287 case BPF_ALU | BPF_MUL | BPF_K:
1288 case BPF_ALU | BPF_MOV | BPF_K:
1289 case BPF_ALU | BPF_DIV | BPF_K:
1290 case BPF_ALU | BPF_MOD | BPF_K:
1291 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1292 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1293 *to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
1296 case BPF_ALU64 | BPF_ADD | BPF_K:
1297 case BPF_ALU64 | BPF_SUB | BPF_K:
1298 case BPF_ALU64 | BPF_AND | BPF_K:
1299 case BPF_ALU64 | BPF_OR | BPF_K:
1300 case BPF_ALU64 | BPF_XOR | BPF_K:
1301 case BPF_ALU64 | BPF_MUL | BPF_K:
1302 case BPF_ALU64 | BPF_MOV | BPF_K:
1303 case BPF_ALU64 | BPF_DIV | BPF_K:
1304 case BPF_ALU64 | BPF_MOD | BPF_K:
1305 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1306 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1307 *to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
1310 case BPF_JMP | BPF_JEQ | BPF_K:
1311 case BPF_JMP | BPF_JNE | BPF_K:
1312 case BPF_JMP | BPF_JGT | BPF_K:
1313 case BPF_JMP | BPF_JLT | BPF_K:
1314 case BPF_JMP | BPF_JGE | BPF_K:
1315 case BPF_JMP | BPF_JLE | BPF_K:
1316 case BPF_JMP | BPF_JSGT | BPF_K:
1317 case BPF_JMP | BPF_JSLT | BPF_K:
1318 case BPF_JMP | BPF_JSGE | BPF_K:
1319 case BPF_JMP | BPF_JSLE | BPF_K:
1320 case BPF_JMP | BPF_JSET | BPF_K:
1321 /* Accommodate for extra offset in case of a backjump. */
1325 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1326 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1327 *to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
1330 case BPF_JMP32 | BPF_JEQ | BPF_K:
1331 case BPF_JMP32 | BPF_JNE | BPF_K:
1332 case BPF_JMP32 | BPF_JGT | BPF_K:
1333 case BPF_JMP32 | BPF_JLT | BPF_K:
1334 case BPF_JMP32 | BPF_JGE | BPF_K:
1335 case BPF_JMP32 | BPF_JLE | BPF_K:
1336 case BPF_JMP32 | BPF_JSGT | BPF_K:
1337 case BPF_JMP32 | BPF_JSLT | BPF_K:
1338 case BPF_JMP32 | BPF_JSGE | BPF_K:
1339 case BPF_JMP32 | BPF_JSLE | BPF_K:
1340 case BPF_JMP32 | BPF_JSET | BPF_K:
1341 /* Accommodate for extra offset in case of a backjump. */
1345 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1346 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1347 *to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX,
1351 case BPF_LD | BPF_IMM | BPF_DW:
1352 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
1353 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1354 *to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
1355 *to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
1357 case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
1358 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
1359 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1361 *to++ = BPF_ZEXT_REG(BPF_REG_AX);
1362 *to++ = BPF_ALU64_REG(BPF_OR, aux[0].dst_reg, BPF_REG_AX);
1365 case BPF_ST | BPF_MEM | BPF_DW:
1366 case BPF_ST | BPF_MEM | BPF_W:
1367 case BPF_ST | BPF_MEM | BPF_H:
1368 case BPF_ST | BPF_MEM | BPF_B:
1369 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1370 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1371 *to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
1375 return to - to_buff;
1378 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
1379 gfp_t gfp_extra_flags)
1381 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
1382 struct bpf_prog *fp;
1384 fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags);
1386 /* aux->prog still points to the fp_other one, so
1387 * when promoting the clone to the real program,
1388 * this still needs to be adapted.
1390 memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
1396 static void bpf_prog_clone_free(struct bpf_prog *fp)
1398 /* aux was stolen by the other clone, so we cannot free
1399 * it from this path! It will be freed eventually by the
1400 * other program on release.
1402 * At this point, we don't need a deferred release since
1403 * clone is guaranteed to not be locked.
1408 __bpf_prog_free(fp);
1411 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
1413 /* We have to repoint aux->prog to self, as we don't
1414 * know whether fp here is the clone or the original.
1417 bpf_prog_clone_free(fp_other);
1420 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
1422 struct bpf_insn insn_buff[16], aux[2];
1423 struct bpf_prog *clone, *tmp;
1424 int insn_delta, insn_cnt;
1425 struct bpf_insn *insn;
1428 if (!prog->blinding_requested || prog->blinded)
1431 clone = bpf_prog_clone_create(prog, GFP_USER);
1433 return ERR_PTR(-ENOMEM);
1435 insn_cnt = clone->len;
1436 insn = clone->insnsi;
1438 for (i = 0; i < insn_cnt; i++, insn++) {
1439 if (bpf_pseudo_func(insn)) {
1440 /* ld_imm64 with an address of bpf subprog is not
1441 * a user controlled constant. Don't randomize it,
1442 * since it will conflict with jit_subprogs() logic.
1449 /* We temporarily need to hold the original ld64 insn
1450 * so that we can still access the first part in the
1451 * second blinding run.
1453 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
1455 memcpy(aux, insn, sizeof(aux));
1457 rewritten = bpf_jit_blind_insn(insn, aux, insn_buff,
1458 clone->aux->verifier_zext);
1462 tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
1464 /* Patching may have repointed aux->prog during
1465 * realloc from the original one, so we need to
1466 * fix it up here on error.
1468 bpf_jit_prog_release_other(prog, clone);
1473 insn_delta = rewritten - 1;
1475 /* Walk new program and skip insns we just inserted. */
1476 insn = clone->insnsi + i + insn_delta;
1477 insn_cnt += insn_delta;
1484 #endif /* CONFIG_BPF_JIT */
1486 /* Base function for offset calculation. Needs to go into .text section,
1487 * therefore keeping it non-static as well; will also be used by JITs
1488 * anyway later on, so do not let the compiler omit it. This also needs
1489 * to go into kallsyms for correlation from e.g. bpftool, so naming
1492 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
1496 EXPORT_SYMBOL_GPL(__bpf_call_base);
1498 /* All UAPI available opcodes. */
1499 #define BPF_INSN_MAP(INSN_2, INSN_3) \
1500 /* 32 bit ALU operations. */ \
1501 /* Register based. */ \
1502 INSN_3(ALU, ADD, X), \
1503 INSN_3(ALU, SUB, X), \
1504 INSN_3(ALU, AND, X), \
1505 INSN_3(ALU, OR, X), \
1506 INSN_3(ALU, LSH, X), \
1507 INSN_3(ALU, RSH, X), \
1508 INSN_3(ALU, XOR, X), \
1509 INSN_3(ALU, MUL, X), \
1510 INSN_3(ALU, MOV, X), \
1511 INSN_3(ALU, ARSH, X), \
1512 INSN_3(ALU, DIV, X), \
1513 INSN_3(ALU, MOD, X), \
1515 INSN_3(ALU, END, TO_BE), \
1516 INSN_3(ALU, END, TO_LE), \
1517 /* Immediate based. */ \
1518 INSN_3(ALU, ADD, K), \
1519 INSN_3(ALU, SUB, K), \
1520 INSN_3(ALU, AND, K), \
1521 INSN_3(ALU, OR, K), \
1522 INSN_3(ALU, LSH, K), \
1523 INSN_3(ALU, RSH, K), \
1524 INSN_3(ALU, XOR, K), \
1525 INSN_3(ALU, MUL, K), \
1526 INSN_3(ALU, MOV, K), \
1527 INSN_3(ALU, ARSH, K), \
1528 INSN_3(ALU, DIV, K), \
1529 INSN_3(ALU, MOD, K), \
1530 /* 64 bit ALU operations. */ \
1531 /* Register based. */ \
1532 INSN_3(ALU64, ADD, X), \
1533 INSN_3(ALU64, SUB, X), \
1534 INSN_3(ALU64, AND, X), \
1535 INSN_3(ALU64, OR, X), \
1536 INSN_3(ALU64, LSH, X), \
1537 INSN_3(ALU64, RSH, X), \
1538 INSN_3(ALU64, XOR, X), \
1539 INSN_3(ALU64, MUL, X), \
1540 INSN_3(ALU64, MOV, X), \
1541 INSN_3(ALU64, ARSH, X), \
1542 INSN_3(ALU64, DIV, X), \
1543 INSN_3(ALU64, MOD, X), \
1544 INSN_2(ALU64, NEG), \
1545 /* Immediate based. */ \
1546 INSN_3(ALU64, ADD, K), \
1547 INSN_3(ALU64, SUB, K), \
1548 INSN_3(ALU64, AND, K), \
1549 INSN_3(ALU64, OR, K), \
1550 INSN_3(ALU64, LSH, K), \
1551 INSN_3(ALU64, RSH, K), \
1552 INSN_3(ALU64, XOR, K), \
1553 INSN_3(ALU64, MUL, K), \
1554 INSN_3(ALU64, MOV, K), \
1555 INSN_3(ALU64, ARSH, K), \
1556 INSN_3(ALU64, DIV, K), \
1557 INSN_3(ALU64, MOD, K), \
1558 /* Call instruction. */ \
1559 INSN_2(JMP, CALL), \
1560 /* Exit instruction. */ \
1561 INSN_2(JMP, EXIT), \
1562 /* 32-bit Jump instructions. */ \
1563 /* Register based. */ \
1564 INSN_3(JMP32, JEQ, X), \
1565 INSN_3(JMP32, JNE, X), \
1566 INSN_3(JMP32, JGT, X), \
1567 INSN_3(JMP32, JLT, X), \
1568 INSN_3(JMP32, JGE, X), \
1569 INSN_3(JMP32, JLE, X), \
1570 INSN_3(JMP32, JSGT, X), \
1571 INSN_3(JMP32, JSLT, X), \
1572 INSN_3(JMP32, JSGE, X), \
1573 INSN_3(JMP32, JSLE, X), \
1574 INSN_3(JMP32, JSET, X), \
1575 /* Immediate based. */ \
1576 INSN_3(JMP32, JEQ, K), \
1577 INSN_3(JMP32, JNE, K), \
1578 INSN_3(JMP32, JGT, K), \
1579 INSN_3(JMP32, JLT, K), \
1580 INSN_3(JMP32, JGE, K), \
1581 INSN_3(JMP32, JLE, K), \
1582 INSN_3(JMP32, JSGT, K), \
1583 INSN_3(JMP32, JSLT, K), \
1584 INSN_3(JMP32, JSGE, K), \
1585 INSN_3(JMP32, JSLE, K), \
1586 INSN_3(JMP32, JSET, K), \
1587 /* Jump instructions. */ \
1588 /* Register based. */ \
1589 INSN_3(JMP, JEQ, X), \
1590 INSN_3(JMP, JNE, X), \
1591 INSN_3(JMP, JGT, X), \
1592 INSN_3(JMP, JLT, X), \
1593 INSN_3(JMP, JGE, X), \
1594 INSN_3(JMP, JLE, X), \
1595 INSN_3(JMP, JSGT, X), \
1596 INSN_3(JMP, JSLT, X), \
1597 INSN_3(JMP, JSGE, X), \
1598 INSN_3(JMP, JSLE, X), \
1599 INSN_3(JMP, JSET, X), \
1600 /* Immediate based. */ \
1601 INSN_3(JMP, JEQ, K), \
1602 INSN_3(JMP, JNE, K), \
1603 INSN_3(JMP, JGT, K), \
1604 INSN_3(JMP, JLT, K), \
1605 INSN_3(JMP, JGE, K), \
1606 INSN_3(JMP, JLE, K), \
1607 INSN_3(JMP, JSGT, K), \
1608 INSN_3(JMP, JSLT, K), \
1609 INSN_3(JMP, JSGE, K), \
1610 INSN_3(JMP, JSLE, K), \
1611 INSN_3(JMP, JSET, K), \
1613 /* Store instructions. */ \
1614 /* Register based. */ \
1615 INSN_3(STX, MEM, B), \
1616 INSN_3(STX, MEM, H), \
1617 INSN_3(STX, MEM, W), \
1618 INSN_3(STX, MEM, DW), \
1619 INSN_3(STX, ATOMIC, W), \
1620 INSN_3(STX, ATOMIC, DW), \
1621 /* Immediate based. */ \
1622 INSN_3(ST, MEM, B), \
1623 INSN_3(ST, MEM, H), \
1624 INSN_3(ST, MEM, W), \
1625 INSN_3(ST, MEM, DW), \
1626 /* Load instructions. */ \
1627 /* Register based. */ \
1628 INSN_3(LDX, MEM, B), \
1629 INSN_3(LDX, MEM, H), \
1630 INSN_3(LDX, MEM, W), \
1631 INSN_3(LDX, MEM, DW), \
1632 /* Immediate based. */ \
1635 bool bpf_opcode_in_insntable(u8 code)
1637 #define BPF_INSN_2_TBL(x, y) [BPF_##x | BPF_##y] = true
1638 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
1639 static const bool public_insntable[256] = {
1640 [0 ... 255] = false,
1641 /* Now overwrite non-defaults ... */
1642 BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
1643 /* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
1644 [BPF_LD | BPF_ABS | BPF_B] = true,
1645 [BPF_LD | BPF_ABS | BPF_H] = true,
1646 [BPF_LD | BPF_ABS | BPF_W] = true,
1647 [BPF_LD | BPF_IND | BPF_B] = true,
1648 [BPF_LD | BPF_IND | BPF_H] = true,
1649 [BPF_LD | BPF_IND | BPF_W] = true,
1651 #undef BPF_INSN_3_TBL
1652 #undef BPF_INSN_2_TBL
1653 return public_insntable[code];
1656 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1657 u64 __weak bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr)
1659 memset(dst, 0, size);
1664 * ___bpf_prog_run - run eBPF program on a given context
1665 * @regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers
1666 * @insn: is the array of eBPF instructions
1668 * Decode and execute eBPF instructions.
1670 * Return: whatever value is in %BPF_R0 at program exit
1672 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn)
1674 #define BPF_INSN_2_LBL(x, y) [BPF_##x | BPF_##y] = &&x##_##y
1675 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
1676 static const void * const jumptable[256] __annotate_jump_table = {
1677 [0 ... 255] = &&default_label,
1678 /* Now overwrite non-defaults ... */
1679 BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
1680 /* Non-UAPI available opcodes. */
1681 [BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
1682 [BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
1683 [BPF_ST | BPF_NOSPEC] = &&ST_NOSPEC,
1684 [BPF_LDX | BPF_PROBE_MEM | BPF_B] = &&LDX_PROBE_MEM_B,
1685 [BPF_LDX | BPF_PROBE_MEM | BPF_H] = &&LDX_PROBE_MEM_H,
1686 [BPF_LDX | BPF_PROBE_MEM | BPF_W] = &&LDX_PROBE_MEM_W,
1687 [BPF_LDX | BPF_PROBE_MEM | BPF_DW] = &&LDX_PROBE_MEM_DW,
1689 #undef BPF_INSN_3_LBL
1690 #undef BPF_INSN_2_LBL
1691 u32 tail_call_cnt = 0;
1693 #define CONT ({ insn++; goto select_insn; })
1694 #define CONT_JMP ({ insn++; goto select_insn; })
1697 goto *jumptable[insn->code];
1699 /* Explicitly mask the register-based shift amounts with 63 or 31
1700 * to avoid undefined behavior. Normally this won't affect the
1701 * generated code, for example, in case of native 64 bit archs such
1702 * as x86-64 or arm64, the compiler is optimizing the AND away for
1703 * the interpreter. In case of JITs, each of the JIT backends compiles
1704 * the BPF shift operations to machine instructions which produce
1705 * implementation-defined results in such a case; the resulting
1706 * contents of the register may be arbitrary, but program behaviour
1707 * as a whole remains defined. In other words, in case of JIT backends,
1708 * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation.
1711 #define SHT(OPCODE, OP) \
1712 ALU64_##OPCODE##_X: \
1713 DST = DST OP (SRC & 63); \
1716 DST = (u32) DST OP ((u32) SRC & 31); \
1718 ALU64_##OPCODE##_K: \
1722 DST = (u32) DST OP (u32) IMM; \
1725 #define ALU(OPCODE, OP) \
1726 ALU64_##OPCODE##_X: \
1730 DST = (u32) DST OP (u32) SRC; \
1732 ALU64_##OPCODE##_K: \
1736 DST = (u32) DST OP (u32) IMM; \
1767 DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1771 DST = (u64) (u32) (((s32) DST) >> (SRC & 31));
1774 DST = (u64) (u32) (((s32) DST) >> IMM);
1777 (*(s64 *) &DST) >>= (SRC & 63);
1780 (*(s64 *) &DST) >>= IMM;
1783 div64_u64_rem(DST, SRC, &AX);
1788 DST = do_div(AX, (u32) SRC);
1791 div64_u64_rem(DST, IMM, &AX);
1796 DST = do_div(AX, (u32) IMM);
1799 DST = div64_u64(DST, SRC);
1803 do_div(AX, (u32) SRC);
1807 DST = div64_u64(DST, IMM);
1811 do_div(AX, (u32) IMM);
1817 DST = (__force u16) cpu_to_be16(DST);
1820 DST = (__force u32) cpu_to_be32(DST);
1823 DST = (__force u64) cpu_to_be64(DST);
1830 DST = (__force u16) cpu_to_le16(DST);
1833 DST = (__force u32) cpu_to_le32(DST);
1836 DST = (__force u64) cpu_to_le64(DST);
1843 /* Function call scratches BPF_R1-BPF_R5 registers,
1844 * preserves BPF_R6-BPF_R9, and stores return value
1847 BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1852 BPF_R0 = (__bpf_call_base_args + insn->imm)(BPF_R1, BPF_R2,
1855 insn + insn->off + 1);
1859 struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1860 struct bpf_array *array = container_of(map, struct bpf_array, map);
1861 struct bpf_prog *prog;
1864 if (unlikely(index >= array->map.max_entries))
1867 if (unlikely(tail_call_cnt >= MAX_TAIL_CALL_CNT))
1872 prog = READ_ONCE(array->ptrs[index]);
1876 /* ARG1 at this point is guaranteed to point to CTX from
1877 * the verifier side due to the fact that the tail call is
1878 * handled like a helper, that is, bpf_tail_call_proto,
1879 * where arg1_type is ARG_PTR_TO_CTX.
1881 insn = prog->insnsi;
1892 #define COND_JMP(SIGN, OPCODE, CMP_OP) \
1894 if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) { \
1895 insn += insn->off; \
1899 JMP32_##OPCODE##_X: \
1900 if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) { \
1901 insn += insn->off; \
1906 if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) { \
1907 insn += insn->off; \
1911 JMP32_##OPCODE##_K: \
1912 if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) { \
1913 insn += insn->off; \
1917 COND_JMP(u, JEQ, ==)
1918 COND_JMP(u, JNE, !=)
1921 COND_JMP(u, JGE, >=)
1922 COND_JMP(u, JLE, <=)
1923 COND_JMP(u, JSET, &)
1924 COND_JMP(s, JSGT, >)
1925 COND_JMP(s, JSLT, <)
1926 COND_JMP(s, JSGE, >=)
1927 COND_JMP(s, JSLE, <=)
1929 /* ST, STX and LDX*/
1931 /* Speculation barrier for mitigating Speculative Store Bypass.
1932 * In case of arm64, we rely on the firmware mitigation as
1933 * controlled via the ssbd kernel parameter. Whenever the
1934 * mitigation is enabled, it works for all of the kernel code
1935 * with no need to provide any additional instructions here.
1936 * In case of x86, we use 'lfence' insn for mitigation. We
1937 * reuse preexisting logic from Spectre v1 mitigation that
1938 * happens to produce the required code on x86 for v4 as well.
1944 #define LDST(SIZEOP, SIZE) \
1946 *(SIZE *)(unsigned long) (DST + insn->off) = SRC; \
1949 *(SIZE *)(unsigned long) (DST + insn->off) = IMM; \
1952 DST = *(SIZE *)(unsigned long) (SRC + insn->off); \
1954 LDX_PROBE_MEM_##SIZEOP: \
1955 bpf_probe_read_kernel(&DST, sizeof(SIZE), \
1956 (const void *)(long) (SRC + insn->off)); \
1957 DST = *((SIZE *)&DST); \
1966 #define ATOMIC_ALU_OP(BOP, KOP) \
1968 if (BPF_SIZE(insn->code) == BPF_W) \
1969 atomic_##KOP((u32) SRC, (atomic_t *)(unsigned long) \
1970 (DST + insn->off)); \
1972 atomic64_##KOP((u64) SRC, (atomic64_t *)(unsigned long) \
1973 (DST + insn->off)); \
1975 case BOP | BPF_FETCH: \
1976 if (BPF_SIZE(insn->code) == BPF_W) \
1977 SRC = (u32) atomic_fetch_##KOP( \
1979 (atomic_t *)(unsigned long) (DST + insn->off)); \
1981 SRC = (u64) atomic64_fetch_##KOP( \
1983 (atomic64_t *)(unsigned long) (DST + insn->off)); \
1989 ATOMIC_ALU_OP(BPF_ADD, add)
1990 ATOMIC_ALU_OP(BPF_AND, and)
1991 ATOMIC_ALU_OP(BPF_OR, or)
1992 ATOMIC_ALU_OP(BPF_XOR, xor)
1993 #undef ATOMIC_ALU_OP
1996 if (BPF_SIZE(insn->code) == BPF_W)
1997 SRC = (u32) atomic_xchg(
1998 (atomic_t *)(unsigned long) (DST + insn->off),
2001 SRC = (u64) atomic64_xchg(
2002 (atomic64_t *)(unsigned long) (DST + insn->off),
2006 if (BPF_SIZE(insn->code) == BPF_W)
2007 BPF_R0 = (u32) atomic_cmpxchg(
2008 (atomic_t *)(unsigned long) (DST + insn->off),
2009 (u32) BPF_R0, (u32) SRC);
2011 BPF_R0 = (u64) atomic64_cmpxchg(
2012 (atomic64_t *)(unsigned long) (DST + insn->off),
2013 (u64) BPF_R0, (u64) SRC);
2022 /* If we ever reach this, we have a bug somewhere. Die hard here
2023 * instead of just returning 0; we could be somewhere in a subprog,
2024 * so execution could continue otherwise which we do /not/ want.
2026 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
2028 pr_warn("BPF interpreter: unknown opcode %02x (imm: 0x%x)\n",
2029 insn->code, insn->imm);
2034 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
2035 #define DEFINE_BPF_PROG_RUN(stack_size) \
2036 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
2038 u64 stack[stack_size / sizeof(u64)]; \
2039 u64 regs[MAX_BPF_EXT_REG]; \
2041 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2042 ARG1 = (u64) (unsigned long) ctx; \
2043 return ___bpf_prog_run(regs, insn); \
2046 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
2047 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
2048 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
2049 const struct bpf_insn *insn) \
2051 u64 stack[stack_size / sizeof(u64)]; \
2052 u64 regs[MAX_BPF_EXT_REG]; \
2054 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2060 return ___bpf_prog_run(regs, insn); \
2063 #define EVAL1(FN, X) FN(X)
2064 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
2065 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
2066 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
2067 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
2068 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
2070 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
2071 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
2072 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
2074 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
2075 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
2076 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
2078 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
2080 static unsigned int (*interpreters[])(const void *ctx,
2081 const struct bpf_insn *insn) = {
2082 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2083 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2084 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2086 #undef PROG_NAME_LIST
2087 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
2088 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
2089 const struct bpf_insn *insn) = {
2090 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2091 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2092 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2094 #undef PROG_NAME_LIST
2096 void bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
2098 stack_depth = max_t(u32, stack_depth, 1);
2099 insn->off = (s16) insn->imm;
2100 insn->imm = interpreters_args[(round_up(stack_depth, 32) / 32) - 1] -
2101 __bpf_call_base_args;
2102 insn->code = BPF_JMP | BPF_CALL_ARGS;
2106 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
2107 const struct bpf_insn *insn)
2109 /* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
2110 * is not working properly, so warn about it!
2117 bool bpf_prog_map_compatible(struct bpf_map *map,
2118 const struct bpf_prog *fp)
2122 if (fp->kprobe_override)
2125 spin_lock(&map->owner.lock);
2126 if (!map->owner.type) {
2127 /* There's no owner yet where we could check for
2130 map->owner.type = fp->type;
2131 map->owner.jited = fp->jited;
2132 map->owner.xdp_has_frags = fp->aux->xdp_has_frags;
2135 ret = map->owner.type == fp->type &&
2136 map->owner.jited == fp->jited &&
2137 map->owner.xdp_has_frags == fp->aux->xdp_has_frags;
2139 spin_unlock(&map->owner.lock);
2144 static int bpf_check_tail_call(const struct bpf_prog *fp)
2146 struct bpf_prog_aux *aux = fp->aux;
2149 mutex_lock(&aux->used_maps_mutex);
2150 for (i = 0; i < aux->used_map_cnt; i++) {
2151 struct bpf_map *map = aux->used_maps[i];
2153 if (!map_type_contains_progs(map))
2156 if (!bpf_prog_map_compatible(map, fp)) {
2163 mutex_unlock(&aux->used_maps_mutex);
2167 static void bpf_prog_select_func(struct bpf_prog *fp)
2169 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2170 u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
2172 fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
2174 fp->bpf_func = __bpf_prog_ret0_warn;
2179 * bpf_prog_select_runtime - select exec runtime for BPF program
2180 * @fp: bpf_prog populated with BPF program
2181 * @err: pointer to error variable
2183 * Try to JIT eBPF program, if JIT is not available, use interpreter.
2184 * The BPF program will be executed via bpf_prog_run() function.
2186 * Return: the &fp argument along with &err set to 0 for success or
2187 * a negative errno code on failure
2189 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
2191 /* In case of BPF to BPF calls, verifier did all the prep
2192 * work with regards to JITing, etc.
2194 bool jit_needed = false;
2199 if (IS_ENABLED(CONFIG_BPF_JIT_ALWAYS_ON) ||
2200 bpf_prog_has_kfunc_call(fp))
2203 bpf_prog_select_func(fp);
2205 /* eBPF JITs can rewrite the program in case constant
2206 * blinding is active. However, in case of error during
2207 * blinding, bpf_int_jit_compile() must always return a
2208 * valid program, which in this case would simply not
2209 * be JITed, but falls back to the interpreter.
2211 if (!bpf_prog_is_dev_bound(fp->aux)) {
2212 *err = bpf_prog_alloc_jited_linfo(fp);
2216 fp = bpf_int_jit_compile(fp);
2217 bpf_prog_jit_attempt_done(fp);
2218 if (!fp->jited && jit_needed) {
2223 *err = bpf_prog_offload_compile(fp);
2229 bpf_prog_lock_ro(fp);
2231 /* The tail call compatibility check can only be done at
2232 * this late stage as we need to determine, if we deal
2233 * with JITed or non JITed program concatenations and not
2234 * all eBPF JITs might immediately support all features.
2236 *err = bpf_check_tail_call(fp);
2240 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
2242 static unsigned int __bpf_prog_ret1(const void *ctx,
2243 const struct bpf_insn *insn)
2248 static struct bpf_prog_dummy {
2249 struct bpf_prog prog;
2250 } dummy_bpf_prog = {
2252 .bpf_func = __bpf_prog_ret1,
2256 struct bpf_empty_prog_array bpf_empty_prog_array = {
2259 EXPORT_SYMBOL(bpf_empty_prog_array);
2261 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
2264 return kzalloc(sizeof(struct bpf_prog_array) +
2265 sizeof(struct bpf_prog_array_item) *
2269 return &bpf_empty_prog_array.hdr;
2272 void bpf_prog_array_free(struct bpf_prog_array *progs)
2274 if (!progs || progs == &bpf_empty_prog_array.hdr)
2276 kfree_rcu(progs, rcu);
2279 int bpf_prog_array_length(struct bpf_prog_array *array)
2281 struct bpf_prog_array_item *item;
2284 for (item = array->items; item->prog; item++)
2285 if (item->prog != &dummy_bpf_prog.prog)
2290 bool bpf_prog_array_is_empty(struct bpf_prog_array *array)
2292 struct bpf_prog_array_item *item;
2294 for (item = array->items; item->prog; item++)
2295 if (item->prog != &dummy_bpf_prog.prog)
2300 static bool bpf_prog_array_copy_core(struct bpf_prog_array *array,
2304 struct bpf_prog_array_item *item;
2307 for (item = array->items; item->prog; item++) {
2308 if (item->prog == &dummy_bpf_prog.prog)
2310 prog_ids[i] = item->prog->aux->id;
2311 if (++i == request_cnt) {
2317 return !!(item->prog);
2320 int bpf_prog_array_copy_to_user(struct bpf_prog_array *array,
2321 __u32 __user *prog_ids, u32 cnt)
2323 unsigned long err = 0;
2327 /* users of this function are doing:
2328 * cnt = bpf_prog_array_length();
2330 * bpf_prog_array_copy_to_user(..., cnt);
2331 * so below kcalloc doesn't need extra cnt > 0 check.
2333 ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
2336 nospc = bpf_prog_array_copy_core(array, ids, cnt);
2337 err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
2346 void bpf_prog_array_delete_safe(struct bpf_prog_array *array,
2347 struct bpf_prog *old_prog)
2349 struct bpf_prog_array_item *item;
2351 for (item = array->items; item->prog; item++)
2352 if (item->prog == old_prog) {
2353 WRITE_ONCE(item->prog, &dummy_bpf_prog.prog);
2359 * bpf_prog_array_delete_safe_at() - Replaces the program at the given
2360 * index into the program array with
2361 * a dummy no-op program.
2362 * @array: a bpf_prog_array
2363 * @index: the index of the program to replace
2365 * Skips over dummy programs, by not counting them, when calculating
2366 * the position of the program to replace.
2370 * * -EINVAL - Invalid index value. Must be a non-negative integer.
2371 * * -ENOENT - Index out of range
2373 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index)
2375 return bpf_prog_array_update_at(array, index, &dummy_bpf_prog.prog);
2379 * bpf_prog_array_update_at() - Updates the program at the given index
2380 * into the program array.
2381 * @array: a bpf_prog_array
2382 * @index: the index of the program to update
2383 * @prog: the program to insert into the array
2385 * Skips over dummy programs, by not counting them, when calculating
2386 * the position of the program to update.
2390 * * -EINVAL - Invalid index value. Must be a non-negative integer.
2391 * * -ENOENT - Index out of range
2393 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index,
2394 struct bpf_prog *prog)
2396 struct bpf_prog_array_item *item;
2398 if (unlikely(index < 0))
2401 for (item = array->items; item->prog; item++) {
2402 if (item->prog == &dummy_bpf_prog.prog)
2405 WRITE_ONCE(item->prog, prog);
2413 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
2414 struct bpf_prog *exclude_prog,
2415 struct bpf_prog *include_prog,
2417 struct bpf_prog_array **new_array)
2419 int new_prog_cnt, carry_prog_cnt = 0;
2420 struct bpf_prog_array_item *existing, *new;
2421 struct bpf_prog_array *array;
2422 bool found_exclude = false;
2424 /* Figure out how many existing progs we need to carry over to
2428 existing = old_array->items;
2429 for (; existing->prog; existing++) {
2430 if (existing->prog == exclude_prog) {
2431 found_exclude = true;
2434 if (existing->prog != &dummy_bpf_prog.prog)
2436 if (existing->prog == include_prog)
2441 if (exclude_prog && !found_exclude)
2444 /* How many progs (not NULL) will be in the new array? */
2445 new_prog_cnt = carry_prog_cnt;
2449 /* Do we have any prog (not NULL) in the new array? */
2450 if (!new_prog_cnt) {
2455 /* +1 as the end of prog_array is marked with NULL */
2456 array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
2461 /* Fill in the new prog array */
2462 if (carry_prog_cnt) {
2463 existing = old_array->items;
2464 for (; existing->prog; existing++) {
2465 if (existing->prog == exclude_prog ||
2466 existing->prog == &dummy_bpf_prog.prog)
2469 new->prog = existing->prog;
2470 new->bpf_cookie = existing->bpf_cookie;
2475 new->prog = include_prog;
2476 new->bpf_cookie = bpf_cookie;
2484 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
2485 u32 *prog_ids, u32 request_cnt,
2491 cnt = bpf_prog_array_length(array);
2495 /* return early if user requested only program count or nothing to copy */
2496 if (!request_cnt || !cnt)
2499 /* this function is called under trace/bpf_trace.c: bpf_event_mutex */
2500 return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC
2504 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
2505 struct bpf_map **used_maps, u32 len)
2507 struct bpf_map *map;
2510 for (i = 0; i < len; i++) {
2512 if (map->ops->map_poke_untrack)
2513 map->ops->map_poke_untrack(map, aux);
2518 static void bpf_free_used_maps(struct bpf_prog_aux *aux)
2520 __bpf_free_used_maps(aux, aux->used_maps, aux->used_map_cnt);
2521 kfree(aux->used_maps);
2524 void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
2525 struct btf_mod_pair *used_btfs, u32 len)
2527 #ifdef CONFIG_BPF_SYSCALL
2528 struct btf_mod_pair *btf_mod;
2531 for (i = 0; i < len; i++) {
2532 btf_mod = &used_btfs[i];
2533 if (btf_mod->module)
2534 module_put(btf_mod->module);
2535 btf_put(btf_mod->btf);
2540 static void bpf_free_used_btfs(struct bpf_prog_aux *aux)
2542 __bpf_free_used_btfs(aux, aux->used_btfs, aux->used_btf_cnt);
2543 kfree(aux->used_btfs);
2546 static void bpf_prog_free_deferred(struct work_struct *work)
2548 struct bpf_prog_aux *aux;
2551 aux = container_of(work, struct bpf_prog_aux, work);
2552 #ifdef CONFIG_BPF_SYSCALL
2553 bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab);
2555 bpf_free_used_maps(aux);
2556 bpf_free_used_btfs(aux);
2557 if (bpf_prog_is_dev_bound(aux))
2558 bpf_prog_offload_destroy(aux->prog);
2559 #ifdef CONFIG_PERF_EVENTS
2560 if (aux->prog->has_callchain_buf)
2561 put_callchain_buffers();
2563 if (aux->dst_trampoline)
2564 bpf_trampoline_put(aux->dst_trampoline);
2565 for (i = 0; i < aux->func_cnt; i++) {
2566 /* We can just unlink the subprog poke descriptor table as
2567 * it was originally linked to the main program and is also
2568 * released along with it.
2570 aux->func[i]->aux->poke_tab = NULL;
2571 bpf_jit_free(aux->func[i]);
2573 if (aux->func_cnt) {
2575 bpf_prog_unlock_free(aux->prog);
2577 bpf_jit_free(aux->prog);
2581 void bpf_prog_free(struct bpf_prog *fp)
2583 struct bpf_prog_aux *aux = fp->aux;
2586 bpf_prog_put(aux->dst_prog);
2587 INIT_WORK(&aux->work, bpf_prog_free_deferred);
2588 schedule_work(&aux->work);
2590 EXPORT_SYMBOL_GPL(bpf_prog_free);
2592 /* RNG for unpriviledged user space with separated state from prandom_u32(). */
2593 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
2595 void bpf_user_rnd_init_once(void)
2597 prandom_init_once(&bpf_user_rnd_state);
2600 BPF_CALL_0(bpf_user_rnd_u32)
2602 /* Should someone ever have the rather unwise idea to use some
2603 * of the registers passed into this function, then note that
2604 * this function is called from native eBPF and classic-to-eBPF
2605 * transformations. Register assignments from both sides are
2606 * different, f.e. classic always sets fn(ctx, A, X) here.
2608 struct rnd_state *state;
2611 state = &get_cpu_var(bpf_user_rnd_state);
2612 res = prandom_u32_state(state);
2613 put_cpu_var(bpf_user_rnd_state);
2618 BPF_CALL_0(bpf_get_raw_cpu_id)
2620 return raw_smp_processor_id();
2623 /* Weak definitions of helper functions in case we don't have bpf syscall. */
2624 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
2625 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
2626 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
2627 const struct bpf_func_proto bpf_map_push_elem_proto __weak;
2628 const struct bpf_func_proto bpf_map_pop_elem_proto __weak;
2629 const struct bpf_func_proto bpf_map_peek_elem_proto __weak;
2630 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto __weak;
2631 const struct bpf_func_proto bpf_spin_lock_proto __weak;
2632 const struct bpf_func_proto bpf_spin_unlock_proto __weak;
2633 const struct bpf_func_proto bpf_jiffies64_proto __weak;
2635 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
2636 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
2637 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
2638 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
2639 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto __weak;
2640 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto __weak;
2642 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
2643 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
2644 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
2645 const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak;
2646 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto __weak;
2647 const struct bpf_func_proto bpf_get_local_storage_proto __weak;
2648 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto __weak;
2649 const struct bpf_func_proto bpf_snprintf_btf_proto __weak;
2650 const struct bpf_func_proto bpf_seq_printf_btf_proto __weak;
2652 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
2657 const struct bpf_func_proto * __weak bpf_get_trace_vprintk_proto(void)
2663 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2664 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
2668 EXPORT_SYMBOL_GPL(bpf_event_output);
2670 /* Always built-in helper functions. */
2671 const struct bpf_func_proto bpf_tail_call_proto = {
2674 .ret_type = RET_VOID,
2675 .arg1_type = ARG_PTR_TO_CTX,
2676 .arg2_type = ARG_CONST_MAP_PTR,
2677 .arg3_type = ARG_ANYTHING,
2680 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
2681 * It is encouraged to implement bpf_int_jit_compile() instead, so that
2682 * eBPF and implicitly also cBPF can get JITed!
2684 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
2689 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
2690 * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
2692 void __weak bpf_jit_compile(struct bpf_prog *prog)
2696 bool __weak bpf_helper_changes_pkt_data(void *func)
2701 /* Return TRUE if the JIT backend wants verifier to enable sub-register usage
2702 * analysis code and wants explicit zero extension inserted by verifier.
2703 * Otherwise, return FALSE.
2705 * The verifier inserts an explicit zero extension after BPF_CMPXCHGs even if
2706 * you don't override this. JITs that don't want these extra insns can detect
2707 * them using insn_is_zext.
2709 bool __weak bpf_jit_needs_zext(void)
2714 /* Return TRUE if the JIT backend supports mixing bpf2bpf and tailcalls. */
2715 bool __weak bpf_jit_supports_subprog_tailcalls(void)
2720 bool __weak bpf_jit_supports_kfunc_call(void)
2725 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
2726 * skb_copy_bits(), so provide a weak definition of it for NET-less config.
2728 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
2734 int __weak bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
2735 void *addr1, void *addr2)
2740 void * __weak bpf_arch_text_copy(void *dst, void *src, size_t len)
2742 return ERR_PTR(-ENOTSUPP);
2745 int __weak bpf_arch_text_invalidate(void *dst, size_t len)
2750 DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key);
2751 EXPORT_SYMBOL(bpf_stats_enabled_key);
2753 /* All definitions of tracepoints related to BPF. */
2754 #define CREATE_TRACE_POINTS
2755 #include <linux/bpf_trace.h>
2757 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
2758 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);