xref: /linux/arch/arm64/net/bpf_jit_comp.c (revision a6923c06a3b2e2c534ae28c53a7531e76cc95cfa)
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/cfi.h>
14 #include <linux/filter.h>
15 #include <linux/memory.h>
16 #include <linux/printk.h>
17 #include <linux/slab.h>
18 
19 #include <asm/asm-extable.h>
20 #include <asm/byteorder.h>
21 #include <asm/cacheflush.h>
22 #include <asm/cpufeature.h>
23 #include <asm/debug-monitors.h>
24 #include <asm/insn.h>
25 #include <asm/text-patching.h>
26 #include <asm/set_memory.h>
27 
28 #include "bpf_jit.h"
29 
30 #define TMP_REG_1 (MAX_BPF_JIT_REG + 0)
31 #define TMP_REG_2 (MAX_BPF_JIT_REG + 1)
32 #define TCCNT_PTR (MAX_BPF_JIT_REG + 2)
33 #define TMP_REG_3 (MAX_BPF_JIT_REG + 3)
34 #define PRIVATE_SP (MAX_BPF_JIT_REG + 4)
35 #define ARENA_VM_START (MAX_BPF_JIT_REG + 5)
36 
37 #define check_imm(bits, imm) do {				\
38 	if ((((imm) > 0) && ((imm) >> (bits))) ||		\
39 	    (((imm) < 0) && (~(imm) >> (bits)))) {		\
40 		pr_info("[%2d] imm=%d(0x%x) out of range\n",	\
41 			i, imm, imm);				\
42 		return -EINVAL;					\
43 	}							\
44 } while (0)
45 #define check_imm19(imm) check_imm(19, imm)
46 #define check_imm26(imm) check_imm(26, imm)
47 
48 /* Map BPF registers to A64 registers */
49 static const int bpf2a64[] = {
50 	/* return value from in-kernel function, and exit value from eBPF */
51 	[BPF_REG_0] = A64_R(7),
52 	/* arguments from eBPF program to in-kernel function */
53 	[BPF_REG_1] = A64_R(0),
54 	[BPF_REG_2] = A64_R(1),
55 	[BPF_REG_3] = A64_R(2),
56 	[BPF_REG_4] = A64_R(3),
57 	[BPF_REG_5] = A64_R(4),
58 	/* callee saved registers that in-kernel function will preserve */
59 	[BPF_REG_6] = A64_R(19),
60 	[BPF_REG_7] = A64_R(20),
61 	[BPF_REG_8] = A64_R(21),
62 	[BPF_REG_9] = A64_R(22),
63 	/* read-only frame pointer to access stack */
64 	[BPF_REG_FP] = A64_R(25),
65 	/* temporary registers for BPF JIT */
66 	[TMP_REG_1] = A64_R(10),
67 	[TMP_REG_2] = A64_R(11),
68 	[TMP_REG_3] = A64_R(12),
69 	/* tail_call_cnt_ptr */
70 	[TCCNT_PTR] = A64_R(26),
71 	/* temporary register for blinding constants */
72 	[BPF_REG_AX] = A64_R(9),
73 	/* callee saved register for private stack pointer */
74 	[PRIVATE_SP] = A64_R(27),
75 	/* callee saved register for kern_vm_start address */
76 	[ARENA_VM_START] = A64_R(28),
77 };
78 
79 struct jit_ctx {
80 	const struct bpf_prog *prog;
81 	int idx;
82 	int epilogue_offset;
83 	int *offset;
84 	int exentry_idx;
85 	int nr_used_callee_reg;
86 	u8 used_callee_reg[8]; /* r6~r9, fp, arena_vm_start */
87 	__le32 *image;
88 	__le32 *ro_image;
89 	u32 stack_size;
90 	u64 user_vm_start;
91 	u64 arena_vm_start;
92 	bool fp_used;
93 	bool priv_sp_used;
94 	bool write;
95 };
96 
97 struct bpf_plt {
98 	u32 insn_ldr; /* load target */
99 	u32 insn_br;  /* branch to target */
100 	u64 target;   /* target value */
101 };
102 
103 #define PLT_TARGET_SIZE   sizeof_field(struct bpf_plt, target)
104 #define PLT_TARGET_OFFSET offsetof(struct bpf_plt, target)
105 
106 /* Memory size/value to protect private stack overflow/underflow */
107 #define PRIV_STACK_GUARD_SZ    16
108 #define PRIV_STACK_GUARD_VAL   0xEB9F12345678eb9fULL
109 
emit(const u32 insn,struct jit_ctx * ctx)110 static inline void emit(const u32 insn, struct jit_ctx *ctx)
111 {
112 	if (ctx->image != NULL && ctx->write)
113 		ctx->image[ctx->idx] = cpu_to_le32(insn);
114 
115 	ctx->idx++;
116 }
117 
emit_u32_data(const u32 data,struct jit_ctx * ctx)118 static inline void emit_u32_data(const u32 data, struct jit_ctx *ctx)
119 {
120 	if (ctx->image != NULL && ctx->write)
121 		ctx->image[ctx->idx] = data;
122 
123 	ctx->idx++;
124 }
125 
emit_a64_mov_i(const int is64,const int reg,const s32 val,struct jit_ctx * ctx)126 static inline void emit_a64_mov_i(const int is64, const int reg,
127 				  const s32 val, struct jit_ctx *ctx)
128 {
129 	u16 hi = val >> 16;
130 	u16 lo = val & 0xffff;
131 
132 	if (hi & 0x8000) {
133 		if (hi == 0xffff) {
134 			emit(A64_MOVN(is64, reg, (u16)~lo, 0), ctx);
135 		} else {
136 			emit(A64_MOVN(is64, reg, (u16)~hi, 16), ctx);
137 			if (lo != 0xffff)
138 				emit(A64_MOVK(is64, reg, lo, 0), ctx);
139 		}
140 	} else {
141 		emit(A64_MOVZ(is64, reg, lo, 0), ctx);
142 		if (hi)
143 			emit(A64_MOVK(is64, reg, hi, 16), ctx);
144 	}
145 }
146 
i64_i16_blocks(const u64 val,bool inverse)147 static int i64_i16_blocks(const u64 val, bool inverse)
148 {
149 	return (((val >>  0) & 0xffff) != (inverse ? 0xffff : 0x0000)) +
150 	       (((val >> 16) & 0xffff) != (inverse ? 0xffff : 0x0000)) +
151 	       (((val >> 32) & 0xffff) != (inverse ? 0xffff : 0x0000)) +
152 	       (((val >> 48) & 0xffff) != (inverse ? 0xffff : 0x0000));
153 }
154 
emit_a64_mov_i64(const int reg,const u64 val,struct jit_ctx * ctx)155 static inline void emit_a64_mov_i64(const int reg, const u64 val,
156 				    struct jit_ctx *ctx)
157 {
158 	u64 nrm_tmp = val, rev_tmp = ~val;
159 	bool inverse;
160 	int shift;
161 
162 	if (!(nrm_tmp >> 32))
163 		return emit_a64_mov_i(0, reg, (u32)val, ctx);
164 
165 	inverse = i64_i16_blocks(nrm_tmp, true) < i64_i16_blocks(nrm_tmp, false);
166 	shift = max(round_down((inverse ? (fls64(rev_tmp) - 1) :
167 					  (fls64(nrm_tmp) - 1)), 16), 0);
168 	if (inverse)
169 		emit(A64_MOVN(1, reg, (rev_tmp >> shift) & 0xffff, shift), ctx);
170 	else
171 		emit(A64_MOVZ(1, reg, (nrm_tmp >> shift) & 0xffff, shift), ctx);
172 	shift -= 16;
173 	while (shift >= 0) {
174 		if (((nrm_tmp >> shift) & 0xffff) != (inverse ? 0xffff : 0x0000))
175 			emit(A64_MOVK(1, reg, (nrm_tmp >> shift) & 0xffff, shift), ctx);
176 		shift -= 16;
177 	}
178 }
179 
emit_bti(u32 insn,struct jit_ctx * ctx)180 static inline void emit_bti(u32 insn, struct jit_ctx *ctx)
181 {
182 	if (IS_ENABLED(CONFIG_ARM64_BTI_KERNEL))
183 		emit(insn, ctx);
184 }
185 
emit_kcfi(u32 hash,struct jit_ctx * ctx)186 static inline void emit_kcfi(u32 hash, struct jit_ctx *ctx)
187 {
188 	if (IS_ENABLED(CONFIG_CFI_CLANG))
189 		emit_u32_data(hash, ctx);
190 }
191 
192 /*
193  * Kernel addresses in the vmalloc space use at most 48 bits, and the
194  * remaining bits are guaranteed to be 0x1. So we can compose the address
195  * with a fixed length movn/movk/movk sequence.
196  */
emit_addr_mov_i64(const int reg,const u64 val,struct jit_ctx * ctx)197 static inline void emit_addr_mov_i64(const int reg, const u64 val,
198 				     struct jit_ctx *ctx)
199 {
200 	u64 tmp = val;
201 	int shift = 0;
202 
203 	emit(A64_MOVN(1, reg, ~tmp & 0xffff, shift), ctx);
204 	while (shift < 32) {
205 		tmp >>= 16;
206 		shift += 16;
207 		emit(A64_MOVK(1, reg, tmp & 0xffff, shift), ctx);
208 	}
209 }
210 
should_emit_indirect_call(long target,const struct jit_ctx * ctx)211 static bool should_emit_indirect_call(long target, const struct jit_ctx *ctx)
212 {
213 	long offset;
214 
215 	/* when ctx->ro_image is not allocated or the target is unknown,
216 	 * emit indirect call
217 	 */
218 	if (!ctx->ro_image || !target)
219 		return true;
220 
221 	offset = target - (long)&ctx->ro_image[ctx->idx];
222 	return offset < -SZ_128M || offset >= SZ_128M;
223 }
224 
emit_direct_call(u64 target,struct jit_ctx * ctx)225 static void emit_direct_call(u64 target, struct jit_ctx *ctx)
226 {
227 	u32 insn;
228 	unsigned long pc;
229 
230 	pc = (unsigned long)&ctx->ro_image[ctx->idx];
231 	insn = aarch64_insn_gen_branch_imm(pc, target, AARCH64_INSN_BRANCH_LINK);
232 	emit(insn, ctx);
233 }
234 
emit_indirect_call(u64 target,struct jit_ctx * ctx)235 static void emit_indirect_call(u64 target, struct jit_ctx *ctx)
236 {
237 	u8 tmp;
238 
239 	tmp = bpf2a64[TMP_REG_1];
240 	emit_addr_mov_i64(tmp, target, ctx);
241 	emit(A64_BLR(tmp), ctx);
242 }
243 
emit_call(u64 target,struct jit_ctx * ctx)244 static void emit_call(u64 target, struct jit_ctx *ctx)
245 {
246 	if (should_emit_indirect_call((long)target, ctx))
247 		emit_indirect_call(target, ctx);
248 	else
249 		emit_direct_call(target, ctx);
250 }
251 
bpf2a64_offset(int bpf_insn,int off,const struct jit_ctx * ctx)252 static inline int bpf2a64_offset(int bpf_insn, int off,
253 				 const struct jit_ctx *ctx)
254 {
255 	/* BPF JMP offset is relative to the next instruction */
256 	bpf_insn++;
257 	/*
258 	 * Whereas arm64 branch instructions encode the offset
259 	 * from the branch itself, so we must subtract 1 from the
260 	 * instruction offset.
261 	 */
262 	return ctx->offset[bpf_insn + off] - (ctx->offset[bpf_insn] - 1);
263 }
264 
jit_fill_hole(void * area,unsigned int size)265 static void jit_fill_hole(void *area, unsigned int size)
266 {
267 	__le32 *ptr;
268 	/* We are guaranteed to have aligned memory. */
269 	for (ptr = area; size >= sizeof(u32); size -= sizeof(u32))
270 		*ptr++ = cpu_to_le32(AARCH64_BREAK_FAULT);
271 }
272 
bpf_arch_text_invalidate(void * dst,size_t len)273 int bpf_arch_text_invalidate(void *dst, size_t len)
274 {
275 	if (!aarch64_insn_set(dst, AARCH64_BREAK_FAULT, len))
276 		return -EINVAL;
277 
278 	return 0;
279 }
280 
epilogue_offset(const struct jit_ctx * ctx)281 static inline int epilogue_offset(const struct jit_ctx *ctx)
282 {
283 	int to = ctx->epilogue_offset;
284 	int from = ctx->idx;
285 
286 	return to - from;
287 }
288 
is_addsub_imm(u32 imm)289 static bool is_addsub_imm(u32 imm)
290 {
291 	/* Either imm12 or shifted imm12. */
292 	return !(imm & ~0xfff) || !(imm & ~0xfff000);
293 }
294 
emit_a64_add_i(const bool is64,const int dst,const int src,const int tmp,const s32 imm,struct jit_ctx * ctx)295 static inline void emit_a64_add_i(const bool is64, const int dst, const int src,
296 				  const int tmp, const s32 imm, struct jit_ctx *ctx)
297 {
298 	if (is_addsub_imm(imm)) {
299 		emit(A64_ADD_I(is64, dst, src, imm), ctx);
300 	} else if (is_addsub_imm(-(u32)imm)) {
301 		emit(A64_SUB_I(is64, dst, src, -imm), ctx);
302 	} else {
303 		emit_a64_mov_i(is64, tmp, imm, ctx);
304 		emit(A64_ADD(is64, dst, src, tmp), ctx);
305 	}
306 }
307 
308 /*
309  * There are 3 types of AArch64 LDR/STR (immediate) instruction:
310  * Post-index, Pre-index, Unsigned offset.
311  *
312  * For BPF ldr/str, the "unsigned offset" type is sufficient.
313  *
314  * "Unsigned offset" type LDR(immediate) format:
315  *
316  *    3                   2                   1                   0
317  *  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
318  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
319  * |x x|1 1 1 0 0 1 0 1|         imm12         |    Rn   |    Rt   |
320  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
321  * scale
322  *
323  * "Unsigned offset" type STR(immediate) format:
324  *    3                   2                   1                   0
325  *  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
326  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
327  * |x x|1 1 1 0 0 1 0 0|         imm12         |    Rn   |    Rt   |
328  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
329  * scale
330  *
331  * The offset is calculated from imm12 and scale in the following way:
332  *
333  * offset = (u64)imm12 << scale
334  */
is_lsi_offset(int offset,int scale)335 static bool is_lsi_offset(int offset, int scale)
336 {
337 	if (offset < 0)
338 		return false;
339 
340 	if (offset > (0xFFF << scale))
341 		return false;
342 
343 	if (offset & ((1 << scale) - 1))
344 		return false;
345 
346 	return true;
347 }
348 
349 /* generated main prog prologue:
350  *      bti c // if CONFIG_ARM64_BTI_KERNEL
351  *      mov x9, lr
352  *      nop  // POKE_OFFSET
353  *      paciasp // if CONFIG_ARM64_PTR_AUTH_KERNEL
354  *      stp x29, lr, [sp, #-16]!
355  *      mov x29, sp
356  *      stp xzr, x26, [sp, #-16]!
357  *      mov x26, sp
358  *      // PROLOGUE_OFFSET
359  *	// save callee-saved registers
360  */
prepare_bpf_tail_call_cnt(struct jit_ctx * ctx)361 static void prepare_bpf_tail_call_cnt(struct jit_ctx *ctx)
362 {
363 	const bool is_main_prog = !bpf_is_subprog(ctx->prog);
364 	const u8 ptr = bpf2a64[TCCNT_PTR];
365 
366 	if (is_main_prog) {
367 		/* Initialize tail_call_cnt. */
368 		emit(A64_PUSH(A64_ZR, ptr, A64_SP), ctx);
369 		emit(A64_MOV(1, ptr, A64_SP), ctx);
370 	} else
371 		emit(A64_PUSH(ptr, ptr, A64_SP), ctx);
372 }
373 
find_used_callee_regs(struct jit_ctx * ctx)374 static void find_used_callee_regs(struct jit_ctx *ctx)
375 {
376 	int i;
377 	const struct bpf_prog *prog = ctx->prog;
378 	const struct bpf_insn *insn = &prog->insnsi[0];
379 	int reg_used = 0;
380 
381 	for (i = 0; i < prog->len; i++, insn++) {
382 		if (insn->dst_reg == BPF_REG_6 || insn->src_reg == BPF_REG_6)
383 			reg_used |= 1;
384 
385 		if (insn->dst_reg == BPF_REG_7 || insn->src_reg == BPF_REG_7)
386 			reg_used |= 2;
387 
388 		if (insn->dst_reg == BPF_REG_8 || insn->src_reg == BPF_REG_8)
389 			reg_used |= 4;
390 
391 		if (insn->dst_reg == BPF_REG_9 || insn->src_reg == BPF_REG_9)
392 			reg_used |= 8;
393 
394 		if (insn->dst_reg == BPF_REG_FP || insn->src_reg == BPF_REG_FP) {
395 			ctx->fp_used = true;
396 			reg_used |= 16;
397 		}
398 	}
399 
400 	i = 0;
401 	if (reg_used & 1)
402 		ctx->used_callee_reg[i++] = bpf2a64[BPF_REG_6];
403 
404 	if (reg_used & 2)
405 		ctx->used_callee_reg[i++] = bpf2a64[BPF_REG_7];
406 
407 	if (reg_used & 4)
408 		ctx->used_callee_reg[i++] = bpf2a64[BPF_REG_8];
409 
410 	if (reg_used & 8)
411 		ctx->used_callee_reg[i++] = bpf2a64[BPF_REG_9];
412 
413 	if (reg_used & 16) {
414 		ctx->used_callee_reg[i++] = bpf2a64[BPF_REG_FP];
415 		if (ctx->priv_sp_used)
416 			ctx->used_callee_reg[i++] = bpf2a64[PRIVATE_SP];
417 	}
418 
419 	if (ctx->arena_vm_start)
420 		ctx->used_callee_reg[i++] = bpf2a64[ARENA_VM_START];
421 
422 	ctx->nr_used_callee_reg = i;
423 }
424 
425 /* Save callee-saved registers */
push_callee_regs(struct jit_ctx * ctx)426 static void push_callee_regs(struct jit_ctx *ctx)
427 {
428 	int reg1, reg2, i;
429 
430 	/*
431 	 * Program acting as exception boundary should save all ARM64
432 	 * Callee-saved registers as the exception callback needs to recover
433 	 * all ARM64 Callee-saved registers in its epilogue.
434 	 */
435 	if (ctx->prog->aux->exception_boundary) {
436 		emit(A64_PUSH(A64_R(19), A64_R(20), A64_SP), ctx);
437 		emit(A64_PUSH(A64_R(21), A64_R(22), A64_SP), ctx);
438 		emit(A64_PUSH(A64_R(23), A64_R(24), A64_SP), ctx);
439 		emit(A64_PUSH(A64_R(25), A64_R(26), A64_SP), ctx);
440 		emit(A64_PUSH(A64_R(27), A64_R(28), A64_SP), ctx);
441 		ctx->fp_used = true;
442 	} else {
443 		find_used_callee_regs(ctx);
444 		for (i = 0; i + 1 < ctx->nr_used_callee_reg; i += 2) {
445 			reg1 = ctx->used_callee_reg[i];
446 			reg2 = ctx->used_callee_reg[i + 1];
447 			emit(A64_PUSH(reg1, reg2, A64_SP), ctx);
448 		}
449 		if (i < ctx->nr_used_callee_reg) {
450 			reg1 = ctx->used_callee_reg[i];
451 			/* keep SP 16-byte aligned */
452 			emit(A64_PUSH(reg1, A64_ZR, A64_SP), ctx);
453 		}
454 	}
455 }
456 
457 /* Restore callee-saved registers */
pop_callee_regs(struct jit_ctx * ctx)458 static void pop_callee_regs(struct jit_ctx *ctx)
459 {
460 	struct bpf_prog_aux *aux = ctx->prog->aux;
461 	int reg1, reg2, i;
462 
463 	/*
464 	 * Program acting as exception boundary pushes R23 and R24 in addition
465 	 * to BPF callee-saved registers. Exception callback uses the boundary
466 	 * program's stack frame, so recover these extra registers in the above
467 	 * two cases.
468 	 */
469 	if (aux->exception_boundary || aux->exception_cb) {
470 		emit(A64_POP(A64_R(27), A64_R(28), A64_SP), ctx);
471 		emit(A64_POP(A64_R(25), A64_R(26), A64_SP), ctx);
472 		emit(A64_POP(A64_R(23), A64_R(24), A64_SP), ctx);
473 		emit(A64_POP(A64_R(21), A64_R(22), A64_SP), ctx);
474 		emit(A64_POP(A64_R(19), A64_R(20), A64_SP), ctx);
475 	} else {
476 		i = ctx->nr_used_callee_reg - 1;
477 		if (ctx->nr_used_callee_reg % 2 != 0) {
478 			reg1 = ctx->used_callee_reg[i];
479 			emit(A64_POP(reg1, A64_ZR, A64_SP), ctx);
480 			i--;
481 		}
482 		while (i > 0) {
483 			reg1 = ctx->used_callee_reg[i - 1];
484 			reg2 = ctx->used_callee_reg[i];
485 			emit(A64_POP(reg1, reg2, A64_SP), ctx);
486 			i -= 2;
487 		}
488 	}
489 }
490 
emit_percpu_ptr(const u8 dst_reg,void __percpu * ptr,struct jit_ctx * ctx)491 static void emit_percpu_ptr(const u8 dst_reg, void __percpu *ptr,
492 			    struct jit_ctx *ctx)
493 {
494 	const u8 tmp = bpf2a64[TMP_REG_1];
495 
496 	emit_a64_mov_i64(dst_reg, (__force const u64)ptr, ctx);
497 	if (cpus_have_cap(ARM64_HAS_VIRT_HOST_EXTN))
498 		emit(A64_MRS_TPIDR_EL2(tmp), ctx);
499 	else
500 		emit(A64_MRS_TPIDR_EL1(tmp), ctx);
501 	emit(A64_ADD(1, dst_reg, dst_reg, tmp), ctx);
502 }
503 
504 #define BTI_INSNS (IS_ENABLED(CONFIG_ARM64_BTI_KERNEL) ? 1 : 0)
505 #define PAC_INSNS (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL) ? 1 : 0)
506 
507 /* Offset of nop instruction in bpf prog entry to be poked */
508 #define POKE_OFFSET (BTI_INSNS + 1)
509 
510 /* Tail call offset to jump into */
511 #define PROLOGUE_OFFSET (BTI_INSNS + 2 + PAC_INSNS + 4)
512 
build_prologue(struct jit_ctx * ctx,bool ebpf_from_cbpf)513 static int build_prologue(struct jit_ctx *ctx, bool ebpf_from_cbpf)
514 {
515 	const struct bpf_prog *prog = ctx->prog;
516 	const bool is_main_prog = !bpf_is_subprog(prog);
517 	const u8 fp = bpf2a64[BPF_REG_FP];
518 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
519 	const u8 priv_sp = bpf2a64[PRIVATE_SP];
520 	void __percpu *priv_stack_ptr;
521 	int cur_offset;
522 
523 	/*
524 	 * BPF prog stack layout
525 	 *
526 	 *                         high
527 	 * original A64_SP =>   0:+-----+ BPF prologue
528 	 *                        |FP/LR|
529 	 * current A64_FP =>  -16:+-----+
530 	 *                        | ... | callee saved registers
531 	 * BPF fp register => -64:+-----+ <= (BPF_FP)
532 	 *                        |     |
533 	 *                        | ... | BPF prog stack
534 	 *                        |     |
535 	 *                        +-----+ <= (BPF_FP - prog->aux->stack_depth)
536 	 *                        |RSVD | padding
537 	 * current A64_SP =>      +-----+ <= (BPF_FP - ctx->stack_size)
538 	 *                        |     |
539 	 *                        | ... | Function call stack
540 	 *                        |     |
541 	 *                        +-----+
542 	 *                          low
543 	 *
544 	 */
545 
546 	emit_kcfi(is_main_prog ? cfi_bpf_hash : cfi_bpf_subprog_hash, ctx);
547 	const int idx0 = ctx->idx;
548 
549 	/* bpf function may be invoked by 3 instruction types:
550 	 * 1. bl, attached via freplace to bpf prog via short jump
551 	 * 2. br, attached via freplace to bpf prog via long jump
552 	 * 3. blr, working as a function pointer, used by emit_call.
553 	 * So BTI_JC should used here to support both br and blr.
554 	 */
555 	emit_bti(A64_BTI_JC, ctx);
556 
557 	emit(A64_MOV(1, A64_R(9), A64_LR), ctx);
558 	emit(A64_NOP, ctx);
559 
560 	if (!prog->aux->exception_cb) {
561 		/* Sign lr */
562 		if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
563 			emit(A64_PACIASP, ctx);
564 
565 		/* Save FP and LR registers to stay align with ARM64 AAPCS */
566 		emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
567 		emit(A64_MOV(1, A64_FP, A64_SP), ctx);
568 
569 		prepare_bpf_tail_call_cnt(ctx);
570 
571 		if (!ebpf_from_cbpf && is_main_prog) {
572 			cur_offset = ctx->idx - idx0;
573 			if (cur_offset != PROLOGUE_OFFSET) {
574 				pr_err_once("PROLOGUE_OFFSET = %d, expected %d!\n",
575 						cur_offset, PROLOGUE_OFFSET);
576 				return -1;
577 			}
578 			/* BTI landing pad for the tail call, done with a BR */
579 			emit_bti(A64_BTI_J, ctx);
580 		}
581 		push_callee_regs(ctx);
582 	} else {
583 		/*
584 		 * Exception callback receives FP of Main Program as third
585 		 * parameter
586 		 */
587 		emit(A64_MOV(1, A64_FP, A64_R(2)), ctx);
588 		/*
589 		 * Main Program already pushed the frame record and the
590 		 * callee-saved registers. The exception callback will not push
591 		 * anything and re-use the main program's stack.
592 		 *
593 		 * 12 registers are on the stack
594 		 */
595 		emit(A64_SUB_I(1, A64_SP, A64_FP, 96), ctx);
596 	}
597 
598 	/* Stack must be multiples of 16B */
599 	ctx->stack_size = round_up(prog->aux->stack_depth, 16);
600 
601 	if (ctx->fp_used) {
602 		if (ctx->priv_sp_used) {
603 			/* Set up private stack pointer */
604 			priv_stack_ptr = prog->aux->priv_stack_ptr + PRIV_STACK_GUARD_SZ;
605 			emit_percpu_ptr(priv_sp, priv_stack_ptr, ctx);
606 			emit(A64_ADD_I(1, fp, priv_sp, ctx->stack_size), ctx);
607 		} else {
608 			/* Set up BPF prog stack base register */
609 			emit(A64_MOV(1, fp, A64_SP), ctx);
610 		}
611 	}
612 
613 	/* Set up function call stack */
614 	if (ctx->stack_size && !ctx->priv_sp_used)
615 		emit(A64_SUB_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
616 
617 	if (ctx->arena_vm_start)
618 		emit_a64_mov_i64(arena_vm_base, ctx->arena_vm_start, ctx);
619 
620 	return 0;
621 }
622 
emit_bpf_tail_call(struct jit_ctx * ctx)623 static int emit_bpf_tail_call(struct jit_ctx *ctx)
624 {
625 	/* bpf_tail_call(void *prog_ctx, struct bpf_array *array, u64 index) */
626 	const u8 r2 = bpf2a64[BPF_REG_2];
627 	const u8 r3 = bpf2a64[BPF_REG_3];
628 
629 	const u8 tmp = bpf2a64[TMP_REG_1];
630 	const u8 prg = bpf2a64[TMP_REG_2];
631 	const u8 tcc = bpf2a64[TMP_REG_3];
632 	const u8 ptr = bpf2a64[TCCNT_PTR];
633 	size_t off;
634 	__le32 *branch1 = NULL;
635 	__le32 *branch2 = NULL;
636 	__le32 *branch3 = NULL;
637 
638 	/* if (index >= array->map.max_entries)
639 	 *     goto out;
640 	 */
641 	off = offsetof(struct bpf_array, map.max_entries);
642 	emit_a64_mov_i64(tmp, off, ctx);
643 	emit(A64_LDR32(tmp, r2, tmp), ctx);
644 	emit(A64_MOV(0, r3, r3), ctx);
645 	emit(A64_CMP(0, r3, tmp), ctx);
646 	branch1 = ctx->image + ctx->idx;
647 	emit(A64_NOP, ctx);
648 
649 	/*
650 	 * if ((*tail_call_cnt_ptr) >= MAX_TAIL_CALL_CNT)
651 	 *     goto out;
652 	 */
653 	emit_a64_mov_i64(tmp, MAX_TAIL_CALL_CNT, ctx);
654 	emit(A64_LDR64I(tcc, ptr, 0), ctx);
655 	emit(A64_CMP(1, tcc, tmp), ctx);
656 	branch2 = ctx->image + ctx->idx;
657 	emit(A64_NOP, ctx);
658 
659 	/* (*tail_call_cnt_ptr)++; */
660 	emit(A64_ADD_I(1, tcc, tcc, 1), ctx);
661 
662 	/* prog = array->ptrs[index];
663 	 * if (prog == NULL)
664 	 *     goto out;
665 	 */
666 	off = offsetof(struct bpf_array, ptrs);
667 	emit_a64_mov_i64(tmp, off, ctx);
668 	emit(A64_ADD(1, tmp, r2, tmp), ctx);
669 	emit(A64_LSL(1, prg, r3, 3), ctx);
670 	emit(A64_LDR64(prg, tmp, prg), ctx);
671 	branch3 = ctx->image + ctx->idx;
672 	emit(A64_NOP, ctx);
673 
674 	/* Update tail_call_cnt if the slot is populated. */
675 	emit(A64_STR64I(tcc, ptr, 0), ctx);
676 
677 	/* restore SP */
678 	if (ctx->stack_size && !ctx->priv_sp_used)
679 		emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
680 
681 	pop_callee_regs(ctx);
682 
683 	/* goto *(prog->bpf_func + prologue_offset); */
684 	off = offsetof(struct bpf_prog, bpf_func);
685 	emit_a64_mov_i64(tmp, off, ctx);
686 	emit(A64_LDR64(tmp, prg, tmp), ctx);
687 	emit(A64_ADD_I(1, tmp, tmp, sizeof(u32) * PROLOGUE_OFFSET), ctx);
688 	emit(A64_BR(tmp), ctx);
689 
690 	if (ctx->image) {
691 		off = &ctx->image[ctx->idx] - branch1;
692 		*branch1 = cpu_to_le32(A64_B_(A64_COND_CS, off));
693 
694 		off = &ctx->image[ctx->idx] - branch2;
695 		*branch2 = cpu_to_le32(A64_B_(A64_COND_CS, off));
696 
697 		off = &ctx->image[ctx->idx] - branch3;
698 		*branch3 = cpu_to_le32(A64_CBZ(1, prg, off));
699 	}
700 
701 	return 0;
702 }
703 
emit_atomic_ld_st(const struct bpf_insn * insn,struct jit_ctx * ctx)704 static int emit_atomic_ld_st(const struct bpf_insn *insn, struct jit_ctx *ctx)
705 {
706 	const s32 imm = insn->imm;
707 	const s16 off = insn->off;
708 	const u8 code = insn->code;
709 	const bool arena = BPF_MODE(code) == BPF_PROBE_ATOMIC;
710 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
711 	const u8 dst = bpf2a64[insn->dst_reg];
712 	const u8 src = bpf2a64[insn->src_reg];
713 	const u8 tmp = bpf2a64[TMP_REG_1];
714 	u8 reg;
715 
716 	switch (imm) {
717 	case BPF_LOAD_ACQ:
718 		reg = src;
719 		break;
720 	case BPF_STORE_REL:
721 		reg = dst;
722 		break;
723 	default:
724 		pr_err_once("unknown atomic load/store op code %02x\n", imm);
725 		return -EINVAL;
726 	}
727 
728 	if (off) {
729 		emit_a64_add_i(1, tmp, reg, tmp, off, ctx);
730 		reg = tmp;
731 	}
732 	if (arena) {
733 		emit(A64_ADD(1, tmp, reg, arena_vm_base), ctx);
734 		reg = tmp;
735 	}
736 
737 	switch (imm) {
738 	case BPF_LOAD_ACQ:
739 		switch (BPF_SIZE(code)) {
740 		case BPF_B:
741 			emit(A64_LDARB(dst, reg), ctx);
742 			break;
743 		case BPF_H:
744 			emit(A64_LDARH(dst, reg), ctx);
745 			break;
746 		case BPF_W:
747 			emit(A64_LDAR32(dst, reg), ctx);
748 			break;
749 		case BPF_DW:
750 			emit(A64_LDAR64(dst, reg), ctx);
751 			break;
752 		}
753 		break;
754 	case BPF_STORE_REL:
755 		switch (BPF_SIZE(code)) {
756 		case BPF_B:
757 			emit(A64_STLRB(src, reg), ctx);
758 			break;
759 		case BPF_H:
760 			emit(A64_STLRH(src, reg), ctx);
761 			break;
762 		case BPF_W:
763 			emit(A64_STLR32(src, reg), ctx);
764 			break;
765 		case BPF_DW:
766 			emit(A64_STLR64(src, reg), ctx);
767 			break;
768 		}
769 		break;
770 	default:
771 		pr_err_once("unexpected atomic load/store op code %02x\n",
772 			    imm);
773 		return -EINVAL;
774 	}
775 
776 	return 0;
777 }
778 
779 #ifdef CONFIG_ARM64_LSE_ATOMICS
emit_lse_atomic(const struct bpf_insn * insn,struct jit_ctx * ctx)780 static int emit_lse_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
781 {
782 	const u8 code = insn->code;
783 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
784 	const u8 dst = bpf2a64[insn->dst_reg];
785 	const u8 src = bpf2a64[insn->src_reg];
786 	const u8 tmp = bpf2a64[TMP_REG_1];
787 	const u8 tmp2 = bpf2a64[TMP_REG_2];
788 	const bool isdw = BPF_SIZE(code) == BPF_DW;
789 	const bool arena = BPF_MODE(code) == BPF_PROBE_ATOMIC;
790 	const s16 off = insn->off;
791 	u8 reg = dst;
792 
793 	if (off) {
794 		emit_a64_add_i(1, tmp, reg, tmp, off, ctx);
795 		reg = tmp;
796 	}
797 	if (arena) {
798 		emit(A64_ADD(1, tmp, reg, arena_vm_base), ctx);
799 		reg = tmp;
800 	}
801 
802 	switch (insn->imm) {
803 	/* lock *(u32/u64 *)(dst_reg + off) <op>= src_reg */
804 	case BPF_ADD:
805 		emit(A64_STADD(isdw, reg, src), ctx);
806 		break;
807 	case BPF_AND:
808 		emit(A64_MVN(isdw, tmp2, src), ctx);
809 		emit(A64_STCLR(isdw, reg, tmp2), ctx);
810 		break;
811 	case BPF_OR:
812 		emit(A64_STSET(isdw, reg, src), ctx);
813 		break;
814 	case BPF_XOR:
815 		emit(A64_STEOR(isdw, reg, src), ctx);
816 		break;
817 	/* src_reg = atomic_fetch_<op>(dst_reg + off, src_reg) */
818 	case BPF_ADD | BPF_FETCH:
819 		emit(A64_LDADDAL(isdw, src, reg, src), ctx);
820 		break;
821 	case BPF_AND | BPF_FETCH:
822 		emit(A64_MVN(isdw, tmp2, src), ctx);
823 		emit(A64_LDCLRAL(isdw, src, reg, tmp2), ctx);
824 		break;
825 	case BPF_OR | BPF_FETCH:
826 		emit(A64_LDSETAL(isdw, src, reg, src), ctx);
827 		break;
828 	case BPF_XOR | BPF_FETCH:
829 		emit(A64_LDEORAL(isdw, src, reg, src), ctx);
830 		break;
831 	/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
832 	case BPF_XCHG:
833 		emit(A64_SWPAL(isdw, src, reg, src), ctx);
834 		break;
835 	/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
836 	case BPF_CMPXCHG:
837 		emit(A64_CASAL(isdw, src, reg, bpf2a64[BPF_REG_0]), ctx);
838 		break;
839 	default:
840 		pr_err_once("unknown atomic op code %02x\n", insn->imm);
841 		return -EINVAL;
842 	}
843 
844 	return 0;
845 }
846 #else
emit_lse_atomic(const struct bpf_insn * insn,struct jit_ctx * ctx)847 static inline int emit_lse_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
848 {
849 	return -EINVAL;
850 }
851 #endif
852 
emit_ll_sc_atomic(const struct bpf_insn * insn,struct jit_ctx * ctx)853 static int emit_ll_sc_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
854 {
855 	const u8 code = insn->code;
856 	const u8 dst = bpf2a64[insn->dst_reg];
857 	const u8 src = bpf2a64[insn->src_reg];
858 	const u8 tmp = bpf2a64[TMP_REG_1];
859 	const u8 tmp2 = bpf2a64[TMP_REG_2];
860 	const u8 tmp3 = bpf2a64[TMP_REG_3];
861 	const int i = insn - ctx->prog->insnsi;
862 	const s32 imm = insn->imm;
863 	const s16 off = insn->off;
864 	const bool isdw = BPF_SIZE(code) == BPF_DW;
865 	u8 reg = dst;
866 	s32 jmp_offset;
867 
868 	if (BPF_MODE(code) == BPF_PROBE_ATOMIC) {
869 		/* ll_sc based atomics don't support unsafe pointers yet. */
870 		pr_err_once("unknown atomic opcode %02x\n", code);
871 		return -EINVAL;
872 	}
873 
874 	if (off) {
875 		emit_a64_add_i(1, tmp, reg, tmp, off, ctx);
876 		reg = tmp;
877 	}
878 
879 	if (imm == BPF_ADD || imm == BPF_AND ||
880 	    imm == BPF_OR || imm == BPF_XOR) {
881 		/* lock *(u32/u64 *)(dst_reg + off) <op>= src_reg */
882 		emit(A64_LDXR(isdw, tmp2, reg), ctx);
883 		if (imm == BPF_ADD)
884 			emit(A64_ADD(isdw, tmp2, tmp2, src), ctx);
885 		else if (imm == BPF_AND)
886 			emit(A64_AND(isdw, tmp2, tmp2, src), ctx);
887 		else if (imm == BPF_OR)
888 			emit(A64_ORR(isdw, tmp2, tmp2, src), ctx);
889 		else
890 			emit(A64_EOR(isdw, tmp2, tmp2, src), ctx);
891 		emit(A64_STXR(isdw, tmp2, reg, tmp3), ctx);
892 		jmp_offset = -3;
893 		check_imm19(jmp_offset);
894 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
895 	} else if (imm == (BPF_ADD | BPF_FETCH) ||
896 		   imm == (BPF_AND | BPF_FETCH) ||
897 		   imm == (BPF_OR | BPF_FETCH) ||
898 		   imm == (BPF_XOR | BPF_FETCH)) {
899 		/* src_reg = atomic_fetch_<op>(dst_reg + off, src_reg) */
900 		const u8 ax = bpf2a64[BPF_REG_AX];
901 
902 		emit(A64_MOV(isdw, ax, src), ctx);
903 		emit(A64_LDXR(isdw, src, reg), ctx);
904 		if (imm == (BPF_ADD | BPF_FETCH))
905 			emit(A64_ADD(isdw, tmp2, src, ax), ctx);
906 		else if (imm == (BPF_AND | BPF_FETCH))
907 			emit(A64_AND(isdw, tmp2, src, ax), ctx);
908 		else if (imm == (BPF_OR | BPF_FETCH))
909 			emit(A64_ORR(isdw, tmp2, src, ax), ctx);
910 		else
911 			emit(A64_EOR(isdw, tmp2, src, ax), ctx);
912 		emit(A64_STLXR(isdw, tmp2, reg, tmp3), ctx);
913 		jmp_offset = -3;
914 		check_imm19(jmp_offset);
915 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
916 		emit(A64_DMB_ISH, ctx);
917 	} else if (imm == BPF_XCHG) {
918 		/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
919 		emit(A64_MOV(isdw, tmp2, src), ctx);
920 		emit(A64_LDXR(isdw, src, reg), ctx);
921 		emit(A64_STLXR(isdw, tmp2, reg, tmp3), ctx);
922 		jmp_offset = -2;
923 		check_imm19(jmp_offset);
924 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
925 		emit(A64_DMB_ISH, ctx);
926 	} else if (imm == BPF_CMPXCHG) {
927 		/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
928 		const u8 r0 = bpf2a64[BPF_REG_0];
929 
930 		emit(A64_MOV(isdw, tmp2, r0), ctx);
931 		emit(A64_LDXR(isdw, r0, reg), ctx);
932 		emit(A64_EOR(isdw, tmp3, r0, tmp2), ctx);
933 		jmp_offset = 4;
934 		check_imm19(jmp_offset);
935 		emit(A64_CBNZ(isdw, tmp3, jmp_offset), ctx);
936 		emit(A64_STLXR(isdw, src, reg, tmp3), ctx);
937 		jmp_offset = -4;
938 		check_imm19(jmp_offset);
939 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
940 		emit(A64_DMB_ISH, ctx);
941 	} else {
942 		pr_err_once("unknown atomic op code %02x\n", imm);
943 		return -EINVAL;
944 	}
945 
946 	return 0;
947 }
948 
949 void dummy_tramp(void);
950 
951 asm (
952 "	.pushsection .text, \"ax\", @progbits\n"
953 "	.global dummy_tramp\n"
954 "	.type dummy_tramp, %function\n"
955 "dummy_tramp:"
956 #if IS_ENABLED(CONFIG_ARM64_BTI_KERNEL)
957 "	bti j\n" /* dummy_tramp is called via "br x10" */
958 #endif
959 "	mov x10, x30\n"
960 "	mov x30, x9\n"
961 "	ret x10\n"
962 "	.size dummy_tramp, .-dummy_tramp\n"
963 "	.popsection\n"
964 );
965 
966 /* build a plt initialized like this:
967  *
968  * plt:
969  *      ldr tmp, target
970  *      br tmp
971  * target:
972  *      .quad dummy_tramp
973  *
974  * when a long jump trampoline is attached, target is filled with the
975  * trampoline address, and when the trampoline is removed, target is
976  * restored to dummy_tramp address.
977  */
build_plt(struct jit_ctx * ctx)978 static void build_plt(struct jit_ctx *ctx)
979 {
980 	const u8 tmp = bpf2a64[TMP_REG_1];
981 	struct bpf_plt *plt = NULL;
982 
983 	/* make sure target is 64-bit aligned */
984 	if ((ctx->idx + PLT_TARGET_OFFSET / AARCH64_INSN_SIZE) % 2)
985 		emit(A64_NOP, ctx);
986 
987 	plt = (struct bpf_plt *)(ctx->image + ctx->idx);
988 	/* plt is called via bl, no BTI needed here */
989 	emit(A64_LDR64LIT(tmp, 2 * AARCH64_INSN_SIZE), ctx);
990 	emit(A64_BR(tmp), ctx);
991 
992 	if (ctx->image)
993 		plt->target = (u64)&dummy_tramp;
994 }
995 
996 /* Clobbers BPF registers 1-4, aka x0-x3 */
build_bhb_mitigation(struct jit_ctx * ctx)997 static void __maybe_unused build_bhb_mitigation(struct jit_ctx *ctx)
998 {
999 	const u8 r1 = bpf2a64[BPF_REG_1]; /* aka x0 */
1000 	u8 k = get_spectre_bhb_loop_value();
1001 
1002 	if (!IS_ENABLED(CONFIG_MITIGATE_SPECTRE_BRANCH_HISTORY) ||
1003 	    cpu_mitigations_off() || __nospectre_bhb ||
1004 	    arm64_get_spectre_v2_state() == SPECTRE_VULNERABLE)
1005 		return;
1006 
1007 	if (capable(CAP_SYS_ADMIN))
1008 		return;
1009 
1010 	if (supports_clearbhb(SCOPE_SYSTEM)) {
1011 		emit(aarch64_insn_gen_hint(AARCH64_INSN_HINT_CLEARBHB), ctx);
1012 		return;
1013 	}
1014 
1015 	if (k) {
1016 		emit_a64_mov_i64(r1, k, ctx);
1017 		emit(A64_B(1), ctx);
1018 		emit(A64_SUBS_I(true, r1, r1, 1), ctx);
1019 		emit(A64_B_(A64_COND_NE, -2), ctx);
1020 		emit(aarch64_insn_gen_dsb(AARCH64_INSN_MB_ISH), ctx);
1021 		emit(aarch64_insn_get_isb_value(), ctx);
1022 	}
1023 
1024 	if (is_spectre_bhb_fw_mitigated()) {
1025 		emit(A64_ORR_I(false, r1, AARCH64_INSN_REG_ZR,
1026 			       ARM_SMCCC_ARCH_WORKAROUND_3), ctx);
1027 		switch (arm_smccc_1_1_get_conduit()) {
1028 		case SMCCC_CONDUIT_HVC:
1029 			emit(aarch64_insn_get_hvc_value(), ctx);
1030 			break;
1031 		case SMCCC_CONDUIT_SMC:
1032 			emit(aarch64_insn_get_smc_value(), ctx);
1033 			break;
1034 		default:
1035 			pr_err_once("Firmware mitigation enabled with unknown conduit\n");
1036 		}
1037 	}
1038 }
1039 
build_epilogue(struct jit_ctx * ctx,bool was_classic)1040 static void build_epilogue(struct jit_ctx *ctx, bool was_classic)
1041 {
1042 	const u8 r0 = bpf2a64[BPF_REG_0];
1043 	const u8 ptr = bpf2a64[TCCNT_PTR];
1044 
1045 	/* We're done with BPF stack */
1046 	if (ctx->stack_size && !ctx->priv_sp_used)
1047 		emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
1048 
1049 	pop_callee_regs(ctx);
1050 
1051 	emit(A64_POP(A64_ZR, ptr, A64_SP), ctx);
1052 
1053 	if (was_classic)
1054 		build_bhb_mitigation(ctx);
1055 
1056 	/* Restore FP/LR registers */
1057 	emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
1058 
1059 	/* Move the return value from bpf:r0 (aka x7) to x0 */
1060 	emit(A64_MOV(1, A64_R(0), r0), ctx);
1061 
1062 	/* Authenticate lr */
1063 	if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
1064 		emit(A64_AUTIASP, ctx);
1065 
1066 	emit(A64_RET(A64_LR), ctx);
1067 }
1068 
1069 #define BPF_FIXUP_OFFSET_MASK	GENMASK(26, 0)
1070 #define BPF_FIXUP_REG_MASK	GENMASK(31, 27)
1071 #define DONT_CLEAR 5 /* Unused ARM64 register from BPF's POV */
1072 
ex_handler_bpf(const struct exception_table_entry * ex,struct pt_regs * regs)1073 bool ex_handler_bpf(const struct exception_table_entry *ex,
1074 		    struct pt_regs *regs)
1075 {
1076 	off_t offset = FIELD_GET(BPF_FIXUP_OFFSET_MASK, ex->fixup);
1077 	int dst_reg = FIELD_GET(BPF_FIXUP_REG_MASK, ex->fixup);
1078 
1079 	if (dst_reg != DONT_CLEAR)
1080 		regs->regs[dst_reg] = 0;
1081 	regs->pc = (unsigned long)&ex->fixup - offset;
1082 	return true;
1083 }
1084 
1085 /* 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)1086 static int add_exception_handler(const struct bpf_insn *insn,
1087 				 struct jit_ctx *ctx,
1088 				 int dst_reg)
1089 {
1090 	off_t ins_offset;
1091 	off_t fixup_offset;
1092 	unsigned long pc;
1093 	struct exception_table_entry *ex;
1094 
1095 	if (!ctx->image)
1096 		/* First pass */
1097 		return 0;
1098 
1099 	if (BPF_MODE(insn->code) != BPF_PROBE_MEM &&
1100 		BPF_MODE(insn->code) != BPF_PROBE_MEMSX &&
1101 			BPF_MODE(insn->code) != BPF_PROBE_MEM32 &&
1102 				BPF_MODE(insn->code) != BPF_PROBE_ATOMIC)
1103 		return 0;
1104 
1105 	if (!ctx->prog->aux->extable ||
1106 	    WARN_ON_ONCE(ctx->exentry_idx >= ctx->prog->aux->num_exentries))
1107 		return -EINVAL;
1108 
1109 	ex = &ctx->prog->aux->extable[ctx->exentry_idx];
1110 	pc = (unsigned long)&ctx->ro_image[ctx->idx - 1];
1111 
1112 	/*
1113 	 * This is the relative offset of the instruction that may fault from
1114 	 * the exception table itself. This will be written to the exception
1115 	 * table and if this instruction faults, the destination register will
1116 	 * be set to '0' and the execution will jump to the next instruction.
1117 	 */
1118 	ins_offset = pc - (long)&ex->insn;
1119 	if (WARN_ON_ONCE(ins_offset >= 0 || ins_offset < INT_MIN))
1120 		return -ERANGE;
1121 
1122 	/*
1123 	 * Since the extable follows the program, the fixup offset is always
1124 	 * negative and limited to BPF_JIT_REGION_SIZE. Store a positive value
1125 	 * to keep things simple, and put the destination register in the upper
1126 	 * bits. We don't need to worry about buildtime or runtime sort
1127 	 * modifying the upper bits because the table is already sorted, and
1128 	 * isn't part of the main exception table.
1129 	 *
1130 	 * The fixup_offset is set to the next instruction from the instruction
1131 	 * that may fault. The execution will jump to this after handling the
1132 	 * fault.
1133 	 */
1134 	fixup_offset = (long)&ex->fixup - (pc + AARCH64_INSN_SIZE);
1135 	if (!FIELD_FIT(BPF_FIXUP_OFFSET_MASK, fixup_offset))
1136 		return -ERANGE;
1137 
1138 	/*
1139 	 * The offsets above have been calculated using the RO buffer but we
1140 	 * need to use the R/W buffer for writes.
1141 	 * switch ex to rw buffer for writing.
1142 	 */
1143 	ex = (void *)ctx->image + ((void *)ex - (void *)ctx->ro_image);
1144 
1145 	ex->insn = ins_offset;
1146 
1147 	if (BPF_CLASS(insn->code) != BPF_LDX)
1148 		dst_reg = DONT_CLEAR;
1149 
1150 	ex->fixup = FIELD_PREP(BPF_FIXUP_OFFSET_MASK, fixup_offset) |
1151 		    FIELD_PREP(BPF_FIXUP_REG_MASK, dst_reg);
1152 
1153 	ex->type = EX_TYPE_BPF;
1154 
1155 	ctx->exentry_idx++;
1156 	return 0;
1157 }
1158 
1159 /* JITs an eBPF instruction.
1160  * Returns:
1161  * 0  - successfully JITed an 8-byte eBPF instruction.
1162  * >0 - successfully JITed a 16-byte eBPF instruction.
1163  * <0 - failed to JIT.
1164  */
build_insn(const struct bpf_insn * insn,struct jit_ctx * ctx,bool extra_pass)1165 static int build_insn(const struct bpf_insn *insn, struct jit_ctx *ctx,
1166 		      bool extra_pass)
1167 {
1168 	const u8 code = insn->code;
1169 	u8 dst = bpf2a64[insn->dst_reg];
1170 	u8 src = bpf2a64[insn->src_reg];
1171 	const u8 tmp = bpf2a64[TMP_REG_1];
1172 	const u8 tmp2 = bpf2a64[TMP_REG_2];
1173 	const u8 fp = bpf2a64[BPF_REG_FP];
1174 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
1175 	const u8 priv_sp = bpf2a64[PRIVATE_SP];
1176 	const s16 off = insn->off;
1177 	const s32 imm = insn->imm;
1178 	const int i = insn - ctx->prog->insnsi;
1179 	const bool is64 = BPF_CLASS(code) == BPF_ALU64 ||
1180 			  BPF_CLASS(code) == BPF_JMP;
1181 	u8 jmp_cond;
1182 	s32 jmp_offset;
1183 	u32 a64_insn;
1184 	u8 src_adj;
1185 	u8 dst_adj;
1186 	int off_adj;
1187 	int ret;
1188 	bool sign_extend;
1189 
1190 	switch (code) {
1191 	/* dst = src */
1192 	case BPF_ALU | BPF_MOV | BPF_X:
1193 	case BPF_ALU64 | BPF_MOV | BPF_X:
1194 		if (insn_is_cast_user(insn)) {
1195 			emit(A64_MOV(0, tmp, src), ctx); // 32-bit mov clears the upper 32 bits
1196 			emit_a64_mov_i(0, dst, ctx->user_vm_start >> 32, ctx);
1197 			emit(A64_LSL(1, dst, dst, 32), ctx);
1198 			emit(A64_CBZ(1, tmp, 2), ctx);
1199 			emit(A64_ORR(1, tmp, dst, tmp), ctx);
1200 			emit(A64_MOV(1, dst, tmp), ctx);
1201 			break;
1202 		} else if (insn_is_mov_percpu_addr(insn)) {
1203 			if (dst != src)
1204 				emit(A64_MOV(1, dst, src), ctx);
1205 			if (cpus_have_cap(ARM64_HAS_VIRT_HOST_EXTN))
1206 				emit(A64_MRS_TPIDR_EL2(tmp), ctx);
1207 			else
1208 				emit(A64_MRS_TPIDR_EL1(tmp), ctx);
1209 			emit(A64_ADD(1, dst, dst, tmp), ctx);
1210 			break;
1211 		}
1212 		switch (insn->off) {
1213 		case 0:
1214 			emit(A64_MOV(is64, dst, src), ctx);
1215 			break;
1216 		case 8:
1217 			emit(A64_SXTB(is64, dst, src), ctx);
1218 			break;
1219 		case 16:
1220 			emit(A64_SXTH(is64, dst, src), ctx);
1221 			break;
1222 		case 32:
1223 			emit(A64_SXTW(is64, dst, src), ctx);
1224 			break;
1225 		}
1226 		break;
1227 	/* dst = dst OP src */
1228 	case BPF_ALU | BPF_ADD | BPF_X:
1229 	case BPF_ALU64 | BPF_ADD | BPF_X:
1230 		emit(A64_ADD(is64, dst, dst, src), ctx);
1231 		break;
1232 	case BPF_ALU | BPF_SUB | BPF_X:
1233 	case BPF_ALU64 | BPF_SUB | BPF_X:
1234 		emit(A64_SUB(is64, dst, dst, src), ctx);
1235 		break;
1236 	case BPF_ALU | BPF_AND | BPF_X:
1237 	case BPF_ALU64 | BPF_AND | BPF_X:
1238 		emit(A64_AND(is64, dst, dst, src), ctx);
1239 		break;
1240 	case BPF_ALU | BPF_OR | BPF_X:
1241 	case BPF_ALU64 | BPF_OR | BPF_X:
1242 		emit(A64_ORR(is64, dst, dst, src), ctx);
1243 		break;
1244 	case BPF_ALU | BPF_XOR | BPF_X:
1245 	case BPF_ALU64 | BPF_XOR | BPF_X:
1246 		emit(A64_EOR(is64, dst, dst, src), ctx);
1247 		break;
1248 	case BPF_ALU | BPF_MUL | BPF_X:
1249 	case BPF_ALU64 | BPF_MUL | BPF_X:
1250 		emit(A64_MUL(is64, dst, dst, src), ctx);
1251 		break;
1252 	case BPF_ALU | BPF_DIV | BPF_X:
1253 	case BPF_ALU64 | BPF_DIV | BPF_X:
1254 		if (!off)
1255 			emit(A64_UDIV(is64, dst, dst, src), ctx);
1256 		else
1257 			emit(A64_SDIV(is64, dst, dst, src), ctx);
1258 		break;
1259 	case BPF_ALU | BPF_MOD | BPF_X:
1260 	case BPF_ALU64 | BPF_MOD | BPF_X:
1261 		if (!off)
1262 			emit(A64_UDIV(is64, tmp, dst, src), ctx);
1263 		else
1264 			emit(A64_SDIV(is64, tmp, dst, src), ctx);
1265 		emit(A64_MSUB(is64, dst, dst, tmp, src), ctx);
1266 		break;
1267 	case BPF_ALU | BPF_LSH | BPF_X:
1268 	case BPF_ALU64 | BPF_LSH | BPF_X:
1269 		emit(A64_LSLV(is64, dst, dst, src), ctx);
1270 		break;
1271 	case BPF_ALU | BPF_RSH | BPF_X:
1272 	case BPF_ALU64 | BPF_RSH | BPF_X:
1273 		emit(A64_LSRV(is64, dst, dst, src), ctx);
1274 		break;
1275 	case BPF_ALU | BPF_ARSH | BPF_X:
1276 	case BPF_ALU64 | BPF_ARSH | BPF_X:
1277 		emit(A64_ASRV(is64, dst, dst, src), ctx);
1278 		break;
1279 	/* dst = -dst */
1280 	case BPF_ALU | BPF_NEG:
1281 	case BPF_ALU64 | BPF_NEG:
1282 		emit(A64_NEG(is64, dst, dst), ctx);
1283 		break;
1284 	/* dst = BSWAP##imm(dst) */
1285 	case BPF_ALU | BPF_END | BPF_FROM_LE:
1286 	case BPF_ALU | BPF_END | BPF_FROM_BE:
1287 	case BPF_ALU64 | BPF_END | BPF_FROM_LE:
1288 #ifdef CONFIG_CPU_BIG_ENDIAN
1289 		if (BPF_CLASS(code) == BPF_ALU && BPF_SRC(code) == BPF_FROM_BE)
1290 			goto emit_bswap_uxt;
1291 #else /* !CONFIG_CPU_BIG_ENDIAN */
1292 		if (BPF_CLASS(code) == BPF_ALU && BPF_SRC(code) == BPF_FROM_LE)
1293 			goto emit_bswap_uxt;
1294 #endif
1295 		switch (imm) {
1296 		case 16:
1297 			emit(A64_REV16(is64, dst, dst), ctx);
1298 			/* zero-extend 16 bits into 64 bits */
1299 			emit(A64_UXTH(is64, dst, dst), ctx);
1300 			break;
1301 		case 32:
1302 			emit(A64_REV32(0, dst, dst), ctx);
1303 			/* upper 32 bits already cleared */
1304 			break;
1305 		case 64:
1306 			emit(A64_REV64(dst, dst), ctx);
1307 			break;
1308 		}
1309 		break;
1310 emit_bswap_uxt:
1311 		switch (imm) {
1312 		case 16:
1313 			/* zero-extend 16 bits into 64 bits */
1314 			emit(A64_UXTH(is64, dst, dst), ctx);
1315 			break;
1316 		case 32:
1317 			/* zero-extend 32 bits into 64 bits */
1318 			emit(A64_UXTW(is64, dst, dst), ctx);
1319 			break;
1320 		case 64:
1321 			/* nop */
1322 			break;
1323 		}
1324 		break;
1325 	/* dst = imm */
1326 	case BPF_ALU | BPF_MOV | BPF_K:
1327 	case BPF_ALU64 | BPF_MOV | BPF_K:
1328 		emit_a64_mov_i(is64, dst, imm, ctx);
1329 		break;
1330 	/* dst = dst OP imm */
1331 	case BPF_ALU | BPF_ADD | BPF_K:
1332 	case BPF_ALU64 | BPF_ADD | BPF_K:
1333 		emit_a64_add_i(is64, dst, dst, tmp, imm, ctx);
1334 		break;
1335 	case BPF_ALU | BPF_SUB | BPF_K:
1336 	case BPF_ALU64 | BPF_SUB | BPF_K:
1337 		if (is_addsub_imm(imm)) {
1338 			emit(A64_SUB_I(is64, dst, dst, imm), ctx);
1339 		} else if (is_addsub_imm(-(u32)imm)) {
1340 			emit(A64_ADD_I(is64, dst, dst, -imm), ctx);
1341 		} else {
1342 			emit_a64_mov_i(is64, tmp, imm, ctx);
1343 			emit(A64_SUB(is64, dst, dst, tmp), ctx);
1344 		}
1345 		break;
1346 	case BPF_ALU | BPF_AND | BPF_K:
1347 	case BPF_ALU64 | BPF_AND | BPF_K:
1348 		a64_insn = A64_AND_I(is64, dst, dst, imm);
1349 		if (a64_insn != AARCH64_BREAK_FAULT) {
1350 			emit(a64_insn, ctx);
1351 		} else {
1352 			emit_a64_mov_i(is64, tmp, imm, ctx);
1353 			emit(A64_AND(is64, dst, dst, tmp), ctx);
1354 		}
1355 		break;
1356 	case BPF_ALU | BPF_OR | BPF_K:
1357 	case BPF_ALU64 | BPF_OR | BPF_K:
1358 		a64_insn = A64_ORR_I(is64, dst, dst, imm);
1359 		if (a64_insn != AARCH64_BREAK_FAULT) {
1360 			emit(a64_insn, ctx);
1361 		} else {
1362 			emit_a64_mov_i(is64, tmp, imm, ctx);
1363 			emit(A64_ORR(is64, dst, dst, tmp), ctx);
1364 		}
1365 		break;
1366 	case BPF_ALU | BPF_XOR | BPF_K:
1367 	case BPF_ALU64 | BPF_XOR | BPF_K:
1368 		a64_insn = A64_EOR_I(is64, dst, dst, imm);
1369 		if (a64_insn != AARCH64_BREAK_FAULT) {
1370 			emit(a64_insn, ctx);
1371 		} else {
1372 			emit_a64_mov_i(is64, tmp, imm, ctx);
1373 			emit(A64_EOR(is64, dst, dst, tmp), ctx);
1374 		}
1375 		break;
1376 	case BPF_ALU | BPF_MUL | BPF_K:
1377 	case BPF_ALU64 | BPF_MUL | BPF_K:
1378 		emit_a64_mov_i(is64, tmp, imm, ctx);
1379 		emit(A64_MUL(is64, dst, dst, tmp), ctx);
1380 		break;
1381 	case BPF_ALU | BPF_DIV | BPF_K:
1382 	case BPF_ALU64 | BPF_DIV | BPF_K:
1383 		emit_a64_mov_i(is64, tmp, imm, ctx);
1384 		if (!off)
1385 			emit(A64_UDIV(is64, dst, dst, tmp), ctx);
1386 		else
1387 			emit(A64_SDIV(is64, dst, dst, tmp), ctx);
1388 		break;
1389 	case BPF_ALU | BPF_MOD | BPF_K:
1390 	case BPF_ALU64 | BPF_MOD | BPF_K:
1391 		emit_a64_mov_i(is64, tmp2, imm, ctx);
1392 		if (!off)
1393 			emit(A64_UDIV(is64, tmp, dst, tmp2), ctx);
1394 		else
1395 			emit(A64_SDIV(is64, tmp, dst, tmp2), ctx);
1396 		emit(A64_MSUB(is64, dst, dst, tmp, tmp2), ctx);
1397 		break;
1398 	case BPF_ALU | BPF_LSH | BPF_K:
1399 	case BPF_ALU64 | BPF_LSH | BPF_K:
1400 		emit(A64_LSL(is64, dst, dst, imm), ctx);
1401 		break;
1402 	case BPF_ALU | BPF_RSH | BPF_K:
1403 	case BPF_ALU64 | BPF_RSH | BPF_K:
1404 		emit(A64_LSR(is64, dst, dst, imm), ctx);
1405 		break;
1406 	case BPF_ALU | BPF_ARSH | BPF_K:
1407 	case BPF_ALU64 | BPF_ARSH | BPF_K:
1408 		emit(A64_ASR(is64, dst, dst, imm), ctx);
1409 		break;
1410 
1411 	/* JUMP off */
1412 	case BPF_JMP | BPF_JA:
1413 	case BPF_JMP32 | BPF_JA:
1414 		if (BPF_CLASS(code) == BPF_JMP)
1415 			jmp_offset = bpf2a64_offset(i, off, ctx);
1416 		else
1417 			jmp_offset = bpf2a64_offset(i, imm, ctx);
1418 		check_imm26(jmp_offset);
1419 		emit(A64_B(jmp_offset), ctx);
1420 		break;
1421 	/* IF (dst COND src) JUMP off */
1422 	case BPF_JMP | BPF_JEQ | BPF_X:
1423 	case BPF_JMP | BPF_JGT | BPF_X:
1424 	case BPF_JMP | BPF_JLT | BPF_X:
1425 	case BPF_JMP | BPF_JGE | BPF_X:
1426 	case BPF_JMP | BPF_JLE | BPF_X:
1427 	case BPF_JMP | BPF_JNE | BPF_X:
1428 	case BPF_JMP | BPF_JSGT | BPF_X:
1429 	case BPF_JMP | BPF_JSLT | BPF_X:
1430 	case BPF_JMP | BPF_JSGE | BPF_X:
1431 	case BPF_JMP | BPF_JSLE | BPF_X:
1432 	case BPF_JMP32 | BPF_JEQ | BPF_X:
1433 	case BPF_JMP32 | BPF_JGT | BPF_X:
1434 	case BPF_JMP32 | BPF_JLT | BPF_X:
1435 	case BPF_JMP32 | BPF_JGE | BPF_X:
1436 	case BPF_JMP32 | BPF_JLE | BPF_X:
1437 	case BPF_JMP32 | BPF_JNE | BPF_X:
1438 	case BPF_JMP32 | BPF_JSGT | BPF_X:
1439 	case BPF_JMP32 | BPF_JSLT | BPF_X:
1440 	case BPF_JMP32 | BPF_JSGE | BPF_X:
1441 	case BPF_JMP32 | BPF_JSLE | BPF_X:
1442 		emit(A64_CMP(is64, dst, src), ctx);
1443 emit_cond_jmp:
1444 		jmp_offset = bpf2a64_offset(i, off, ctx);
1445 		check_imm19(jmp_offset);
1446 		switch (BPF_OP(code)) {
1447 		case BPF_JEQ:
1448 			jmp_cond = A64_COND_EQ;
1449 			break;
1450 		case BPF_JGT:
1451 			jmp_cond = A64_COND_HI;
1452 			break;
1453 		case BPF_JLT:
1454 			jmp_cond = A64_COND_CC;
1455 			break;
1456 		case BPF_JGE:
1457 			jmp_cond = A64_COND_CS;
1458 			break;
1459 		case BPF_JLE:
1460 			jmp_cond = A64_COND_LS;
1461 			break;
1462 		case BPF_JSET:
1463 		case BPF_JNE:
1464 			jmp_cond = A64_COND_NE;
1465 			break;
1466 		case BPF_JSGT:
1467 			jmp_cond = A64_COND_GT;
1468 			break;
1469 		case BPF_JSLT:
1470 			jmp_cond = A64_COND_LT;
1471 			break;
1472 		case BPF_JSGE:
1473 			jmp_cond = A64_COND_GE;
1474 			break;
1475 		case BPF_JSLE:
1476 			jmp_cond = A64_COND_LE;
1477 			break;
1478 		default:
1479 			return -EFAULT;
1480 		}
1481 		emit(A64_B_(jmp_cond, jmp_offset), ctx);
1482 		break;
1483 	case BPF_JMP | BPF_JSET | BPF_X:
1484 	case BPF_JMP32 | BPF_JSET | BPF_X:
1485 		emit(A64_TST(is64, dst, src), ctx);
1486 		goto emit_cond_jmp;
1487 	/* IF (dst COND imm) JUMP off */
1488 	case BPF_JMP | BPF_JEQ | BPF_K:
1489 	case BPF_JMP | BPF_JGT | BPF_K:
1490 	case BPF_JMP | BPF_JLT | BPF_K:
1491 	case BPF_JMP | BPF_JGE | BPF_K:
1492 	case BPF_JMP | BPF_JLE | BPF_K:
1493 	case BPF_JMP | BPF_JNE | BPF_K:
1494 	case BPF_JMP | BPF_JSGT | BPF_K:
1495 	case BPF_JMP | BPF_JSLT | BPF_K:
1496 	case BPF_JMP | BPF_JSGE | BPF_K:
1497 	case BPF_JMP | BPF_JSLE | BPF_K:
1498 	case BPF_JMP32 | BPF_JEQ | BPF_K:
1499 	case BPF_JMP32 | BPF_JGT | BPF_K:
1500 	case BPF_JMP32 | BPF_JLT | BPF_K:
1501 	case BPF_JMP32 | BPF_JGE | BPF_K:
1502 	case BPF_JMP32 | BPF_JLE | BPF_K:
1503 	case BPF_JMP32 | BPF_JNE | BPF_K:
1504 	case BPF_JMP32 | BPF_JSGT | BPF_K:
1505 	case BPF_JMP32 | BPF_JSLT | BPF_K:
1506 	case BPF_JMP32 | BPF_JSGE | BPF_K:
1507 	case BPF_JMP32 | BPF_JSLE | BPF_K:
1508 		if (is_addsub_imm(imm)) {
1509 			emit(A64_CMP_I(is64, dst, imm), ctx);
1510 		} else if (is_addsub_imm(-(u32)imm)) {
1511 			emit(A64_CMN_I(is64, dst, -imm), ctx);
1512 		} else {
1513 			emit_a64_mov_i(is64, tmp, imm, ctx);
1514 			emit(A64_CMP(is64, dst, tmp), ctx);
1515 		}
1516 		goto emit_cond_jmp;
1517 	case BPF_JMP | BPF_JSET | BPF_K:
1518 	case BPF_JMP32 | BPF_JSET | BPF_K:
1519 		a64_insn = A64_TST_I(is64, dst, imm);
1520 		if (a64_insn != AARCH64_BREAK_FAULT) {
1521 			emit(a64_insn, ctx);
1522 		} else {
1523 			emit_a64_mov_i(is64, tmp, imm, ctx);
1524 			emit(A64_TST(is64, dst, tmp), ctx);
1525 		}
1526 		goto emit_cond_jmp;
1527 	/* function call */
1528 	case BPF_JMP | BPF_CALL:
1529 	{
1530 		const u8 r0 = bpf2a64[BPF_REG_0];
1531 		bool func_addr_fixed;
1532 		u64 func_addr;
1533 		u32 cpu_offset;
1534 
1535 		/* Implement helper call to bpf_get_smp_processor_id() inline */
1536 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_get_smp_processor_id) {
1537 			cpu_offset = offsetof(struct thread_info, cpu);
1538 
1539 			emit(A64_MRS_SP_EL0(tmp), ctx);
1540 			if (is_lsi_offset(cpu_offset, 2)) {
1541 				emit(A64_LDR32I(r0, tmp, cpu_offset), ctx);
1542 			} else {
1543 				emit_a64_mov_i(1, tmp2, cpu_offset, ctx);
1544 				emit(A64_LDR32(r0, tmp, tmp2), ctx);
1545 			}
1546 			break;
1547 		}
1548 
1549 		/* Implement helper call to bpf_get_current_task/_btf() inline */
1550 		if (insn->src_reg == 0 && (insn->imm == BPF_FUNC_get_current_task ||
1551 					   insn->imm == BPF_FUNC_get_current_task_btf)) {
1552 			emit(A64_MRS_SP_EL0(r0), ctx);
1553 			break;
1554 		}
1555 
1556 		ret = bpf_jit_get_func_addr(ctx->prog, insn, extra_pass,
1557 					    &func_addr, &func_addr_fixed);
1558 		if (ret < 0)
1559 			return ret;
1560 		emit_call(func_addr, ctx);
1561 		emit(A64_MOV(1, r0, A64_R(0)), ctx);
1562 		break;
1563 	}
1564 	/* tail call */
1565 	case BPF_JMP | BPF_TAIL_CALL:
1566 		if (emit_bpf_tail_call(ctx))
1567 			return -EFAULT;
1568 		break;
1569 	/* function return */
1570 	case BPF_JMP | BPF_EXIT:
1571 		/* Optimization: when last instruction is EXIT,
1572 		   simply fallthrough to epilogue. */
1573 		if (i == ctx->prog->len - 1)
1574 			break;
1575 		jmp_offset = epilogue_offset(ctx);
1576 		check_imm26(jmp_offset);
1577 		emit(A64_B(jmp_offset), ctx);
1578 		break;
1579 
1580 	/* dst = imm64 */
1581 	case BPF_LD | BPF_IMM | BPF_DW:
1582 	{
1583 		const struct bpf_insn insn1 = insn[1];
1584 		u64 imm64;
1585 
1586 		imm64 = (u64)insn1.imm << 32 | (u32)imm;
1587 		if (bpf_pseudo_func(insn))
1588 			emit_addr_mov_i64(dst, imm64, ctx);
1589 		else
1590 			emit_a64_mov_i64(dst, imm64, ctx);
1591 
1592 		return 1;
1593 	}
1594 
1595 	/* LDX: dst = (u64)*(unsigned size *)(src + off) */
1596 	case BPF_LDX | BPF_MEM | BPF_W:
1597 	case BPF_LDX | BPF_MEM | BPF_H:
1598 	case BPF_LDX | BPF_MEM | BPF_B:
1599 	case BPF_LDX | BPF_MEM | BPF_DW:
1600 	case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
1601 	case BPF_LDX | BPF_PROBE_MEM | BPF_W:
1602 	case BPF_LDX | BPF_PROBE_MEM | BPF_H:
1603 	case BPF_LDX | BPF_PROBE_MEM | BPF_B:
1604 	/* LDXS: dst_reg = (s64)*(signed size *)(src_reg + off) */
1605 	case BPF_LDX | BPF_MEMSX | BPF_B:
1606 	case BPF_LDX | BPF_MEMSX | BPF_H:
1607 	case BPF_LDX | BPF_MEMSX | BPF_W:
1608 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
1609 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
1610 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
1611 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_B:
1612 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
1613 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
1614 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
1615 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) {
1616 			emit(A64_ADD(1, tmp2, src, arena_vm_base), ctx);
1617 			src = tmp2;
1618 		}
1619 		if (src == fp) {
1620 			src_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
1621 			off_adj = off + ctx->stack_size;
1622 		} else {
1623 			src_adj = src;
1624 			off_adj = off;
1625 		}
1626 		sign_extend = (BPF_MODE(insn->code) == BPF_MEMSX ||
1627 				BPF_MODE(insn->code) == BPF_PROBE_MEMSX);
1628 		switch (BPF_SIZE(code)) {
1629 		case BPF_W:
1630 			if (is_lsi_offset(off_adj, 2)) {
1631 				if (sign_extend)
1632 					emit(A64_LDRSWI(dst, src_adj, off_adj), ctx);
1633 				else
1634 					emit(A64_LDR32I(dst, src_adj, off_adj), ctx);
1635 			} else {
1636 				emit_a64_mov_i(1, tmp, off, ctx);
1637 				if (sign_extend)
1638 					emit(A64_LDRSW(dst, src, tmp), ctx);
1639 				else
1640 					emit(A64_LDR32(dst, src, tmp), ctx);
1641 			}
1642 			break;
1643 		case BPF_H:
1644 			if (is_lsi_offset(off_adj, 1)) {
1645 				if (sign_extend)
1646 					emit(A64_LDRSHI(dst, src_adj, off_adj), ctx);
1647 				else
1648 					emit(A64_LDRHI(dst, src_adj, off_adj), ctx);
1649 			} else {
1650 				emit_a64_mov_i(1, tmp, off, ctx);
1651 				if (sign_extend)
1652 					emit(A64_LDRSH(dst, src, tmp), ctx);
1653 				else
1654 					emit(A64_LDRH(dst, src, tmp), ctx);
1655 			}
1656 			break;
1657 		case BPF_B:
1658 			if (is_lsi_offset(off_adj, 0)) {
1659 				if (sign_extend)
1660 					emit(A64_LDRSBI(dst, src_adj, off_adj), ctx);
1661 				else
1662 					emit(A64_LDRBI(dst, src_adj, off_adj), ctx);
1663 			} else {
1664 				emit_a64_mov_i(1, tmp, off, ctx);
1665 				if (sign_extend)
1666 					emit(A64_LDRSB(dst, src, tmp), ctx);
1667 				else
1668 					emit(A64_LDRB(dst, src, tmp), ctx);
1669 			}
1670 			break;
1671 		case BPF_DW:
1672 			if (is_lsi_offset(off_adj, 3)) {
1673 				emit(A64_LDR64I(dst, src_adj, off_adj), ctx);
1674 			} else {
1675 				emit_a64_mov_i(1, tmp, off, ctx);
1676 				emit(A64_LDR64(dst, src, tmp), ctx);
1677 			}
1678 			break;
1679 		}
1680 
1681 		ret = add_exception_handler(insn, ctx, dst);
1682 		if (ret)
1683 			return ret;
1684 		break;
1685 
1686 	/* speculation barrier against v1 and v4 */
1687 	case BPF_ST | BPF_NOSPEC:
1688 		if (alternative_has_cap_likely(ARM64_HAS_SB)) {
1689 			emit(A64_SB, ctx);
1690 		} else {
1691 			emit(A64_DSB_NSH, ctx);
1692 			emit(A64_ISB, ctx);
1693 		}
1694 		break;
1695 
1696 	/* ST: *(size *)(dst + off) = imm */
1697 	case BPF_ST | BPF_MEM | BPF_W:
1698 	case BPF_ST | BPF_MEM | BPF_H:
1699 	case BPF_ST | BPF_MEM | BPF_B:
1700 	case BPF_ST | BPF_MEM | BPF_DW:
1701 	case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
1702 	case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
1703 	case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
1704 	case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
1705 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) {
1706 			emit(A64_ADD(1, tmp2, dst, arena_vm_base), ctx);
1707 			dst = tmp2;
1708 		}
1709 		if (dst == fp) {
1710 			dst_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
1711 			off_adj = off + ctx->stack_size;
1712 		} else {
1713 			dst_adj = dst;
1714 			off_adj = off;
1715 		}
1716 		/* Load imm to a register then store it */
1717 		emit_a64_mov_i(1, tmp, imm, ctx);
1718 		switch (BPF_SIZE(code)) {
1719 		case BPF_W:
1720 			if (is_lsi_offset(off_adj, 2)) {
1721 				emit(A64_STR32I(tmp, dst_adj, off_adj), ctx);
1722 			} else {
1723 				emit_a64_mov_i(1, tmp2, off, ctx);
1724 				emit(A64_STR32(tmp, dst, tmp2), ctx);
1725 			}
1726 			break;
1727 		case BPF_H:
1728 			if (is_lsi_offset(off_adj, 1)) {
1729 				emit(A64_STRHI(tmp, dst_adj, off_adj), ctx);
1730 			} else {
1731 				emit_a64_mov_i(1, tmp2, off, ctx);
1732 				emit(A64_STRH(tmp, dst, tmp2), ctx);
1733 			}
1734 			break;
1735 		case BPF_B:
1736 			if (is_lsi_offset(off_adj, 0)) {
1737 				emit(A64_STRBI(tmp, dst_adj, off_adj), ctx);
1738 			} else {
1739 				emit_a64_mov_i(1, tmp2, off, ctx);
1740 				emit(A64_STRB(tmp, dst, tmp2), ctx);
1741 			}
1742 			break;
1743 		case BPF_DW:
1744 			if (is_lsi_offset(off_adj, 3)) {
1745 				emit(A64_STR64I(tmp, dst_adj, off_adj), ctx);
1746 			} else {
1747 				emit_a64_mov_i(1, tmp2, off, ctx);
1748 				emit(A64_STR64(tmp, dst, tmp2), ctx);
1749 			}
1750 			break;
1751 		}
1752 
1753 		ret = add_exception_handler(insn, ctx, dst);
1754 		if (ret)
1755 			return ret;
1756 		break;
1757 
1758 	/* STX: *(size *)(dst + off) = src */
1759 	case BPF_STX | BPF_MEM | BPF_W:
1760 	case BPF_STX | BPF_MEM | BPF_H:
1761 	case BPF_STX | BPF_MEM | BPF_B:
1762 	case BPF_STX | BPF_MEM | BPF_DW:
1763 	case BPF_STX | BPF_PROBE_MEM32 | BPF_B:
1764 	case BPF_STX | BPF_PROBE_MEM32 | BPF_H:
1765 	case BPF_STX | BPF_PROBE_MEM32 | BPF_W:
1766 	case BPF_STX | BPF_PROBE_MEM32 | BPF_DW:
1767 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) {
1768 			emit(A64_ADD(1, tmp2, dst, arena_vm_base), ctx);
1769 			dst = tmp2;
1770 		}
1771 		if (dst == fp) {
1772 			dst_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
1773 			off_adj = off + ctx->stack_size;
1774 		} else {
1775 			dst_adj = dst;
1776 			off_adj = off;
1777 		}
1778 		switch (BPF_SIZE(code)) {
1779 		case BPF_W:
1780 			if (is_lsi_offset(off_adj, 2)) {
1781 				emit(A64_STR32I(src, dst_adj, off_adj), ctx);
1782 			} else {
1783 				emit_a64_mov_i(1, tmp, off, ctx);
1784 				emit(A64_STR32(src, dst, tmp), ctx);
1785 			}
1786 			break;
1787 		case BPF_H:
1788 			if (is_lsi_offset(off_adj, 1)) {
1789 				emit(A64_STRHI(src, dst_adj, off_adj), ctx);
1790 			} else {
1791 				emit_a64_mov_i(1, tmp, off, ctx);
1792 				emit(A64_STRH(src, dst, tmp), ctx);
1793 			}
1794 			break;
1795 		case BPF_B:
1796 			if (is_lsi_offset(off_adj, 0)) {
1797 				emit(A64_STRBI(src, dst_adj, off_adj), ctx);
1798 			} else {
1799 				emit_a64_mov_i(1, tmp, off, ctx);
1800 				emit(A64_STRB(src, dst, tmp), ctx);
1801 			}
1802 			break;
1803 		case BPF_DW:
1804 			if (is_lsi_offset(off_adj, 3)) {
1805 				emit(A64_STR64I(src, dst_adj, off_adj), ctx);
1806 			} else {
1807 				emit_a64_mov_i(1, tmp, off, ctx);
1808 				emit(A64_STR64(src, dst, tmp), ctx);
1809 			}
1810 			break;
1811 		}
1812 
1813 		ret = add_exception_handler(insn, ctx, dst);
1814 		if (ret)
1815 			return ret;
1816 		break;
1817 
1818 	case BPF_STX | BPF_ATOMIC | BPF_B:
1819 	case BPF_STX | BPF_ATOMIC | BPF_H:
1820 	case BPF_STX | BPF_ATOMIC | BPF_W:
1821 	case BPF_STX | BPF_ATOMIC | BPF_DW:
1822 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_B:
1823 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_H:
1824 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_W:
1825 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
1826 		if (bpf_atomic_is_load_store(insn))
1827 			ret = emit_atomic_ld_st(insn, ctx);
1828 		else if (cpus_have_cap(ARM64_HAS_LSE_ATOMICS))
1829 			ret = emit_lse_atomic(insn, ctx);
1830 		else
1831 			ret = emit_ll_sc_atomic(insn, ctx);
1832 		if (ret)
1833 			return ret;
1834 
1835 		ret = add_exception_handler(insn, ctx, dst);
1836 		if (ret)
1837 			return ret;
1838 		break;
1839 
1840 	default:
1841 		pr_err_once("unknown opcode %02x\n", code);
1842 		return -EINVAL;
1843 	}
1844 
1845 	return 0;
1846 }
1847 
build_body(struct jit_ctx * ctx,bool extra_pass)1848 static int build_body(struct jit_ctx *ctx, bool extra_pass)
1849 {
1850 	const struct bpf_prog *prog = ctx->prog;
1851 	int i;
1852 
1853 	/*
1854 	 * - offset[0] offset of the end of prologue,
1855 	 *   start of the 1st instruction.
1856 	 * - offset[1] - offset of the end of 1st instruction,
1857 	 *   start of the 2nd instruction
1858 	 * [....]
1859 	 * - offset[3] - offset of the end of 3rd instruction,
1860 	 *   start of 4th instruction
1861 	 */
1862 	for (i = 0; i < prog->len; i++) {
1863 		const struct bpf_insn *insn = &prog->insnsi[i];
1864 		int ret;
1865 
1866 		ctx->offset[i] = ctx->idx;
1867 		ret = build_insn(insn, ctx, extra_pass);
1868 		if (ret > 0) {
1869 			i++;
1870 			ctx->offset[i] = ctx->idx;
1871 			continue;
1872 		}
1873 		if (ret)
1874 			return ret;
1875 	}
1876 	/*
1877 	 * offset is allocated with prog->len + 1 so fill in
1878 	 * the last element with the offset after the last
1879 	 * instruction (end of program)
1880 	 */
1881 	ctx->offset[i] = ctx->idx;
1882 
1883 	return 0;
1884 }
1885 
validate_code(struct jit_ctx * ctx)1886 static int validate_code(struct jit_ctx *ctx)
1887 {
1888 	int i;
1889 
1890 	for (i = 0; i < ctx->idx; i++) {
1891 		u32 a64_insn = le32_to_cpu(ctx->image[i]);
1892 
1893 		if (a64_insn == AARCH64_BREAK_FAULT)
1894 			return -1;
1895 	}
1896 	return 0;
1897 }
1898 
validate_ctx(struct jit_ctx * ctx)1899 static int validate_ctx(struct jit_ctx *ctx)
1900 {
1901 	if (validate_code(ctx))
1902 		return -1;
1903 
1904 	if (WARN_ON_ONCE(ctx->exentry_idx != ctx->prog->aux->num_exentries))
1905 		return -1;
1906 
1907 	return 0;
1908 }
1909 
bpf_flush_icache(void * start,void * end)1910 static inline void bpf_flush_icache(void *start, void *end)
1911 {
1912 	flush_icache_range((unsigned long)start, (unsigned long)end);
1913 }
1914 
priv_stack_init_guard(void __percpu * priv_stack_ptr,int alloc_size)1915 static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
1916 {
1917 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
1918 	u64 *stack_ptr;
1919 
1920 	for_each_possible_cpu(cpu) {
1921 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
1922 		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
1923 		stack_ptr[1] = PRIV_STACK_GUARD_VAL;
1924 		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
1925 		stack_ptr[underflow_idx + 1] = PRIV_STACK_GUARD_VAL;
1926 	}
1927 }
1928 
priv_stack_check_guard(void __percpu * priv_stack_ptr,int alloc_size,struct bpf_prog * prog)1929 static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
1930 				   struct bpf_prog *prog)
1931 {
1932 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
1933 	u64 *stack_ptr;
1934 
1935 	for_each_possible_cpu(cpu) {
1936 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
1937 		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
1938 		    stack_ptr[1] != PRIV_STACK_GUARD_VAL ||
1939 		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL ||
1940 		    stack_ptr[underflow_idx + 1] != PRIV_STACK_GUARD_VAL) {
1941 			pr_err("BPF private stack overflow/underflow detected for prog %sx\n",
1942 			       bpf_jit_get_prog_name(prog));
1943 			break;
1944 		}
1945 	}
1946 }
1947 
1948 struct arm64_jit_data {
1949 	struct bpf_binary_header *header;
1950 	u8 *ro_image;
1951 	struct bpf_binary_header *ro_header;
1952 	struct jit_ctx ctx;
1953 };
1954 
bpf_int_jit_compile(struct bpf_prog * prog)1955 struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
1956 {
1957 	int image_size, prog_size, extable_size, extable_align, extable_offset;
1958 	struct bpf_prog *tmp, *orig_prog = prog;
1959 	struct bpf_binary_header *header;
1960 	struct bpf_binary_header *ro_header = NULL;
1961 	struct arm64_jit_data *jit_data;
1962 	void __percpu *priv_stack_ptr = NULL;
1963 	bool was_classic = bpf_prog_was_classic(prog);
1964 	int priv_stack_alloc_sz;
1965 	bool tmp_blinded = false;
1966 	bool extra_pass = false;
1967 	struct jit_ctx ctx;
1968 	u8 *image_ptr;
1969 	u8 *ro_image_ptr;
1970 	int body_idx;
1971 	int exentry_idx;
1972 
1973 	if (!prog->jit_requested)
1974 		return orig_prog;
1975 
1976 	tmp = bpf_jit_blind_constants(prog);
1977 	/* If blinding was requested and we failed during blinding,
1978 	 * we must fall back to the interpreter.
1979 	 */
1980 	if (IS_ERR(tmp))
1981 		return orig_prog;
1982 	if (tmp != prog) {
1983 		tmp_blinded = true;
1984 		prog = tmp;
1985 	}
1986 
1987 	jit_data = prog->aux->jit_data;
1988 	if (!jit_data) {
1989 		jit_data = kzalloc(sizeof(*jit_data), GFP_KERNEL);
1990 		if (!jit_data) {
1991 			prog = orig_prog;
1992 			goto out;
1993 		}
1994 		prog->aux->jit_data = jit_data;
1995 	}
1996 	priv_stack_ptr = prog->aux->priv_stack_ptr;
1997 	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
1998 		/* Allocate actual private stack size with verifier-calculated
1999 		 * stack size plus two memory guards to protect overflow and
2000 		 * underflow.
2001 		 */
2002 		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
2003 				      2 * PRIV_STACK_GUARD_SZ;
2004 		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 16, GFP_KERNEL);
2005 		if (!priv_stack_ptr) {
2006 			prog = orig_prog;
2007 			goto out_priv_stack;
2008 		}
2009 
2010 		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
2011 		prog->aux->priv_stack_ptr = priv_stack_ptr;
2012 	}
2013 	if (jit_data->ctx.offset) {
2014 		ctx = jit_data->ctx;
2015 		ro_image_ptr = jit_data->ro_image;
2016 		ro_header = jit_data->ro_header;
2017 		header = jit_data->header;
2018 		image_ptr = (void *)header + ((void *)ro_image_ptr
2019 						 - (void *)ro_header);
2020 		extra_pass = true;
2021 		prog_size = sizeof(u32) * ctx.idx;
2022 		goto skip_init_ctx;
2023 	}
2024 	memset(&ctx, 0, sizeof(ctx));
2025 	ctx.prog = prog;
2026 
2027 	ctx.offset = kvcalloc(prog->len + 1, sizeof(int), GFP_KERNEL);
2028 	if (ctx.offset == NULL) {
2029 		prog = orig_prog;
2030 		goto out_off;
2031 	}
2032 
2033 	ctx.user_vm_start = bpf_arena_get_user_vm_start(prog->aux->arena);
2034 	ctx.arena_vm_start = bpf_arena_get_kern_vm_start(prog->aux->arena);
2035 
2036 	if (priv_stack_ptr)
2037 		ctx.priv_sp_used = true;
2038 
2039 	/* Pass 1: Estimate the maximum image size.
2040 	 *
2041 	 * BPF line info needs ctx->offset[i] to be the offset of
2042 	 * instruction[i] in jited image, so build prologue first.
2043 	 */
2044 	if (build_prologue(&ctx, was_classic)) {
2045 		prog = orig_prog;
2046 		goto out_off;
2047 	}
2048 
2049 	if (build_body(&ctx, extra_pass)) {
2050 		prog = orig_prog;
2051 		goto out_off;
2052 	}
2053 
2054 	ctx.epilogue_offset = ctx.idx;
2055 	build_epilogue(&ctx, was_classic);
2056 	build_plt(&ctx);
2057 
2058 	extable_align = __alignof__(struct exception_table_entry);
2059 	extable_size = prog->aux->num_exentries *
2060 		sizeof(struct exception_table_entry);
2061 
2062 	/* Now we know the maximum image size. */
2063 	prog_size = sizeof(u32) * ctx.idx;
2064 	/* also allocate space for plt target */
2065 	extable_offset = round_up(prog_size + PLT_TARGET_SIZE, extable_align);
2066 	image_size = extable_offset + extable_size;
2067 	ro_header = bpf_jit_binary_pack_alloc(image_size, &ro_image_ptr,
2068 					      sizeof(u32), &header, &image_ptr,
2069 					      jit_fill_hole);
2070 	if (!ro_header) {
2071 		prog = orig_prog;
2072 		goto out_off;
2073 	}
2074 
2075 	/* Pass 2: Determine jited position and result for each instruction */
2076 
2077 	/*
2078 	 * Use the image(RW) for writing the JITed instructions. But also save
2079 	 * the ro_image(RX) for calculating the offsets in the image. The RW
2080 	 * image will be later copied to the RX image from where the program
2081 	 * will run. The bpf_jit_binary_pack_finalize() will do this copy in the
2082 	 * final step.
2083 	 */
2084 	ctx.image = (__le32 *)image_ptr;
2085 	ctx.ro_image = (__le32 *)ro_image_ptr;
2086 	if (extable_size)
2087 		prog->aux->extable = (void *)ro_image_ptr + extable_offset;
2088 skip_init_ctx:
2089 	ctx.idx = 0;
2090 	ctx.exentry_idx = 0;
2091 	ctx.write = true;
2092 
2093 	build_prologue(&ctx, was_classic);
2094 
2095 	/* Record exentry_idx and body_idx before first build_body */
2096 	exentry_idx = ctx.exentry_idx;
2097 	body_idx = ctx.idx;
2098 	/* Dont write body instructions to memory for now */
2099 	ctx.write = false;
2100 
2101 	if (build_body(&ctx, extra_pass)) {
2102 		prog = orig_prog;
2103 		goto out_free_hdr;
2104 	}
2105 
2106 	ctx.epilogue_offset = ctx.idx;
2107 	ctx.exentry_idx = exentry_idx;
2108 	ctx.idx = body_idx;
2109 	ctx.write = true;
2110 
2111 	/* Pass 3: Adjust jump offset and write final image */
2112 	if (build_body(&ctx, extra_pass) ||
2113 		WARN_ON_ONCE(ctx.idx != ctx.epilogue_offset)) {
2114 		prog = orig_prog;
2115 		goto out_free_hdr;
2116 	}
2117 
2118 	build_epilogue(&ctx, was_classic);
2119 	build_plt(&ctx);
2120 
2121 	/* Extra pass to validate JITed code. */
2122 	if (validate_ctx(&ctx)) {
2123 		prog = orig_prog;
2124 		goto out_free_hdr;
2125 	}
2126 
2127 	/* update the real prog size */
2128 	prog_size = sizeof(u32) * ctx.idx;
2129 
2130 	/* And we're done. */
2131 	if (bpf_jit_enable > 1)
2132 		bpf_jit_dump(prog->len, prog_size, 2, ctx.image);
2133 
2134 	if (!prog->is_func || extra_pass) {
2135 		/* The jited image may shrink since the jited result for
2136 		 * BPF_CALL to subprog may be changed from indirect call
2137 		 * to direct call.
2138 		 */
2139 		if (extra_pass && ctx.idx > jit_data->ctx.idx) {
2140 			pr_err_once("multi-func JIT bug %d > %d\n",
2141 				    ctx.idx, jit_data->ctx.idx);
2142 			prog->bpf_func = NULL;
2143 			prog->jited = 0;
2144 			prog->jited_len = 0;
2145 			goto out_free_hdr;
2146 		}
2147 		if (WARN_ON(bpf_jit_binary_pack_finalize(ro_header, header))) {
2148 			/* ro_header has been freed */
2149 			ro_header = NULL;
2150 			prog = orig_prog;
2151 			goto out_off;
2152 		}
2153 		/*
2154 		 * The instructions have now been copied to the ROX region from
2155 		 * where they will execute. Now the data cache has to be cleaned to
2156 		 * the PoU and the I-cache has to be invalidated for the VAs.
2157 		 */
2158 		bpf_flush_icache(ro_header, ctx.ro_image + ctx.idx);
2159 	} else {
2160 		jit_data->ctx = ctx;
2161 		jit_data->ro_image = ro_image_ptr;
2162 		jit_data->header = header;
2163 		jit_data->ro_header = ro_header;
2164 	}
2165 
2166 	prog->bpf_func = (void *)ctx.ro_image + cfi_get_offset();
2167 	prog->jited = 1;
2168 	prog->jited_len = prog_size - cfi_get_offset();
2169 
2170 	if (!prog->is_func || extra_pass) {
2171 		int i;
2172 
2173 		/* offset[prog->len] is the size of program */
2174 		for (i = 0; i <= prog->len; i++)
2175 			ctx.offset[i] *= AARCH64_INSN_SIZE;
2176 		bpf_prog_fill_jited_linfo(prog, ctx.offset + 1);
2177 out_off:
2178 		if (!ro_header && priv_stack_ptr) {
2179 			free_percpu(priv_stack_ptr);
2180 			prog->aux->priv_stack_ptr = NULL;
2181 		}
2182 		kvfree(ctx.offset);
2183 out_priv_stack:
2184 		kfree(jit_data);
2185 		prog->aux->jit_data = NULL;
2186 	}
2187 out:
2188 	if (tmp_blinded)
2189 		bpf_jit_prog_release_other(prog, prog == orig_prog ?
2190 					   tmp : orig_prog);
2191 	return prog;
2192 
2193 out_free_hdr:
2194 	if (header) {
2195 		bpf_arch_text_copy(&ro_header->size, &header->size,
2196 				   sizeof(header->size));
2197 		bpf_jit_binary_pack_free(ro_header, header);
2198 	}
2199 	goto out_off;
2200 }
2201 
bpf_jit_supports_private_stack(void)2202 bool bpf_jit_supports_private_stack(void)
2203 {
2204 	return true;
2205 }
2206 
bpf_jit_supports_kfunc_call(void)2207 bool bpf_jit_supports_kfunc_call(void)
2208 {
2209 	return true;
2210 }
2211 
bpf_arch_text_copy(void * dst,void * src,size_t len)2212 void *bpf_arch_text_copy(void *dst, void *src, size_t len)
2213 {
2214 	if (!aarch64_insn_copy(dst, src, len))
2215 		return ERR_PTR(-EINVAL);
2216 	return dst;
2217 }
2218 
bpf_jit_alloc_exec_limit(void)2219 u64 bpf_jit_alloc_exec_limit(void)
2220 {
2221 	return VMALLOC_END - VMALLOC_START;
2222 }
2223 
2224 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
bpf_jit_supports_subprog_tailcalls(void)2225 bool bpf_jit_supports_subprog_tailcalls(void)
2226 {
2227 	return true;
2228 }
2229 
invoke_bpf_prog(struct jit_ctx * ctx,struct bpf_tramp_link * l,int bargs_off,int retval_off,int run_ctx_off,bool save_ret)2230 static void invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_link *l,
2231 			    int bargs_off, int retval_off, int run_ctx_off,
2232 			    bool save_ret)
2233 {
2234 	__le32 *branch;
2235 	u64 enter_prog;
2236 	u64 exit_prog;
2237 	struct bpf_prog *p = l->link.prog;
2238 	int cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
2239 
2240 	enter_prog = (u64)bpf_trampoline_enter(p);
2241 	exit_prog = (u64)bpf_trampoline_exit(p);
2242 
2243 	if (l->cookie == 0) {
2244 		/* if cookie is zero, one instruction is enough to store it */
2245 		emit(A64_STR64I(A64_ZR, A64_SP, run_ctx_off + cookie_off), ctx);
2246 	} else {
2247 		emit_a64_mov_i64(A64_R(10), l->cookie, ctx);
2248 		emit(A64_STR64I(A64_R(10), A64_SP, run_ctx_off + cookie_off),
2249 		     ctx);
2250 	}
2251 
2252 	/* save p to callee saved register x19 to avoid loading p with mov_i64
2253 	 * each time.
2254 	 */
2255 	emit_addr_mov_i64(A64_R(19), (const u64)p, ctx);
2256 
2257 	/* arg1: prog */
2258 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
2259 	/* arg2: &run_ctx */
2260 	emit(A64_ADD_I(1, A64_R(1), A64_SP, run_ctx_off), ctx);
2261 
2262 	emit_call(enter_prog, ctx);
2263 
2264 	/* save return value to callee saved register x20 */
2265 	emit(A64_MOV(1, A64_R(20), A64_R(0)), ctx);
2266 
2267 	/* if (__bpf_prog_enter(prog) == 0)
2268 	 *         goto skip_exec_of_prog;
2269 	 */
2270 	branch = ctx->image + ctx->idx;
2271 	emit(A64_NOP, ctx);
2272 
2273 	emit(A64_ADD_I(1, A64_R(0), A64_SP, bargs_off), ctx);
2274 	if (!p->jited)
2275 		emit_addr_mov_i64(A64_R(1), (const u64)p->insnsi, ctx);
2276 
2277 	emit_call((const u64)p->bpf_func, ctx);
2278 
2279 	if (save_ret)
2280 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
2281 
2282 	if (ctx->image) {
2283 		int offset = &ctx->image[ctx->idx] - branch;
2284 		*branch = cpu_to_le32(A64_CBZ(1, A64_R(0), offset));
2285 	}
2286 
2287 	/* arg1: prog */
2288 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
2289 	/* arg2: start time */
2290 	emit(A64_MOV(1, A64_R(1), A64_R(20)), ctx);
2291 	/* arg3: &run_ctx */
2292 	emit(A64_ADD_I(1, A64_R(2), A64_SP, run_ctx_off), ctx);
2293 
2294 	emit_call(exit_prog, ctx);
2295 }
2296 
invoke_bpf_mod_ret(struct jit_ctx * ctx,struct bpf_tramp_links * tl,int bargs_off,int retval_off,int run_ctx_off,__le32 ** branches)2297 static void invoke_bpf_mod_ret(struct jit_ctx *ctx, struct bpf_tramp_links *tl,
2298 			       int bargs_off, int retval_off, int run_ctx_off,
2299 			       __le32 **branches)
2300 {
2301 	int i;
2302 
2303 	/* The first fmod_ret program will receive a garbage return value.
2304 	 * Set this to 0 to avoid confusing the program.
2305 	 */
2306 	emit(A64_STR64I(A64_ZR, A64_SP, retval_off), ctx);
2307 	for (i = 0; i < tl->nr_links; i++) {
2308 		invoke_bpf_prog(ctx, tl->links[i], bargs_off, retval_off,
2309 				run_ctx_off, true);
2310 		/* if (*(u64 *)(sp + retval_off) !=  0)
2311 		 *	goto do_fexit;
2312 		 */
2313 		emit(A64_LDR64I(A64_R(10), A64_SP, retval_off), ctx);
2314 		/* Save the location of branch, and generate a nop.
2315 		 * This nop will be replaced with a cbnz later.
2316 		 */
2317 		branches[i] = ctx->image + ctx->idx;
2318 		emit(A64_NOP, ctx);
2319 	}
2320 }
2321 
2322 struct arg_aux {
2323 	/* how many args are passed through registers, the rest of the args are
2324 	 * passed through stack
2325 	 */
2326 	int args_in_regs;
2327 	/* how many registers are used to pass arguments */
2328 	int regs_for_args;
2329 	/* how much stack is used for additional args passed to bpf program
2330 	 * that did not fit in original function registers
2331 	 */
2332 	int bstack_for_args;
2333 	/* home much stack is used for additional args passed to the
2334 	 * original function when called from trampoline (this one needs
2335 	 * arguments to be properly aligned)
2336 	 */
2337 	int ostack_for_args;
2338 };
2339 
calc_arg_aux(const struct btf_func_model * m,struct arg_aux * a)2340 static int calc_arg_aux(const struct btf_func_model *m,
2341 			 struct arg_aux *a)
2342 {
2343 	int stack_slots, nregs, slots, i;
2344 
2345 	/* verifier ensures m->nr_args <= MAX_BPF_FUNC_ARGS */
2346 	for (i = 0, nregs = 0; i < m->nr_args; i++) {
2347 		slots = (m->arg_size[i] + 7) / 8;
2348 		if (nregs + slots <= 8) /* passed through register ? */
2349 			nregs += slots;
2350 		else
2351 			break;
2352 	}
2353 
2354 	a->args_in_regs = i;
2355 	a->regs_for_args = nregs;
2356 	a->ostack_for_args = 0;
2357 	a->bstack_for_args = 0;
2358 
2359 	/* the rest arguments are passed through stack */
2360 	for (; i < m->nr_args; i++) {
2361 		stack_slots = (m->arg_size[i] + 7) / 8;
2362 		a->bstack_for_args += stack_slots * 8;
2363 		a->ostack_for_args = a->ostack_for_args + stack_slots * 8;
2364 	}
2365 
2366 	return 0;
2367 }
2368 
clear_garbage(struct jit_ctx * ctx,int reg,int effective_bytes)2369 static void clear_garbage(struct jit_ctx *ctx, int reg, int effective_bytes)
2370 {
2371 	if (effective_bytes) {
2372 		int garbage_bits = 64 - 8 * effective_bytes;
2373 #ifdef CONFIG_CPU_BIG_ENDIAN
2374 		/* garbage bits are at the right end */
2375 		emit(A64_LSR(1, reg, reg, garbage_bits), ctx);
2376 		emit(A64_LSL(1, reg, reg, garbage_bits), ctx);
2377 #else
2378 		/* garbage bits are at the left end */
2379 		emit(A64_LSL(1, reg, reg, garbage_bits), ctx);
2380 		emit(A64_LSR(1, reg, reg, garbage_bits), ctx);
2381 #endif
2382 	}
2383 }
2384 
save_args(struct jit_ctx * ctx,int bargs_off,int oargs_off,const struct btf_func_model * m,const struct arg_aux * a,bool for_call_origin)2385 static void save_args(struct jit_ctx *ctx, int bargs_off, int oargs_off,
2386 		      const struct btf_func_model *m,
2387 		      const struct arg_aux *a,
2388 		      bool for_call_origin)
2389 {
2390 	int i;
2391 	int reg;
2392 	int doff;
2393 	int soff;
2394 	int slots;
2395 	u8 tmp = bpf2a64[TMP_REG_1];
2396 
2397 	/* store arguments to the stack for the bpf program, or restore
2398 	 * arguments from stack for the original function
2399 	 */
2400 	for (reg = 0; reg < a->regs_for_args; reg++) {
2401 		emit(for_call_origin ?
2402 		     A64_LDR64I(reg, A64_SP, bargs_off) :
2403 		     A64_STR64I(reg, A64_SP, bargs_off),
2404 		     ctx);
2405 		bargs_off += 8;
2406 	}
2407 
2408 	soff = 32; /* on stack arguments start from FP + 32 */
2409 	doff = (for_call_origin ? oargs_off : bargs_off);
2410 
2411 	/* save on stack arguments */
2412 	for (i = a->args_in_regs; i < m->nr_args; i++) {
2413 		slots = (m->arg_size[i] + 7) / 8;
2414 		/* verifier ensures arg_size <= 16, so slots equals 1 or 2 */
2415 		while (slots-- > 0) {
2416 			emit(A64_LDR64I(tmp, A64_FP, soff), ctx);
2417 			/* if there is unused space in the last slot, clear
2418 			 * the garbage contained in the space.
2419 			 */
2420 			if (slots == 0 && !for_call_origin)
2421 				clear_garbage(ctx, tmp, m->arg_size[i] % 8);
2422 			emit(A64_STR64I(tmp, A64_SP, doff), ctx);
2423 			soff += 8;
2424 			doff += 8;
2425 		}
2426 	}
2427 }
2428 
restore_args(struct jit_ctx * ctx,int bargs_off,int nregs)2429 static void restore_args(struct jit_ctx *ctx, int bargs_off, int nregs)
2430 {
2431 	int reg;
2432 
2433 	for (reg = 0; reg < nregs; reg++) {
2434 		emit(A64_LDR64I(reg, A64_SP, bargs_off), ctx);
2435 		bargs_off += 8;
2436 	}
2437 }
2438 
is_struct_ops_tramp(const struct bpf_tramp_links * fentry_links)2439 static bool is_struct_ops_tramp(const struct bpf_tramp_links *fentry_links)
2440 {
2441 	return fentry_links->nr_links == 1 &&
2442 		fentry_links->links[0]->link.type == BPF_LINK_TYPE_STRUCT_OPS;
2443 }
2444 
2445 /* Based on the x86's implementation of arch_prepare_bpf_trampoline().
2446  *
2447  * bpf prog and function entry before bpf trampoline hooked:
2448  *   mov x9, lr
2449  *   nop
2450  *
2451  * bpf prog and function entry after bpf trampoline hooked:
2452  *   mov x9, lr
2453  *   bl  <bpf_trampoline or plt>
2454  *
2455  */
prepare_trampoline(struct jit_ctx * ctx,struct bpf_tramp_image * im,struct bpf_tramp_links * tlinks,void * func_addr,const struct btf_func_model * m,const struct arg_aux * a,u32 flags)2456 static int prepare_trampoline(struct jit_ctx *ctx, struct bpf_tramp_image *im,
2457 			      struct bpf_tramp_links *tlinks, void *func_addr,
2458 			      const struct btf_func_model *m,
2459 			      const struct arg_aux *a,
2460 			      u32 flags)
2461 {
2462 	int i;
2463 	int stack_size;
2464 	int retaddr_off;
2465 	int regs_off;
2466 	int retval_off;
2467 	int bargs_off;
2468 	int nfuncargs_off;
2469 	int ip_off;
2470 	int run_ctx_off;
2471 	int oargs_off;
2472 	int nfuncargs;
2473 	struct bpf_tramp_links *fentry = &tlinks[BPF_TRAMP_FENTRY];
2474 	struct bpf_tramp_links *fexit = &tlinks[BPF_TRAMP_FEXIT];
2475 	struct bpf_tramp_links *fmod_ret = &tlinks[BPF_TRAMP_MODIFY_RETURN];
2476 	bool save_ret;
2477 	__le32 **branches = NULL;
2478 	bool is_struct_ops = is_struct_ops_tramp(fentry);
2479 
2480 	/* trampoline stack layout:
2481 	 *                    [ parent ip         ]
2482 	 *                    [ FP                ]
2483 	 * SP + retaddr_off   [ self ip           ]
2484 	 *                    [ FP                ]
2485 	 *
2486 	 *                    [ padding           ] align SP to multiples of 16
2487 	 *
2488 	 *                    [ x20               ] callee saved reg x20
2489 	 * SP + regs_off      [ x19               ] callee saved reg x19
2490 	 *
2491 	 * SP + retval_off    [ return value      ] BPF_TRAMP_F_CALL_ORIG or
2492 	 *                                          BPF_TRAMP_F_RET_FENTRY_RET
2493 	 *                    [ arg reg N         ]
2494 	 *                    [ ...               ]
2495 	 * SP + bargs_off     [ arg reg 1         ] for bpf
2496 	 *
2497 	 * SP + nfuncargs_off [ arg regs count    ]
2498 	 *
2499 	 * SP + ip_off        [ traced function   ] BPF_TRAMP_F_IP_ARG flag
2500 	 *
2501 	 * SP + run_ctx_off   [ bpf_tramp_run_ctx ]
2502 	 *
2503 	 *                    [ stack arg N       ]
2504 	 *                    [ ...               ]
2505 	 * SP + oargs_off     [ stack arg 1       ] for original func
2506 	 */
2507 
2508 	stack_size = 0;
2509 	oargs_off = stack_size;
2510 	if (flags & BPF_TRAMP_F_CALL_ORIG)
2511 		stack_size +=  a->ostack_for_args;
2512 
2513 	run_ctx_off = stack_size;
2514 	/* room for bpf_tramp_run_ctx */
2515 	stack_size += round_up(sizeof(struct bpf_tramp_run_ctx), 8);
2516 
2517 	ip_off = stack_size;
2518 	/* room for IP address argument */
2519 	if (flags & BPF_TRAMP_F_IP_ARG)
2520 		stack_size += 8;
2521 
2522 	nfuncargs_off = stack_size;
2523 	/* room for args count */
2524 	stack_size += 8;
2525 
2526 	bargs_off = stack_size;
2527 	/* room for args */
2528 	nfuncargs = a->regs_for_args + a->bstack_for_args / 8;
2529 	stack_size += 8 * nfuncargs;
2530 
2531 	/* room for return value */
2532 	retval_off = stack_size;
2533 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
2534 	if (save_ret)
2535 		stack_size += 8;
2536 
2537 	/* room for callee saved registers, currently x19 and x20 are used */
2538 	regs_off = stack_size;
2539 	stack_size += 16;
2540 
2541 	/* round up to multiples of 16 to avoid SPAlignmentFault */
2542 	stack_size = round_up(stack_size, 16);
2543 
2544 	/* return address locates above FP */
2545 	retaddr_off = stack_size + 8;
2546 
2547 	if (flags & BPF_TRAMP_F_INDIRECT) {
2548 		/*
2549 		 * Indirect call for bpf_struct_ops
2550 		 */
2551 		emit_kcfi(cfi_get_func_hash(func_addr), ctx);
2552 	}
2553 	/* bpf trampoline may be invoked by 3 instruction types:
2554 	 * 1. bl, attached to bpf prog or kernel function via short jump
2555 	 * 2. br, attached to bpf prog or kernel function via long jump
2556 	 * 3. blr, working as a function pointer, used by struct_ops.
2557 	 * So BTI_JC should used here to support both br and blr.
2558 	 */
2559 	emit_bti(A64_BTI_JC, ctx);
2560 
2561 	/* x9 is not set for struct_ops */
2562 	if (!is_struct_ops) {
2563 		/* frame for parent function */
2564 		emit(A64_PUSH(A64_FP, A64_R(9), A64_SP), ctx);
2565 		emit(A64_MOV(1, A64_FP, A64_SP), ctx);
2566 	}
2567 
2568 	/* frame for patched function for tracing, or caller for struct_ops */
2569 	emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
2570 	emit(A64_MOV(1, A64_FP, A64_SP), ctx);
2571 
2572 	/* allocate stack space */
2573 	emit(A64_SUB_I(1, A64_SP, A64_SP, stack_size), ctx);
2574 
2575 	if (flags & BPF_TRAMP_F_IP_ARG) {
2576 		/* save ip address of the traced function */
2577 		emit_addr_mov_i64(A64_R(10), (const u64)func_addr, ctx);
2578 		emit(A64_STR64I(A64_R(10), A64_SP, ip_off), ctx);
2579 	}
2580 
2581 	/* save arg regs count*/
2582 	emit(A64_MOVZ(1, A64_R(10), nfuncargs, 0), ctx);
2583 	emit(A64_STR64I(A64_R(10), A64_SP, nfuncargs_off), ctx);
2584 
2585 	/* save args for bpf */
2586 	save_args(ctx, bargs_off, oargs_off, m, a, false);
2587 
2588 	/* save callee saved registers */
2589 	emit(A64_STR64I(A64_R(19), A64_SP, regs_off), ctx);
2590 	emit(A64_STR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
2591 
2592 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2593 		/* for the first pass, assume the worst case */
2594 		if (!ctx->image)
2595 			ctx->idx += 4;
2596 		else
2597 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
2598 		emit_call((const u64)__bpf_tramp_enter, ctx);
2599 	}
2600 
2601 	for (i = 0; i < fentry->nr_links; i++)
2602 		invoke_bpf_prog(ctx, fentry->links[i], bargs_off,
2603 				retval_off, run_ctx_off,
2604 				flags & BPF_TRAMP_F_RET_FENTRY_RET);
2605 
2606 	if (fmod_ret->nr_links) {
2607 		branches = kcalloc(fmod_ret->nr_links, sizeof(__le32 *),
2608 				   GFP_KERNEL);
2609 		if (!branches)
2610 			return -ENOMEM;
2611 
2612 		invoke_bpf_mod_ret(ctx, fmod_ret, bargs_off, retval_off,
2613 				   run_ctx_off, branches);
2614 	}
2615 
2616 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2617 		/* save args for original func */
2618 		save_args(ctx, bargs_off, oargs_off, m, a, true);
2619 		/* call original func */
2620 		emit(A64_LDR64I(A64_R(10), A64_SP, retaddr_off), ctx);
2621 		emit(A64_ADR(A64_LR, AARCH64_INSN_SIZE * 2), ctx);
2622 		emit(A64_RET(A64_R(10)), ctx);
2623 		/* store return value */
2624 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
2625 		/* reserve a nop for bpf_tramp_image_put */
2626 		im->ip_after_call = ctx->ro_image + ctx->idx;
2627 		emit(A64_NOP, ctx);
2628 	}
2629 
2630 	/* update the branches saved in invoke_bpf_mod_ret with cbnz */
2631 	for (i = 0; i < fmod_ret->nr_links && ctx->image != NULL; i++) {
2632 		int offset = &ctx->image[ctx->idx] - branches[i];
2633 		*branches[i] = cpu_to_le32(A64_CBNZ(1, A64_R(10), offset));
2634 	}
2635 
2636 	for (i = 0; i < fexit->nr_links; i++)
2637 		invoke_bpf_prog(ctx, fexit->links[i], bargs_off, retval_off,
2638 				run_ctx_off, false);
2639 
2640 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2641 		im->ip_epilogue = ctx->ro_image + ctx->idx;
2642 		/* for the first pass, assume the worst case */
2643 		if (!ctx->image)
2644 			ctx->idx += 4;
2645 		else
2646 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
2647 		emit_call((const u64)__bpf_tramp_exit, ctx);
2648 	}
2649 
2650 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
2651 		restore_args(ctx, bargs_off, a->regs_for_args);
2652 
2653 	/* restore callee saved register x19 and x20 */
2654 	emit(A64_LDR64I(A64_R(19), A64_SP, regs_off), ctx);
2655 	emit(A64_LDR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
2656 
2657 	if (save_ret)
2658 		emit(A64_LDR64I(A64_R(0), A64_SP, retval_off), ctx);
2659 
2660 	/* reset SP  */
2661 	emit(A64_MOV(1, A64_SP, A64_FP), ctx);
2662 
2663 	if (is_struct_ops) {
2664 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
2665 		emit(A64_RET(A64_LR), ctx);
2666 	} else {
2667 		/* pop frames */
2668 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
2669 		emit(A64_POP(A64_FP, A64_R(9), A64_SP), ctx);
2670 
2671 		if (flags & BPF_TRAMP_F_SKIP_FRAME) {
2672 			/* skip patched function, return to parent */
2673 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
2674 			emit(A64_RET(A64_R(9)), ctx);
2675 		} else {
2676 			/* return to patched function */
2677 			emit(A64_MOV(1, A64_R(10), A64_LR), ctx);
2678 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
2679 			emit(A64_RET(A64_R(10)), ctx);
2680 		}
2681 	}
2682 
2683 	kfree(branches);
2684 
2685 	return ctx->idx;
2686 }
2687 
arch_bpf_trampoline_size(const struct btf_func_model * m,u32 flags,struct bpf_tramp_links * tlinks,void * func_addr)2688 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
2689 			     struct bpf_tramp_links *tlinks, void *func_addr)
2690 {
2691 	struct jit_ctx ctx = {
2692 		.image = NULL,
2693 		.idx = 0,
2694 	};
2695 	struct bpf_tramp_image im;
2696 	struct arg_aux aaux;
2697 	int ret;
2698 
2699 	ret = calc_arg_aux(m, &aaux);
2700 	if (ret < 0)
2701 		return ret;
2702 
2703 	ret = prepare_trampoline(&ctx, &im, tlinks, func_addr, m, &aaux, flags);
2704 	if (ret < 0)
2705 		return ret;
2706 
2707 	return ret < 0 ? ret : ret * AARCH64_INSN_SIZE;
2708 }
2709 
arch_alloc_bpf_trampoline(unsigned int size)2710 void *arch_alloc_bpf_trampoline(unsigned int size)
2711 {
2712 	return bpf_prog_pack_alloc(size, jit_fill_hole);
2713 }
2714 
arch_free_bpf_trampoline(void * image,unsigned int size)2715 void arch_free_bpf_trampoline(void *image, unsigned int size)
2716 {
2717 	bpf_prog_pack_free(image, size);
2718 }
2719 
arch_protect_bpf_trampoline(void * image,unsigned int size)2720 int arch_protect_bpf_trampoline(void *image, unsigned int size)
2721 {
2722 	return 0;
2723 }
2724 
arch_prepare_bpf_trampoline(struct bpf_tramp_image * im,void * ro_image,void * ro_image_end,const struct btf_func_model * m,u32 flags,struct bpf_tramp_links * tlinks,void * func_addr)2725 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *ro_image,
2726 				void *ro_image_end, const struct btf_func_model *m,
2727 				u32 flags, struct bpf_tramp_links *tlinks,
2728 				void *func_addr)
2729 {
2730 	u32 size = ro_image_end - ro_image;
2731 	struct arg_aux aaux;
2732 	void *image, *tmp;
2733 	int ret;
2734 
2735 	/* image doesn't need to be in module memory range, so we can
2736 	 * use kvmalloc.
2737 	 */
2738 	image = kvmalloc(size, GFP_KERNEL);
2739 	if (!image)
2740 		return -ENOMEM;
2741 
2742 	struct jit_ctx ctx = {
2743 		.image = image,
2744 		.ro_image = ro_image,
2745 		.idx = 0,
2746 		.write = true,
2747 	};
2748 
2749 
2750 	jit_fill_hole(image, (unsigned int)(ro_image_end - ro_image));
2751 	ret = calc_arg_aux(m, &aaux);
2752 	if (ret)
2753 		goto out;
2754 	ret = prepare_trampoline(&ctx, im, tlinks, func_addr, m, &aaux, flags);
2755 
2756 	if (ret > 0 && validate_code(&ctx) < 0) {
2757 		ret = -EINVAL;
2758 		goto out;
2759 	}
2760 
2761 	if (ret > 0)
2762 		ret *= AARCH64_INSN_SIZE;
2763 
2764 	tmp = bpf_arch_text_copy(ro_image, image, size);
2765 	if (IS_ERR(tmp)) {
2766 		ret = PTR_ERR(tmp);
2767 		goto out;
2768 	}
2769 
2770 	bpf_flush_icache(ro_image, ro_image + size);
2771 out:
2772 	kvfree(image);
2773 	return ret;
2774 }
2775 
is_long_jump(void * ip,void * target)2776 static bool is_long_jump(void *ip, void *target)
2777 {
2778 	long offset;
2779 
2780 	/* NULL target means this is a NOP */
2781 	if (!target)
2782 		return false;
2783 
2784 	offset = (long)target - (long)ip;
2785 	return offset < -SZ_128M || offset >= SZ_128M;
2786 }
2787 
gen_branch_or_nop(enum aarch64_insn_branch_type type,void * ip,void * addr,void * plt,u32 * insn)2788 static int gen_branch_or_nop(enum aarch64_insn_branch_type type, void *ip,
2789 			     void *addr, void *plt, u32 *insn)
2790 {
2791 	void *target;
2792 
2793 	if (!addr) {
2794 		*insn = aarch64_insn_gen_nop();
2795 		return 0;
2796 	}
2797 
2798 	if (is_long_jump(ip, addr))
2799 		target = plt;
2800 	else
2801 		target = addr;
2802 
2803 	*insn = aarch64_insn_gen_branch_imm((unsigned long)ip,
2804 					    (unsigned long)target,
2805 					    type);
2806 
2807 	return *insn != AARCH64_BREAK_FAULT ? 0 : -EFAULT;
2808 }
2809 
2810 /* Replace the branch instruction from @ip to @old_addr in a bpf prog or a bpf
2811  * trampoline with the branch instruction from @ip to @new_addr. If @old_addr
2812  * or @new_addr is NULL, the old or new instruction is NOP.
2813  *
2814  * When @ip is the bpf prog entry, a bpf trampoline is being attached or
2815  * detached. Since bpf trampoline and bpf prog are allocated separately with
2816  * vmalloc, the address distance may exceed 128MB, the maximum branch range.
2817  * So long jump should be handled.
2818  *
2819  * When a bpf prog is constructed, a plt pointing to empty trampoline
2820  * dummy_tramp is placed at the end:
2821  *
2822  *      bpf_prog:
2823  *              mov x9, lr
2824  *              nop // patchsite
2825  *              ...
2826  *              ret
2827  *
2828  *      plt:
2829  *              ldr x10, target
2830  *              br x10
2831  *      target:
2832  *              .quad dummy_tramp // plt target
2833  *
2834  * This is also the state when no trampoline is attached.
2835  *
2836  * When a short-jump bpf trampoline is attached, the patchsite is patched
2837  * to a bl instruction to the trampoline directly:
2838  *
2839  *      bpf_prog:
2840  *              mov x9, lr
2841  *              bl <short-jump bpf trampoline address> // patchsite
2842  *              ...
2843  *              ret
2844  *
2845  *      plt:
2846  *              ldr x10, target
2847  *              br x10
2848  *      target:
2849  *              .quad dummy_tramp // plt target
2850  *
2851  * When a long-jump bpf trampoline is attached, the plt target is filled with
2852  * the trampoline address and the patchsite is patched to a bl instruction to
2853  * the plt:
2854  *
2855  *      bpf_prog:
2856  *              mov x9, lr
2857  *              bl plt // patchsite
2858  *              ...
2859  *              ret
2860  *
2861  *      plt:
2862  *              ldr x10, target
2863  *              br x10
2864  *      target:
2865  *              .quad <long-jump bpf trampoline address> // plt target
2866  *
2867  * The dummy_tramp is used to prevent another CPU from jumping to unknown
2868  * locations during the patching process, making the patching process easier.
2869  */
bpf_arch_text_poke(void * ip,enum bpf_text_poke_type poke_type,void * old_addr,void * new_addr)2870 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type poke_type,
2871 		       void *old_addr, void *new_addr)
2872 {
2873 	int ret;
2874 	u32 old_insn;
2875 	u32 new_insn;
2876 	u32 replaced;
2877 	struct bpf_plt *plt = NULL;
2878 	unsigned long size = 0UL;
2879 	unsigned long offset = ~0UL;
2880 	enum aarch64_insn_branch_type branch_type;
2881 	char namebuf[KSYM_NAME_LEN];
2882 	void *image = NULL;
2883 	u64 plt_target = 0ULL;
2884 	bool poking_bpf_entry;
2885 
2886 	if (!__bpf_address_lookup((unsigned long)ip, &size, &offset, namebuf))
2887 		/* Only poking bpf text is supported. Since kernel function
2888 		 * entry is set up by ftrace, we reply on ftrace to poke kernel
2889 		 * functions.
2890 		 */
2891 		return -ENOTSUPP;
2892 
2893 	image = ip - offset;
2894 	/* zero offset means we're poking bpf prog entry */
2895 	poking_bpf_entry = (offset == 0UL);
2896 
2897 	/* bpf prog entry, find plt and the real patchsite */
2898 	if (poking_bpf_entry) {
2899 		/* plt locates at the end of bpf prog */
2900 		plt = image + size - PLT_TARGET_OFFSET;
2901 
2902 		/* skip to the nop instruction in bpf prog entry:
2903 		 * bti c // if BTI enabled
2904 		 * mov x9, x30
2905 		 * nop
2906 		 */
2907 		ip = image + POKE_OFFSET * AARCH64_INSN_SIZE;
2908 	}
2909 
2910 	/* long jump is only possible at bpf prog entry */
2911 	if (WARN_ON((is_long_jump(ip, new_addr) || is_long_jump(ip, old_addr)) &&
2912 		    !poking_bpf_entry))
2913 		return -EINVAL;
2914 
2915 	if (poke_type == BPF_MOD_CALL)
2916 		branch_type = AARCH64_INSN_BRANCH_LINK;
2917 	else
2918 		branch_type = AARCH64_INSN_BRANCH_NOLINK;
2919 
2920 	if (gen_branch_or_nop(branch_type, ip, old_addr, plt, &old_insn) < 0)
2921 		return -EFAULT;
2922 
2923 	if (gen_branch_or_nop(branch_type, ip, new_addr, plt, &new_insn) < 0)
2924 		return -EFAULT;
2925 
2926 	if (is_long_jump(ip, new_addr))
2927 		plt_target = (u64)new_addr;
2928 	else if (is_long_jump(ip, old_addr))
2929 		/* if the old target is a long jump and the new target is not,
2930 		 * restore the plt target to dummy_tramp, so there is always a
2931 		 * legal and harmless address stored in plt target, and we'll
2932 		 * never jump from plt to an unknown place.
2933 		 */
2934 		plt_target = (u64)&dummy_tramp;
2935 
2936 	if (plt_target) {
2937 		/* non-zero plt_target indicates we're patching a bpf prog,
2938 		 * which is read only.
2939 		 */
2940 		if (set_memory_rw(PAGE_MASK & ((uintptr_t)&plt->target), 1))
2941 			return -EFAULT;
2942 		WRITE_ONCE(plt->target, plt_target);
2943 		set_memory_ro(PAGE_MASK & ((uintptr_t)&plt->target), 1);
2944 		/* since plt target points to either the new trampoline
2945 		 * or dummy_tramp, even if another CPU reads the old plt
2946 		 * target value before fetching the bl instruction to plt,
2947 		 * it will be brought back by dummy_tramp, so no barrier is
2948 		 * required here.
2949 		 */
2950 	}
2951 
2952 	/* if the old target and the new target are both long jumps, no
2953 	 * patching is required
2954 	 */
2955 	if (old_insn == new_insn)
2956 		return 0;
2957 
2958 	mutex_lock(&text_mutex);
2959 	if (aarch64_insn_read(ip, &replaced)) {
2960 		ret = -EFAULT;
2961 		goto out;
2962 	}
2963 
2964 	if (replaced != old_insn) {
2965 		ret = -EFAULT;
2966 		goto out;
2967 	}
2968 
2969 	/* We call aarch64_insn_patch_text_nosync() to replace instruction
2970 	 * atomically, so no other CPUs will fetch a half-new and half-old
2971 	 * instruction. But there is chance that another CPU executes the
2972 	 * old instruction after the patching operation finishes (e.g.,
2973 	 * pipeline not flushed, or icache not synchronized yet).
2974 	 *
2975 	 * 1. when a new trampoline is attached, it is not a problem for
2976 	 *    different CPUs to jump to different trampolines temporarily.
2977 	 *
2978 	 * 2. when an old trampoline is freed, we should wait for all other
2979 	 *    CPUs to exit the trampoline and make sure the trampoline is no
2980 	 *    longer reachable, since bpf_tramp_image_put() function already
2981 	 *    uses percpu_ref and task-based rcu to do the sync, no need to call
2982 	 *    the sync version here, see bpf_tramp_image_put() for details.
2983 	 */
2984 	ret = aarch64_insn_patch_text_nosync(ip, new_insn);
2985 out:
2986 	mutex_unlock(&text_mutex);
2987 
2988 	return ret;
2989 }
2990 
bpf_jit_supports_ptr_xchg(void)2991 bool bpf_jit_supports_ptr_xchg(void)
2992 {
2993 	return true;
2994 }
2995 
bpf_jit_supports_exceptions(void)2996 bool bpf_jit_supports_exceptions(void)
2997 {
2998 	/* We unwind through both kernel frames starting from within bpf_throw
2999 	 * call and BPF frames. Therefore we require FP unwinder to be enabled
3000 	 * to walk kernel frames and reach BPF frames in the stack trace.
3001 	 * ARM64 kernel is aways compiled with CONFIG_FRAME_POINTER=y
3002 	 */
3003 	return true;
3004 }
3005 
bpf_jit_supports_arena(void)3006 bool bpf_jit_supports_arena(void)
3007 {
3008 	return true;
3009 }
3010 
bpf_jit_supports_insn(struct bpf_insn * insn,bool in_arena)3011 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
3012 {
3013 	if (!in_arena)
3014 		return true;
3015 	switch (insn->code) {
3016 	case BPF_STX | BPF_ATOMIC | BPF_W:
3017 	case BPF_STX | BPF_ATOMIC | BPF_DW:
3018 		if (!bpf_atomic_is_load_store(insn) &&
3019 		    !cpus_have_cap(ARM64_HAS_LSE_ATOMICS))
3020 			return false;
3021 	}
3022 	return true;
3023 }
3024 
bpf_jit_supports_percpu_insn(void)3025 bool bpf_jit_supports_percpu_insn(void)
3026 {
3027 	return true;
3028 }
3029 
bpf_jit_bypass_spec_v4(void)3030 bool bpf_jit_bypass_spec_v4(void)
3031 {
3032 	/* In case of arm64, we rely on the firmware mitigation of Speculative
3033 	 * Store Bypass as controlled via the ssbd kernel parameter. Whenever
3034 	 * the mitigation is enabled, it works for all of the kernel code with
3035 	 * no need to provide any additional instructions. Therefore, skip
3036 	 * inserting nospec insns against Spectre v4.
3037 	 */
3038 	return true;
3039 }
3040 
bpf_jit_inlines_helper_call(s32 imm)3041 bool bpf_jit_inlines_helper_call(s32 imm)
3042 {
3043 	switch (imm) {
3044 	case BPF_FUNC_get_smp_processor_id:
3045 	case BPF_FUNC_get_current_task:
3046 	case BPF_FUNC_get_current_task_btf:
3047 		return true;
3048 	default:
3049 		return false;
3050 	}
3051 }
3052 
bpf_jit_free(struct bpf_prog * prog)3053 void bpf_jit_free(struct bpf_prog *prog)
3054 {
3055 	if (prog->jited) {
3056 		struct arm64_jit_data *jit_data = prog->aux->jit_data;
3057 		struct bpf_binary_header *hdr;
3058 		void __percpu *priv_stack_ptr;
3059 		int priv_stack_alloc_sz;
3060 
3061 		/*
3062 		 * If we fail the final pass of JIT (from jit_subprogs),
3063 		 * the program may not be finalized yet. Call finalize here
3064 		 * before freeing it.
3065 		 */
3066 		if (jit_data) {
3067 			bpf_arch_text_copy(&jit_data->ro_header->size, &jit_data->header->size,
3068 					   sizeof(jit_data->header->size));
3069 			kfree(jit_data);
3070 		}
3071 		prog->bpf_func -= cfi_get_offset();
3072 		hdr = bpf_jit_binary_pack_hdr(prog);
3073 		bpf_jit_binary_pack_free(hdr, NULL);
3074 		priv_stack_ptr = prog->aux->priv_stack_ptr;
3075 		if (priv_stack_ptr) {
3076 			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
3077 					      2 * PRIV_STACK_GUARD_SZ;
3078 			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
3079 			free_percpu(prog->aux->priv_stack_ptr);
3080 		}
3081 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
3082 	}
3083 
3084 	bpf_prog_unlock_free(prog);
3085 }
3086