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