xref: /linux/arch/arm64/net/bpf_jit_comp.c (revision 09b1704f5b02c18dd02b21343530463fcfc92c54)
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 
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 
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 
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 
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 
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 
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 
186 static inline void emit_kcfi(u32 hash, struct jit_ctx *ctx)
187 {
188 	if (IS_ENABLED(CONFIG_CFI))
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  */
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 
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 
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 
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 
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 
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 
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 
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 
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 
289 static bool is_addsub_imm(u32 imm)
290 {
291 	/* Either imm12 or shifted imm12. */
292 	return !(imm & ~0xfff) || !(imm & ~0xfff000);
293 }
294 
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  */
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  */
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 
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 */
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 */
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 
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 
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 
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 
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
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
847 static inline int emit_lse_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
848 {
849 	return -EINVAL;
850 }
851 #endif
852 
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  */
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 */
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 
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 /*
1070  * Metadata encoding for exception handling in JITed code.
1071  *
1072  * Format of `fixup` field in `struct exception_table_entry`:
1073  *
1074  * Bit layout of `fixup` (32-bit):
1075  *
1076  * +-----------+--------+-----------+-----------+----------+
1077  * |   31-27   | 26-22  |     21    |   20-16   |   15-0   |
1078  * |           |        |           |           |          |
1079  * | FIXUP_REG | Unused | ARENA_ACC | ARENA_REG |  OFFSET  |
1080  * +-----------+--------+-----------+-----------+----------+
1081  *
1082  * - OFFSET (16 bits): Offset used to compute address for Load/Store instruction.
1083  * - ARENA_REG (5 bits): Register that is used to calculate the address for load/store when
1084  *                       accessing the arena region.
1085  * - ARENA_ACCESS (1 bit): This bit is set when the faulting instruction accessed the arena region.
1086  * - FIXUP_REG (5 bits): Destination register for the load instruction (cleared on fault) or set to
1087  *                       DONT_CLEAR if it is a store instruction.
1088  */
1089 
1090 #define BPF_FIXUP_OFFSET_MASK      GENMASK(15, 0)
1091 #define BPF_FIXUP_ARENA_REG_MASK   GENMASK(20, 16)
1092 #define BPF_ARENA_ACCESS           BIT(21)
1093 #define BPF_FIXUP_REG_MASK	GENMASK(31, 27)
1094 #define DONT_CLEAR 5 /* Unused ARM64 register from BPF's POV */
1095 
1096 bool ex_handler_bpf(const struct exception_table_entry *ex,
1097 		    struct pt_regs *regs)
1098 {
1099 	int dst_reg = FIELD_GET(BPF_FIXUP_REG_MASK, ex->fixup);
1100 	s16 off = FIELD_GET(BPF_FIXUP_OFFSET_MASK, ex->fixup);
1101 	int arena_reg = FIELD_GET(BPF_FIXUP_ARENA_REG_MASK, ex->fixup);
1102 	bool is_arena = !!(ex->fixup & BPF_ARENA_ACCESS);
1103 	bool is_write = (dst_reg == DONT_CLEAR);
1104 	unsigned long addr;
1105 
1106 	if (is_arena) {
1107 		addr = regs->regs[arena_reg] + off;
1108 		bpf_prog_report_arena_violation(is_write, addr, regs->pc);
1109 	}
1110 
1111 	if (dst_reg != DONT_CLEAR)
1112 		regs->regs[dst_reg] = 0;
1113 	/* Skip the faulting instruction */
1114 	regs->pc += AARCH64_INSN_SIZE;
1115 
1116 	return true;
1117 }
1118 
1119 /* For accesses to BTF pointers, add an entry to the exception table */
1120 static int add_exception_handler(const struct bpf_insn *insn,
1121 				 struct jit_ctx *ctx,
1122 				 int dst_reg)
1123 {
1124 	off_t ins_offset;
1125 	s16 off = insn->off;
1126 	bool is_arena;
1127 	int arena_reg;
1128 	unsigned long pc;
1129 	struct exception_table_entry *ex;
1130 
1131 	if (!ctx->image)
1132 		/* First pass */
1133 		return 0;
1134 
1135 	if (BPF_MODE(insn->code) != BPF_PROBE_MEM &&
1136 	    BPF_MODE(insn->code) != BPF_PROBE_MEMSX &&
1137 	    BPF_MODE(insn->code) != BPF_PROBE_MEM32 &&
1138 	    BPF_MODE(insn->code) != BPF_PROBE_MEM32SX &&
1139 	    BPF_MODE(insn->code) != BPF_PROBE_ATOMIC)
1140 		return 0;
1141 
1142 	is_arena = (BPF_MODE(insn->code) == BPF_PROBE_MEM32) ||
1143 		   (BPF_MODE(insn->code) == BPF_PROBE_MEM32SX) ||
1144 		   (BPF_MODE(insn->code) == BPF_PROBE_ATOMIC);
1145 
1146 	if (!ctx->prog->aux->extable ||
1147 	    WARN_ON_ONCE(ctx->exentry_idx >= ctx->prog->aux->num_exentries))
1148 		return -EINVAL;
1149 
1150 	ex = &ctx->prog->aux->extable[ctx->exentry_idx];
1151 	pc = (unsigned long)&ctx->ro_image[ctx->idx - 1];
1152 
1153 	/*
1154 	 * This is the relative offset of the instruction that may fault from
1155 	 * the exception table itself. This will be written to the exception
1156 	 * table and if this instruction faults, the destination register will
1157 	 * be set to '0' and the execution will jump to the next instruction.
1158 	 */
1159 	ins_offset = pc - (long)&ex->insn;
1160 	if (WARN_ON_ONCE(ins_offset >= 0 || ins_offset < INT_MIN))
1161 		return -ERANGE;
1162 
1163 	/*
1164 	 * The offsets above have been calculated using the RO buffer but we
1165 	 * need to use the R/W buffer for writes.
1166 	 * switch ex to rw buffer for writing.
1167 	 */
1168 	ex = (void *)ctx->image + ((void *)ex - (void *)ctx->ro_image);
1169 
1170 	ex->insn = ins_offset;
1171 
1172 	if (BPF_CLASS(insn->code) != BPF_LDX)
1173 		dst_reg = DONT_CLEAR;
1174 
1175 	ex->fixup = FIELD_PREP(BPF_FIXUP_REG_MASK, dst_reg);
1176 
1177 	if (is_arena) {
1178 		ex->fixup |= BPF_ARENA_ACCESS;
1179 		/*
1180 		 * insn->src_reg/dst_reg holds the address in the arena region with upper 32-bits
1181 		 * being zero because of a preceding addr_space_cast(r<n>, 0x0, 0x1) instruction.
1182 		 * This address is adjusted with the addition of arena_vm_start (see the
1183 		 * implementation of BPF_PROBE_MEM32 and BPF_PROBE_ATOMIC) before being used for the
1184 		 * memory access. Pass the reg holding the unmodified 32-bit address to
1185 		 * ex_handler_bpf.
1186 		 */
1187 		if (BPF_CLASS(insn->code) == BPF_LDX)
1188 			arena_reg = bpf2a64[insn->src_reg];
1189 		else
1190 			arena_reg = bpf2a64[insn->dst_reg];
1191 
1192 		ex->fixup |=  FIELD_PREP(BPF_FIXUP_OFFSET_MASK, off) |
1193 			      FIELD_PREP(BPF_FIXUP_ARENA_REG_MASK, arena_reg);
1194 	}
1195 
1196 	ex->type = EX_TYPE_BPF;
1197 
1198 	ctx->exentry_idx++;
1199 	return 0;
1200 }
1201 
1202 /* JITs an eBPF instruction.
1203  * Returns:
1204  * 0  - successfully JITed an 8-byte eBPF instruction.
1205  * >0 - successfully JITed a 16-byte eBPF instruction.
1206  * <0 - failed to JIT.
1207  */
1208 static int build_insn(const struct bpf_insn *insn, struct jit_ctx *ctx,
1209 		      bool extra_pass)
1210 {
1211 	const u8 code = insn->code;
1212 	u8 dst = bpf2a64[insn->dst_reg];
1213 	u8 src = bpf2a64[insn->src_reg];
1214 	const u8 tmp = bpf2a64[TMP_REG_1];
1215 	const u8 tmp2 = bpf2a64[TMP_REG_2];
1216 	const u8 tmp3 = bpf2a64[TMP_REG_3];
1217 	const u8 fp = bpf2a64[BPF_REG_FP];
1218 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
1219 	const u8 priv_sp = bpf2a64[PRIVATE_SP];
1220 	const s16 off = insn->off;
1221 	const s32 imm = insn->imm;
1222 	const int i = insn - ctx->prog->insnsi;
1223 	const bool is64 = BPF_CLASS(code) == BPF_ALU64 ||
1224 			  BPF_CLASS(code) == BPF_JMP;
1225 	u8 jmp_cond;
1226 	s32 jmp_offset;
1227 	u32 a64_insn;
1228 	u8 src_adj;
1229 	u8 dst_adj;
1230 	int off_adj;
1231 	int ret;
1232 	bool sign_extend;
1233 
1234 	switch (code) {
1235 	/* dst = src */
1236 	case BPF_ALU | BPF_MOV | BPF_X:
1237 	case BPF_ALU64 | BPF_MOV | BPF_X:
1238 		if (insn_is_cast_user(insn)) {
1239 			emit(A64_MOV(0, tmp, src), ctx); // 32-bit mov clears the upper 32 bits
1240 			emit_a64_mov_i(0, dst, ctx->user_vm_start >> 32, ctx);
1241 			emit(A64_LSL(1, dst, dst, 32), ctx);
1242 			emit(A64_CBZ(1, tmp, 2), ctx);
1243 			emit(A64_ORR(1, tmp, dst, tmp), ctx);
1244 			emit(A64_MOV(1, dst, tmp), ctx);
1245 			break;
1246 		} else if (insn_is_mov_percpu_addr(insn)) {
1247 			if (dst != src)
1248 				emit(A64_MOV(1, dst, src), ctx);
1249 			if (cpus_have_cap(ARM64_HAS_VIRT_HOST_EXTN))
1250 				emit(A64_MRS_TPIDR_EL2(tmp), ctx);
1251 			else
1252 				emit(A64_MRS_TPIDR_EL1(tmp), ctx);
1253 			emit(A64_ADD(1, dst, dst, tmp), ctx);
1254 			break;
1255 		}
1256 		switch (insn->off) {
1257 		case 0:
1258 			emit(A64_MOV(is64, dst, src), ctx);
1259 			break;
1260 		case 8:
1261 			emit(A64_SXTB(is64, dst, src), ctx);
1262 			break;
1263 		case 16:
1264 			emit(A64_SXTH(is64, dst, src), ctx);
1265 			break;
1266 		case 32:
1267 			emit(A64_SXTW(is64, dst, src), ctx);
1268 			break;
1269 		}
1270 		break;
1271 	/* dst = dst OP src */
1272 	case BPF_ALU | BPF_ADD | BPF_X:
1273 	case BPF_ALU64 | BPF_ADD | BPF_X:
1274 		emit(A64_ADD(is64, dst, dst, src), ctx);
1275 		break;
1276 	case BPF_ALU | BPF_SUB | BPF_X:
1277 	case BPF_ALU64 | BPF_SUB | BPF_X:
1278 		emit(A64_SUB(is64, dst, dst, src), ctx);
1279 		break;
1280 	case BPF_ALU | BPF_AND | BPF_X:
1281 	case BPF_ALU64 | BPF_AND | BPF_X:
1282 		emit(A64_AND(is64, dst, dst, src), ctx);
1283 		break;
1284 	case BPF_ALU | BPF_OR | BPF_X:
1285 	case BPF_ALU64 | BPF_OR | BPF_X:
1286 		emit(A64_ORR(is64, dst, dst, src), ctx);
1287 		break;
1288 	case BPF_ALU | BPF_XOR | BPF_X:
1289 	case BPF_ALU64 | BPF_XOR | BPF_X:
1290 		emit(A64_EOR(is64, dst, dst, src), ctx);
1291 		break;
1292 	case BPF_ALU | BPF_MUL | BPF_X:
1293 	case BPF_ALU64 | BPF_MUL | BPF_X:
1294 		emit(A64_MUL(is64, dst, dst, src), ctx);
1295 		break;
1296 	case BPF_ALU | BPF_DIV | BPF_X:
1297 	case BPF_ALU64 | BPF_DIV | BPF_X:
1298 		if (!off)
1299 			emit(A64_UDIV(is64, dst, dst, src), ctx);
1300 		else
1301 			emit(A64_SDIV(is64, dst, dst, src), ctx);
1302 		break;
1303 	case BPF_ALU | BPF_MOD | BPF_X:
1304 	case BPF_ALU64 | BPF_MOD | BPF_X:
1305 		if (!off)
1306 			emit(A64_UDIV(is64, tmp, dst, src), ctx);
1307 		else
1308 			emit(A64_SDIV(is64, tmp, dst, src), ctx);
1309 		emit(A64_MSUB(is64, dst, dst, tmp, src), ctx);
1310 		break;
1311 	case BPF_ALU | BPF_LSH | BPF_X:
1312 	case BPF_ALU64 | BPF_LSH | BPF_X:
1313 		emit(A64_LSLV(is64, dst, dst, src), ctx);
1314 		break;
1315 	case BPF_ALU | BPF_RSH | BPF_X:
1316 	case BPF_ALU64 | BPF_RSH | BPF_X:
1317 		emit(A64_LSRV(is64, dst, dst, src), ctx);
1318 		break;
1319 	case BPF_ALU | BPF_ARSH | BPF_X:
1320 	case BPF_ALU64 | BPF_ARSH | BPF_X:
1321 		emit(A64_ASRV(is64, dst, dst, src), ctx);
1322 		break;
1323 	/* dst = -dst */
1324 	case BPF_ALU | BPF_NEG:
1325 	case BPF_ALU64 | BPF_NEG:
1326 		emit(A64_NEG(is64, dst, dst), ctx);
1327 		break;
1328 	/* dst = BSWAP##imm(dst) */
1329 	case BPF_ALU | BPF_END | BPF_FROM_LE:
1330 	case BPF_ALU | BPF_END | BPF_FROM_BE:
1331 	case BPF_ALU64 | BPF_END | BPF_FROM_LE:
1332 #ifdef CONFIG_CPU_BIG_ENDIAN
1333 		if (BPF_CLASS(code) == BPF_ALU && BPF_SRC(code) == BPF_FROM_BE)
1334 			goto emit_bswap_uxt;
1335 #else /* !CONFIG_CPU_BIG_ENDIAN */
1336 		if (BPF_CLASS(code) == BPF_ALU && BPF_SRC(code) == BPF_FROM_LE)
1337 			goto emit_bswap_uxt;
1338 #endif
1339 		switch (imm) {
1340 		case 16:
1341 			emit(A64_REV16(is64, dst, dst), ctx);
1342 			/* zero-extend 16 bits into 64 bits */
1343 			emit(A64_UXTH(is64, dst, dst), ctx);
1344 			break;
1345 		case 32:
1346 			emit(A64_REV32(0, dst, dst), ctx);
1347 			/* upper 32 bits already cleared */
1348 			break;
1349 		case 64:
1350 			emit(A64_REV64(dst, dst), ctx);
1351 			break;
1352 		}
1353 		break;
1354 emit_bswap_uxt:
1355 		switch (imm) {
1356 		case 16:
1357 			/* zero-extend 16 bits into 64 bits */
1358 			emit(A64_UXTH(is64, dst, dst), ctx);
1359 			break;
1360 		case 32:
1361 			/* zero-extend 32 bits into 64 bits */
1362 			emit(A64_UXTW(is64, dst, dst), ctx);
1363 			break;
1364 		case 64:
1365 			/* nop */
1366 			break;
1367 		}
1368 		break;
1369 	/* dst = imm */
1370 	case BPF_ALU | BPF_MOV | BPF_K:
1371 	case BPF_ALU64 | BPF_MOV | BPF_K:
1372 		emit_a64_mov_i(is64, dst, imm, ctx);
1373 		break;
1374 	/* dst = dst OP imm */
1375 	case BPF_ALU | BPF_ADD | BPF_K:
1376 	case BPF_ALU64 | BPF_ADD | BPF_K:
1377 		emit_a64_add_i(is64, dst, dst, tmp, imm, ctx);
1378 		break;
1379 	case BPF_ALU | BPF_SUB | BPF_K:
1380 	case BPF_ALU64 | BPF_SUB | BPF_K:
1381 		if (is_addsub_imm(imm)) {
1382 			emit(A64_SUB_I(is64, dst, dst, imm), ctx);
1383 		} else if (is_addsub_imm(-(u32)imm)) {
1384 			emit(A64_ADD_I(is64, dst, dst, -imm), ctx);
1385 		} else {
1386 			emit_a64_mov_i(is64, tmp, imm, ctx);
1387 			emit(A64_SUB(is64, dst, dst, tmp), ctx);
1388 		}
1389 		break;
1390 	case BPF_ALU | BPF_AND | BPF_K:
1391 	case BPF_ALU64 | BPF_AND | BPF_K:
1392 		a64_insn = A64_AND_I(is64, dst, dst, imm);
1393 		if (a64_insn != AARCH64_BREAK_FAULT) {
1394 			emit(a64_insn, ctx);
1395 		} else {
1396 			emit_a64_mov_i(is64, tmp, imm, ctx);
1397 			emit(A64_AND(is64, dst, dst, tmp), ctx);
1398 		}
1399 		break;
1400 	case BPF_ALU | BPF_OR | BPF_K:
1401 	case BPF_ALU64 | BPF_OR | BPF_K:
1402 		a64_insn = A64_ORR_I(is64, dst, dst, imm);
1403 		if (a64_insn != AARCH64_BREAK_FAULT) {
1404 			emit(a64_insn, ctx);
1405 		} else {
1406 			emit_a64_mov_i(is64, tmp, imm, ctx);
1407 			emit(A64_ORR(is64, dst, dst, tmp), ctx);
1408 		}
1409 		break;
1410 	case BPF_ALU | BPF_XOR | BPF_K:
1411 	case BPF_ALU64 | BPF_XOR | BPF_K:
1412 		a64_insn = A64_EOR_I(is64, dst, dst, imm);
1413 		if (a64_insn != AARCH64_BREAK_FAULT) {
1414 			emit(a64_insn, ctx);
1415 		} else {
1416 			emit_a64_mov_i(is64, tmp, imm, ctx);
1417 			emit(A64_EOR(is64, dst, dst, tmp), ctx);
1418 		}
1419 		break;
1420 	case BPF_ALU | BPF_MUL | BPF_K:
1421 	case BPF_ALU64 | BPF_MUL | BPF_K:
1422 		emit_a64_mov_i(is64, tmp, imm, ctx);
1423 		emit(A64_MUL(is64, dst, dst, tmp), ctx);
1424 		break;
1425 	case BPF_ALU | BPF_DIV | BPF_K:
1426 	case BPF_ALU64 | BPF_DIV | BPF_K:
1427 		emit_a64_mov_i(is64, tmp, imm, ctx);
1428 		if (!off)
1429 			emit(A64_UDIV(is64, dst, dst, tmp), ctx);
1430 		else
1431 			emit(A64_SDIV(is64, dst, dst, tmp), ctx);
1432 		break;
1433 	case BPF_ALU | BPF_MOD | BPF_K:
1434 	case BPF_ALU64 | BPF_MOD | BPF_K:
1435 		emit_a64_mov_i(is64, tmp2, imm, ctx);
1436 		if (!off)
1437 			emit(A64_UDIV(is64, tmp, dst, tmp2), ctx);
1438 		else
1439 			emit(A64_SDIV(is64, tmp, dst, tmp2), ctx);
1440 		emit(A64_MSUB(is64, dst, dst, tmp, tmp2), ctx);
1441 		break;
1442 	case BPF_ALU | BPF_LSH | BPF_K:
1443 	case BPF_ALU64 | BPF_LSH | BPF_K:
1444 		emit(A64_LSL(is64, dst, dst, imm), ctx);
1445 		break;
1446 	case BPF_ALU | BPF_RSH | BPF_K:
1447 	case BPF_ALU64 | BPF_RSH | BPF_K:
1448 		emit(A64_LSR(is64, dst, dst, imm), ctx);
1449 		break;
1450 	case BPF_ALU | BPF_ARSH | BPF_K:
1451 	case BPF_ALU64 | BPF_ARSH | BPF_K:
1452 		emit(A64_ASR(is64, dst, dst, imm), ctx);
1453 		break;
1454 
1455 	/* JUMP off */
1456 	case BPF_JMP | BPF_JA:
1457 	case BPF_JMP32 | BPF_JA:
1458 		if (BPF_CLASS(code) == BPF_JMP)
1459 			jmp_offset = bpf2a64_offset(i, off, ctx);
1460 		else
1461 			jmp_offset = bpf2a64_offset(i, imm, ctx);
1462 		check_imm26(jmp_offset);
1463 		emit(A64_B(jmp_offset), ctx);
1464 		break;
1465 	/* IF (dst COND src) JUMP off */
1466 	case BPF_JMP | BPF_JEQ | BPF_X:
1467 	case BPF_JMP | BPF_JGT | BPF_X:
1468 	case BPF_JMP | BPF_JLT | BPF_X:
1469 	case BPF_JMP | BPF_JGE | BPF_X:
1470 	case BPF_JMP | BPF_JLE | BPF_X:
1471 	case BPF_JMP | BPF_JNE | BPF_X:
1472 	case BPF_JMP | BPF_JSGT | BPF_X:
1473 	case BPF_JMP | BPF_JSLT | BPF_X:
1474 	case BPF_JMP | BPF_JSGE | BPF_X:
1475 	case BPF_JMP | BPF_JSLE | BPF_X:
1476 	case BPF_JMP32 | BPF_JEQ | BPF_X:
1477 	case BPF_JMP32 | BPF_JGT | BPF_X:
1478 	case BPF_JMP32 | BPF_JLT | BPF_X:
1479 	case BPF_JMP32 | BPF_JGE | BPF_X:
1480 	case BPF_JMP32 | BPF_JLE | BPF_X:
1481 	case BPF_JMP32 | BPF_JNE | BPF_X:
1482 	case BPF_JMP32 | BPF_JSGT | BPF_X:
1483 	case BPF_JMP32 | BPF_JSLT | BPF_X:
1484 	case BPF_JMP32 | BPF_JSGE | BPF_X:
1485 	case BPF_JMP32 | BPF_JSLE | BPF_X:
1486 		emit(A64_CMP(is64, dst, src), ctx);
1487 emit_cond_jmp:
1488 		jmp_offset = bpf2a64_offset(i, off, ctx);
1489 		check_imm19(jmp_offset);
1490 		switch (BPF_OP(code)) {
1491 		case BPF_JEQ:
1492 			jmp_cond = A64_COND_EQ;
1493 			break;
1494 		case BPF_JGT:
1495 			jmp_cond = A64_COND_HI;
1496 			break;
1497 		case BPF_JLT:
1498 			jmp_cond = A64_COND_CC;
1499 			break;
1500 		case BPF_JGE:
1501 			jmp_cond = A64_COND_CS;
1502 			break;
1503 		case BPF_JLE:
1504 			jmp_cond = A64_COND_LS;
1505 			break;
1506 		case BPF_JSET:
1507 		case BPF_JNE:
1508 			jmp_cond = A64_COND_NE;
1509 			break;
1510 		case BPF_JSGT:
1511 			jmp_cond = A64_COND_GT;
1512 			break;
1513 		case BPF_JSLT:
1514 			jmp_cond = A64_COND_LT;
1515 			break;
1516 		case BPF_JSGE:
1517 			jmp_cond = A64_COND_GE;
1518 			break;
1519 		case BPF_JSLE:
1520 			jmp_cond = A64_COND_LE;
1521 			break;
1522 		default:
1523 			return -EFAULT;
1524 		}
1525 		emit(A64_B_(jmp_cond, jmp_offset), ctx);
1526 		break;
1527 	case BPF_JMP | BPF_JSET | BPF_X:
1528 	case BPF_JMP32 | BPF_JSET | BPF_X:
1529 		emit(A64_TST(is64, dst, src), ctx);
1530 		goto emit_cond_jmp;
1531 	/* IF (dst COND imm) JUMP off */
1532 	case BPF_JMP | BPF_JEQ | BPF_K:
1533 	case BPF_JMP | BPF_JGT | BPF_K:
1534 	case BPF_JMP | BPF_JLT | BPF_K:
1535 	case BPF_JMP | BPF_JGE | BPF_K:
1536 	case BPF_JMP | BPF_JLE | BPF_K:
1537 	case BPF_JMP | BPF_JNE | BPF_K:
1538 	case BPF_JMP | BPF_JSGT | BPF_K:
1539 	case BPF_JMP | BPF_JSLT | BPF_K:
1540 	case BPF_JMP | BPF_JSGE | BPF_K:
1541 	case BPF_JMP | BPF_JSLE | BPF_K:
1542 	case BPF_JMP32 | BPF_JEQ | BPF_K:
1543 	case BPF_JMP32 | BPF_JGT | BPF_K:
1544 	case BPF_JMP32 | BPF_JLT | BPF_K:
1545 	case BPF_JMP32 | BPF_JGE | BPF_K:
1546 	case BPF_JMP32 | BPF_JLE | BPF_K:
1547 	case BPF_JMP32 | BPF_JNE | BPF_K:
1548 	case BPF_JMP32 | BPF_JSGT | BPF_K:
1549 	case BPF_JMP32 | BPF_JSLT | BPF_K:
1550 	case BPF_JMP32 | BPF_JSGE | BPF_K:
1551 	case BPF_JMP32 | BPF_JSLE | BPF_K:
1552 		if (is_addsub_imm(imm)) {
1553 			emit(A64_CMP_I(is64, dst, imm), ctx);
1554 		} else if (is_addsub_imm(-(u32)imm)) {
1555 			emit(A64_CMN_I(is64, dst, -imm), ctx);
1556 		} else {
1557 			emit_a64_mov_i(is64, tmp, imm, ctx);
1558 			emit(A64_CMP(is64, dst, tmp), ctx);
1559 		}
1560 		goto emit_cond_jmp;
1561 	case BPF_JMP | BPF_JSET | BPF_K:
1562 	case BPF_JMP32 | BPF_JSET | BPF_K:
1563 		a64_insn = A64_TST_I(is64, dst, imm);
1564 		if (a64_insn != AARCH64_BREAK_FAULT) {
1565 			emit(a64_insn, ctx);
1566 		} else {
1567 			emit_a64_mov_i(is64, tmp, imm, ctx);
1568 			emit(A64_TST(is64, dst, tmp), ctx);
1569 		}
1570 		goto emit_cond_jmp;
1571 	/* function call */
1572 	case BPF_JMP | BPF_CALL:
1573 	{
1574 		const u8 r0 = bpf2a64[BPF_REG_0];
1575 		bool func_addr_fixed;
1576 		u64 func_addr;
1577 		u32 cpu_offset;
1578 
1579 		/* Implement helper call to bpf_get_smp_processor_id() inline */
1580 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_get_smp_processor_id) {
1581 			cpu_offset = offsetof(struct thread_info, cpu);
1582 
1583 			emit(A64_MRS_SP_EL0(tmp), ctx);
1584 			if (is_lsi_offset(cpu_offset, 2)) {
1585 				emit(A64_LDR32I(r0, tmp, cpu_offset), ctx);
1586 			} else {
1587 				emit_a64_mov_i(1, tmp2, cpu_offset, ctx);
1588 				emit(A64_LDR32(r0, tmp, tmp2), ctx);
1589 			}
1590 			break;
1591 		}
1592 
1593 		/* Implement helper call to bpf_get_current_task/_btf() inline */
1594 		if (insn->src_reg == 0 && (insn->imm == BPF_FUNC_get_current_task ||
1595 					   insn->imm == BPF_FUNC_get_current_task_btf)) {
1596 			emit(A64_MRS_SP_EL0(r0), ctx);
1597 			break;
1598 		}
1599 
1600 		ret = bpf_jit_get_func_addr(ctx->prog, insn, extra_pass,
1601 					    &func_addr, &func_addr_fixed);
1602 		if (ret < 0)
1603 			return ret;
1604 		emit_call(func_addr, ctx);
1605 		/*
1606 		 * Call to arch_bpf_timed_may_goto() is emitted by the
1607 		 * verifier and called with custom calling convention with
1608 		 * first argument and return value in BPF_REG_AX (x9).
1609 		 */
1610 		if (func_addr != (u64)arch_bpf_timed_may_goto)
1611 			emit(A64_MOV(1, r0, A64_R(0)), ctx);
1612 		break;
1613 	}
1614 	/* tail call */
1615 	case BPF_JMP | BPF_TAIL_CALL:
1616 		if (emit_bpf_tail_call(ctx))
1617 			return -EFAULT;
1618 		break;
1619 	/* function return */
1620 	case BPF_JMP | BPF_EXIT:
1621 		/* Optimization: when last instruction is EXIT,
1622 		   simply fallthrough to epilogue. */
1623 		if (i == ctx->prog->len - 1)
1624 			break;
1625 		jmp_offset = epilogue_offset(ctx);
1626 		check_imm26(jmp_offset);
1627 		emit(A64_B(jmp_offset), ctx);
1628 		break;
1629 
1630 	/* dst = imm64 */
1631 	case BPF_LD | BPF_IMM | BPF_DW:
1632 	{
1633 		const struct bpf_insn insn1 = insn[1];
1634 		u64 imm64;
1635 
1636 		imm64 = (u64)insn1.imm << 32 | (u32)imm;
1637 		if (bpf_pseudo_func(insn))
1638 			emit_addr_mov_i64(dst, imm64, ctx);
1639 		else
1640 			emit_a64_mov_i64(dst, imm64, ctx);
1641 
1642 		return 1;
1643 	}
1644 
1645 	/* LDX: dst = (u64)*(unsigned size *)(src + off) */
1646 	case BPF_LDX | BPF_MEM | BPF_W:
1647 	case BPF_LDX | BPF_MEM | BPF_H:
1648 	case BPF_LDX | BPF_MEM | BPF_B:
1649 	case BPF_LDX | BPF_MEM | BPF_DW:
1650 	case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
1651 	case BPF_LDX | BPF_PROBE_MEM | BPF_W:
1652 	case BPF_LDX | BPF_PROBE_MEM | BPF_H:
1653 	case BPF_LDX | BPF_PROBE_MEM | BPF_B:
1654 	/* LDXS: dst_reg = (s64)*(signed size *)(src_reg + off) */
1655 	case BPF_LDX | BPF_MEMSX | BPF_B:
1656 	case BPF_LDX | BPF_MEMSX | BPF_H:
1657 	case BPF_LDX | BPF_MEMSX | BPF_W:
1658 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
1659 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
1660 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
1661 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_B:
1662 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
1663 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
1664 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
1665 	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_B:
1666 	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_H:
1667 	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_W:
1668 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
1669 		    BPF_MODE(insn->code) == BPF_PROBE_MEM32SX) {
1670 			emit(A64_ADD(1, tmp2, src, arena_vm_base), ctx);
1671 			src = tmp2;
1672 		}
1673 		if (src == fp) {
1674 			src_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
1675 			off_adj = off + ctx->stack_size;
1676 		} else {
1677 			src_adj = src;
1678 			off_adj = off;
1679 		}
1680 		sign_extend = (BPF_MODE(insn->code) == BPF_MEMSX ||
1681 				BPF_MODE(insn->code) == BPF_PROBE_MEMSX ||
1682 				 BPF_MODE(insn->code) == BPF_PROBE_MEM32SX);
1683 		switch (BPF_SIZE(code)) {
1684 		case BPF_W:
1685 			if (is_lsi_offset(off_adj, 2)) {
1686 				if (sign_extend)
1687 					emit(A64_LDRSWI(dst, src_adj, off_adj), ctx);
1688 				else
1689 					emit(A64_LDR32I(dst, src_adj, off_adj), ctx);
1690 			} else {
1691 				emit_a64_mov_i(1, tmp, off, ctx);
1692 				if (sign_extend)
1693 					emit(A64_LDRSW(dst, src, tmp), ctx);
1694 				else
1695 					emit(A64_LDR32(dst, src, tmp), ctx);
1696 			}
1697 			break;
1698 		case BPF_H:
1699 			if (is_lsi_offset(off_adj, 1)) {
1700 				if (sign_extend)
1701 					emit(A64_LDRSHI(dst, src_adj, off_adj), ctx);
1702 				else
1703 					emit(A64_LDRHI(dst, src_adj, off_adj), ctx);
1704 			} else {
1705 				emit_a64_mov_i(1, tmp, off, ctx);
1706 				if (sign_extend)
1707 					emit(A64_LDRSH(dst, src, tmp), ctx);
1708 				else
1709 					emit(A64_LDRH(dst, src, tmp), ctx);
1710 			}
1711 			break;
1712 		case BPF_B:
1713 			if (is_lsi_offset(off_adj, 0)) {
1714 				if (sign_extend)
1715 					emit(A64_LDRSBI(dst, src_adj, off_adj), ctx);
1716 				else
1717 					emit(A64_LDRBI(dst, src_adj, off_adj), ctx);
1718 			} else {
1719 				emit_a64_mov_i(1, tmp, off, ctx);
1720 				if (sign_extend)
1721 					emit(A64_LDRSB(dst, src, tmp), ctx);
1722 				else
1723 					emit(A64_LDRB(dst, src, tmp), ctx);
1724 			}
1725 			break;
1726 		case BPF_DW:
1727 			if (is_lsi_offset(off_adj, 3)) {
1728 				emit(A64_LDR64I(dst, src_adj, off_adj), ctx);
1729 			} else {
1730 				emit_a64_mov_i(1, tmp, off, ctx);
1731 				emit(A64_LDR64(dst, src, tmp), ctx);
1732 			}
1733 			break;
1734 		}
1735 
1736 		ret = add_exception_handler(insn, ctx, dst);
1737 		if (ret)
1738 			return ret;
1739 		break;
1740 
1741 	/* speculation barrier against v1 and v4 */
1742 	case BPF_ST | BPF_NOSPEC:
1743 		if (alternative_has_cap_likely(ARM64_HAS_SB)) {
1744 			emit(A64_SB, ctx);
1745 		} else {
1746 			emit(A64_DSB_NSH, ctx);
1747 			emit(A64_ISB, ctx);
1748 		}
1749 		break;
1750 
1751 	/* ST: *(size *)(dst + off) = imm */
1752 	case BPF_ST | BPF_MEM | BPF_W:
1753 	case BPF_ST | BPF_MEM | BPF_H:
1754 	case BPF_ST | BPF_MEM | BPF_B:
1755 	case BPF_ST | BPF_MEM | BPF_DW:
1756 	case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
1757 	case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
1758 	case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
1759 	case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
1760 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) {
1761 			emit(A64_ADD(1, tmp3, dst, arena_vm_base), ctx);
1762 			dst = tmp3;
1763 		}
1764 		if (dst == fp) {
1765 			dst_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
1766 			off_adj = off + ctx->stack_size;
1767 		} else {
1768 			dst_adj = dst;
1769 			off_adj = off;
1770 		}
1771 		/* Load imm to a register then store it */
1772 		emit_a64_mov_i(1, tmp, imm, ctx);
1773 		switch (BPF_SIZE(code)) {
1774 		case BPF_W:
1775 			if (is_lsi_offset(off_adj, 2)) {
1776 				emit(A64_STR32I(tmp, dst_adj, off_adj), ctx);
1777 			} else {
1778 				emit_a64_mov_i(1, tmp2, off, ctx);
1779 				emit(A64_STR32(tmp, dst, tmp2), ctx);
1780 			}
1781 			break;
1782 		case BPF_H:
1783 			if (is_lsi_offset(off_adj, 1)) {
1784 				emit(A64_STRHI(tmp, dst_adj, off_adj), ctx);
1785 			} else {
1786 				emit_a64_mov_i(1, tmp2, off, ctx);
1787 				emit(A64_STRH(tmp, dst, tmp2), ctx);
1788 			}
1789 			break;
1790 		case BPF_B:
1791 			if (is_lsi_offset(off_adj, 0)) {
1792 				emit(A64_STRBI(tmp, dst_adj, off_adj), ctx);
1793 			} else {
1794 				emit_a64_mov_i(1, tmp2, off, ctx);
1795 				emit(A64_STRB(tmp, dst, tmp2), ctx);
1796 			}
1797 			break;
1798 		case BPF_DW:
1799 			if (is_lsi_offset(off_adj, 3)) {
1800 				emit(A64_STR64I(tmp, dst_adj, off_adj), ctx);
1801 			} else {
1802 				emit_a64_mov_i(1, tmp2, off, ctx);
1803 				emit(A64_STR64(tmp, dst, tmp2), ctx);
1804 			}
1805 			break;
1806 		}
1807 
1808 		ret = add_exception_handler(insn, ctx, dst);
1809 		if (ret)
1810 			return ret;
1811 		break;
1812 
1813 	/* STX: *(size *)(dst + off) = src */
1814 	case BPF_STX | BPF_MEM | BPF_W:
1815 	case BPF_STX | BPF_MEM | BPF_H:
1816 	case BPF_STX | BPF_MEM | BPF_B:
1817 	case BPF_STX | BPF_MEM | BPF_DW:
1818 	case BPF_STX | BPF_PROBE_MEM32 | BPF_B:
1819 	case BPF_STX | BPF_PROBE_MEM32 | BPF_H:
1820 	case BPF_STX | BPF_PROBE_MEM32 | BPF_W:
1821 	case BPF_STX | BPF_PROBE_MEM32 | BPF_DW:
1822 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) {
1823 			emit(A64_ADD(1, tmp2, dst, arena_vm_base), ctx);
1824 			dst = tmp2;
1825 		}
1826 		if (dst == fp) {
1827 			dst_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
1828 			off_adj = off + ctx->stack_size;
1829 		} else {
1830 			dst_adj = dst;
1831 			off_adj = off;
1832 		}
1833 		switch (BPF_SIZE(code)) {
1834 		case BPF_W:
1835 			if (is_lsi_offset(off_adj, 2)) {
1836 				emit(A64_STR32I(src, dst_adj, off_adj), ctx);
1837 			} else {
1838 				emit_a64_mov_i(1, tmp, off, ctx);
1839 				emit(A64_STR32(src, dst, tmp), ctx);
1840 			}
1841 			break;
1842 		case BPF_H:
1843 			if (is_lsi_offset(off_adj, 1)) {
1844 				emit(A64_STRHI(src, dst_adj, off_adj), ctx);
1845 			} else {
1846 				emit_a64_mov_i(1, tmp, off, ctx);
1847 				emit(A64_STRH(src, dst, tmp), ctx);
1848 			}
1849 			break;
1850 		case BPF_B:
1851 			if (is_lsi_offset(off_adj, 0)) {
1852 				emit(A64_STRBI(src, dst_adj, off_adj), ctx);
1853 			} else {
1854 				emit_a64_mov_i(1, tmp, off, ctx);
1855 				emit(A64_STRB(src, dst, tmp), ctx);
1856 			}
1857 			break;
1858 		case BPF_DW:
1859 			if (is_lsi_offset(off_adj, 3)) {
1860 				emit(A64_STR64I(src, dst_adj, off_adj), ctx);
1861 			} else {
1862 				emit_a64_mov_i(1, tmp, off, ctx);
1863 				emit(A64_STR64(src, dst, tmp), ctx);
1864 			}
1865 			break;
1866 		}
1867 
1868 		ret = add_exception_handler(insn, ctx, dst);
1869 		if (ret)
1870 			return ret;
1871 		break;
1872 
1873 	case BPF_STX | BPF_ATOMIC | BPF_B:
1874 	case BPF_STX | BPF_ATOMIC | BPF_H:
1875 	case BPF_STX | BPF_ATOMIC | BPF_W:
1876 	case BPF_STX | BPF_ATOMIC | BPF_DW:
1877 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_B:
1878 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_H:
1879 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_W:
1880 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
1881 		if (bpf_atomic_is_load_store(insn))
1882 			ret = emit_atomic_ld_st(insn, ctx);
1883 		else if (cpus_have_cap(ARM64_HAS_LSE_ATOMICS))
1884 			ret = emit_lse_atomic(insn, ctx);
1885 		else
1886 			ret = emit_ll_sc_atomic(insn, ctx);
1887 		if (ret)
1888 			return ret;
1889 
1890 		if (BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
1891 			ret = add_exception_handler(insn, ctx, dst);
1892 			if (ret)
1893 				return ret;
1894 		}
1895 		break;
1896 
1897 	default:
1898 		pr_err_once("unknown opcode %02x\n", code);
1899 		return -EINVAL;
1900 	}
1901 
1902 	return 0;
1903 }
1904 
1905 static int build_body(struct jit_ctx *ctx, bool extra_pass)
1906 {
1907 	const struct bpf_prog *prog = ctx->prog;
1908 	int i;
1909 
1910 	/*
1911 	 * - offset[0] offset of the end of prologue,
1912 	 *   start of the 1st instruction.
1913 	 * - offset[1] - offset of the end of 1st instruction,
1914 	 *   start of the 2nd instruction
1915 	 * [....]
1916 	 * - offset[3] - offset of the end of 3rd instruction,
1917 	 *   start of 4th instruction
1918 	 */
1919 	for (i = 0; i < prog->len; i++) {
1920 		const struct bpf_insn *insn = &prog->insnsi[i];
1921 		int ret;
1922 
1923 		ctx->offset[i] = ctx->idx;
1924 		ret = build_insn(insn, ctx, extra_pass);
1925 		if (ret > 0) {
1926 			i++;
1927 			ctx->offset[i] = ctx->idx;
1928 			continue;
1929 		}
1930 		if (ret)
1931 			return ret;
1932 	}
1933 	/*
1934 	 * offset is allocated with prog->len + 1 so fill in
1935 	 * the last element with the offset after the last
1936 	 * instruction (end of program)
1937 	 */
1938 	ctx->offset[i] = ctx->idx;
1939 
1940 	return 0;
1941 }
1942 
1943 static int validate_code(struct jit_ctx *ctx)
1944 {
1945 	int i;
1946 
1947 	for (i = 0; i < ctx->idx; i++) {
1948 		u32 a64_insn = le32_to_cpu(ctx->image[i]);
1949 
1950 		if (a64_insn == AARCH64_BREAK_FAULT)
1951 			return -1;
1952 	}
1953 	return 0;
1954 }
1955 
1956 static int validate_ctx(struct jit_ctx *ctx)
1957 {
1958 	if (validate_code(ctx))
1959 		return -1;
1960 
1961 	if (WARN_ON_ONCE(ctx->exentry_idx != ctx->prog->aux->num_exentries))
1962 		return -1;
1963 
1964 	return 0;
1965 }
1966 
1967 static inline void bpf_flush_icache(void *start, void *end)
1968 {
1969 	flush_icache_range((unsigned long)start, (unsigned long)end);
1970 }
1971 
1972 static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
1973 {
1974 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
1975 	u64 *stack_ptr;
1976 
1977 	for_each_possible_cpu(cpu) {
1978 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
1979 		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
1980 		stack_ptr[1] = PRIV_STACK_GUARD_VAL;
1981 		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
1982 		stack_ptr[underflow_idx + 1] = PRIV_STACK_GUARD_VAL;
1983 	}
1984 }
1985 
1986 static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
1987 				   struct bpf_prog *prog)
1988 {
1989 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
1990 	u64 *stack_ptr;
1991 
1992 	for_each_possible_cpu(cpu) {
1993 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
1994 		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
1995 		    stack_ptr[1] != PRIV_STACK_GUARD_VAL ||
1996 		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL ||
1997 		    stack_ptr[underflow_idx + 1] != PRIV_STACK_GUARD_VAL) {
1998 			pr_err("BPF private stack overflow/underflow detected for prog %sx\n",
1999 			       bpf_jit_get_prog_name(prog));
2000 			break;
2001 		}
2002 	}
2003 }
2004 
2005 struct arm64_jit_data {
2006 	struct bpf_binary_header *header;
2007 	u8 *ro_image;
2008 	struct bpf_binary_header *ro_header;
2009 	struct jit_ctx ctx;
2010 };
2011 
2012 struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
2013 {
2014 	int image_size, prog_size, extable_size, extable_align, extable_offset;
2015 	struct bpf_prog *tmp, *orig_prog = prog;
2016 	struct bpf_binary_header *header;
2017 	struct bpf_binary_header *ro_header = NULL;
2018 	struct arm64_jit_data *jit_data;
2019 	void __percpu *priv_stack_ptr = NULL;
2020 	bool was_classic = bpf_prog_was_classic(prog);
2021 	int priv_stack_alloc_sz;
2022 	bool tmp_blinded = false;
2023 	bool extra_pass = false;
2024 	struct jit_ctx ctx;
2025 	u8 *image_ptr;
2026 	u8 *ro_image_ptr;
2027 	int body_idx;
2028 	int exentry_idx;
2029 
2030 	if (!prog->jit_requested)
2031 		return orig_prog;
2032 
2033 	tmp = bpf_jit_blind_constants(prog);
2034 	/* If blinding was requested and we failed during blinding,
2035 	 * we must fall back to the interpreter.
2036 	 */
2037 	if (IS_ERR(tmp))
2038 		return orig_prog;
2039 	if (tmp != prog) {
2040 		tmp_blinded = true;
2041 		prog = tmp;
2042 	}
2043 
2044 	jit_data = prog->aux->jit_data;
2045 	if (!jit_data) {
2046 		jit_data = kzalloc(sizeof(*jit_data), GFP_KERNEL);
2047 		if (!jit_data) {
2048 			prog = orig_prog;
2049 			goto out;
2050 		}
2051 		prog->aux->jit_data = jit_data;
2052 	}
2053 	priv_stack_ptr = prog->aux->priv_stack_ptr;
2054 	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
2055 		/* Allocate actual private stack size with verifier-calculated
2056 		 * stack size plus two memory guards to protect overflow and
2057 		 * underflow.
2058 		 */
2059 		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
2060 				      2 * PRIV_STACK_GUARD_SZ;
2061 		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 16, GFP_KERNEL);
2062 		if (!priv_stack_ptr) {
2063 			prog = orig_prog;
2064 			goto out_priv_stack;
2065 		}
2066 
2067 		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
2068 		prog->aux->priv_stack_ptr = priv_stack_ptr;
2069 	}
2070 	if (jit_data->ctx.offset) {
2071 		ctx = jit_data->ctx;
2072 		ro_image_ptr = jit_data->ro_image;
2073 		ro_header = jit_data->ro_header;
2074 		header = jit_data->header;
2075 		image_ptr = (void *)header + ((void *)ro_image_ptr
2076 						 - (void *)ro_header);
2077 		extra_pass = true;
2078 		prog_size = sizeof(u32) * ctx.idx;
2079 		goto skip_init_ctx;
2080 	}
2081 	memset(&ctx, 0, sizeof(ctx));
2082 	ctx.prog = prog;
2083 
2084 	ctx.offset = kvcalloc(prog->len + 1, sizeof(int), GFP_KERNEL);
2085 	if (ctx.offset == NULL) {
2086 		prog = orig_prog;
2087 		goto out_off;
2088 	}
2089 
2090 	ctx.user_vm_start = bpf_arena_get_user_vm_start(prog->aux->arena);
2091 	ctx.arena_vm_start = bpf_arena_get_kern_vm_start(prog->aux->arena);
2092 
2093 	if (priv_stack_ptr)
2094 		ctx.priv_sp_used = true;
2095 
2096 	/* Pass 1: Estimate the maximum image size.
2097 	 *
2098 	 * BPF line info needs ctx->offset[i] to be the offset of
2099 	 * instruction[i] in jited image, so build prologue first.
2100 	 */
2101 	if (build_prologue(&ctx, was_classic)) {
2102 		prog = orig_prog;
2103 		goto out_off;
2104 	}
2105 
2106 	if (build_body(&ctx, extra_pass)) {
2107 		prog = orig_prog;
2108 		goto out_off;
2109 	}
2110 
2111 	ctx.epilogue_offset = ctx.idx;
2112 	build_epilogue(&ctx, was_classic);
2113 	build_plt(&ctx);
2114 
2115 	extable_align = __alignof__(struct exception_table_entry);
2116 	extable_size = prog->aux->num_exentries *
2117 		sizeof(struct exception_table_entry);
2118 
2119 	/* Now we know the maximum image size. */
2120 	prog_size = sizeof(u32) * ctx.idx;
2121 	/* also allocate space for plt target */
2122 	extable_offset = round_up(prog_size + PLT_TARGET_SIZE, extable_align);
2123 	image_size = extable_offset + extable_size;
2124 	ro_header = bpf_jit_binary_pack_alloc(image_size, &ro_image_ptr,
2125 					      sizeof(u32), &header, &image_ptr,
2126 					      jit_fill_hole);
2127 	if (!ro_header) {
2128 		prog = orig_prog;
2129 		goto out_off;
2130 	}
2131 
2132 	/* Pass 2: Determine jited position and result for each instruction */
2133 
2134 	/*
2135 	 * Use the image(RW) for writing the JITed instructions. But also save
2136 	 * the ro_image(RX) for calculating the offsets in the image. The RW
2137 	 * image will be later copied to the RX image from where the program
2138 	 * will run. The bpf_jit_binary_pack_finalize() will do this copy in the
2139 	 * final step.
2140 	 */
2141 	ctx.image = (__le32 *)image_ptr;
2142 	ctx.ro_image = (__le32 *)ro_image_ptr;
2143 	if (extable_size)
2144 		prog->aux->extable = (void *)ro_image_ptr + extable_offset;
2145 skip_init_ctx:
2146 	ctx.idx = 0;
2147 	ctx.exentry_idx = 0;
2148 	ctx.write = true;
2149 
2150 	build_prologue(&ctx, was_classic);
2151 
2152 	/* Record exentry_idx and body_idx before first build_body */
2153 	exentry_idx = ctx.exentry_idx;
2154 	body_idx = ctx.idx;
2155 	/* Dont write body instructions to memory for now */
2156 	ctx.write = false;
2157 
2158 	if (build_body(&ctx, extra_pass)) {
2159 		prog = orig_prog;
2160 		goto out_free_hdr;
2161 	}
2162 
2163 	ctx.epilogue_offset = ctx.idx;
2164 	ctx.exentry_idx = exentry_idx;
2165 	ctx.idx = body_idx;
2166 	ctx.write = true;
2167 
2168 	/* Pass 3: Adjust jump offset and write final image */
2169 	if (build_body(&ctx, extra_pass) ||
2170 		WARN_ON_ONCE(ctx.idx != ctx.epilogue_offset)) {
2171 		prog = orig_prog;
2172 		goto out_free_hdr;
2173 	}
2174 
2175 	build_epilogue(&ctx, was_classic);
2176 	build_plt(&ctx);
2177 
2178 	/* Extra pass to validate JITed code. */
2179 	if (validate_ctx(&ctx)) {
2180 		prog = orig_prog;
2181 		goto out_free_hdr;
2182 	}
2183 
2184 	/* update the real prog size */
2185 	prog_size = sizeof(u32) * ctx.idx;
2186 
2187 	/* And we're done. */
2188 	if (bpf_jit_enable > 1)
2189 		bpf_jit_dump(prog->len, prog_size, 2, ctx.image);
2190 
2191 	if (!prog->is_func || extra_pass) {
2192 		/* The jited image may shrink since the jited result for
2193 		 * BPF_CALL to subprog may be changed from indirect call
2194 		 * to direct call.
2195 		 */
2196 		if (extra_pass && ctx.idx > jit_data->ctx.idx) {
2197 			pr_err_once("multi-func JIT bug %d > %d\n",
2198 				    ctx.idx, jit_data->ctx.idx);
2199 			prog->bpf_func = NULL;
2200 			prog->jited = 0;
2201 			prog->jited_len = 0;
2202 			goto out_free_hdr;
2203 		}
2204 		if (WARN_ON(bpf_jit_binary_pack_finalize(ro_header, header))) {
2205 			/* ro_header has been freed */
2206 			ro_header = NULL;
2207 			prog = orig_prog;
2208 			goto out_off;
2209 		}
2210 		/*
2211 		 * The instructions have now been copied to the ROX region from
2212 		 * where they will execute. Now the data cache has to be cleaned to
2213 		 * the PoU and the I-cache has to be invalidated for the VAs.
2214 		 */
2215 		bpf_flush_icache(ro_header, ctx.ro_image + ctx.idx);
2216 	} else {
2217 		jit_data->ctx = ctx;
2218 		jit_data->ro_image = ro_image_ptr;
2219 		jit_data->header = header;
2220 		jit_data->ro_header = ro_header;
2221 	}
2222 
2223 	prog->bpf_func = (void *)ctx.ro_image + cfi_get_offset();
2224 	prog->jited = 1;
2225 	prog->jited_len = prog_size - cfi_get_offset();
2226 
2227 	if (!prog->is_func || extra_pass) {
2228 		int i;
2229 
2230 		/* offset[prog->len] is the size of program */
2231 		for (i = 0; i <= prog->len; i++)
2232 			ctx.offset[i] *= AARCH64_INSN_SIZE;
2233 		bpf_prog_fill_jited_linfo(prog, ctx.offset + 1);
2234 out_off:
2235 		if (!ro_header && priv_stack_ptr) {
2236 			free_percpu(priv_stack_ptr);
2237 			prog->aux->priv_stack_ptr = NULL;
2238 		}
2239 		kvfree(ctx.offset);
2240 out_priv_stack:
2241 		kfree(jit_data);
2242 		prog->aux->jit_data = NULL;
2243 	}
2244 out:
2245 	if (tmp_blinded)
2246 		bpf_jit_prog_release_other(prog, prog == orig_prog ?
2247 					   tmp : orig_prog);
2248 	return prog;
2249 
2250 out_free_hdr:
2251 	if (header) {
2252 		bpf_arch_text_copy(&ro_header->size, &header->size,
2253 				   sizeof(header->size));
2254 		bpf_jit_binary_pack_free(ro_header, header);
2255 	}
2256 	goto out_off;
2257 }
2258 
2259 bool bpf_jit_supports_private_stack(void)
2260 {
2261 	return true;
2262 }
2263 
2264 bool bpf_jit_supports_kfunc_call(void)
2265 {
2266 	return true;
2267 }
2268 
2269 void *bpf_arch_text_copy(void *dst, void *src, size_t len)
2270 {
2271 	if (!aarch64_insn_copy(dst, src, len))
2272 		return ERR_PTR(-EINVAL);
2273 	return dst;
2274 }
2275 
2276 u64 bpf_jit_alloc_exec_limit(void)
2277 {
2278 	return VMALLOC_END - VMALLOC_START;
2279 }
2280 
2281 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
2282 bool bpf_jit_supports_subprog_tailcalls(void)
2283 {
2284 	return true;
2285 }
2286 
2287 static void invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_link *l,
2288 			    int bargs_off, int retval_off, int run_ctx_off,
2289 			    bool save_ret)
2290 {
2291 	__le32 *branch;
2292 	u64 enter_prog;
2293 	u64 exit_prog;
2294 	struct bpf_prog *p = l->link.prog;
2295 	int cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
2296 
2297 	enter_prog = (u64)bpf_trampoline_enter(p);
2298 	exit_prog = (u64)bpf_trampoline_exit(p);
2299 
2300 	if (l->cookie == 0) {
2301 		/* if cookie is zero, one instruction is enough to store it */
2302 		emit(A64_STR64I(A64_ZR, A64_SP, run_ctx_off + cookie_off), ctx);
2303 	} else {
2304 		emit_a64_mov_i64(A64_R(10), l->cookie, ctx);
2305 		emit(A64_STR64I(A64_R(10), A64_SP, run_ctx_off + cookie_off),
2306 		     ctx);
2307 	}
2308 
2309 	/* save p to callee saved register x19 to avoid loading p with mov_i64
2310 	 * each time.
2311 	 */
2312 	emit_addr_mov_i64(A64_R(19), (const u64)p, ctx);
2313 
2314 	/* arg1: prog */
2315 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
2316 	/* arg2: &run_ctx */
2317 	emit(A64_ADD_I(1, A64_R(1), A64_SP, run_ctx_off), ctx);
2318 
2319 	emit_call(enter_prog, ctx);
2320 
2321 	/* save return value to callee saved register x20 */
2322 	emit(A64_MOV(1, A64_R(20), A64_R(0)), ctx);
2323 
2324 	/* if (__bpf_prog_enter(prog) == 0)
2325 	 *         goto skip_exec_of_prog;
2326 	 */
2327 	branch = ctx->image + ctx->idx;
2328 	emit(A64_NOP, ctx);
2329 
2330 	emit(A64_ADD_I(1, A64_R(0), A64_SP, bargs_off), ctx);
2331 	if (!p->jited)
2332 		emit_addr_mov_i64(A64_R(1), (const u64)p->insnsi, ctx);
2333 
2334 	emit_call((const u64)p->bpf_func, ctx);
2335 
2336 	if (save_ret)
2337 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
2338 
2339 	if (ctx->image) {
2340 		int offset = &ctx->image[ctx->idx] - branch;
2341 		*branch = cpu_to_le32(A64_CBZ(1, A64_R(0), offset));
2342 	}
2343 
2344 	/* arg1: prog */
2345 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
2346 	/* arg2: start time */
2347 	emit(A64_MOV(1, A64_R(1), A64_R(20)), ctx);
2348 	/* arg3: &run_ctx */
2349 	emit(A64_ADD_I(1, A64_R(2), A64_SP, run_ctx_off), ctx);
2350 
2351 	emit_call(exit_prog, ctx);
2352 }
2353 
2354 static void invoke_bpf_mod_ret(struct jit_ctx *ctx, struct bpf_tramp_links *tl,
2355 			       int bargs_off, int retval_off, int run_ctx_off,
2356 			       __le32 **branches)
2357 {
2358 	int i;
2359 
2360 	/* The first fmod_ret program will receive a garbage return value.
2361 	 * Set this to 0 to avoid confusing the program.
2362 	 */
2363 	emit(A64_STR64I(A64_ZR, A64_SP, retval_off), ctx);
2364 	for (i = 0; i < tl->nr_links; i++) {
2365 		invoke_bpf_prog(ctx, tl->links[i], bargs_off, retval_off,
2366 				run_ctx_off, true);
2367 		/* if (*(u64 *)(sp + retval_off) !=  0)
2368 		 *	goto do_fexit;
2369 		 */
2370 		emit(A64_LDR64I(A64_R(10), A64_SP, retval_off), ctx);
2371 		/* Save the location of branch, and generate a nop.
2372 		 * This nop will be replaced with a cbnz later.
2373 		 */
2374 		branches[i] = ctx->image + ctx->idx;
2375 		emit(A64_NOP, ctx);
2376 	}
2377 }
2378 
2379 struct arg_aux {
2380 	/* how many args are passed through registers, the rest of the args are
2381 	 * passed through stack
2382 	 */
2383 	int args_in_regs;
2384 	/* how many registers are used to pass arguments */
2385 	int regs_for_args;
2386 	/* how much stack is used for additional args passed to bpf program
2387 	 * that did not fit in original function registers
2388 	 */
2389 	int bstack_for_args;
2390 	/* home much stack is used for additional args passed to the
2391 	 * original function when called from trampoline (this one needs
2392 	 * arguments to be properly aligned)
2393 	 */
2394 	int ostack_for_args;
2395 };
2396 
2397 static int calc_arg_aux(const struct btf_func_model *m,
2398 			 struct arg_aux *a)
2399 {
2400 	int stack_slots, nregs, slots, i;
2401 
2402 	/* verifier ensures m->nr_args <= MAX_BPF_FUNC_ARGS */
2403 	for (i = 0, nregs = 0; i < m->nr_args; i++) {
2404 		slots = (m->arg_size[i] + 7) / 8;
2405 		if (nregs + slots <= 8) /* passed through register ? */
2406 			nregs += slots;
2407 		else
2408 			break;
2409 	}
2410 
2411 	a->args_in_regs = i;
2412 	a->regs_for_args = nregs;
2413 	a->ostack_for_args = 0;
2414 	a->bstack_for_args = 0;
2415 
2416 	/* the rest arguments are passed through stack */
2417 	for (; i < m->nr_args; i++) {
2418 		stack_slots = (m->arg_size[i] + 7) / 8;
2419 		a->bstack_for_args += stack_slots * 8;
2420 		a->ostack_for_args = a->ostack_for_args + stack_slots * 8;
2421 	}
2422 
2423 	return 0;
2424 }
2425 
2426 static void clear_garbage(struct jit_ctx *ctx, int reg, int effective_bytes)
2427 {
2428 	if (effective_bytes) {
2429 		int garbage_bits = 64 - 8 * effective_bytes;
2430 #ifdef CONFIG_CPU_BIG_ENDIAN
2431 		/* garbage bits are at the right end */
2432 		emit(A64_LSR(1, reg, reg, garbage_bits), ctx);
2433 		emit(A64_LSL(1, reg, reg, garbage_bits), ctx);
2434 #else
2435 		/* garbage bits are at the left end */
2436 		emit(A64_LSL(1, reg, reg, garbage_bits), ctx);
2437 		emit(A64_LSR(1, reg, reg, garbage_bits), ctx);
2438 #endif
2439 	}
2440 }
2441 
2442 static void save_args(struct jit_ctx *ctx, int bargs_off, int oargs_off,
2443 		      const struct btf_func_model *m,
2444 		      const struct arg_aux *a,
2445 		      bool for_call_origin)
2446 {
2447 	int i;
2448 	int reg;
2449 	int doff;
2450 	int soff;
2451 	int slots;
2452 	u8 tmp = bpf2a64[TMP_REG_1];
2453 
2454 	/* store arguments to the stack for the bpf program, or restore
2455 	 * arguments from stack for the original function
2456 	 */
2457 	for (reg = 0; reg < a->regs_for_args; reg++) {
2458 		emit(for_call_origin ?
2459 		     A64_LDR64I(reg, A64_SP, bargs_off) :
2460 		     A64_STR64I(reg, A64_SP, bargs_off),
2461 		     ctx);
2462 		bargs_off += 8;
2463 	}
2464 
2465 	soff = 32; /* on stack arguments start from FP + 32 */
2466 	doff = (for_call_origin ? oargs_off : bargs_off);
2467 
2468 	/* save on stack arguments */
2469 	for (i = a->args_in_regs; i < m->nr_args; i++) {
2470 		slots = (m->arg_size[i] + 7) / 8;
2471 		/* verifier ensures arg_size <= 16, so slots equals 1 or 2 */
2472 		while (slots-- > 0) {
2473 			emit(A64_LDR64I(tmp, A64_FP, soff), ctx);
2474 			/* if there is unused space in the last slot, clear
2475 			 * the garbage contained in the space.
2476 			 */
2477 			if (slots == 0 && !for_call_origin)
2478 				clear_garbage(ctx, tmp, m->arg_size[i] % 8);
2479 			emit(A64_STR64I(tmp, A64_SP, doff), ctx);
2480 			soff += 8;
2481 			doff += 8;
2482 		}
2483 	}
2484 }
2485 
2486 static void restore_args(struct jit_ctx *ctx, int bargs_off, int nregs)
2487 {
2488 	int reg;
2489 
2490 	for (reg = 0; reg < nregs; reg++) {
2491 		emit(A64_LDR64I(reg, A64_SP, bargs_off), ctx);
2492 		bargs_off += 8;
2493 	}
2494 }
2495 
2496 static bool is_struct_ops_tramp(const struct bpf_tramp_links *fentry_links)
2497 {
2498 	return fentry_links->nr_links == 1 &&
2499 		fentry_links->links[0]->link.type == BPF_LINK_TYPE_STRUCT_OPS;
2500 }
2501 
2502 /* Based on the x86's implementation of arch_prepare_bpf_trampoline().
2503  *
2504  * bpf prog and function entry before bpf trampoline hooked:
2505  *   mov x9, lr
2506  *   nop
2507  *
2508  * bpf prog and function entry after bpf trampoline hooked:
2509  *   mov x9, lr
2510  *   bl  <bpf_trampoline or plt>
2511  *
2512  */
2513 static int prepare_trampoline(struct jit_ctx *ctx, struct bpf_tramp_image *im,
2514 			      struct bpf_tramp_links *tlinks, void *func_addr,
2515 			      const struct btf_func_model *m,
2516 			      const struct arg_aux *a,
2517 			      u32 flags)
2518 {
2519 	int i;
2520 	int stack_size;
2521 	int retaddr_off;
2522 	int regs_off;
2523 	int retval_off;
2524 	int bargs_off;
2525 	int nfuncargs_off;
2526 	int ip_off;
2527 	int run_ctx_off;
2528 	int oargs_off;
2529 	int nfuncargs;
2530 	struct bpf_tramp_links *fentry = &tlinks[BPF_TRAMP_FENTRY];
2531 	struct bpf_tramp_links *fexit = &tlinks[BPF_TRAMP_FEXIT];
2532 	struct bpf_tramp_links *fmod_ret = &tlinks[BPF_TRAMP_MODIFY_RETURN];
2533 	bool save_ret;
2534 	__le32 **branches = NULL;
2535 	bool is_struct_ops = is_struct_ops_tramp(fentry);
2536 
2537 	/* trampoline stack layout:
2538 	 *                    [ parent ip         ]
2539 	 *                    [ FP                ]
2540 	 * SP + retaddr_off   [ self ip           ]
2541 	 *                    [ FP                ]
2542 	 *
2543 	 *                    [ padding           ] align SP to multiples of 16
2544 	 *
2545 	 *                    [ x20               ] callee saved reg x20
2546 	 * SP + regs_off      [ x19               ] callee saved reg x19
2547 	 *
2548 	 * SP + retval_off    [ return value      ] BPF_TRAMP_F_CALL_ORIG or
2549 	 *                                          BPF_TRAMP_F_RET_FENTRY_RET
2550 	 *                    [ arg reg N         ]
2551 	 *                    [ ...               ]
2552 	 * SP + bargs_off     [ arg reg 1         ] for bpf
2553 	 *
2554 	 * SP + nfuncargs_off [ arg regs count    ]
2555 	 *
2556 	 * SP + ip_off        [ traced function   ] BPF_TRAMP_F_IP_ARG flag
2557 	 *
2558 	 * SP + run_ctx_off   [ bpf_tramp_run_ctx ]
2559 	 *
2560 	 *                    [ stack arg N       ]
2561 	 *                    [ ...               ]
2562 	 * SP + oargs_off     [ stack arg 1       ] for original func
2563 	 */
2564 
2565 	stack_size = 0;
2566 	oargs_off = stack_size;
2567 	if (flags & BPF_TRAMP_F_CALL_ORIG)
2568 		stack_size +=  a->ostack_for_args;
2569 
2570 	run_ctx_off = stack_size;
2571 	/* room for bpf_tramp_run_ctx */
2572 	stack_size += round_up(sizeof(struct bpf_tramp_run_ctx), 8);
2573 
2574 	ip_off = stack_size;
2575 	/* room for IP address argument */
2576 	if (flags & BPF_TRAMP_F_IP_ARG)
2577 		stack_size += 8;
2578 
2579 	nfuncargs_off = stack_size;
2580 	/* room for args count */
2581 	stack_size += 8;
2582 
2583 	bargs_off = stack_size;
2584 	/* room for args */
2585 	nfuncargs = a->regs_for_args + a->bstack_for_args / 8;
2586 	stack_size += 8 * nfuncargs;
2587 
2588 	/* room for return value */
2589 	retval_off = stack_size;
2590 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
2591 	if (save_ret)
2592 		stack_size += 8;
2593 
2594 	/* room for callee saved registers, currently x19 and x20 are used */
2595 	regs_off = stack_size;
2596 	stack_size += 16;
2597 
2598 	/* round up to multiples of 16 to avoid SPAlignmentFault */
2599 	stack_size = round_up(stack_size, 16);
2600 
2601 	/* return address locates above FP */
2602 	retaddr_off = stack_size + 8;
2603 
2604 	if (flags & BPF_TRAMP_F_INDIRECT) {
2605 		/*
2606 		 * Indirect call for bpf_struct_ops
2607 		 */
2608 		emit_kcfi(cfi_get_func_hash(func_addr), ctx);
2609 	}
2610 	/* bpf trampoline may be invoked by 3 instruction types:
2611 	 * 1. bl, attached to bpf prog or kernel function via short jump
2612 	 * 2. br, attached to bpf prog or kernel function via long jump
2613 	 * 3. blr, working as a function pointer, used by struct_ops.
2614 	 * So BTI_JC should used here to support both br and blr.
2615 	 */
2616 	emit_bti(A64_BTI_JC, ctx);
2617 
2618 	/* x9 is not set for struct_ops */
2619 	if (!is_struct_ops) {
2620 		/* frame for parent function */
2621 		emit(A64_PUSH(A64_FP, A64_R(9), A64_SP), ctx);
2622 		emit(A64_MOV(1, A64_FP, A64_SP), ctx);
2623 	}
2624 
2625 	/* frame for patched function for tracing, or caller for struct_ops */
2626 	emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
2627 	emit(A64_MOV(1, A64_FP, A64_SP), ctx);
2628 
2629 	/* allocate stack space */
2630 	emit(A64_SUB_I(1, A64_SP, A64_SP, stack_size), ctx);
2631 
2632 	if (flags & BPF_TRAMP_F_IP_ARG) {
2633 		/* save ip address of the traced function */
2634 		emit_addr_mov_i64(A64_R(10), (const u64)func_addr, ctx);
2635 		emit(A64_STR64I(A64_R(10), A64_SP, ip_off), ctx);
2636 	}
2637 
2638 	/* save arg regs count*/
2639 	emit(A64_MOVZ(1, A64_R(10), nfuncargs, 0), ctx);
2640 	emit(A64_STR64I(A64_R(10), A64_SP, nfuncargs_off), ctx);
2641 
2642 	/* save args for bpf */
2643 	save_args(ctx, bargs_off, oargs_off, m, a, false);
2644 
2645 	/* save callee saved registers */
2646 	emit(A64_STR64I(A64_R(19), A64_SP, regs_off), ctx);
2647 	emit(A64_STR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
2648 
2649 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2650 		/* for the first pass, assume the worst case */
2651 		if (!ctx->image)
2652 			ctx->idx += 4;
2653 		else
2654 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
2655 		emit_call((const u64)__bpf_tramp_enter, ctx);
2656 	}
2657 
2658 	for (i = 0; i < fentry->nr_links; i++)
2659 		invoke_bpf_prog(ctx, fentry->links[i], bargs_off,
2660 				retval_off, run_ctx_off,
2661 				flags & BPF_TRAMP_F_RET_FENTRY_RET);
2662 
2663 	if (fmod_ret->nr_links) {
2664 		branches = kcalloc(fmod_ret->nr_links, sizeof(__le32 *),
2665 				   GFP_KERNEL);
2666 		if (!branches)
2667 			return -ENOMEM;
2668 
2669 		invoke_bpf_mod_ret(ctx, fmod_ret, bargs_off, retval_off,
2670 				   run_ctx_off, branches);
2671 	}
2672 
2673 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2674 		/* save args for original func */
2675 		save_args(ctx, bargs_off, oargs_off, m, a, true);
2676 		/* call original func */
2677 		emit(A64_LDR64I(A64_R(10), A64_SP, retaddr_off), ctx);
2678 		emit(A64_ADR(A64_LR, AARCH64_INSN_SIZE * 2), ctx);
2679 		emit(A64_RET(A64_R(10)), ctx);
2680 		/* store return value */
2681 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
2682 		/* reserve a nop for bpf_tramp_image_put */
2683 		im->ip_after_call = ctx->ro_image + ctx->idx;
2684 		emit(A64_NOP, ctx);
2685 	}
2686 
2687 	/* update the branches saved in invoke_bpf_mod_ret with cbnz */
2688 	for (i = 0; i < fmod_ret->nr_links && ctx->image != NULL; i++) {
2689 		int offset = &ctx->image[ctx->idx] - branches[i];
2690 		*branches[i] = cpu_to_le32(A64_CBNZ(1, A64_R(10), offset));
2691 	}
2692 
2693 	for (i = 0; i < fexit->nr_links; i++)
2694 		invoke_bpf_prog(ctx, fexit->links[i], bargs_off, retval_off,
2695 				run_ctx_off, false);
2696 
2697 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
2698 		im->ip_epilogue = ctx->ro_image + ctx->idx;
2699 		/* for the first pass, assume the worst case */
2700 		if (!ctx->image)
2701 			ctx->idx += 4;
2702 		else
2703 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
2704 		emit_call((const u64)__bpf_tramp_exit, ctx);
2705 	}
2706 
2707 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
2708 		restore_args(ctx, bargs_off, a->regs_for_args);
2709 
2710 	/* restore callee saved register x19 and x20 */
2711 	emit(A64_LDR64I(A64_R(19), A64_SP, regs_off), ctx);
2712 	emit(A64_LDR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
2713 
2714 	if (save_ret)
2715 		emit(A64_LDR64I(A64_R(0), A64_SP, retval_off), ctx);
2716 
2717 	/* reset SP  */
2718 	emit(A64_MOV(1, A64_SP, A64_FP), ctx);
2719 
2720 	if (is_struct_ops) {
2721 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
2722 		emit(A64_RET(A64_LR), ctx);
2723 	} else {
2724 		/* pop frames */
2725 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
2726 		emit(A64_POP(A64_FP, A64_R(9), A64_SP), ctx);
2727 
2728 		if (flags & BPF_TRAMP_F_SKIP_FRAME) {
2729 			/* skip patched function, return to parent */
2730 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
2731 			emit(A64_RET(A64_R(9)), ctx);
2732 		} else {
2733 			/* return to patched function */
2734 			emit(A64_MOV(1, A64_R(10), A64_LR), ctx);
2735 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
2736 			emit(A64_RET(A64_R(10)), ctx);
2737 		}
2738 	}
2739 
2740 	kfree(branches);
2741 
2742 	return ctx->idx;
2743 }
2744 
2745 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
2746 			     struct bpf_tramp_links *tlinks, void *func_addr)
2747 {
2748 	struct jit_ctx ctx = {
2749 		.image = NULL,
2750 		.idx = 0,
2751 	};
2752 	struct bpf_tramp_image im;
2753 	struct arg_aux aaux;
2754 	int ret;
2755 
2756 	ret = calc_arg_aux(m, &aaux);
2757 	if (ret < 0)
2758 		return ret;
2759 
2760 	ret = prepare_trampoline(&ctx, &im, tlinks, func_addr, m, &aaux, flags);
2761 	if (ret < 0)
2762 		return ret;
2763 
2764 	return ret < 0 ? ret : ret * AARCH64_INSN_SIZE;
2765 }
2766 
2767 void *arch_alloc_bpf_trampoline(unsigned int size)
2768 {
2769 	return bpf_prog_pack_alloc(size, jit_fill_hole);
2770 }
2771 
2772 void arch_free_bpf_trampoline(void *image, unsigned int size)
2773 {
2774 	bpf_prog_pack_free(image, size);
2775 }
2776 
2777 int arch_protect_bpf_trampoline(void *image, unsigned int size)
2778 {
2779 	return 0;
2780 }
2781 
2782 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *ro_image,
2783 				void *ro_image_end, const struct btf_func_model *m,
2784 				u32 flags, struct bpf_tramp_links *tlinks,
2785 				void *func_addr)
2786 {
2787 	u32 size = ro_image_end - ro_image;
2788 	struct arg_aux aaux;
2789 	void *image, *tmp;
2790 	int ret;
2791 
2792 	/* image doesn't need to be in module memory range, so we can
2793 	 * use kvmalloc.
2794 	 */
2795 	image = kvmalloc(size, GFP_KERNEL);
2796 	if (!image)
2797 		return -ENOMEM;
2798 
2799 	struct jit_ctx ctx = {
2800 		.image = image,
2801 		.ro_image = ro_image,
2802 		.idx = 0,
2803 		.write = true,
2804 	};
2805 
2806 
2807 	jit_fill_hole(image, (unsigned int)(ro_image_end - ro_image));
2808 	ret = calc_arg_aux(m, &aaux);
2809 	if (ret)
2810 		goto out;
2811 	ret = prepare_trampoline(&ctx, im, tlinks, func_addr, m, &aaux, flags);
2812 
2813 	if (ret > 0 && validate_code(&ctx) < 0) {
2814 		ret = -EINVAL;
2815 		goto out;
2816 	}
2817 
2818 	if (ret > 0)
2819 		ret *= AARCH64_INSN_SIZE;
2820 
2821 	tmp = bpf_arch_text_copy(ro_image, image, size);
2822 	if (IS_ERR(tmp)) {
2823 		ret = PTR_ERR(tmp);
2824 		goto out;
2825 	}
2826 
2827 out:
2828 	kvfree(image);
2829 	return ret;
2830 }
2831 
2832 static bool is_long_jump(void *ip, void *target)
2833 {
2834 	long offset;
2835 
2836 	/* NULL target means this is a NOP */
2837 	if (!target)
2838 		return false;
2839 
2840 	offset = (long)target - (long)ip;
2841 	return offset < -SZ_128M || offset >= SZ_128M;
2842 }
2843 
2844 static int gen_branch_or_nop(enum aarch64_insn_branch_type type, void *ip,
2845 			     void *addr, void *plt, u32 *insn)
2846 {
2847 	void *target;
2848 
2849 	if (!addr) {
2850 		*insn = aarch64_insn_gen_nop();
2851 		return 0;
2852 	}
2853 
2854 	if (is_long_jump(ip, addr))
2855 		target = plt;
2856 	else
2857 		target = addr;
2858 
2859 	*insn = aarch64_insn_gen_branch_imm((unsigned long)ip,
2860 					    (unsigned long)target,
2861 					    type);
2862 
2863 	return *insn != AARCH64_BREAK_FAULT ? 0 : -EFAULT;
2864 }
2865 
2866 /* Replace the branch instruction from @ip to @old_addr in a bpf prog or a bpf
2867  * trampoline with the branch instruction from @ip to @new_addr. If @old_addr
2868  * or @new_addr is NULL, the old or new instruction is NOP.
2869  *
2870  * When @ip is the bpf prog entry, a bpf trampoline is being attached or
2871  * detached. Since bpf trampoline and bpf prog are allocated separately with
2872  * vmalloc, the address distance may exceed 128MB, the maximum branch range.
2873  * So long jump should be handled.
2874  *
2875  * When a bpf prog is constructed, a plt pointing to empty trampoline
2876  * dummy_tramp is placed at the end:
2877  *
2878  *      bpf_prog:
2879  *              mov x9, lr
2880  *              nop // patchsite
2881  *              ...
2882  *              ret
2883  *
2884  *      plt:
2885  *              ldr x10, target
2886  *              br x10
2887  *      target:
2888  *              .quad dummy_tramp // plt target
2889  *
2890  * This is also the state when no trampoline is attached.
2891  *
2892  * When a short-jump bpf trampoline is attached, the patchsite is patched
2893  * to a bl instruction to the trampoline directly:
2894  *
2895  *      bpf_prog:
2896  *              mov x9, lr
2897  *              bl <short-jump bpf trampoline address> // patchsite
2898  *              ...
2899  *              ret
2900  *
2901  *      plt:
2902  *              ldr x10, target
2903  *              br x10
2904  *      target:
2905  *              .quad dummy_tramp // plt target
2906  *
2907  * When a long-jump bpf trampoline is attached, the plt target is filled with
2908  * the trampoline address and the patchsite is patched to a bl instruction to
2909  * the plt:
2910  *
2911  *      bpf_prog:
2912  *              mov x9, lr
2913  *              bl plt // patchsite
2914  *              ...
2915  *              ret
2916  *
2917  *      plt:
2918  *              ldr x10, target
2919  *              br x10
2920  *      target:
2921  *              .quad <long-jump bpf trampoline address> // plt target
2922  *
2923  * The dummy_tramp is used to prevent another CPU from jumping to unknown
2924  * locations during the patching process, making the patching process easier.
2925  */
2926 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type poke_type,
2927 		       void *old_addr, void *new_addr)
2928 {
2929 	int ret;
2930 	u32 old_insn;
2931 	u32 new_insn;
2932 	u32 replaced;
2933 	struct bpf_plt *plt = NULL;
2934 	unsigned long size = 0UL;
2935 	unsigned long offset = ~0UL;
2936 	enum aarch64_insn_branch_type branch_type;
2937 	char namebuf[KSYM_NAME_LEN];
2938 	void *image = NULL;
2939 	u64 plt_target = 0ULL;
2940 	bool poking_bpf_entry;
2941 
2942 	if (!__bpf_address_lookup((unsigned long)ip, &size, &offset, namebuf))
2943 		/* Only poking bpf text is supported. Since kernel function
2944 		 * entry is set up by ftrace, we reply on ftrace to poke kernel
2945 		 * functions.
2946 		 */
2947 		return -ENOTSUPP;
2948 
2949 	image = ip - offset;
2950 	/* zero offset means we're poking bpf prog entry */
2951 	poking_bpf_entry = (offset == 0UL);
2952 
2953 	/* bpf prog entry, find plt and the real patchsite */
2954 	if (poking_bpf_entry) {
2955 		/* plt locates at the end of bpf prog */
2956 		plt = image + size - PLT_TARGET_OFFSET;
2957 
2958 		/* skip to the nop instruction in bpf prog entry:
2959 		 * bti c // if BTI enabled
2960 		 * mov x9, x30
2961 		 * nop
2962 		 */
2963 		ip = image + POKE_OFFSET * AARCH64_INSN_SIZE;
2964 	}
2965 
2966 	/* long jump is only possible at bpf prog entry */
2967 	if (WARN_ON((is_long_jump(ip, new_addr) || is_long_jump(ip, old_addr)) &&
2968 		    !poking_bpf_entry))
2969 		return -EINVAL;
2970 
2971 	if (poke_type == BPF_MOD_CALL)
2972 		branch_type = AARCH64_INSN_BRANCH_LINK;
2973 	else
2974 		branch_type = AARCH64_INSN_BRANCH_NOLINK;
2975 
2976 	if (gen_branch_or_nop(branch_type, ip, old_addr, plt, &old_insn) < 0)
2977 		return -EFAULT;
2978 
2979 	if (gen_branch_or_nop(branch_type, ip, new_addr, plt, &new_insn) < 0)
2980 		return -EFAULT;
2981 
2982 	if (is_long_jump(ip, new_addr))
2983 		plt_target = (u64)new_addr;
2984 	else if (is_long_jump(ip, old_addr))
2985 		/* if the old target is a long jump and the new target is not,
2986 		 * restore the plt target to dummy_tramp, so there is always a
2987 		 * legal and harmless address stored in plt target, and we'll
2988 		 * never jump from plt to an unknown place.
2989 		 */
2990 		plt_target = (u64)&dummy_tramp;
2991 
2992 	if (plt_target) {
2993 		/* non-zero plt_target indicates we're patching a bpf prog,
2994 		 * which is read only.
2995 		 */
2996 		if (set_memory_rw(PAGE_MASK & ((uintptr_t)&plt->target), 1))
2997 			return -EFAULT;
2998 		WRITE_ONCE(plt->target, plt_target);
2999 		set_memory_ro(PAGE_MASK & ((uintptr_t)&plt->target), 1);
3000 		/* since plt target points to either the new trampoline
3001 		 * or dummy_tramp, even if another CPU reads the old plt
3002 		 * target value before fetching the bl instruction to plt,
3003 		 * it will be brought back by dummy_tramp, so no barrier is
3004 		 * required here.
3005 		 */
3006 	}
3007 
3008 	/* if the old target and the new target are both long jumps, no
3009 	 * patching is required
3010 	 */
3011 	if (old_insn == new_insn)
3012 		return 0;
3013 
3014 	mutex_lock(&text_mutex);
3015 	if (aarch64_insn_read(ip, &replaced)) {
3016 		ret = -EFAULT;
3017 		goto out;
3018 	}
3019 
3020 	if (replaced != old_insn) {
3021 		ret = -EFAULT;
3022 		goto out;
3023 	}
3024 
3025 	/* We call aarch64_insn_patch_text_nosync() to replace instruction
3026 	 * atomically, so no other CPUs will fetch a half-new and half-old
3027 	 * instruction. But there is chance that another CPU executes the
3028 	 * old instruction after the patching operation finishes (e.g.,
3029 	 * pipeline not flushed, or icache not synchronized yet).
3030 	 *
3031 	 * 1. when a new trampoline is attached, it is not a problem for
3032 	 *    different CPUs to jump to different trampolines temporarily.
3033 	 *
3034 	 * 2. when an old trampoline is freed, we should wait for all other
3035 	 *    CPUs to exit the trampoline and make sure the trampoline is no
3036 	 *    longer reachable, since bpf_tramp_image_put() function already
3037 	 *    uses percpu_ref and task-based rcu to do the sync, no need to call
3038 	 *    the sync version here, see bpf_tramp_image_put() for details.
3039 	 */
3040 	ret = aarch64_insn_patch_text_nosync(ip, new_insn);
3041 out:
3042 	mutex_unlock(&text_mutex);
3043 
3044 	return ret;
3045 }
3046 
3047 bool bpf_jit_supports_ptr_xchg(void)
3048 {
3049 	return true;
3050 }
3051 
3052 bool bpf_jit_supports_exceptions(void)
3053 {
3054 	/* We unwind through both kernel frames starting from within bpf_throw
3055 	 * call and BPF frames. Therefore we require FP unwinder to be enabled
3056 	 * to walk kernel frames and reach BPF frames in the stack trace.
3057 	 * ARM64 kernel is aways compiled with CONFIG_FRAME_POINTER=y
3058 	 */
3059 	return true;
3060 }
3061 
3062 bool bpf_jit_supports_arena(void)
3063 {
3064 	return true;
3065 }
3066 
3067 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
3068 {
3069 	if (!in_arena)
3070 		return true;
3071 	switch (insn->code) {
3072 	case BPF_STX | BPF_ATOMIC | BPF_W:
3073 	case BPF_STX | BPF_ATOMIC | BPF_DW:
3074 		if (!bpf_atomic_is_load_store(insn) &&
3075 		    !cpus_have_cap(ARM64_HAS_LSE_ATOMICS))
3076 			return false;
3077 	}
3078 	return true;
3079 }
3080 
3081 bool bpf_jit_supports_percpu_insn(void)
3082 {
3083 	return true;
3084 }
3085 
3086 bool bpf_jit_bypass_spec_v4(void)
3087 {
3088 	/* In case of arm64, we rely on the firmware mitigation of Speculative
3089 	 * Store Bypass as controlled via the ssbd kernel parameter. Whenever
3090 	 * the mitigation is enabled, it works for all of the kernel code with
3091 	 * no need to provide any additional instructions. Therefore, skip
3092 	 * inserting nospec insns against Spectre v4.
3093 	 */
3094 	return true;
3095 }
3096 
3097 bool bpf_jit_supports_timed_may_goto(void)
3098 {
3099 	return true;
3100 }
3101 
3102 bool bpf_jit_inlines_helper_call(s32 imm)
3103 {
3104 	switch (imm) {
3105 	case BPF_FUNC_get_smp_processor_id:
3106 	case BPF_FUNC_get_current_task:
3107 	case BPF_FUNC_get_current_task_btf:
3108 		return true;
3109 	default:
3110 		return false;
3111 	}
3112 }
3113 
3114 void bpf_jit_free(struct bpf_prog *prog)
3115 {
3116 	if (prog->jited) {
3117 		struct arm64_jit_data *jit_data = prog->aux->jit_data;
3118 		struct bpf_binary_header *hdr;
3119 		void __percpu *priv_stack_ptr;
3120 		int priv_stack_alloc_sz;
3121 
3122 		/*
3123 		 * If we fail the final pass of JIT (from jit_subprogs),
3124 		 * the program may not be finalized yet. Call finalize here
3125 		 * before freeing it.
3126 		 */
3127 		if (jit_data) {
3128 			bpf_jit_binary_pack_finalize(jit_data->ro_header, jit_data->header);
3129 			kfree(jit_data);
3130 		}
3131 		prog->bpf_func -= cfi_get_offset();
3132 		hdr = bpf_jit_binary_pack_hdr(prog);
3133 		bpf_jit_binary_pack_free(hdr, NULL);
3134 		priv_stack_ptr = prog->aux->priv_stack_ptr;
3135 		if (priv_stack_ptr) {
3136 			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
3137 					      2 * PRIV_STACK_GUARD_SZ;
3138 			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
3139 			free_percpu(prog->aux->priv_stack_ptr);
3140 		}
3141 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
3142 	}
3143 
3144 	bpf_prog_unlock_free(prog);
3145 }
3146