xref: /openbmc/linux/arch/arm64/net/bpf_jit_comp.c (revision 6f6249a599e52e1a5f0b632f8edff733cfa76450)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * BPF JIT compiler for ARM64
4  *
5  * Copyright (C) 2014-2016 Zi Shen Lim <zlim.lnx@gmail.com>
6  */
7 
8 #define pr_fmt(fmt) "bpf_jit: " fmt
9 
10 #include <linux/arm-smccc.h>
11 #include <linux/bitfield.h>
12 #include <linux/bpf.h>
13 #include <linux/filter.h>
14 #include <linux/memory.h>
15 #include <linux/printk.h>
16 #include <linux/slab.h>
17 
18 #include <asm/asm-extable.h>
19 #include <asm/byteorder.h>
20 #include <asm/cacheflush.h>
21 #include <asm/cpufeature.h>
22 #include <asm/debug-monitors.h>
23 #include <asm/insn.h>
24 #include <asm/patching.h>
25 #include <asm/set_memory.h>
26 
27 #include "bpf_jit.h"
28 
29 #define TMP_REG_1 (MAX_BPF_JIT_REG + 0)
30 #define TMP_REG_2 (MAX_BPF_JIT_REG + 1)
31 #define TCALL_CNT (MAX_BPF_JIT_REG + 2)
32 #define TMP_REG_3 (MAX_BPF_JIT_REG + 3)
33 #define FP_BOTTOM (MAX_BPF_JIT_REG + 4)
34 
35 #define check_imm(bits, imm) do {				\
36 	if ((((imm) > 0) && ((imm) >> (bits))) ||		\
37 	    (((imm) < 0) && (~(imm) >> (bits)))) {		\
38 		pr_info("[%2d] imm=%d(0x%x) out of range\n",	\
39 			i, imm, imm);				\
40 		return -EINVAL;					\
41 	}							\
42 } while (0)
43 #define check_imm19(imm) check_imm(19, imm)
44 #define check_imm26(imm) check_imm(26, imm)
45 
46 /* Map BPF registers to A64 registers */
47 static const int bpf2a64[] = {
48 	/* return value from in-kernel function, and exit value from eBPF */
49 	[BPF_REG_0] = A64_R(7),
50 	/* arguments from eBPF program to in-kernel function */
51 	[BPF_REG_1] = A64_R(0),
52 	[BPF_REG_2] = A64_R(1),
53 	[BPF_REG_3] = A64_R(2),
54 	[BPF_REG_4] = A64_R(3),
55 	[BPF_REG_5] = A64_R(4),
56 	/* callee saved registers that in-kernel function will preserve */
57 	[BPF_REG_6] = A64_R(19),
58 	[BPF_REG_7] = A64_R(20),
59 	[BPF_REG_8] = A64_R(21),
60 	[BPF_REG_9] = A64_R(22),
61 	/* read-only frame pointer to access stack */
62 	[BPF_REG_FP] = A64_R(25),
63 	/* temporary registers for BPF JIT */
64 	[TMP_REG_1] = A64_R(10),
65 	[TMP_REG_2] = A64_R(11),
66 	[TMP_REG_3] = A64_R(12),
67 	/* tail_call_cnt */
68 	[TCALL_CNT] = A64_R(26),
69 	/* temporary register for blinding constants */
70 	[BPF_REG_AX] = A64_R(9),
71 	[FP_BOTTOM] = A64_R(27),
72 };
73 
74 struct jit_ctx {
75 	const struct bpf_prog *prog;
76 	int idx;
77 	int epilogue_offset;
78 	int *offset;
79 	int exentry_idx;
80 	__le32 *image;
81 	u32 stack_size;
82 	int fpb_offset;
83 };
84 
85 struct bpf_plt {
86 	u32 insn_ldr; /* load target */
87 	u32 insn_br;  /* branch to target */
88 	u64 target;   /* target value */
89 };
90 
91 #define PLT_TARGET_SIZE   sizeof_field(struct bpf_plt, target)
92 #define PLT_TARGET_OFFSET offsetof(struct bpf_plt, target)
93 
emit(const u32 insn,struct jit_ctx * ctx)94 static inline void emit(const u32 insn, struct jit_ctx *ctx)
95 {
96 	if (ctx->image != NULL)
97 		ctx->image[ctx->idx] = cpu_to_le32(insn);
98 
99 	ctx->idx++;
100 }
101 
emit_a64_mov_i(const int is64,const int reg,const s32 val,struct jit_ctx * ctx)102 static inline void emit_a64_mov_i(const int is64, const int reg,
103 				  const s32 val, struct jit_ctx *ctx)
104 {
105 	u16 hi = val >> 16;
106 	u16 lo = val & 0xffff;
107 
108 	if (hi & 0x8000) {
109 		if (hi == 0xffff) {
110 			emit(A64_MOVN(is64, reg, (u16)~lo, 0), ctx);
111 		} else {
112 			emit(A64_MOVN(is64, reg, (u16)~hi, 16), ctx);
113 			if (lo != 0xffff)
114 				emit(A64_MOVK(is64, reg, lo, 0), ctx);
115 		}
116 	} else {
117 		emit(A64_MOVZ(is64, reg, lo, 0), ctx);
118 		if (hi)
119 			emit(A64_MOVK(is64, reg, hi, 16), ctx);
120 	}
121 }
122 
i64_i16_blocks(const u64 val,bool inverse)123 static int i64_i16_blocks(const u64 val, bool inverse)
124 {
125 	return (((val >>  0) & 0xffff) != (inverse ? 0xffff : 0x0000)) +
126 	       (((val >> 16) & 0xffff) != (inverse ? 0xffff : 0x0000)) +
127 	       (((val >> 32) & 0xffff) != (inverse ? 0xffff : 0x0000)) +
128 	       (((val >> 48) & 0xffff) != (inverse ? 0xffff : 0x0000));
129 }
130 
emit_a64_mov_i64(const int reg,const u64 val,struct jit_ctx * ctx)131 static inline void emit_a64_mov_i64(const int reg, const u64 val,
132 				    struct jit_ctx *ctx)
133 {
134 	u64 nrm_tmp = val, rev_tmp = ~val;
135 	bool inverse;
136 	int shift;
137 
138 	if (!(nrm_tmp >> 32))
139 		return emit_a64_mov_i(0, reg, (u32)val, ctx);
140 
141 	inverse = i64_i16_blocks(nrm_tmp, true) < i64_i16_blocks(nrm_tmp, false);
142 	shift = max(round_down((inverse ? (fls64(rev_tmp) - 1) :
143 					  (fls64(nrm_tmp) - 1)), 16), 0);
144 	if (inverse)
145 		emit(A64_MOVN(1, reg, (rev_tmp >> shift) & 0xffff, shift), ctx);
146 	else
147 		emit(A64_MOVZ(1, reg, (nrm_tmp >> shift) & 0xffff, shift), ctx);
148 	shift -= 16;
149 	while (shift >= 0) {
150 		if (((nrm_tmp >> shift) & 0xffff) != (inverse ? 0xffff : 0x0000))
151 			emit(A64_MOVK(1, reg, (nrm_tmp >> shift) & 0xffff, shift), ctx);
152 		shift -= 16;
153 	}
154 }
155 
emit_bti(u32 insn,struct jit_ctx * ctx)156 static inline void emit_bti(u32 insn, struct jit_ctx *ctx)
157 {
158 	if (IS_ENABLED(CONFIG_ARM64_BTI_KERNEL))
159 		emit(insn, ctx);
160 }
161 
162 /*
163  * Kernel addresses in the vmalloc space use at most 48 bits, and the
164  * remaining bits are guaranteed to be 0x1. So we can compose the address
165  * with a fixed length movn/movk/movk sequence.
166  */
emit_addr_mov_i64(const int reg,const u64 val,struct jit_ctx * ctx)167 static inline void emit_addr_mov_i64(const int reg, const u64 val,
168 				     struct jit_ctx *ctx)
169 {
170 	u64 tmp = val;
171 	int shift = 0;
172 
173 	emit(A64_MOVN(1, reg, ~tmp & 0xffff, shift), ctx);
174 	while (shift < 32) {
175 		tmp >>= 16;
176 		shift += 16;
177 		emit(A64_MOVK(1, reg, tmp & 0xffff, shift), ctx);
178 	}
179 }
180 
emit_call(u64 target,struct jit_ctx * ctx)181 static inline void emit_call(u64 target, struct jit_ctx *ctx)
182 {
183 	u8 tmp = bpf2a64[TMP_REG_1];
184 
185 	emit_addr_mov_i64(tmp, target, ctx);
186 	emit(A64_BLR(tmp), ctx);
187 }
188 
bpf2a64_offset(int bpf_insn,int off,const struct jit_ctx * ctx)189 static inline int bpf2a64_offset(int bpf_insn, int off,
190 				 const struct jit_ctx *ctx)
191 {
192 	/* BPF JMP offset is relative to the next instruction */
193 	bpf_insn++;
194 	/*
195 	 * Whereas arm64 branch instructions encode the offset
196 	 * from the branch itself, so we must subtract 1 from the
197 	 * instruction offset.
198 	 */
199 	return ctx->offset[bpf_insn + off] - (ctx->offset[bpf_insn] - 1);
200 }
201 
jit_fill_hole(void * area,unsigned int size)202 static void jit_fill_hole(void *area, unsigned int size)
203 {
204 	__le32 *ptr;
205 	/* We are guaranteed to have aligned memory. */
206 	for (ptr = area; size >= sizeof(u32); size -= sizeof(u32))
207 		*ptr++ = cpu_to_le32(AARCH64_BREAK_FAULT);
208 }
209 
epilogue_offset(const struct jit_ctx * ctx)210 static inline int epilogue_offset(const struct jit_ctx *ctx)
211 {
212 	int to = ctx->epilogue_offset;
213 	int from = ctx->idx;
214 
215 	return to - from;
216 }
217 
is_addsub_imm(u32 imm)218 static bool is_addsub_imm(u32 imm)
219 {
220 	/* Either imm12 or shifted imm12. */
221 	return !(imm & ~0xfff) || !(imm & ~0xfff000);
222 }
223 
224 /*
225  * There are 3 types of AArch64 LDR/STR (immediate) instruction:
226  * Post-index, Pre-index, Unsigned offset.
227  *
228  * For BPF ldr/str, the "unsigned offset" type is sufficient.
229  *
230  * "Unsigned offset" type LDR(immediate) format:
231  *
232  *    3                   2                   1                   0
233  *  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
234  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
235  * |x x|1 1 1 0 0 1 0 1|         imm12         |    Rn   |    Rt   |
236  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
237  * scale
238  *
239  * "Unsigned offset" type STR(immediate) format:
240  *    3                   2                   1                   0
241  *  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
242  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
243  * |x x|1 1 1 0 0 1 0 0|         imm12         |    Rn   |    Rt   |
244  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
245  * scale
246  *
247  * The offset is calculated from imm12 and scale in the following way:
248  *
249  * offset = (u64)imm12 << scale
250  */
is_lsi_offset(int offset,int scale)251 static bool is_lsi_offset(int offset, int scale)
252 {
253 	if (offset < 0)
254 		return false;
255 
256 	if (offset > (0xFFF << scale))
257 		return false;
258 
259 	if (offset & ((1 << scale) - 1))
260 		return false;
261 
262 	return true;
263 }
264 
265 /* generated prologue:
266  *      bti c // if CONFIG_ARM64_BTI_KERNEL
267  *      mov x9, lr
268  *      nop  // POKE_OFFSET
269  *      paciasp // if CONFIG_ARM64_PTR_AUTH_KERNEL
270  *      stp x29, lr, [sp, #-16]!
271  *      mov x29, sp
272  *      stp x19, x20, [sp, #-16]!
273  *      stp x21, x22, [sp, #-16]!
274  *      stp x25, x26, [sp, #-16]!
275  *      stp x27, x28, [sp, #-16]!
276  *      mov x25, sp
277  *      mov tcc, #0
278  *      // PROLOGUE_OFFSET
279  */
280 
281 #define BTI_INSNS (IS_ENABLED(CONFIG_ARM64_BTI_KERNEL) ? 1 : 0)
282 #define PAC_INSNS (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL) ? 1 : 0)
283 
284 /* Offset of nop instruction in bpf prog entry to be poked */
285 #define POKE_OFFSET (BTI_INSNS + 1)
286 
287 /* Tail call offset to jump into */
288 #define PROLOGUE_OFFSET (BTI_INSNS + 2 + PAC_INSNS + 8)
289 
build_prologue(struct jit_ctx * ctx,bool ebpf_from_cbpf)290 static int build_prologue(struct jit_ctx *ctx, bool ebpf_from_cbpf)
291 {
292 	const struct bpf_prog *prog = ctx->prog;
293 	const bool is_main_prog = prog->aux->func_idx == 0;
294 	const u8 r6 = bpf2a64[BPF_REG_6];
295 	const u8 r7 = bpf2a64[BPF_REG_7];
296 	const u8 r8 = bpf2a64[BPF_REG_8];
297 	const u8 r9 = bpf2a64[BPF_REG_9];
298 	const u8 fp = bpf2a64[BPF_REG_FP];
299 	const u8 tcc = bpf2a64[TCALL_CNT];
300 	const u8 fpb = bpf2a64[FP_BOTTOM];
301 	const int idx0 = ctx->idx;
302 	int cur_offset;
303 
304 	/*
305 	 * BPF prog stack layout
306 	 *
307 	 *                         high
308 	 * original A64_SP =>   0:+-----+ BPF prologue
309 	 *                        |FP/LR|
310 	 * current A64_FP =>  -16:+-----+
311 	 *                        | ... | callee saved registers
312 	 * BPF fp register => -64:+-----+ <= (BPF_FP)
313 	 *                        |     |
314 	 *                        | ... | BPF prog stack
315 	 *                        |     |
316 	 *                        +-----+ <= (BPF_FP - prog->aux->stack_depth)
317 	 *                        |RSVD | padding
318 	 * current A64_SP =>      +-----+ <= (BPF_FP - ctx->stack_size)
319 	 *                        |     |
320 	 *                        | ... | Function call stack
321 	 *                        |     |
322 	 *                        +-----+
323 	 *                          low
324 	 *
325 	 */
326 
327 	/* bpf function may be invoked by 3 instruction types:
328 	 * 1. bl, attached via freplace to bpf prog via short jump
329 	 * 2. br, attached via freplace to bpf prog via long jump
330 	 * 3. blr, working as a function pointer, used by emit_call.
331 	 * So BTI_JC should used here to support both br and blr.
332 	 */
333 	emit_bti(A64_BTI_JC, ctx);
334 
335 	emit(A64_MOV(1, A64_R(9), A64_LR), ctx);
336 	emit(A64_NOP, ctx);
337 
338 	/* Sign lr */
339 	if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
340 		emit(A64_PACIASP, ctx);
341 
342 	/* Save FP and LR registers to stay align with ARM64 AAPCS */
343 	emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
344 	emit(A64_MOV(1, A64_FP, A64_SP), ctx);
345 
346 	/* Save callee-saved registers */
347 	emit(A64_PUSH(r6, r7, A64_SP), ctx);
348 	emit(A64_PUSH(r8, r9, A64_SP), ctx);
349 	emit(A64_PUSH(fp, tcc, A64_SP), ctx);
350 	emit(A64_PUSH(fpb, A64_R(28), A64_SP), ctx);
351 
352 	/* Set up BPF prog stack base register */
353 	emit(A64_MOV(1, fp, A64_SP), ctx);
354 
355 	if (!ebpf_from_cbpf && is_main_prog) {
356 		/* Initialize tail_call_cnt */
357 		emit(A64_MOVZ(1, tcc, 0, 0), ctx);
358 
359 		cur_offset = ctx->idx - idx0;
360 		if (cur_offset != PROLOGUE_OFFSET) {
361 			pr_err_once("PROLOGUE_OFFSET = %d, expected %d!\n",
362 				    cur_offset, PROLOGUE_OFFSET);
363 			return -1;
364 		}
365 
366 		/* BTI landing pad for the tail call, done with a BR */
367 		emit_bti(A64_BTI_J, ctx);
368 	}
369 
370 	emit(A64_SUB_I(1, fpb, fp, ctx->fpb_offset), ctx);
371 
372 	/* Stack must be multiples of 16B */
373 	ctx->stack_size = round_up(prog->aux->stack_depth, 16);
374 
375 	/* Set up function call stack */
376 	emit(A64_SUB_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
377 	return 0;
378 }
379 
380 static int out_offset = -1; /* initialized on the first pass of build_body() */
emit_bpf_tail_call(struct jit_ctx * ctx)381 static int emit_bpf_tail_call(struct jit_ctx *ctx)
382 {
383 	/* bpf_tail_call(void *prog_ctx, struct bpf_array *array, u64 index) */
384 	const u8 r2 = bpf2a64[BPF_REG_2];
385 	const u8 r3 = bpf2a64[BPF_REG_3];
386 
387 	const u8 tmp = bpf2a64[TMP_REG_1];
388 	const u8 prg = bpf2a64[TMP_REG_2];
389 	const u8 tcc = bpf2a64[TCALL_CNT];
390 	const int idx0 = ctx->idx;
391 #define cur_offset (ctx->idx - idx0)
392 #define jmp_offset (out_offset - (cur_offset))
393 	size_t off;
394 
395 	/* if (index >= array->map.max_entries)
396 	 *     goto out;
397 	 */
398 	off = offsetof(struct bpf_array, map.max_entries);
399 	emit_a64_mov_i64(tmp, off, ctx);
400 	emit(A64_LDR32(tmp, r2, tmp), ctx);
401 	emit(A64_MOV(0, r3, r3), ctx);
402 	emit(A64_CMP(0, r3, tmp), ctx);
403 	emit(A64_B_(A64_COND_CS, jmp_offset), ctx);
404 
405 	/*
406 	 * if (tail_call_cnt >= MAX_TAIL_CALL_CNT)
407 	 *     goto out;
408 	 * tail_call_cnt++;
409 	 */
410 	emit_a64_mov_i64(tmp, MAX_TAIL_CALL_CNT, ctx);
411 	emit(A64_CMP(1, tcc, tmp), ctx);
412 	emit(A64_B_(A64_COND_CS, jmp_offset), ctx);
413 	emit(A64_ADD_I(1, tcc, tcc, 1), ctx);
414 
415 	/* prog = array->ptrs[index];
416 	 * if (prog == NULL)
417 	 *     goto out;
418 	 */
419 	off = offsetof(struct bpf_array, ptrs);
420 	emit_a64_mov_i64(tmp, off, ctx);
421 	emit(A64_ADD(1, tmp, r2, tmp), ctx);
422 	emit(A64_LSL(1, prg, r3, 3), ctx);
423 	emit(A64_LDR64(prg, tmp, prg), ctx);
424 	emit(A64_CBZ(1, prg, jmp_offset), ctx);
425 
426 	/* goto *(prog->bpf_func + prologue_offset); */
427 	off = offsetof(struct bpf_prog, bpf_func);
428 	emit_a64_mov_i64(tmp, off, ctx);
429 	emit(A64_LDR64(tmp, prg, tmp), ctx);
430 	emit(A64_ADD_I(1, tmp, tmp, sizeof(u32) * PROLOGUE_OFFSET), ctx);
431 	emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
432 	emit(A64_BR(tmp), ctx);
433 
434 	/* out: */
435 	if (out_offset == -1)
436 		out_offset = cur_offset;
437 	if (cur_offset != out_offset) {
438 		pr_err_once("tail_call out_offset = %d, expected %d!\n",
439 			    cur_offset, out_offset);
440 		return -1;
441 	}
442 	return 0;
443 #undef cur_offset
444 #undef jmp_offset
445 }
446 
447 #ifdef CONFIG_ARM64_LSE_ATOMICS
emit_lse_atomic(const struct bpf_insn * insn,struct jit_ctx * ctx)448 static int emit_lse_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
449 {
450 	const u8 code = insn->code;
451 	const u8 dst = bpf2a64[insn->dst_reg];
452 	const u8 src = bpf2a64[insn->src_reg];
453 	const u8 tmp = bpf2a64[TMP_REG_1];
454 	const u8 tmp2 = bpf2a64[TMP_REG_2];
455 	const bool isdw = BPF_SIZE(code) == BPF_DW;
456 	const s16 off = insn->off;
457 	u8 reg;
458 
459 	if (!off) {
460 		reg = dst;
461 	} else {
462 		emit_a64_mov_i(1, tmp, off, ctx);
463 		emit(A64_ADD(1, tmp, tmp, dst), ctx);
464 		reg = tmp;
465 	}
466 
467 	switch (insn->imm) {
468 	/* lock *(u32/u64 *)(dst_reg + off) <op>= src_reg */
469 	case BPF_ADD:
470 		emit(A64_STADD(isdw, reg, src), ctx);
471 		break;
472 	case BPF_AND:
473 		emit(A64_MVN(isdw, tmp2, src), ctx);
474 		emit(A64_STCLR(isdw, reg, tmp2), ctx);
475 		break;
476 	case BPF_OR:
477 		emit(A64_STSET(isdw, reg, src), ctx);
478 		break;
479 	case BPF_XOR:
480 		emit(A64_STEOR(isdw, reg, src), ctx);
481 		break;
482 	/* src_reg = atomic_fetch_<op>(dst_reg + off, src_reg) */
483 	case BPF_ADD | BPF_FETCH:
484 		emit(A64_LDADDAL(isdw, src, reg, src), ctx);
485 		break;
486 	case BPF_AND | BPF_FETCH:
487 		emit(A64_MVN(isdw, tmp2, src), ctx);
488 		emit(A64_LDCLRAL(isdw, src, reg, tmp2), ctx);
489 		break;
490 	case BPF_OR | BPF_FETCH:
491 		emit(A64_LDSETAL(isdw, src, reg, src), ctx);
492 		break;
493 	case BPF_XOR | BPF_FETCH:
494 		emit(A64_LDEORAL(isdw, src, reg, src), ctx);
495 		break;
496 	/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
497 	case BPF_XCHG:
498 		emit(A64_SWPAL(isdw, src, reg, src), ctx);
499 		break;
500 	/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
501 	case BPF_CMPXCHG:
502 		emit(A64_CASAL(isdw, src, reg, bpf2a64[BPF_REG_0]), ctx);
503 		break;
504 	default:
505 		pr_err_once("unknown atomic op code %02x\n", insn->imm);
506 		return -EINVAL;
507 	}
508 
509 	return 0;
510 }
511 #else
emit_lse_atomic(const struct bpf_insn * insn,struct jit_ctx * ctx)512 static inline int emit_lse_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
513 {
514 	return -EINVAL;
515 }
516 #endif
517 
emit_ll_sc_atomic(const struct bpf_insn * insn,struct jit_ctx * ctx)518 static int emit_ll_sc_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
519 {
520 	const u8 code = insn->code;
521 	const u8 dst = bpf2a64[insn->dst_reg];
522 	const u8 src = bpf2a64[insn->src_reg];
523 	const u8 tmp = bpf2a64[TMP_REG_1];
524 	const u8 tmp2 = bpf2a64[TMP_REG_2];
525 	const u8 tmp3 = bpf2a64[TMP_REG_3];
526 	const int i = insn - ctx->prog->insnsi;
527 	const s32 imm = insn->imm;
528 	const s16 off = insn->off;
529 	const bool isdw = BPF_SIZE(code) == BPF_DW;
530 	u8 reg;
531 	s32 jmp_offset;
532 
533 	if (!off) {
534 		reg = dst;
535 	} else {
536 		emit_a64_mov_i(1, tmp, off, ctx);
537 		emit(A64_ADD(1, tmp, tmp, dst), ctx);
538 		reg = tmp;
539 	}
540 
541 	if (imm == BPF_ADD || imm == BPF_AND ||
542 	    imm == BPF_OR || imm == BPF_XOR) {
543 		/* lock *(u32/u64 *)(dst_reg + off) <op>= src_reg */
544 		emit(A64_LDXR(isdw, tmp2, reg), ctx);
545 		if (imm == BPF_ADD)
546 			emit(A64_ADD(isdw, tmp2, tmp2, src), ctx);
547 		else if (imm == BPF_AND)
548 			emit(A64_AND(isdw, tmp2, tmp2, src), ctx);
549 		else if (imm == BPF_OR)
550 			emit(A64_ORR(isdw, tmp2, tmp2, src), ctx);
551 		else
552 			emit(A64_EOR(isdw, tmp2, tmp2, src), ctx);
553 		emit(A64_STXR(isdw, tmp2, reg, tmp3), ctx);
554 		jmp_offset = -3;
555 		check_imm19(jmp_offset);
556 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
557 	} else if (imm == (BPF_ADD | BPF_FETCH) ||
558 		   imm == (BPF_AND | BPF_FETCH) ||
559 		   imm == (BPF_OR | BPF_FETCH) ||
560 		   imm == (BPF_XOR | BPF_FETCH)) {
561 		/* src_reg = atomic_fetch_<op>(dst_reg + off, src_reg) */
562 		const u8 ax = bpf2a64[BPF_REG_AX];
563 
564 		emit(A64_MOV(isdw, ax, src), ctx);
565 		emit(A64_LDXR(isdw, src, reg), ctx);
566 		if (imm == (BPF_ADD | BPF_FETCH))
567 			emit(A64_ADD(isdw, tmp2, src, ax), ctx);
568 		else if (imm == (BPF_AND | BPF_FETCH))
569 			emit(A64_AND(isdw, tmp2, src, ax), ctx);
570 		else if (imm == (BPF_OR | BPF_FETCH))
571 			emit(A64_ORR(isdw, tmp2, src, ax), ctx);
572 		else
573 			emit(A64_EOR(isdw, tmp2, src, ax), ctx);
574 		emit(A64_STLXR(isdw, tmp2, reg, tmp3), ctx);
575 		jmp_offset = -3;
576 		check_imm19(jmp_offset);
577 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
578 		emit(A64_DMB_ISH, ctx);
579 	} else if (imm == BPF_XCHG) {
580 		/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
581 		emit(A64_MOV(isdw, tmp2, src), ctx);
582 		emit(A64_LDXR(isdw, src, reg), ctx);
583 		emit(A64_STLXR(isdw, tmp2, reg, tmp3), ctx);
584 		jmp_offset = -2;
585 		check_imm19(jmp_offset);
586 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
587 		emit(A64_DMB_ISH, ctx);
588 	} else if (imm == BPF_CMPXCHG) {
589 		/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
590 		const u8 r0 = bpf2a64[BPF_REG_0];
591 
592 		emit(A64_MOV(isdw, tmp2, r0), ctx);
593 		emit(A64_LDXR(isdw, r0, reg), ctx);
594 		emit(A64_EOR(isdw, tmp3, r0, tmp2), ctx);
595 		jmp_offset = 4;
596 		check_imm19(jmp_offset);
597 		emit(A64_CBNZ(isdw, tmp3, jmp_offset), ctx);
598 		emit(A64_STLXR(isdw, src, reg, tmp3), ctx);
599 		jmp_offset = -4;
600 		check_imm19(jmp_offset);
601 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
602 		emit(A64_DMB_ISH, ctx);
603 	} else {
604 		pr_err_once("unknown atomic op code %02x\n", imm);
605 		return -EINVAL;
606 	}
607 
608 	return 0;
609 }
610 
611 void dummy_tramp(void);
612 
613 asm (
614 "	.pushsection .text, \"ax\", @progbits\n"
615 "	.global dummy_tramp\n"
616 "	.type dummy_tramp, %function\n"
617 "dummy_tramp:"
618 #if IS_ENABLED(CONFIG_ARM64_BTI_KERNEL)
619 "	bti j\n" /* dummy_tramp is called via "br x10" */
620 #endif
621 "	mov x10, x30\n"
622 "	mov x30, x9\n"
623 "	ret x10\n"
624 "	.size dummy_tramp, .-dummy_tramp\n"
625 "	.popsection\n"
626 );
627 
628 /* build a plt initialized like this:
629  *
630  * plt:
631  *      ldr tmp, target
632  *      br tmp
633  * target:
634  *      .quad dummy_tramp
635  *
636  * when a long jump trampoline is attached, target is filled with the
637  * trampoline address, and when the trampoline is removed, target is
638  * restored to dummy_tramp address.
639  */
build_plt(struct jit_ctx * ctx)640 static void build_plt(struct jit_ctx *ctx)
641 {
642 	const u8 tmp = bpf2a64[TMP_REG_1];
643 	struct bpf_plt *plt = NULL;
644 
645 	/* make sure target is 64-bit aligned */
646 	if ((ctx->idx + PLT_TARGET_OFFSET / AARCH64_INSN_SIZE) % 2)
647 		emit(A64_NOP, ctx);
648 
649 	plt = (struct bpf_plt *)(ctx->image + ctx->idx);
650 	/* plt is called via bl, no BTI needed here */
651 	emit(A64_LDR64LIT(tmp, 2 * AARCH64_INSN_SIZE), ctx);
652 	emit(A64_BR(tmp), ctx);
653 
654 	if (ctx->image)
655 		plt->target = (u64)&dummy_tramp;
656 }
657 
658 /* Clobbers BPF registers 1-4, aka x0-x3 */
build_bhb_mitigation(struct jit_ctx * ctx)659 static void __maybe_unused build_bhb_mitigation(struct jit_ctx *ctx)
660 {
661 	const u8 r1 = bpf2a64[BPF_REG_1]; /* aka x0 */
662 	u8 k = get_spectre_bhb_loop_value();
663 
664 	if (!IS_ENABLED(CONFIG_MITIGATE_SPECTRE_BRANCH_HISTORY) ||
665 	    cpu_mitigations_off() || __nospectre_bhb ||
666 	    arm64_get_spectre_v2_state() == SPECTRE_VULNERABLE)
667 		return;
668 
669 	if (capable(CAP_SYS_ADMIN))
670 		return;
671 
672 	if (supports_clearbhb(SCOPE_SYSTEM)) {
673 		emit(aarch64_insn_gen_hint(AARCH64_INSN_HINT_CLEARBHB), ctx);
674 		return;
675 	}
676 
677 	if (k) {
678 		emit_a64_mov_i64(r1, k, ctx);
679 		emit(A64_B(1), ctx);
680 		emit(A64_SUBS_I(true, r1, r1, 1), ctx);
681 		emit(A64_B_(A64_COND_NE, -2), ctx);
682 		emit(aarch64_insn_gen_dsb(AARCH64_INSN_MB_ISH), ctx);
683 		emit(aarch64_insn_get_isb_value(), ctx);
684 	}
685 
686 	if (is_spectre_bhb_fw_mitigated()) {
687 		emit(A64_ORR_I(false, r1, AARCH64_INSN_REG_ZR,
688 			       ARM_SMCCC_ARCH_WORKAROUND_3), ctx);
689 		switch (arm_smccc_1_1_get_conduit()) {
690 		case SMCCC_CONDUIT_HVC:
691 			emit(aarch64_insn_get_hvc_value(), ctx);
692 			break;
693 		case SMCCC_CONDUIT_SMC:
694 			emit(aarch64_insn_get_smc_value(), ctx);
695 			break;
696 		default:
697 			pr_err_once("Firmware mitigation enabled with unknown conduit\n");
698 		}
699 	}
700 }
701 
build_epilogue(struct jit_ctx * ctx,bool was_classic)702 static void build_epilogue(struct jit_ctx *ctx, bool was_classic)
703 {
704 	const u8 r0 = bpf2a64[BPF_REG_0];
705 	const u8 r6 = bpf2a64[BPF_REG_6];
706 	const u8 r7 = bpf2a64[BPF_REG_7];
707 	const u8 r8 = bpf2a64[BPF_REG_8];
708 	const u8 r9 = bpf2a64[BPF_REG_9];
709 	const u8 fp = bpf2a64[BPF_REG_FP];
710 	const u8 fpb = bpf2a64[FP_BOTTOM];
711 
712 	/* We're done with BPF stack */
713 	emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
714 
715 	/* Restore x27 and x28 */
716 	emit(A64_POP(fpb, A64_R(28), A64_SP), ctx);
717 	/* Restore fs (x25) and x26 */
718 	emit(A64_POP(fp, A64_R(26), A64_SP), ctx);
719 
720 	/* Restore callee-saved register */
721 	emit(A64_POP(r8, r9, A64_SP), ctx);
722 	emit(A64_POP(r6, r7, A64_SP), ctx);
723 
724 	if (was_classic)
725 		build_bhb_mitigation(ctx);
726 
727 	/* Restore FP/LR registers */
728 	emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
729 
730 	/* Move the return value from bpf:r0 (aka x7) to x0 */
731 	emit(A64_MOV(1, A64_R(0), r0), ctx);
732 
733 	/* Authenticate lr */
734 	if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
735 		emit(A64_AUTIASP, ctx);
736 
737 	emit(A64_RET(A64_LR), ctx);
738 }
739 
740 #define BPF_FIXUP_OFFSET_MASK	GENMASK(26, 0)
741 #define BPF_FIXUP_REG_MASK	GENMASK(31, 27)
742 
ex_handler_bpf(const struct exception_table_entry * ex,struct pt_regs * regs)743 bool ex_handler_bpf(const struct exception_table_entry *ex,
744 		    struct pt_regs *regs)
745 {
746 	off_t offset = FIELD_GET(BPF_FIXUP_OFFSET_MASK, ex->fixup);
747 	int dst_reg = FIELD_GET(BPF_FIXUP_REG_MASK, ex->fixup);
748 
749 	regs->regs[dst_reg] = 0;
750 	regs->pc = (unsigned long)&ex->fixup - offset;
751 	return true;
752 }
753 
754 /* For accesses to BTF pointers, add an entry to the exception table */
add_exception_handler(const struct bpf_insn * insn,struct jit_ctx * ctx,int dst_reg)755 static int add_exception_handler(const struct bpf_insn *insn,
756 				 struct jit_ctx *ctx,
757 				 int dst_reg)
758 {
759 	off_t offset;
760 	unsigned long pc;
761 	struct exception_table_entry *ex;
762 
763 	if (!ctx->image)
764 		/* First pass */
765 		return 0;
766 
767 	if (BPF_MODE(insn->code) != BPF_PROBE_MEM &&
768 		BPF_MODE(insn->code) != BPF_PROBE_MEMSX)
769 		return 0;
770 
771 	if (!ctx->prog->aux->extable ||
772 	    WARN_ON_ONCE(ctx->exentry_idx >= ctx->prog->aux->num_exentries))
773 		return -EINVAL;
774 
775 	ex = &ctx->prog->aux->extable[ctx->exentry_idx];
776 	pc = (unsigned long)&ctx->image[ctx->idx - 1];
777 
778 	offset = pc - (long)&ex->insn;
779 	if (WARN_ON_ONCE(offset >= 0 || offset < INT_MIN))
780 		return -ERANGE;
781 	ex->insn = offset;
782 
783 	/*
784 	 * Since the extable follows the program, the fixup offset is always
785 	 * negative and limited to BPF_JIT_REGION_SIZE. Store a positive value
786 	 * to keep things simple, and put the destination register in the upper
787 	 * bits. We don't need to worry about buildtime or runtime sort
788 	 * modifying the upper bits because the table is already sorted, and
789 	 * isn't part of the main exception table.
790 	 */
791 	offset = (long)&ex->fixup - (pc + AARCH64_INSN_SIZE);
792 	if (!FIELD_FIT(BPF_FIXUP_OFFSET_MASK, offset))
793 		return -ERANGE;
794 
795 	ex->fixup = FIELD_PREP(BPF_FIXUP_OFFSET_MASK, offset) |
796 		    FIELD_PREP(BPF_FIXUP_REG_MASK, dst_reg);
797 
798 	ex->type = EX_TYPE_BPF;
799 
800 	ctx->exentry_idx++;
801 	return 0;
802 }
803 
804 /* JITs an eBPF instruction.
805  * Returns:
806  * 0  - successfully JITed an 8-byte eBPF instruction.
807  * >0 - successfully JITed a 16-byte eBPF instruction.
808  * <0 - failed to JIT.
809  */
build_insn(const struct bpf_insn * insn,struct jit_ctx * ctx,bool extra_pass)810 static int build_insn(const struct bpf_insn *insn, struct jit_ctx *ctx,
811 		      bool extra_pass)
812 {
813 	const u8 code = insn->code;
814 	const u8 dst = bpf2a64[insn->dst_reg];
815 	const u8 src = bpf2a64[insn->src_reg];
816 	const u8 tmp = bpf2a64[TMP_REG_1];
817 	const u8 tmp2 = bpf2a64[TMP_REG_2];
818 	const u8 fp = bpf2a64[BPF_REG_FP];
819 	const u8 fpb = bpf2a64[FP_BOTTOM];
820 	const s16 off = insn->off;
821 	const s32 imm = insn->imm;
822 	const int i = insn - ctx->prog->insnsi;
823 	const bool is64 = BPF_CLASS(code) == BPF_ALU64 ||
824 			  BPF_CLASS(code) == BPF_JMP;
825 	u8 jmp_cond;
826 	s32 jmp_offset;
827 	u32 a64_insn;
828 	u8 src_adj;
829 	u8 dst_adj;
830 	int off_adj;
831 	int ret;
832 	bool sign_extend;
833 
834 	switch (code) {
835 	/* dst = src */
836 	case BPF_ALU | BPF_MOV | BPF_X:
837 	case BPF_ALU64 | BPF_MOV | BPF_X:
838 		switch (insn->off) {
839 		case 0:
840 			emit(A64_MOV(is64, dst, src), ctx);
841 			break;
842 		case 8:
843 			emit(A64_SXTB(is64, dst, src), ctx);
844 			break;
845 		case 16:
846 			emit(A64_SXTH(is64, dst, src), ctx);
847 			break;
848 		case 32:
849 			emit(A64_SXTW(is64, dst, src), ctx);
850 			break;
851 		}
852 		break;
853 	/* dst = dst OP src */
854 	case BPF_ALU | BPF_ADD | BPF_X:
855 	case BPF_ALU64 | BPF_ADD | BPF_X:
856 		emit(A64_ADD(is64, dst, dst, src), ctx);
857 		break;
858 	case BPF_ALU | BPF_SUB | BPF_X:
859 	case BPF_ALU64 | BPF_SUB | BPF_X:
860 		emit(A64_SUB(is64, dst, dst, src), ctx);
861 		break;
862 	case BPF_ALU | BPF_AND | BPF_X:
863 	case BPF_ALU64 | BPF_AND | BPF_X:
864 		emit(A64_AND(is64, dst, dst, src), ctx);
865 		break;
866 	case BPF_ALU | BPF_OR | BPF_X:
867 	case BPF_ALU64 | BPF_OR | BPF_X:
868 		emit(A64_ORR(is64, dst, dst, src), ctx);
869 		break;
870 	case BPF_ALU | BPF_XOR | BPF_X:
871 	case BPF_ALU64 | BPF_XOR | BPF_X:
872 		emit(A64_EOR(is64, dst, dst, src), ctx);
873 		break;
874 	case BPF_ALU | BPF_MUL | BPF_X:
875 	case BPF_ALU64 | BPF_MUL | BPF_X:
876 		emit(A64_MUL(is64, dst, dst, src), ctx);
877 		break;
878 	case BPF_ALU | BPF_DIV | BPF_X:
879 	case BPF_ALU64 | BPF_DIV | BPF_X:
880 		if (!off)
881 			emit(A64_UDIV(is64, dst, dst, src), ctx);
882 		else
883 			emit(A64_SDIV(is64, dst, dst, src), ctx);
884 		break;
885 	case BPF_ALU | BPF_MOD | BPF_X:
886 	case BPF_ALU64 | BPF_MOD | BPF_X:
887 		if (!off)
888 			emit(A64_UDIV(is64, tmp, dst, src), ctx);
889 		else
890 			emit(A64_SDIV(is64, tmp, dst, src), ctx);
891 		emit(A64_MSUB(is64, dst, dst, tmp, src), ctx);
892 		break;
893 	case BPF_ALU | BPF_LSH | BPF_X:
894 	case BPF_ALU64 | BPF_LSH | BPF_X:
895 		emit(A64_LSLV(is64, dst, dst, src), ctx);
896 		break;
897 	case BPF_ALU | BPF_RSH | BPF_X:
898 	case BPF_ALU64 | BPF_RSH | BPF_X:
899 		emit(A64_LSRV(is64, dst, dst, src), ctx);
900 		break;
901 	case BPF_ALU | BPF_ARSH | BPF_X:
902 	case BPF_ALU64 | BPF_ARSH | BPF_X:
903 		emit(A64_ASRV(is64, dst, dst, src), ctx);
904 		break;
905 	/* dst = -dst */
906 	case BPF_ALU | BPF_NEG:
907 	case BPF_ALU64 | BPF_NEG:
908 		emit(A64_NEG(is64, dst, dst), ctx);
909 		break;
910 	/* dst = BSWAP##imm(dst) */
911 	case BPF_ALU | BPF_END | BPF_FROM_LE:
912 	case BPF_ALU | BPF_END | BPF_FROM_BE:
913 	case BPF_ALU64 | BPF_END | BPF_FROM_LE:
914 #ifdef CONFIG_CPU_BIG_ENDIAN
915 		if (BPF_CLASS(code) == BPF_ALU && BPF_SRC(code) == BPF_FROM_BE)
916 			goto emit_bswap_uxt;
917 #else /* !CONFIG_CPU_BIG_ENDIAN */
918 		if (BPF_CLASS(code) == BPF_ALU && BPF_SRC(code) == BPF_FROM_LE)
919 			goto emit_bswap_uxt;
920 #endif
921 		switch (imm) {
922 		case 16:
923 			emit(A64_REV16(is64, dst, dst), ctx);
924 			/* zero-extend 16 bits into 64 bits */
925 			emit(A64_UXTH(is64, dst, dst), ctx);
926 			break;
927 		case 32:
928 			emit(A64_REV32(0, dst, dst), ctx);
929 			/* upper 32 bits already cleared */
930 			break;
931 		case 64:
932 			emit(A64_REV64(dst, dst), ctx);
933 			break;
934 		}
935 		break;
936 emit_bswap_uxt:
937 		switch (imm) {
938 		case 16:
939 			/* zero-extend 16 bits into 64 bits */
940 			emit(A64_UXTH(is64, dst, dst), ctx);
941 			break;
942 		case 32:
943 			/* zero-extend 32 bits into 64 bits */
944 			emit(A64_UXTW(is64, dst, dst), ctx);
945 			break;
946 		case 64:
947 			/* nop */
948 			break;
949 		}
950 		break;
951 	/* dst = imm */
952 	case BPF_ALU | BPF_MOV | BPF_K:
953 	case BPF_ALU64 | BPF_MOV | BPF_K:
954 		emit_a64_mov_i(is64, dst, imm, ctx);
955 		break;
956 	/* dst = dst OP imm */
957 	case BPF_ALU | BPF_ADD | BPF_K:
958 	case BPF_ALU64 | BPF_ADD | BPF_K:
959 		if (is_addsub_imm(imm)) {
960 			emit(A64_ADD_I(is64, dst, dst, imm), ctx);
961 		} else if (is_addsub_imm(-imm)) {
962 			emit(A64_SUB_I(is64, dst, dst, -imm), ctx);
963 		} else {
964 			emit_a64_mov_i(is64, tmp, imm, ctx);
965 			emit(A64_ADD(is64, dst, dst, tmp), ctx);
966 		}
967 		break;
968 	case BPF_ALU | BPF_SUB | BPF_K:
969 	case BPF_ALU64 | BPF_SUB | BPF_K:
970 		if (is_addsub_imm(imm)) {
971 			emit(A64_SUB_I(is64, dst, dst, imm), ctx);
972 		} else if (is_addsub_imm(-imm)) {
973 			emit(A64_ADD_I(is64, dst, dst, -imm), ctx);
974 		} else {
975 			emit_a64_mov_i(is64, tmp, imm, ctx);
976 			emit(A64_SUB(is64, dst, dst, tmp), ctx);
977 		}
978 		break;
979 	case BPF_ALU | BPF_AND | BPF_K:
980 	case BPF_ALU64 | BPF_AND | BPF_K:
981 		a64_insn = A64_AND_I(is64, dst, dst, imm);
982 		if (a64_insn != AARCH64_BREAK_FAULT) {
983 			emit(a64_insn, ctx);
984 		} else {
985 			emit_a64_mov_i(is64, tmp, imm, ctx);
986 			emit(A64_AND(is64, dst, dst, tmp), ctx);
987 		}
988 		break;
989 	case BPF_ALU | BPF_OR | BPF_K:
990 	case BPF_ALU64 | BPF_OR | BPF_K:
991 		a64_insn = A64_ORR_I(is64, dst, dst, imm);
992 		if (a64_insn != AARCH64_BREAK_FAULT) {
993 			emit(a64_insn, ctx);
994 		} else {
995 			emit_a64_mov_i(is64, tmp, imm, ctx);
996 			emit(A64_ORR(is64, dst, dst, tmp), ctx);
997 		}
998 		break;
999 	case BPF_ALU | BPF_XOR | BPF_K:
1000 	case BPF_ALU64 | BPF_XOR | BPF_K:
1001 		a64_insn = A64_EOR_I(is64, dst, dst, imm);
1002 		if (a64_insn != AARCH64_BREAK_FAULT) {
1003 			emit(a64_insn, ctx);
1004 		} else {
1005 			emit_a64_mov_i(is64, tmp, imm, ctx);
1006 			emit(A64_EOR(is64, dst, dst, tmp), ctx);
1007 		}
1008 		break;
1009 	case BPF_ALU | BPF_MUL | BPF_K:
1010 	case BPF_ALU64 | BPF_MUL | BPF_K:
1011 		emit_a64_mov_i(is64, tmp, imm, ctx);
1012 		emit(A64_MUL(is64, dst, dst, tmp), ctx);
1013 		break;
1014 	case BPF_ALU | BPF_DIV | BPF_K:
1015 	case BPF_ALU64 | BPF_DIV | BPF_K:
1016 		emit_a64_mov_i(is64, tmp, imm, ctx);
1017 		if (!off)
1018 			emit(A64_UDIV(is64, dst, dst, tmp), ctx);
1019 		else
1020 			emit(A64_SDIV(is64, dst, dst, tmp), ctx);
1021 		break;
1022 	case BPF_ALU | BPF_MOD | BPF_K:
1023 	case BPF_ALU64 | BPF_MOD | BPF_K:
1024 		emit_a64_mov_i(is64, tmp2, imm, ctx);
1025 		if (!off)
1026 			emit(A64_UDIV(is64, tmp, dst, tmp2), ctx);
1027 		else
1028 			emit(A64_SDIV(is64, tmp, dst, tmp2), ctx);
1029 		emit(A64_MSUB(is64, dst, dst, tmp, tmp2), ctx);
1030 		break;
1031 	case BPF_ALU | BPF_LSH | BPF_K:
1032 	case BPF_ALU64 | BPF_LSH | BPF_K:
1033 		emit(A64_LSL(is64, dst, dst, imm), ctx);
1034 		break;
1035 	case BPF_ALU | BPF_RSH | BPF_K:
1036 	case BPF_ALU64 | BPF_RSH | BPF_K:
1037 		emit(A64_LSR(is64, dst, dst, imm), ctx);
1038 		break;
1039 	case BPF_ALU | BPF_ARSH | BPF_K:
1040 	case BPF_ALU64 | BPF_ARSH | BPF_K:
1041 		emit(A64_ASR(is64, dst, dst, imm), ctx);
1042 		break;
1043 
1044 	/* JUMP off */
1045 	case BPF_JMP | BPF_JA:
1046 	case BPF_JMP32 | BPF_JA:
1047 		if (BPF_CLASS(code) == BPF_JMP)
1048 			jmp_offset = bpf2a64_offset(i, off, ctx);
1049 		else
1050 			jmp_offset = bpf2a64_offset(i, imm, ctx);
1051 		check_imm26(jmp_offset);
1052 		emit(A64_B(jmp_offset), ctx);
1053 		break;
1054 	/* IF (dst COND src) JUMP off */
1055 	case BPF_JMP | BPF_JEQ | BPF_X:
1056 	case BPF_JMP | BPF_JGT | BPF_X:
1057 	case BPF_JMP | BPF_JLT | BPF_X:
1058 	case BPF_JMP | BPF_JGE | BPF_X:
1059 	case BPF_JMP | BPF_JLE | BPF_X:
1060 	case BPF_JMP | BPF_JNE | BPF_X:
1061 	case BPF_JMP | BPF_JSGT | BPF_X:
1062 	case BPF_JMP | BPF_JSLT | BPF_X:
1063 	case BPF_JMP | BPF_JSGE | BPF_X:
1064 	case BPF_JMP | BPF_JSLE | BPF_X:
1065 	case BPF_JMP32 | BPF_JEQ | BPF_X:
1066 	case BPF_JMP32 | BPF_JGT | BPF_X:
1067 	case BPF_JMP32 | BPF_JLT | BPF_X:
1068 	case BPF_JMP32 | BPF_JGE | BPF_X:
1069 	case BPF_JMP32 | BPF_JLE | BPF_X:
1070 	case BPF_JMP32 | BPF_JNE | BPF_X:
1071 	case BPF_JMP32 | BPF_JSGT | BPF_X:
1072 	case BPF_JMP32 | BPF_JSLT | BPF_X:
1073 	case BPF_JMP32 | BPF_JSGE | BPF_X:
1074 	case BPF_JMP32 | BPF_JSLE | BPF_X:
1075 		emit(A64_CMP(is64, dst, src), ctx);
1076 emit_cond_jmp:
1077 		jmp_offset = bpf2a64_offset(i, off, ctx);
1078 		check_imm19(jmp_offset);
1079 		switch (BPF_OP(code)) {
1080 		case BPF_JEQ:
1081 			jmp_cond = A64_COND_EQ;
1082 			break;
1083 		case BPF_JGT:
1084 			jmp_cond = A64_COND_HI;
1085 			break;
1086 		case BPF_JLT:
1087 			jmp_cond = A64_COND_CC;
1088 			break;
1089 		case BPF_JGE:
1090 			jmp_cond = A64_COND_CS;
1091 			break;
1092 		case BPF_JLE:
1093 			jmp_cond = A64_COND_LS;
1094 			break;
1095 		case BPF_JSET:
1096 		case BPF_JNE:
1097 			jmp_cond = A64_COND_NE;
1098 			break;
1099 		case BPF_JSGT:
1100 			jmp_cond = A64_COND_GT;
1101 			break;
1102 		case BPF_JSLT:
1103 			jmp_cond = A64_COND_LT;
1104 			break;
1105 		case BPF_JSGE:
1106 			jmp_cond = A64_COND_GE;
1107 			break;
1108 		case BPF_JSLE:
1109 			jmp_cond = A64_COND_LE;
1110 			break;
1111 		default:
1112 			return -EFAULT;
1113 		}
1114 		emit(A64_B_(jmp_cond, jmp_offset), ctx);
1115 		break;
1116 	case BPF_JMP | BPF_JSET | BPF_X:
1117 	case BPF_JMP32 | BPF_JSET | BPF_X:
1118 		emit(A64_TST(is64, dst, src), ctx);
1119 		goto emit_cond_jmp;
1120 	/* IF (dst COND imm) JUMP off */
1121 	case BPF_JMP | BPF_JEQ | BPF_K:
1122 	case BPF_JMP | BPF_JGT | BPF_K:
1123 	case BPF_JMP | BPF_JLT | BPF_K:
1124 	case BPF_JMP | BPF_JGE | BPF_K:
1125 	case BPF_JMP | BPF_JLE | BPF_K:
1126 	case BPF_JMP | BPF_JNE | BPF_K:
1127 	case BPF_JMP | BPF_JSGT | BPF_K:
1128 	case BPF_JMP | BPF_JSLT | BPF_K:
1129 	case BPF_JMP | BPF_JSGE | BPF_K:
1130 	case BPF_JMP | BPF_JSLE | BPF_K:
1131 	case BPF_JMP32 | BPF_JEQ | BPF_K:
1132 	case BPF_JMP32 | BPF_JGT | BPF_K:
1133 	case BPF_JMP32 | BPF_JLT | BPF_K:
1134 	case BPF_JMP32 | BPF_JGE | BPF_K:
1135 	case BPF_JMP32 | BPF_JLE | BPF_K:
1136 	case BPF_JMP32 | BPF_JNE | BPF_K:
1137 	case BPF_JMP32 | BPF_JSGT | BPF_K:
1138 	case BPF_JMP32 | BPF_JSLT | BPF_K:
1139 	case BPF_JMP32 | BPF_JSGE | BPF_K:
1140 	case BPF_JMP32 | BPF_JSLE | BPF_K:
1141 		if (is_addsub_imm(imm)) {
1142 			emit(A64_CMP_I(is64, dst, imm), ctx);
1143 		} else if (is_addsub_imm(-imm)) {
1144 			emit(A64_CMN_I(is64, dst, -imm), ctx);
1145 		} else {
1146 			emit_a64_mov_i(is64, tmp, imm, ctx);
1147 			emit(A64_CMP(is64, dst, tmp), ctx);
1148 		}
1149 		goto emit_cond_jmp;
1150 	case BPF_JMP | BPF_JSET | BPF_K:
1151 	case BPF_JMP32 | BPF_JSET | BPF_K:
1152 		a64_insn = A64_TST_I(is64, dst, imm);
1153 		if (a64_insn != AARCH64_BREAK_FAULT) {
1154 			emit(a64_insn, ctx);
1155 		} else {
1156 			emit_a64_mov_i(is64, tmp, imm, ctx);
1157 			emit(A64_TST(is64, dst, tmp), ctx);
1158 		}
1159 		goto emit_cond_jmp;
1160 	/* function call */
1161 	case BPF_JMP | BPF_CALL:
1162 	{
1163 		const u8 r0 = bpf2a64[BPF_REG_0];
1164 		bool func_addr_fixed;
1165 		u64 func_addr;
1166 
1167 		ret = bpf_jit_get_func_addr(ctx->prog, insn, extra_pass,
1168 					    &func_addr, &func_addr_fixed);
1169 		if (ret < 0)
1170 			return ret;
1171 		emit_call(func_addr, ctx);
1172 		emit(A64_MOV(1, r0, A64_R(0)), ctx);
1173 		break;
1174 	}
1175 	/* tail call */
1176 	case BPF_JMP | BPF_TAIL_CALL:
1177 		if (emit_bpf_tail_call(ctx))
1178 			return -EFAULT;
1179 		break;
1180 	/* function return */
1181 	case BPF_JMP | BPF_EXIT:
1182 		/* Optimization: when last instruction is EXIT,
1183 		   simply fallthrough to epilogue. */
1184 		if (i == ctx->prog->len - 1)
1185 			break;
1186 		jmp_offset = epilogue_offset(ctx);
1187 		check_imm26(jmp_offset);
1188 		emit(A64_B(jmp_offset), ctx);
1189 		break;
1190 
1191 	/* dst = imm64 */
1192 	case BPF_LD | BPF_IMM | BPF_DW:
1193 	{
1194 		const struct bpf_insn insn1 = insn[1];
1195 		u64 imm64;
1196 
1197 		imm64 = (u64)insn1.imm << 32 | (u32)imm;
1198 		if (bpf_pseudo_func(insn))
1199 			emit_addr_mov_i64(dst, imm64, ctx);
1200 		else
1201 			emit_a64_mov_i64(dst, imm64, ctx);
1202 
1203 		return 1;
1204 	}
1205 
1206 	/* LDX: dst = (u64)*(unsigned size *)(src + off) */
1207 	case BPF_LDX | BPF_MEM | BPF_W:
1208 	case BPF_LDX | BPF_MEM | BPF_H:
1209 	case BPF_LDX | BPF_MEM | BPF_B:
1210 	case BPF_LDX | BPF_MEM | BPF_DW:
1211 	case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
1212 	case BPF_LDX | BPF_PROBE_MEM | BPF_W:
1213 	case BPF_LDX | BPF_PROBE_MEM | BPF_H:
1214 	case BPF_LDX | BPF_PROBE_MEM | BPF_B:
1215 	/* LDXS: dst_reg = (s64)*(signed size *)(src_reg + off) */
1216 	case BPF_LDX | BPF_MEMSX | BPF_B:
1217 	case BPF_LDX | BPF_MEMSX | BPF_H:
1218 	case BPF_LDX | BPF_MEMSX | BPF_W:
1219 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
1220 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
1221 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
1222 		if (ctx->fpb_offset > 0 && src == fp) {
1223 			src_adj = fpb;
1224 			off_adj = off + ctx->fpb_offset;
1225 		} else {
1226 			src_adj = src;
1227 			off_adj = off;
1228 		}
1229 		sign_extend = (BPF_MODE(insn->code) == BPF_MEMSX ||
1230 				BPF_MODE(insn->code) == BPF_PROBE_MEMSX);
1231 		switch (BPF_SIZE(code)) {
1232 		case BPF_W:
1233 			if (is_lsi_offset(off_adj, 2)) {
1234 				if (sign_extend)
1235 					emit(A64_LDRSWI(dst, src_adj, off_adj), ctx);
1236 				else
1237 					emit(A64_LDR32I(dst, src_adj, off_adj), ctx);
1238 			} else {
1239 				emit_a64_mov_i(1, tmp, off, ctx);
1240 				if (sign_extend)
1241 					emit(A64_LDRSW(dst, src, tmp), ctx);
1242 				else
1243 					emit(A64_LDR32(dst, src, tmp), ctx);
1244 			}
1245 			break;
1246 		case BPF_H:
1247 			if (is_lsi_offset(off_adj, 1)) {
1248 				if (sign_extend)
1249 					emit(A64_LDRSHI(dst, src_adj, off_adj), ctx);
1250 				else
1251 					emit(A64_LDRHI(dst, src_adj, off_adj), ctx);
1252 			} else {
1253 				emit_a64_mov_i(1, tmp, off, ctx);
1254 				if (sign_extend)
1255 					emit(A64_LDRSH(dst, src, tmp), ctx);
1256 				else
1257 					emit(A64_LDRH(dst, src, tmp), ctx);
1258 			}
1259 			break;
1260 		case BPF_B:
1261 			if (is_lsi_offset(off_adj, 0)) {
1262 				if (sign_extend)
1263 					emit(A64_LDRSBI(dst, src_adj, off_adj), ctx);
1264 				else
1265 					emit(A64_LDRBI(dst, src_adj, off_adj), ctx);
1266 			} else {
1267 				emit_a64_mov_i(1, tmp, off, ctx);
1268 				if (sign_extend)
1269 					emit(A64_LDRSB(dst, src, tmp), ctx);
1270 				else
1271 					emit(A64_LDRB(dst, src, tmp), ctx);
1272 			}
1273 			break;
1274 		case BPF_DW:
1275 			if (is_lsi_offset(off_adj, 3)) {
1276 				emit(A64_LDR64I(dst, src_adj, off_adj), ctx);
1277 			} else {
1278 				emit_a64_mov_i(1, tmp, off, ctx);
1279 				emit(A64_LDR64(dst, src, tmp), ctx);
1280 			}
1281 			break;
1282 		}
1283 
1284 		ret = add_exception_handler(insn, ctx, dst);
1285 		if (ret)
1286 			return ret;
1287 		break;
1288 
1289 	/* speculation barrier */
1290 	case BPF_ST | BPF_NOSPEC:
1291 		/*
1292 		 * Nothing required here.
1293 		 *
1294 		 * In case of arm64, we rely on the firmware mitigation of
1295 		 * Speculative Store Bypass as controlled via the ssbd kernel
1296 		 * parameter. Whenever the mitigation is enabled, it works
1297 		 * for all of the kernel code with no need to provide any
1298 		 * additional instructions.
1299 		 */
1300 		break;
1301 
1302 	/* ST: *(size *)(dst + off) = imm */
1303 	case BPF_ST | BPF_MEM | BPF_W:
1304 	case BPF_ST | BPF_MEM | BPF_H:
1305 	case BPF_ST | BPF_MEM | BPF_B:
1306 	case BPF_ST | BPF_MEM | BPF_DW:
1307 		if (ctx->fpb_offset > 0 && dst == fp) {
1308 			dst_adj = fpb;
1309 			off_adj = off + ctx->fpb_offset;
1310 		} else {
1311 			dst_adj = dst;
1312 			off_adj = off;
1313 		}
1314 		/* Load imm to a register then store it */
1315 		emit_a64_mov_i(1, tmp, imm, ctx);
1316 		switch (BPF_SIZE(code)) {
1317 		case BPF_W:
1318 			if (is_lsi_offset(off_adj, 2)) {
1319 				emit(A64_STR32I(tmp, dst_adj, off_adj), ctx);
1320 			} else {
1321 				emit_a64_mov_i(1, tmp2, off, ctx);
1322 				emit(A64_STR32(tmp, dst, tmp2), ctx);
1323 			}
1324 			break;
1325 		case BPF_H:
1326 			if (is_lsi_offset(off_adj, 1)) {
1327 				emit(A64_STRHI(tmp, dst_adj, off_adj), ctx);
1328 			} else {
1329 				emit_a64_mov_i(1, tmp2, off, ctx);
1330 				emit(A64_STRH(tmp, dst, tmp2), ctx);
1331 			}
1332 			break;
1333 		case BPF_B:
1334 			if (is_lsi_offset(off_adj, 0)) {
1335 				emit(A64_STRBI(tmp, dst_adj, off_adj), ctx);
1336 			} else {
1337 				emit_a64_mov_i(1, tmp2, off, ctx);
1338 				emit(A64_STRB(tmp, dst, tmp2), ctx);
1339 			}
1340 			break;
1341 		case BPF_DW:
1342 			if (is_lsi_offset(off_adj, 3)) {
1343 				emit(A64_STR64I(tmp, dst_adj, off_adj), ctx);
1344 			} else {
1345 				emit_a64_mov_i(1, tmp2, off, ctx);
1346 				emit(A64_STR64(tmp, dst, tmp2), ctx);
1347 			}
1348 			break;
1349 		}
1350 		break;
1351 
1352 	/* STX: *(size *)(dst + off) = src */
1353 	case BPF_STX | BPF_MEM | BPF_W:
1354 	case BPF_STX | BPF_MEM | BPF_H:
1355 	case BPF_STX | BPF_MEM | BPF_B:
1356 	case BPF_STX | BPF_MEM | BPF_DW:
1357 		if (ctx->fpb_offset > 0 && dst == fp) {
1358 			dst_adj = fpb;
1359 			off_adj = off + ctx->fpb_offset;
1360 		} else {
1361 			dst_adj = dst;
1362 			off_adj = off;
1363 		}
1364 		switch (BPF_SIZE(code)) {
1365 		case BPF_W:
1366 			if (is_lsi_offset(off_adj, 2)) {
1367 				emit(A64_STR32I(src, dst_adj, off_adj), ctx);
1368 			} else {
1369 				emit_a64_mov_i(1, tmp, off, ctx);
1370 				emit(A64_STR32(src, dst, tmp), ctx);
1371 			}
1372 			break;
1373 		case BPF_H:
1374 			if (is_lsi_offset(off_adj, 1)) {
1375 				emit(A64_STRHI(src, dst_adj, off_adj), ctx);
1376 			} else {
1377 				emit_a64_mov_i(1, tmp, off, ctx);
1378 				emit(A64_STRH(src, dst, tmp), ctx);
1379 			}
1380 			break;
1381 		case BPF_B:
1382 			if (is_lsi_offset(off_adj, 0)) {
1383 				emit(A64_STRBI(src, dst_adj, off_adj), ctx);
1384 			} else {
1385 				emit_a64_mov_i(1, tmp, off, ctx);
1386 				emit(A64_STRB(src, dst, tmp), ctx);
1387 			}
1388 			break;
1389 		case BPF_DW:
1390 			if (is_lsi_offset(off_adj, 3)) {
1391 				emit(A64_STR64I(src, dst_adj, off_adj), ctx);
1392 			} else {
1393 				emit_a64_mov_i(1, tmp, off, ctx);
1394 				emit(A64_STR64(src, dst, tmp), ctx);
1395 			}
1396 			break;
1397 		}
1398 		break;
1399 
1400 	case BPF_STX | BPF_ATOMIC | BPF_W:
1401 	case BPF_STX | BPF_ATOMIC | BPF_DW:
1402 		if (cpus_have_cap(ARM64_HAS_LSE_ATOMICS))
1403 			ret = emit_lse_atomic(insn, ctx);
1404 		else
1405 			ret = emit_ll_sc_atomic(insn, ctx);
1406 		if (ret)
1407 			return ret;
1408 		break;
1409 
1410 	default:
1411 		pr_err_once("unknown opcode %02x\n", code);
1412 		return -EINVAL;
1413 	}
1414 
1415 	return 0;
1416 }
1417 
1418 /*
1419  * Return 0 if FP may change at runtime, otherwise find the minimum negative
1420  * offset to FP, converts it to positive number, and align down to 8 bytes.
1421  */
find_fpb_offset(struct bpf_prog * prog)1422 static int find_fpb_offset(struct bpf_prog *prog)
1423 {
1424 	int i;
1425 	int offset = 0;
1426 
1427 	for (i = 0; i < prog->len; i++) {
1428 		const struct bpf_insn *insn = &prog->insnsi[i];
1429 		const u8 class = BPF_CLASS(insn->code);
1430 		const u8 mode = BPF_MODE(insn->code);
1431 		const u8 src = insn->src_reg;
1432 		const u8 dst = insn->dst_reg;
1433 		const s32 imm = insn->imm;
1434 		const s16 off = insn->off;
1435 
1436 		switch (class) {
1437 		case BPF_STX:
1438 		case BPF_ST:
1439 			/* fp holds atomic operation result */
1440 			if (class == BPF_STX && mode == BPF_ATOMIC &&
1441 			    ((imm == BPF_XCHG ||
1442 			      imm == (BPF_FETCH | BPF_ADD) ||
1443 			      imm == (BPF_FETCH | BPF_AND) ||
1444 			      imm == (BPF_FETCH | BPF_XOR) ||
1445 			      imm == (BPF_FETCH | BPF_OR)) &&
1446 			     src == BPF_REG_FP))
1447 				return 0;
1448 
1449 			if (mode == BPF_MEM && dst == BPF_REG_FP &&
1450 			    off < offset)
1451 				offset = insn->off;
1452 			break;
1453 
1454 		case BPF_JMP32:
1455 		case BPF_JMP:
1456 			break;
1457 
1458 		case BPF_LDX:
1459 		case BPF_LD:
1460 			/* fp holds load result */
1461 			if (dst == BPF_REG_FP)
1462 				return 0;
1463 
1464 			if (class == BPF_LDX && mode == BPF_MEM &&
1465 			    src == BPF_REG_FP && off < offset)
1466 				offset = off;
1467 			break;
1468 
1469 		case BPF_ALU:
1470 		case BPF_ALU64:
1471 		default:
1472 			/* fp holds ALU result */
1473 			if (dst == BPF_REG_FP)
1474 				return 0;
1475 		}
1476 	}
1477 
1478 	if (offset < 0) {
1479 		/*
1480 		 * safely be converted to a positive 'int', since insn->off
1481 		 * is 's16'
1482 		 */
1483 		offset = -offset;
1484 		/* align down to 8 bytes */
1485 		offset = ALIGN_DOWN(offset, 8);
1486 	}
1487 
1488 	return offset;
1489 }
1490 
build_body(struct jit_ctx * ctx,bool extra_pass)1491 static int build_body(struct jit_ctx *ctx, bool extra_pass)
1492 {
1493 	const struct bpf_prog *prog = ctx->prog;
1494 	int i;
1495 
1496 	/*
1497 	 * - offset[0] offset of the end of prologue,
1498 	 *   start of the 1st instruction.
1499 	 * - offset[1] - offset of the end of 1st instruction,
1500 	 *   start of the 2nd instruction
1501 	 * [....]
1502 	 * - offset[3] - offset of the end of 3rd instruction,
1503 	 *   start of 4th instruction
1504 	 */
1505 	for (i = 0; i < prog->len; i++) {
1506 		const struct bpf_insn *insn = &prog->insnsi[i];
1507 		int ret;
1508 
1509 		if (ctx->image == NULL)
1510 			ctx->offset[i] = ctx->idx;
1511 		ret = build_insn(insn, ctx, extra_pass);
1512 		if (ret > 0) {
1513 			i++;
1514 			if (ctx->image == NULL)
1515 				ctx->offset[i] = ctx->idx;
1516 			continue;
1517 		}
1518 		if (ret)
1519 			return ret;
1520 	}
1521 	/*
1522 	 * offset is allocated with prog->len + 1 so fill in
1523 	 * the last element with the offset after the last
1524 	 * instruction (end of program)
1525 	 */
1526 	if (ctx->image == NULL)
1527 		ctx->offset[i] = ctx->idx;
1528 
1529 	return 0;
1530 }
1531 
validate_code(struct jit_ctx * ctx)1532 static int validate_code(struct jit_ctx *ctx)
1533 {
1534 	int i;
1535 
1536 	for (i = 0; i < ctx->idx; i++) {
1537 		u32 a64_insn = le32_to_cpu(ctx->image[i]);
1538 
1539 		if (a64_insn == AARCH64_BREAK_FAULT)
1540 			return -1;
1541 	}
1542 	return 0;
1543 }
1544 
validate_ctx(struct jit_ctx * ctx)1545 static int validate_ctx(struct jit_ctx *ctx)
1546 {
1547 	if (validate_code(ctx))
1548 		return -1;
1549 
1550 	if (WARN_ON_ONCE(ctx->exentry_idx != ctx->prog->aux->num_exentries))
1551 		return -1;
1552 
1553 	return 0;
1554 }
1555 
bpf_flush_icache(void * start,void * end)1556 static inline void bpf_flush_icache(void *start, void *end)
1557 {
1558 	flush_icache_range((unsigned long)start, (unsigned long)end);
1559 }
1560 
1561 struct arm64_jit_data {
1562 	struct bpf_binary_header *header;
1563 	u8 *image;
1564 	struct jit_ctx ctx;
1565 };
1566 
bpf_int_jit_compile(struct bpf_prog * prog)1567 struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
1568 {
1569 	int image_size, prog_size, extable_size, extable_align, extable_offset;
1570 	struct bpf_prog *tmp, *orig_prog = prog;
1571 	struct bpf_binary_header *header;
1572 	struct arm64_jit_data *jit_data;
1573 	bool was_classic = bpf_prog_was_classic(prog);
1574 	bool tmp_blinded = false;
1575 	bool extra_pass = false;
1576 	struct jit_ctx ctx;
1577 	u8 *image_ptr;
1578 
1579 	if (!prog->jit_requested)
1580 		return orig_prog;
1581 
1582 	tmp = bpf_jit_blind_constants(prog);
1583 	/* If blinding was requested and we failed during blinding,
1584 	 * we must fall back to the interpreter.
1585 	 */
1586 	if (IS_ERR(tmp))
1587 		return orig_prog;
1588 	if (tmp != prog) {
1589 		tmp_blinded = true;
1590 		prog = tmp;
1591 	}
1592 
1593 	jit_data = prog->aux->jit_data;
1594 	if (!jit_data) {
1595 		jit_data = kzalloc(sizeof(*jit_data), GFP_KERNEL);
1596 		if (!jit_data) {
1597 			prog = orig_prog;
1598 			goto out;
1599 		}
1600 		prog->aux->jit_data = jit_data;
1601 	}
1602 	if (jit_data->ctx.offset) {
1603 		ctx = jit_data->ctx;
1604 		image_ptr = jit_data->image;
1605 		header = jit_data->header;
1606 		extra_pass = true;
1607 		prog_size = sizeof(u32) * ctx.idx;
1608 		goto skip_init_ctx;
1609 	}
1610 	memset(&ctx, 0, sizeof(ctx));
1611 	ctx.prog = prog;
1612 
1613 	ctx.offset = kvcalloc(prog->len + 1, sizeof(int), GFP_KERNEL);
1614 	if (ctx.offset == NULL) {
1615 		prog = orig_prog;
1616 		goto out_off;
1617 	}
1618 
1619 	ctx.fpb_offset = find_fpb_offset(prog);
1620 
1621 	/*
1622 	 * 1. Initial fake pass to compute ctx->idx and ctx->offset.
1623 	 *
1624 	 * BPF line info needs ctx->offset[i] to be the offset of
1625 	 * instruction[i] in jited image, so build prologue first.
1626 	 */
1627 	if (build_prologue(&ctx, was_classic)) {
1628 		prog = orig_prog;
1629 		goto out_off;
1630 	}
1631 
1632 	if (build_body(&ctx, extra_pass)) {
1633 		prog = orig_prog;
1634 		goto out_off;
1635 	}
1636 
1637 	ctx.epilogue_offset = ctx.idx;
1638 	build_epilogue(&ctx, was_classic);
1639 	build_plt(&ctx);
1640 
1641 	extable_align = __alignof__(struct exception_table_entry);
1642 	extable_size = prog->aux->num_exentries *
1643 		sizeof(struct exception_table_entry);
1644 
1645 	/* Now we know the actual image size. */
1646 	prog_size = sizeof(u32) * ctx.idx;
1647 	/* also allocate space for plt target */
1648 	extable_offset = round_up(prog_size + PLT_TARGET_SIZE, extable_align);
1649 	image_size = extable_offset + extable_size;
1650 	header = bpf_jit_binary_alloc(image_size, &image_ptr,
1651 				      sizeof(u32), jit_fill_hole);
1652 	if (header == NULL) {
1653 		prog = orig_prog;
1654 		goto out_off;
1655 	}
1656 
1657 	/* 2. Now, the actual pass. */
1658 
1659 	ctx.image = (__le32 *)image_ptr;
1660 	if (extable_size)
1661 		prog->aux->extable = (void *)image_ptr + extable_offset;
1662 skip_init_ctx:
1663 	ctx.idx = 0;
1664 	ctx.exentry_idx = 0;
1665 
1666 	build_prologue(&ctx, was_classic);
1667 
1668 	if (build_body(&ctx, extra_pass)) {
1669 		bpf_jit_binary_free(header);
1670 		prog = orig_prog;
1671 		goto out_off;
1672 	}
1673 
1674 	build_epilogue(&ctx, was_classic);
1675 	build_plt(&ctx);
1676 
1677 	/* 3. Extra pass to validate JITed code. */
1678 	if (validate_ctx(&ctx)) {
1679 		bpf_jit_binary_free(header);
1680 		prog = orig_prog;
1681 		goto out_off;
1682 	}
1683 
1684 	/* And we're done. */
1685 	if (bpf_jit_enable > 1)
1686 		bpf_jit_dump(prog->len, prog_size, 2, ctx.image);
1687 
1688 	bpf_flush_icache(header, ctx.image + ctx.idx);
1689 
1690 	if (!prog->is_func || extra_pass) {
1691 		if (extra_pass && ctx.idx != jit_data->ctx.idx) {
1692 			pr_err_once("multi-func JIT bug %d != %d\n",
1693 				    ctx.idx, jit_data->ctx.idx);
1694 			bpf_jit_binary_free(header);
1695 			prog->bpf_func = NULL;
1696 			prog->jited = 0;
1697 			prog->jited_len = 0;
1698 			goto out_off;
1699 		}
1700 		bpf_jit_binary_lock_ro(header);
1701 	} else {
1702 		jit_data->ctx = ctx;
1703 		jit_data->image = image_ptr;
1704 		jit_data->header = header;
1705 	}
1706 	prog->bpf_func = (void *)ctx.image;
1707 	prog->jited = 1;
1708 	prog->jited_len = prog_size;
1709 
1710 	if (!prog->is_func || extra_pass) {
1711 		int i;
1712 
1713 		/* offset[prog->len] is the size of program */
1714 		for (i = 0; i <= prog->len; i++)
1715 			ctx.offset[i] *= AARCH64_INSN_SIZE;
1716 		bpf_prog_fill_jited_linfo(prog, ctx.offset + 1);
1717 out_off:
1718 		kvfree(ctx.offset);
1719 		kfree(jit_data);
1720 		prog->aux->jit_data = NULL;
1721 	}
1722 out:
1723 	if (tmp_blinded)
1724 		bpf_jit_prog_release_other(prog, prog == orig_prog ?
1725 					   tmp : orig_prog);
1726 	return prog;
1727 }
1728 
bpf_jit_supports_kfunc_call(void)1729 bool bpf_jit_supports_kfunc_call(void)
1730 {
1731 	return true;
1732 }
1733 
bpf_jit_alloc_exec_limit(void)1734 u64 bpf_jit_alloc_exec_limit(void)
1735 {
1736 	return VMALLOC_END - VMALLOC_START;
1737 }
1738 
bpf_jit_alloc_exec(unsigned long size)1739 void *bpf_jit_alloc_exec(unsigned long size)
1740 {
1741 	/* Memory is intended to be executable, reset the pointer tag. */
1742 	return kasan_reset_tag(vmalloc(size));
1743 }
1744 
bpf_jit_free_exec(void * addr)1745 void bpf_jit_free_exec(void *addr)
1746 {
1747 	return vfree(addr);
1748 }
1749 
1750 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
bpf_jit_supports_subprog_tailcalls(void)1751 bool bpf_jit_supports_subprog_tailcalls(void)
1752 {
1753 	return true;
1754 }
1755 
invoke_bpf_prog(struct jit_ctx * ctx,struct bpf_tramp_link * l,int args_off,int retval_off,int run_ctx_off,bool save_ret)1756 static void invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_link *l,
1757 			    int args_off, int retval_off, int run_ctx_off,
1758 			    bool save_ret)
1759 {
1760 	__le32 *branch;
1761 	u64 enter_prog;
1762 	u64 exit_prog;
1763 	struct bpf_prog *p = l->link.prog;
1764 	int cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
1765 
1766 	enter_prog = (u64)bpf_trampoline_enter(p);
1767 	exit_prog = (u64)bpf_trampoline_exit(p);
1768 
1769 	if (l->cookie == 0) {
1770 		/* if cookie is zero, one instruction is enough to store it */
1771 		emit(A64_STR64I(A64_ZR, A64_SP, run_ctx_off + cookie_off), ctx);
1772 	} else {
1773 		emit_a64_mov_i64(A64_R(10), l->cookie, ctx);
1774 		emit(A64_STR64I(A64_R(10), A64_SP, run_ctx_off + cookie_off),
1775 		     ctx);
1776 	}
1777 
1778 	/* save p to callee saved register x19 to avoid loading p with mov_i64
1779 	 * each time.
1780 	 */
1781 	emit_addr_mov_i64(A64_R(19), (const u64)p, ctx);
1782 
1783 	/* arg1: prog */
1784 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
1785 	/* arg2: &run_ctx */
1786 	emit(A64_ADD_I(1, A64_R(1), A64_SP, run_ctx_off), ctx);
1787 
1788 	emit_call(enter_prog, ctx);
1789 
1790 	/* save return value to callee saved register x20 */
1791 	emit(A64_MOV(1, A64_R(20), A64_R(0)), ctx);
1792 
1793 	/* if (__bpf_prog_enter(prog) == 0)
1794 	 *         goto skip_exec_of_prog;
1795 	 */
1796 	branch = ctx->image + ctx->idx;
1797 	emit(A64_NOP, ctx);
1798 
1799 	emit(A64_ADD_I(1, A64_R(0), A64_SP, args_off), ctx);
1800 	if (!p->jited)
1801 		emit_addr_mov_i64(A64_R(1), (const u64)p->insnsi, ctx);
1802 
1803 	emit_call((const u64)p->bpf_func, ctx);
1804 
1805 	if (save_ret)
1806 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
1807 
1808 	if (ctx->image) {
1809 		int offset = &ctx->image[ctx->idx] - branch;
1810 		*branch = cpu_to_le32(A64_CBZ(1, A64_R(0), offset));
1811 	}
1812 
1813 	/* arg1: prog */
1814 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
1815 	/* arg2: start time */
1816 	emit(A64_MOV(1, A64_R(1), A64_R(20)), ctx);
1817 	/* arg3: &run_ctx */
1818 	emit(A64_ADD_I(1, A64_R(2), A64_SP, run_ctx_off), ctx);
1819 
1820 	emit_call(exit_prog, ctx);
1821 }
1822 
invoke_bpf_mod_ret(struct jit_ctx * ctx,struct bpf_tramp_links * tl,int args_off,int retval_off,int run_ctx_off,__le32 ** branches)1823 static void invoke_bpf_mod_ret(struct jit_ctx *ctx, struct bpf_tramp_links *tl,
1824 			       int args_off, int retval_off, int run_ctx_off,
1825 			       __le32 **branches)
1826 {
1827 	int i;
1828 
1829 	/* The first fmod_ret program will receive a garbage return value.
1830 	 * Set this to 0 to avoid confusing the program.
1831 	 */
1832 	emit(A64_STR64I(A64_ZR, A64_SP, retval_off), ctx);
1833 	for (i = 0; i < tl->nr_links; i++) {
1834 		invoke_bpf_prog(ctx, tl->links[i], args_off, retval_off,
1835 				run_ctx_off, true);
1836 		/* if (*(u64 *)(sp + retval_off) !=  0)
1837 		 *	goto do_fexit;
1838 		 */
1839 		emit(A64_LDR64I(A64_R(10), A64_SP, retval_off), ctx);
1840 		/* Save the location of branch, and generate a nop.
1841 		 * This nop will be replaced with a cbnz later.
1842 		 */
1843 		branches[i] = ctx->image + ctx->idx;
1844 		emit(A64_NOP, ctx);
1845 	}
1846 }
1847 
save_args(struct jit_ctx * ctx,int args_off,int nregs)1848 static void save_args(struct jit_ctx *ctx, int args_off, int nregs)
1849 {
1850 	int i;
1851 
1852 	for (i = 0; i < nregs; i++) {
1853 		emit(A64_STR64I(i, A64_SP, args_off), ctx);
1854 		args_off += 8;
1855 	}
1856 }
1857 
restore_args(struct jit_ctx * ctx,int args_off,int nregs)1858 static void restore_args(struct jit_ctx *ctx, int args_off, int nregs)
1859 {
1860 	int i;
1861 
1862 	for (i = 0; i < nregs; i++) {
1863 		emit(A64_LDR64I(i, A64_SP, args_off), ctx);
1864 		args_off += 8;
1865 	}
1866 }
1867 
is_struct_ops_tramp(const struct bpf_tramp_links * fentry_links)1868 static bool is_struct_ops_tramp(const struct bpf_tramp_links *fentry_links)
1869 {
1870 	return fentry_links->nr_links == 1 &&
1871 		fentry_links->links[0]->link.type == BPF_LINK_TYPE_STRUCT_OPS;
1872 }
1873 
1874 /* Based on the x86's implementation of arch_prepare_bpf_trampoline().
1875  *
1876  * bpf prog and function entry before bpf trampoline hooked:
1877  *   mov x9, lr
1878  *   nop
1879  *
1880  * bpf prog and function entry after bpf trampoline hooked:
1881  *   mov x9, lr
1882  *   bl  <bpf_trampoline or plt>
1883  *
1884  */
prepare_trampoline(struct jit_ctx * ctx,struct bpf_tramp_image * im,struct bpf_tramp_links * tlinks,void * orig_call,int nregs,u32 flags)1885 static int prepare_trampoline(struct jit_ctx *ctx, struct bpf_tramp_image *im,
1886 			      struct bpf_tramp_links *tlinks, void *orig_call,
1887 			      int nregs, u32 flags)
1888 {
1889 	int i;
1890 	int stack_size;
1891 	int retaddr_off;
1892 	int regs_off;
1893 	int retval_off;
1894 	int args_off;
1895 	int nregs_off;
1896 	int ip_off;
1897 	int run_ctx_off;
1898 	struct bpf_tramp_links *fentry = &tlinks[BPF_TRAMP_FENTRY];
1899 	struct bpf_tramp_links *fexit = &tlinks[BPF_TRAMP_FEXIT];
1900 	struct bpf_tramp_links *fmod_ret = &tlinks[BPF_TRAMP_MODIFY_RETURN];
1901 	bool save_ret;
1902 	__le32 **branches = NULL;
1903 	bool is_struct_ops = is_struct_ops_tramp(fentry);
1904 
1905 	/* trampoline stack layout:
1906 	 *                  [ parent ip         ]
1907 	 *                  [ FP                ]
1908 	 * SP + retaddr_off [ self ip           ]
1909 	 *                  [ FP                ]
1910 	 *
1911 	 *                  [ padding           ] align SP to multiples of 16
1912 	 *
1913 	 *                  [ x20               ] callee saved reg x20
1914 	 * SP + regs_off    [ x19               ] callee saved reg x19
1915 	 *
1916 	 * SP + retval_off  [ return value      ] BPF_TRAMP_F_CALL_ORIG or
1917 	 *                                        BPF_TRAMP_F_RET_FENTRY_RET
1918 	 *
1919 	 *                  [ arg reg N         ]
1920 	 *                  [ ...               ]
1921 	 * SP + args_off    [ arg reg 1         ]
1922 	 *
1923 	 * SP + nregs_off   [ arg regs count    ]
1924 	 *
1925 	 * SP + ip_off      [ traced function   ] BPF_TRAMP_F_IP_ARG flag
1926 	 *
1927 	 * SP + run_ctx_off [ bpf_tramp_run_ctx ]
1928 	 */
1929 
1930 	stack_size = 0;
1931 	run_ctx_off = stack_size;
1932 	/* room for bpf_tramp_run_ctx */
1933 	stack_size += round_up(sizeof(struct bpf_tramp_run_ctx), 8);
1934 
1935 	ip_off = stack_size;
1936 	/* room for IP address argument */
1937 	if (flags & BPF_TRAMP_F_IP_ARG)
1938 		stack_size += 8;
1939 
1940 	nregs_off = stack_size;
1941 	/* room for args count */
1942 	stack_size += 8;
1943 
1944 	args_off = stack_size;
1945 	/* room for args */
1946 	stack_size += nregs * 8;
1947 
1948 	/* room for return value */
1949 	retval_off = stack_size;
1950 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
1951 	if (save_ret)
1952 		stack_size += 8;
1953 
1954 	/* room for callee saved registers, currently x19 and x20 are used */
1955 	regs_off = stack_size;
1956 	stack_size += 16;
1957 
1958 	/* round up to multiples of 16 to avoid SPAlignmentFault */
1959 	stack_size = round_up(stack_size, 16);
1960 
1961 	/* return address locates above FP */
1962 	retaddr_off = stack_size + 8;
1963 
1964 	/* bpf trampoline may be invoked by 3 instruction types:
1965 	 * 1. bl, attached to bpf prog or kernel function via short jump
1966 	 * 2. br, attached to bpf prog or kernel function via long jump
1967 	 * 3. blr, working as a function pointer, used by struct_ops.
1968 	 * So BTI_JC should used here to support both br and blr.
1969 	 */
1970 	emit_bti(A64_BTI_JC, ctx);
1971 
1972 	/* x9 is not set for struct_ops */
1973 	if (!is_struct_ops) {
1974 		/* frame for parent function */
1975 		emit(A64_PUSH(A64_FP, A64_R(9), A64_SP), ctx);
1976 		emit(A64_MOV(1, A64_FP, A64_SP), ctx);
1977 	}
1978 
1979 	/* frame for patched function for tracing, or caller for struct_ops */
1980 	emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
1981 	emit(A64_MOV(1, A64_FP, A64_SP), ctx);
1982 
1983 	/* allocate stack space */
1984 	emit(A64_SUB_I(1, A64_SP, A64_SP, stack_size), ctx);
1985 
1986 	if (flags & BPF_TRAMP_F_IP_ARG) {
1987 		/* save ip address of the traced function */
1988 		emit_addr_mov_i64(A64_R(10), (const u64)orig_call, ctx);
1989 		emit(A64_STR64I(A64_R(10), A64_SP, ip_off), ctx);
1990 	}
1991 
1992 	/* save arg regs count*/
1993 	emit(A64_MOVZ(1, A64_R(10), nregs, 0), ctx);
1994 	emit(A64_STR64I(A64_R(10), A64_SP, nregs_off), ctx);
1995 
1996 	/* save arg regs */
1997 	save_args(ctx, args_off, nregs);
1998 
1999 	/* save callee saved registers */
2000 	emit(A64_STR64I(A64_R(19), A64_SP, regs_off), ctx);
2001 	emit(A64_STR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
2002 
2003 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2004 		/* for the first pass, assume the worst case */
2005 		if (!ctx->image)
2006 			ctx->idx += 4;
2007 		else
2008 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
2009 		emit_call((const u64)__bpf_tramp_enter, ctx);
2010 	}
2011 
2012 	for (i = 0; i < fentry->nr_links; i++)
2013 		invoke_bpf_prog(ctx, fentry->links[i], args_off,
2014 				retval_off, run_ctx_off,
2015 				flags & BPF_TRAMP_F_RET_FENTRY_RET);
2016 
2017 	if (fmod_ret->nr_links) {
2018 		branches = kcalloc(fmod_ret->nr_links, sizeof(__le32 *),
2019 				   GFP_KERNEL);
2020 		if (!branches)
2021 			return -ENOMEM;
2022 
2023 		invoke_bpf_mod_ret(ctx, fmod_ret, args_off, retval_off,
2024 				   run_ctx_off, branches);
2025 	}
2026 
2027 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2028 		restore_args(ctx, args_off, nregs);
2029 		/* call original func */
2030 		emit(A64_LDR64I(A64_R(10), A64_SP, retaddr_off), ctx);
2031 		emit(A64_ADR(A64_LR, AARCH64_INSN_SIZE * 2), ctx);
2032 		emit(A64_RET(A64_R(10)), ctx);
2033 		/* store return value */
2034 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
2035 		/* reserve a nop for bpf_tramp_image_put */
2036 		im->ip_after_call = ctx->image + ctx->idx;
2037 		emit(A64_NOP, ctx);
2038 	}
2039 
2040 	/* update the branches saved in invoke_bpf_mod_ret with cbnz */
2041 	for (i = 0; i < fmod_ret->nr_links && ctx->image != NULL; i++) {
2042 		int offset = &ctx->image[ctx->idx] - branches[i];
2043 		*branches[i] = cpu_to_le32(A64_CBNZ(1, A64_R(10), offset));
2044 	}
2045 
2046 	for (i = 0; i < fexit->nr_links; i++)
2047 		invoke_bpf_prog(ctx, fexit->links[i], args_off, retval_off,
2048 				run_ctx_off, false);
2049 
2050 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2051 		im->ip_epilogue = ctx->image + ctx->idx;
2052 		/* for the first pass, assume the worst case */
2053 		if (!ctx->image)
2054 			ctx->idx += 4;
2055 		else
2056 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
2057 		emit_call((const u64)__bpf_tramp_exit, ctx);
2058 	}
2059 
2060 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
2061 		restore_args(ctx, args_off, nregs);
2062 
2063 	/* restore callee saved register x19 and x20 */
2064 	emit(A64_LDR64I(A64_R(19), A64_SP, regs_off), ctx);
2065 	emit(A64_LDR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
2066 
2067 	if (save_ret)
2068 		emit(A64_LDR64I(A64_R(0), A64_SP, retval_off), ctx);
2069 
2070 	/* reset SP  */
2071 	emit(A64_MOV(1, A64_SP, A64_FP), ctx);
2072 
2073 	if (is_struct_ops) {
2074 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
2075 		emit(A64_RET(A64_LR), ctx);
2076 	} else {
2077 		/* pop frames */
2078 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
2079 		emit(A64_POP(A64_FP, A64_R(9), A64_SP), ctx);
2080 
2081 		if (flags & BPF_TRAMP_F_SKIP_FRAME) {
2082 			/* skip patched function, return to parent */
2083 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
2084 			emit(A64_RET(A64_R(9)), ctx);
2085 		} else {
2086 			/* return to patched function */
2087 			emit(A64_MOV(1, A64_R(10), A64_LR), ctx);
2088 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
2089 			emit(A64_RET(A64_R(10)), ctx);
2090 		}
2091 	}
2092 
2093 	if (ctx->image)
2094 		bpf_flush_icache(ctx->image, ctx->image + ctx->idx);
2095 
2096 	kfree(branches);
2097 
2098 	return ctx->idx;
2099 }
2100 
arch_prepare_bpf_trampoline(struct bpf_tramp_image * im,void * image,void * image_end,const struct btf_func_model * m,u32 flags,struct bpf_tramp_links * tlinks,void * orig_call)2101 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image,
2102 				void *image_end, const struct btf_func_model *m,
2103 				u32 flags, struct bpf_tramp_links *tlinks,
2104 				void *orig_call)
2105 {
2106 	int i, ret;
2107 	int nregs = m->nr_args;
2108 	int max_insns = ((long)image_end - (long)image) / AARCH64_INSN_SIZE;
2109 	struct jit_ctx ctx = {
2110 		.image = NULL,
2111 		.idx = 0,
2112 	};
2113 
2114 	/* extra registers needed for struct argument */
2115 	for (i = 0; i < MAX_BPF_FUNC_ARGS; i++) {
2116 		/* The arg_size is at most 16 bytes, enforced by the verifier. */
2117 		if (m->arg_flags[i] & BTF_FMODEL_STRUCT_ARG)
2118 			nregs += (m->arg_size[i] + 7) / 8 - 1;
2119 	}
2120 
2121 	/* the first 8 registers are used for arguments */
2122 	if (nregs > 8)
2123 		return -ENOTSUPP;
2124 
2125 	ret = prepare_trampoline(&ctx, im, tlinks, orig_call, nregs, flags);
2126 	if (ret < 0)
2127 		return ret;
2128 
2129 	if (ret > max_insns)
2130 		return -EFBIG;
2131 
2132 	ctx.image = image;
2133 	ctx.idx = 0;
2134 
2135 	jit_fill_hole(image, (unsigned int)(image_end - image));
2136 	ret = prepare_trampoline(&ctx, im, tlinks, orig_call, nregs, flags);
2137 
2138 	if (ret > 0 && validate_code(&ctx) < 0)
2139 		ret = -EINVAL;
2140 
2141 	if (ret > 0)
2142 		ret *= AARCH64_INSN_SIZE;
2143 
2144 	return ret;
2145 }
2146 
is_long_jump(void * ip,void * target)2147 static bool is_long_jump(void *ip, void *target)
2148 {
2149 	long offset;
2150 
2151 	/* NULL target means this is a NOP */
2152 	if (!target)
2153 		return false;
2154 
2155 	offset = (long)target - (long)ip;
2156 	return offset < -SZ_128M || offset >= SZ_128M;
2157 }
2158 
gen_branch_or_nop(enum aarch64_insn_branch_type type,void * ip,void * addr,void * plt,u32 * insn)2159 static int gen_branch_or_nop(enum aarch64_insn_branch_type type, void *ip,
2160 			     void *addr, void *plt, u32 *insn)
2161 {
2162 	void *target;
2163 
2164 	if (!addr) {
2165 		*insn = aarch64_insn_gen_nop();
2166 		return 0;
2167 	}
2168 
2169 	if (is_long_jump(ip, addr))
2170 		target = plt;
2171 	else
2172 		target = addr;
2173 
2174 	*insn = aarch64_insn_gen_branch_imm((unsigned long)ip,
2175 					    (unsigned long)target,
2176 					    type);
2177 
2178 	return *insn != AARCH64_BREAK_FAULT ? 0 : -EFAULT;
2179 }
2180 
2181 /* Replace the branch instruction from @ip to @old_addr in a bpf prog or a bpf
2182  * trampoline with the branch instruction from @ip to @new_addr. If @old_addr
2183  * or @new_addr is NULL, the old or new instruction is NOP.
2184  *
2185  * When @ip is the bpf prog entry, a bpf trampoline is being attached or
2186  * detached. Since bpf trampoline and bpf prog are allocated separately with
2187  * vmalloc, the address distance may exceed 128MB, the maximum branch range.
2188  * So long jump should be handled.
2189  *
2190  * When a bpf prog is constructed, a plt pointing to empty trampoline
2191  * dummy_tramp is placed at the end:
2192  *
2193  *      bpf_prog:
2194  *              mov x9, lr
2195  *              nop // patchsite
2196  *              ...
2197  *              ret
2198  *
2199  *      plt:
2200  *              ldr x10, target
2201  *              br x10
2202  *      target:
2203  *              .quad dummy_tramp // plt target
2204  *
2205  * This is also the state when no trampoline is attached.
2206  *
2207  * When a short-jump bpf trampoline is attached, the patchsite is patched
2208  * to a bl instruction to the trampoline directly:
2209  *
2210  *      bpf_prog:
2211  *              mov x9, lr
2212  *              bl <short-jump bpf trampoline address> // patchsite
2213  *              ...
2214  *              ret
2215  *
2216  *      plt:
2217  *              ldr x10, target
2218  *              br x10
2219  *      target:
2220  *              .quad dummy_tramp // plt target
2221  *
2222  * When a long-jump bpf trampoline is attached, the plt target is filled with
2223  * the trampoline address and the patchsite is patched to a bl instruction to
2224  * the plt:
2225  *
2226  *      bpf_prog:
2227  *              mov x9, lr
2228  *              bl plt // patchsite
2229  *              ...
2230  *              ret
2231  *
2232  *      plt:
2233  *              ldr x10, target
2234  *              br x10
2235  *      target:
2236  *              .quad <long-jump bpf trampoline address> // plt target
2237  *
2238  * The dummy_tramp is used to prevent another CPU from jumping to unknown
2239  * locations during the patching process, making the patching process easier.
2240  */
bpf_arch_text_poke(void * ip,enum bpf_text_poke_type poke_type,void * old_addr,void * new_addr)2241 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type poke_type,
2242 		       void *old_addr, void *new_addr)
2243 {
2244 	int ret;
2245 	u32 old_insn;
2246 	u32 new_insn;
2247 	u32 replaced;
2248 	struct bpf_plt *plt = NULL;
2249 	unsigned long size = 0UL;
2250 	unsigned long offset = ~0UL;
2251 	enum aarch64_insn_branch_type branch_type;
2252 	char namebuf[KSYM_NAME_LEN];
2253 	void *image = NULL;
2254 	u64 plt_target = 0ULL;
2255 	bool poking_bpf_entry;
2256 
2257 	if (!__bpf_address_lookup((unsigned long)ip, &size, &offset, namebuf))
2258 		/* Only poking bpf text is supported. Since kernel function
2259 		 * entry is set up by ftrace, we reply on ftrace to poke kernel
2260 		 * functions.
2261 		 */
2262 		return -ENOTSUPP;
2263 
2264 	image = ip - offset;
2265 	/* zero offset means we're poking bpf prog entry */
2266 	poking_bpf_entry = (offset == 0UL);
2267 
2268 	/* bpf prog entry, find plt and the real patchsite */
2269 	if (poking_bpf_entry) {
2270 		/* plt locates at the end of bpf prog */
2271 		plt = image + size - PLT_TARGET_OFFSET;
2272 
2273 		/* skip to the nop instruction in bpf prog entry:
2274 		 * bti c // if BTI enabled
2275 		 * mov x9, x30
2276 		 * nop
2277 		 */
2278 		ip = image + POKE_OFFSET * AARCH64_INSN_SIZE;
2279 	}
2280 
2281 	/* long jump is only possible at bpf prog entry */
2282 	if (WARN_ON((is_long_jump(ip, new_addr) || is_long_jump(ip, old_addr)) &&
2283 		    !poking_bpf_entry))
2284 		return -EINVAL;
2285 
2286 	if (poke_type == BPF_MOD_CALL)
2287 		branch_type = AARCH64_INSN_BRANCH_LINK;
2288 	else
2289 		branch_type = AARCH64_INSN_BRANCH_NOLINK;
2290 
2291 	if (gen_branch_or_nop(branch_type, ip, old_addr, plt, &old_insn) < 0)
2292 		return -EFAULT;
2293 
2294 	if (gen_branch_or_nop(branch_type, ip, new_addr, plt, &new_insn) < 0)
2295 		return -EFAULT;
2296 
2297 	if (is_long_jump(ip, new_addr))
2298 		plt_target = (u64)new_addr;
2299 	else if (is_long_jump(ip, old_addr))
2300 		/* if the old target is a long jump and the new target is not,
2301 		 * restore the plt target to dummy_tramp, so there is always a
2302 		 * legal and harmless address stored in plt target, and we'll
2303 		 * never jump from plt to an unknown place.
2304 		 */
2305 		plt_target = (u64)&dummy_tramp;
2306 
2307 	if (plt_target) {
2308 		/* non-zero plt_target indicates we're patching a bpf prog,
2309 		 * which is read only.
2310 		 */
2311 		if (set_memory_rw(PAGE_MASK & ((uintptr_t)&plt->target), 1))
2312 			return -EFAULT;
2313 		WRITE_ONCE(plt->target, plt_target);
2314 		set_memory_ro(PAGE_MASK & ((uintptr_t)&plt->target), 1);
2315 		/* since plt target points to either the new trampoline
2316 		 * or dummy_tramp, even if another CPU reads the old plt
2317 		 * target value before fetching the bl instruction to plt,
2318 		 * it will be brought back by dummy_tramp, so no barrier is
2319 		 * required here.
2320 		 */
2321 	}
2322 
2323 	/* if the old target and the new target are both long jumps, no
2324 	 * patching is required
2325 	 */
2326 	if (old_insn == new_insn)
2327 		return 0;
2328 
2329 	mutex_lock(&text_mutex);
2330 	if (aarch64_insn_read(ip, &replaced)) {
2331 		ret = -EFAULT;
2332 		goto out;
2333 	}
2334 
2335 	if (replaced != old_insn) {
2336 		ret = -EFAULT;
2337 		goto out;
2338 	}
2339 
2340 	/* We call aarch64_insn_patch_text_nosync() to replace instruction
2341 	 * atomically, so no other CPUs will fetch a half-new and half-old
2342 	 * instruction. But there is chance that another CPU executes the
2343 	 * old instruction after the patching operation finishes (e.g.,
2344 	 * pipeline not flushed, or icache not synchronized yet).
2345 	 *
2346 	 * 1. when a new trampoline is attached, it is not a problem for
2347 	 *    different CPUs to jump to different trampolines temporarily.
2348 	 *
2349 	 * 2. when an old trampoline is freed, we should wait for all other
2350 	 *    CPUs to exit the trampoline and make sure the trampoline is no
2351 	 *    longer reachable, since bpf_tramp_image_put() function already
2352 	 *    uses percpu_ref and task-based rcu to do the sync, no need to call
2353 	 *    the sync version here, see bpf_tramp_image_put() for details.
2354 	 */
2355 	ret = aarch64_insn_patch_text_nosync(ip, new_insn);
2356 out:
2357 	mutex_unlock(&text_mutex);
2358 
2359 	return ret;
2360 }
2361