1 // SPDX-License-Identifier: GPL-2.0
3 * Common functionality for RV32 and RV64 BPF JIT compilers
10 #include <linux/filter.h>
13 /* Number of iterations to try until offsets converge. */
14 #define NR_JIT_ITERATIONS 16
16 static int build_body(struct rv_jit_context *ctx, bool extra_pass, int *offset)
18 const struct bpf_prog *prog = ctx->prog;
21 for (i = 0; i < prog->len; i++) {
22 const struct bpf_insn *insn = &prog->insnsi[i];
25 ret = bpf_jit_emit_insn(insn, ctx, extra_pass);
26 /* BPF_LD | BPF_IMM | BPF_DW: skip the next instruction. */
30 offset[i] = ctx->ninsns;
37 bool bpf_jit_needs_zext(void)
42 struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
44 bool tmp_blinded = false, extra_pass = false;
45 struct bpf_prog *tmp, *orig_prog = prog;
46 int pass = 0, prev_ninsns = 0, i;
47 struct rv_jit_data *jit_data;
48 struct rv_jit_context *ctx;
49 unsigned int image_size = 0;
51 if (!prog->jit_requested)
54 tmp = bpf_jit_blind_constants(prog);
62 jit_data = prog->aux->jit_data;
64 jit_data = kzalloc(sizeof(*jit_data), GFP_KERNEL);
69 prog->aux->jit_data = jit_data;
76 image_size = sizeof(*ctx->insns) * ctx->ninsns;
81 ctx->offset = kcalloc(prog->len, sizeof(int), GFP_KERNEL);
86 for (i = 0; i < prog->len; i++) {
88 ctx->offset[i] = prev_ninsns;
91 for (i = 0; i < NR_JIT_ITERATIONS; i++) {
94 if (build_body(ctx, extra_pass, ctx->offset)) {
98 bpf_jit_build_prologue(ctx);
99 ctx->epilogue_offset = ctx->ninsns;
100 bpf_jit_build_epilogue(ctx);
102 if (ctx->ninsns == prev_ninsns) {
103 if (jit_data->header)
106 image_size = sizeof(*ctx->insns) * ctx->ninsns;
108 bpf_jit_binary_alloc(image_size,
112 if (!jit_data->header) {
117 ctx->insns = (u16 *)jit_data->image;
119 * Now, when the image is allocated, the image can
120 * potentially shrink more (auipc/jalr -> jal).
123 prev_ninsns = ctx->ninsns;
126 if (i == NR_JIT_ITERATIONS) {
127 pr_err("bpf-jit: image did not converge in <%d passes!\n", i);
128 bpf_jit_binary_free(jit_data->header);
137 bpf_jit_build_prologue(ctx);
138 if (build_body(ctx, extra_pass, NULL)) {
139 bpf_jit_binary_free(jit_data->header);
143 bpf_jit_build_epilogue(ctx);
145 if (bpf_jit_enable > 1)
146 bpf_jit_dump(prog->len, image_size, pass, ctx->insns);
148 prog->bpf_func = (void *)ctx->insns;
150 prog->jited_len = image_size;
152 bpf_flush_icache(jit_data->header, ctx->insns + ctx->ninsns);
154 if (!prog->is_func || extra_pass) {
158 prog->aux->jit_data = NULL;
163 bpf_jit_prog_release_other(prog, prog == orig_prog ?