xref: /linux/arch/arm64/net/bpf_jit_comp.c (revision 55fbedcec622a943cb09a969aef1ddcba87ee40a)
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/extable.h>
15 #include <linux/filter.h>
16 #include <linux/memory.h>
17 #include <linux/printk.h>
18 #include <linux/slab.h>
19 
20 #include <asm/asm-extable.h>
21 #include <asm/byteorder.h>
22 #include <asm/cpufeature.h>
23 #include <asm/debug-monitors.h>
24 #include <asm/insn.h>
25 #include <asm/text-patching.h>
26 
27 #include "bpf_jit.h"
28 
29 #define TMP_REG_1 (MAX_BPF_JIT_REG + 0)
30 #define TMP_REG_2 (MAX_BPF_JIT_REG + 1)
31 #define TCCNT_PTR (MAX_BPF_JIT_REG + 2)
32 #define TMP_REG_3 (MAX_BPF_JIT_REG + 3)
33 #define PRIVATE_SP (MAX_BPF_JIT_REG + 4)
34 #define ARENA_VM_START (MAX_BPF_JIT_REG + 5)
35 
36 #define check_imm(bits, imm) do {				\
37 	if ((((imm) > 0) && ((imm) >> ((bits) - 1))) ||		\
38 	    (((imm) < 0) && (~(imm) >> ((bits) - 1)))) {	\
39 		pr_info("[%2d] imm=%d(0x%x) out of range\n",	\
40 			i, imm, imm);				\
41 		return -EINVAL;					\
42 	}							\
43 } while (0)
44 #define check_imm19(imm) check_imm(19, imm)
45 #define check_imm26(imm) check_imm(26, imm)
46 
47 /* Map BPF registers to A64 registers */
48 static const int bpf2a64[] = {
49 	/* return value from in-kernel function, and exit value from eBPF */
50 	[BPF_REG_0] = A64_R(8),
51 	/* arguments from eBPF program to in-kernel function */
52 	[BPF_REG_1] = A64_R(0),
53 	[BPF_REG_2] = A64_R(1),
54 	[BPF_REG_3] = A64_R(2),
55 	[BPF_REG_4] = A64_R(3),
56 	[BPF_REG_5] = A64_R(4),
57 	/* callee saved registers that in-kernel function will preserve */
58 	[BPF_REG_6] = A64_R(19),
59 	[BPF_REG_7] = A64_R(20),
60 	[BPF_REG_8] = A64_R(21),
61 	[BPF_REG_9] = A64_R(22),
62 	/* read-only frame pointer to access stack */
63 	[BPF_REG_FP] = A64_R(25),
64 	/* temporary registers for BPF JIT */
65 	[TMP_REG_1] = A64_R(10),
66 	[TMP_REG_2] = A64_R(11),
67 	[TMP_REG_3] = A64_R(12),
68 	/* tail_call_cnt_ptr */
69 	[TCCNT_PTR] = A64_R(26),
70 	/* temporary register for blinding constants */
71 	[BPF_REG_AX] = A64_R(9),
72 	/* callee saved register for private stack pointer */
73 	[PRIVATE_SP] = A64_R(27),
74 	/* callee saved register for kern_vm_start address */
75 	[ARENA_VM_START] = A64_R(28),
76 };
77 
78 struct jit_ctx {
79 	const struct bpf_prog *prog;
80 	int idx;
81 	int epilogue_offset;
82 	int *offset;
83 	int exentry_idx;
84 	int nr_used_callee_reg;
85 	u8 used_callee_reg[8]; /* r6~r9, fp, arena_vm_start */
86 	__le32 *image;
87 	__le32 *ro_image;
88 	u32 stack_size;
89 	u16 stack_arg_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] = (__force __le32)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 	 *                        +-----+ <= (BPF_FP - ctx->stack_size)
538 	 *                        |     |
539 	 *                        | ... | outgoing stack args (9+, if any)
540 	 *                        |     |
541 	 * current A64_SP =>      +-----+
542 	 *                        |     |
543 	 *                        | ... | Function call stack
544 	 *                        |     |
545 	 *                        +-----+
546 	 *                          low
547 	 *
548 	 * Stack args 6-8 are passed in x5-x7, args 9+ at [SP].
549 	 * Incoming args 9+ are at [A64_FP + 16], [A64_FP + 24], ...
550 	 * (above the saved FP/LR pair pushed in the callee prologue).
551 	 */
552 
553 	emit_kcfi(is_main_prog ? cfi_bpf_hash : cfi_bpf_subprog_hash, ctx);
554 	const int idx0 = ctx->idx;
555 
556 	/* bpf function may be invoked by 3 instruction types:
557 	 * 1. bl, attached via freplace to bpf prog via short jump
558 	 * 2. br, attached via freplace to bpf prog via long jump
559 	 * 3. blr, working as a function pointer, used by emit_call.
560 	 * So BTI_JC should used here to support both br and blr.
561 	 */
562 	emit_bti(A64_BTI_JC, ctx);
563 
564 	emit(A64_MOV(1, A64_R(9), A64_LR), ctx);
565 	emit(A64_NOP, ctx);
566 
567 	if (!prog->aux->exception_cb) {
568 		/* Sign lr */
569 		if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
570 			emit(A64_PACIASP, ctx);
571 
572 		/* Save FP and LR registers to stay align with ARM64 AAPCS */
573 		emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
574 		emit(A64_MOV(1, A64_FP, A64_SP), ctx);
575 
576 		prepare_bpf_tail_call_cnt(ctx);
577 
578 		if (!ebpf_from_cbpf && is_main_prog) {
579 			cur_offset = ctx->idx - idx0;
580 			if (cur_offset != PROLOGUE_OFFSET) {
581 				pr_err_once("PROLOGUE_OFFSET = %d, expected %d!\n",
582 						cur_offset, PROLOGUE_OFFSET);
583 				return -1;
584 			}
585 			/* BTI landing pad for the tail call, done with a BR */
586 			emit_bti(A64_BTI_J, ctx);
587 		}
588 		push_callee_regs(ctx);
589 	} else {
590 		/*
591 		 * Exception callback receives FP of Main Program as third
592 		 * parameter
593 		 */
594 		emit(A64_MOV(1, A64_FP, A64_R(2)), ctx);
595 		/*
596 		 * Main Program already pushed the frame record and the
597 		 * callee-saved registers. The exception callback will not push
598 		 * anything and re-use the main program's stack.
599 		 *
600 		 * 12 registers are on the stack
601 		 */
602 		emit(A64_SUB_I(1, A64_SP, A64_FP, 96), ctx);
603 		/* The callback may use its own BPF stack, set up fp for it. */
604 		ctx->fp_used = true;
605 	}
606 
607 	/* Stack must be multiples of 16B */
608 	ctx->stack_size = round_up(prog->aux->stack_depth, 16);
609 
610 	if (ctx->fp_used) {
611 		if (ctx->priv_sp_used) {
612 			/* Set up private stack pointer */
613 			priv_stack_ptr = prog->aux->priv_stack_ptr + PRIV_STACK_GUARD_SZ;
614 			emit_percpu_ptr(priv_sp, priv_stack_ptr, ctx);
615 			emit(A64_ADD_I(1, fp, priv_sp, ctx->stack_size), ctx);
616 		} else {
617 			/* Set up BPF prog stack base register */
618 			emit(A64_MOV(1, fp, A64_SP), ctx);
619 		}
620 	}
621 
622 	/* Set up function call stack */
623 	if (ctx->stack_size && !ctx->priv_sp_used)
624 		emit(A64_SUB_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
625 
626 	if (ctx->stack_arg_size)
627 		emit(A64_SUB_I(1, A64_SP, A64_SP, ctx->stack_arg_size), ctx);
628 
629 	if (ctx->arena_vm_start)
630 		emit_a64_mov_i64(arena_vm_base, ctx->arena_vm_start, ctx);
631 
632 	return 0;
633 }
634 
635 static int emit_bpf_tail_call(struct jit_ctx *ctx)
636 {
637 	/* bpf_tail_call(void *prog_ctx, struct bpf_array *array, u64 index) */
638 	const u8 r2 = bpf2a64[BPF_REG_2];
639 	const u8 r3 = bpf2a64[BPF_REG_3];
640 
641 	const u8 tmp = bpf2a64[TMP_REG_1];
642 	const u8 prg = bpf2a64[TMP_REG_2];
643 	const u8 tcc = bpf2a64[TMP_REG_3];
644 	const u8 ptr = bpf2a64[TCCNT_PTR];
645 	size_t off;
646 	__le32 *branch1 = NULL;
647 	__le32 *branch2 = NULL;
648 	__le32 *branch3 = NULL;
649 
650 	/* if (index >= array->map.max_entries)
651 	 *     goto out;
652 	 */
653 	off = offsetof(struct bpf_array, map.max_entries);
654 	emit_a64_mov_i64(tmp, off, ctx);
655 	emit(A64_LDR32(tmp, r2, tmp), ctx);
656 	emit(A64_MOV(0, r3, r3), ctx);
657 	emit(A64_CMP(0, r3, tmp), ctx);
658 	branch1 = ctx->image + ctx->idx;
659 	emit(A64_NOP, ctx);
660 
661 	/*
662 	 * if ((*tail_call_cnt_ptr) >= MAX_TAIL_CALL_CNT)
663 	 *     goto out;
664 	 */
665 	emit_a64_mov_i64(tmp, MAX_TAIL_CALL_CNT, ctx);
666 	emit(A64_LDR64I(tcc, ptr, 0), ctx);
667 	emit(A64_CMP(1, tcc, tmp), ctx);
668 	branch2 = ctx->image + ctx->idx;
669 	emit(A64_NOP, ctx);
670 
671 	/* (*tail_call_cnt_ptr)++; */
672 	emit(A64_ADD_I(1, tcc, tcc, 1), ctx);
673 
674 	/* prog = array->ptrs[index];
675 	 * if (prog == NULL)
676 	 *     goto out;
677 	 */
678 	off = offsetof(struct bpf_array, ptrs);
679 	emit_a64_mov_i64(tmp, off, ctx);
680 	emit(A64_ADD(1, tmp, r2, tmp), ctx);
681 	emit(A64_LSL(1, prg, r3, 3), ctx);
682 	emit(A64_LDR64(prg, tmp, prg), ctx);
683 	branch3 = ctx->image + ctx->idx;
684 	emit(A64_NOP, ctx);
685 
686 	/* Update tail_call_cnt if the slot is populated. */
687 	emit(A64_STR64I(tcc, ptr, 0), ctx);
688 
689 	if (ctx->stack_arg_size)
690 		emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_arg_size), ctx);
691 
692 	/* restore SP */
693 	if (ctx->stack_size && !ctx->priv_sp_used)
694 		emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
695 
696 	pop_callee_regs(ctx);
697 
698 	/* goto *(prog->bpf_func + prologue_offset); */
699 	off = offsetof(struct bpf_prog, bpf_func);
700 	emit_a64_mov_i64(tmp, off, ctx);
701 	emit(A64_LDR64(tmp, prg, tmp), ctx);
702 	emit(A64_ADD_I(1, tmp, tmp, sizeof(u32) * PROLOGUE_OFFSET), ctx);
703 	emit(A64_BR(tmp), ctx);
704 
705 	if (ctx->image) {
706 		off = &ctx->image[ctx->idx] - branch1;
707 		*branch1 = cpu_to_le32(A64_B_(A64_COND_CS, off));
708 
709 		off = &ctx->image[ctx->idx] - branch2;
710 		*branch2 = cpu_to_le32(A64_B_(A64_COND_CS, off));
711 
712 		off = &ctx->image[ctx->idx] - branch3;
713 		*branch3 = cpu_to_le32(A64_CBZ(1, prg, off));
714 	}
715 
716 	return 0;
717 }
718 
719 static int emit_atomic_ld_st(const struct bpf_insn *insn, struct jit_ctx *ctx)
720 {
721 	const s32 imm = insn->imm;
722 	const s16 off = insn->off;
723 	const u8 code = insn->code;
724 	const bool arena = BPF_MODE(code) == BPF_PROBE_ATOMIC;
725 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
726 	const u8 dst = bpf2a64[insn->dst_reg];
727 	const u8 src = bpf2a64[insn->src_reg];
728 	const u8 tmp = bpf2a64[TMP_REG_1];
729 	u8 reg;
730 
731 	switch (imm) {
732 	case BPF_LOAD_ACQ:
733 		reg = src;
734 		break;
735 	case BPF_STORE_REL:
736 		reg = dst;
737 		break;
738 	default:
739 		pr_err_once("unknown atomic load/store op code %02x\n", imm);
740 		return -EINVAL;
741 	}
742 
743 	if (off) {
744 		emit_a64_add_i(1, tmp, reg, tmp, off, ctx);
745 		reg = tmp;
746 	}
747 	if (arena) {
748 		emit(A64_ADD(1, tmp, reg, arena_vm_base), ctx);
749 		reg = tmp;
750 	}
751 
752 	switch (imm) {
753 	case BPF_LOAD_ACQ:
754 		switch (BPF_SIZE(code)) {
755 		case BPF_B:
756 			emit(A64_LDARB(dst, reg), ctx);
757 			break;
758 		case BPF_H:
759 			emit(A64_LDARH(dst, reg), ctx);
760 			break;
761 		case BPF_W:
762 			emit(A64_LDAR32(dst, reg), ctx);
763 			break;
764 		case BPF_DW:
765 			emit(A64_LDAR64(dst, reg), ctx);
766 			break;
767 		}
768 		break;
769 	case BPF_STORE_REL:
770 		switch (BPF_SIZE(code)) {
771 		case BPF_B:
772 			emit(A64_STLRB(src, reg), ctx);
773 			break;
774 		case BPF_H:
775 			emit(A64_STLRH(src, reg), ctx);
776 			break;
777 		case BPF_W:
778 			emit(A64_STLR32(src, reg), ctx);
779 			break;
780 		case BPF_DW:
781 			emit(A64_STLR64(src, reg), ctx);
782 			break;
783 		}
784 		break;
785 	default:
786 		pr_err_once("unexpected atomic load/store op code %02x\n",
787 			    imm);
788 		return -EINVAL;
789 	}
790 
791 	return 0;
792 }
793 
794 static int emit_lse_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
795 {
796 	const u8 code = insn->code;
797 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
798 	const u8 dst = bpf2a64[insn->dst_reg];
799 	const u8 src = bpf2a64[insn->src_reg];
800 	const u8 tmp = bpf2a64[TMP_REG_1];
801 	const u8 tmp2 = bpf2a64[TMP_REG_2];
802 	const bool isdw = BPF_SIZE(code) == BPF_DW;
803 	const bool arena = BPF_MODE(code) == BPF_PROBE_ATOMIC;
804 	const s16 off = insn->off;
805 	u8 reg = dst;
806 
807 	if (off) {
808 		emit_a64_add_i(1, tmp, reg, tmp, off, ctx);
809 		reg = tmp;
810 	}
811 	if (arena) {
812 		emit(A64_ADD(1, tmp, reg, arena_vm_base), ctx);
813 		reg = tmp;
814 	}
815 
816 	switch (insn->imm) {
817 	/* lock *(u32/u64 *)(dst_reg + off) <op>= src_reg */
818 	case BPF_ADD:
819 		emit(A64_STADD(isdw, reg, src), ctx);
820 		break;
821 	case BPF_AND:
822 		emit(A64_MVN(isdw, tmp2, src), ctx);
823 		emit(A64_STCLR(isdw, reg, tmp2), ctx);
824 		break;
825 	case BPF_OR:
826 		emit(A64_STSET(isdw, reg, src), ctx);
827 		break;
828 	case BPF_XOR:
829 		emit(A64_STEOR(isdw, reg, src), ctx);
830 		break;
831 	/* src_reg = atomic_fetch_<op>(dst_reg + off, src_reg) */
832 	case BPF_ADD | BPF_FETCH:
833 		emit(A64_LDADDAL(isdw, src, reg, src), ctx);
834 		break;
835 	case BPF_AND | BPF_FETCH:
836 		emit(A64_MVN(isdw, tmp2, src), ctx);
837 		emit(A64_LDCLRAL(isdw, src, reg, tmp2), ctx);
838 		break;
839 	case BPF_OR | BPF_FETCH:
840 		emit(A64_LDSETAL(isdw, src, reg, src), ctx);
841 		break;
842 	case BPF_XOR | BPF_FETCH:
843 		emit(A64_LDEORAL(isdw, src, reg, src), ctx);
844 		break;
845 	/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
846 	case BPF_XCHG:
847 		emit(A64_SWPAL(isdw, src, reg, src), ctx);
848 		break;
849 	/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
850 	case BPF_CMPXCHG:
851 		emit(A64_CASAL(isdw, src, reg, bpf2a64[BPF_REG_0]), ctx);
852 		break;
853 	default:
854 		pr_err_once("unknown atomic op code %02x\n", insn->imm);
855 		return -EINVAL;
856 	}
857 
858 	return 0;
859 }
860 
861 static int emit_ll_sc_atomic(const struct bpf_insn *insn, struct jit_ctx *ctx)
862 {
863 	const u8 code = insn->code;
864 	const u8 dst = bpf2a64[insn->dst_reg];
865 	const u8 src = bpf2a64[insn->src_reg];
866 	const u8 tmp = bpf2a64[TMP_REG_1];
867 	const u8 tmp2 = bpf2a64[TMP_REG_2];
868 	const u8 tmp3 = bpf2a64[TMP_REG_3];
869 	const int i = insn - ctx->prog->insnsi;
870 	const s32 imm = insn->imm;
871 	const s16 off = insn->off;
872 	const bool isdw = BPF_SIZE(code) == BPF_DW;
873 	u8 reg = dst;
874 	s32 jmp_offset;
875 
876 	if (BPF_MODE(code) == BPF_PROBE_ATOMIC) {
877 		/* ll_sc based atomics don't support unsafe pointers yet. */
878 		pr_err_once("unknown atomic opcode %02x\n", code);
879 		return -EINVAL;
880 	}
881 
882 	if (off) {
883 		emit_a64_add_i(1, tmp, reg, tmp, off, ctx);
884 		reg = tmp;
885 	}
886 
887 	if (imm == BPF_ADD || imm == BPF_AND ||
888 	    imm == BPF_OR || imm == BPF_XOR) {
889 		/* lock *(u32/u64 *)(dst_reg + off) <op>= src_reg */
890 		emit(A64_LDXR(isdw, tmp2, reg), ctx);
891 		if (imm == BPF_ADD)
892 			emit(A64_ADD(isdw, tmp2, tmp2, src), ctx);
893 		else if (imm == BPF_AND)
894 			emit(A64_AND(isdw, tmp2, tmp2, src), ctx);
895 		else if (imm == BPF_OR)
896 			emit(A64_ORR(isdw, tmp2, tmp2, src), ctx);
897 		else
898 			emit(A64_EOR(isdw, tmp2, tmp2, src), ctx);
899 		emit(A64_STXR(isdw, tmp2, reg, tmp3), ctx);
900 		jmp_offset = -3;
901 		check_imm19(jmp_offset);
902 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
903 	} else if (imm == (BPF_ADD | BPF_FETCH) ||
904 		   imm == (BPF_AND | BPF_FETCH) ||
905 		   imm == (BPF_OR | BPF_FETCH) ||
906 		   imm == (BPF_XOR | BPF_FETCH)) {
907 		/* src_reg = atomic_fetch_<op>(dst_reg + off, src_reg) */
908 		const u8 ax = bpf2a64[BPF_REG_AX];
909 
910 		emit(A64_MOV(isdw, ax, src), ctx);
911 		emit(A64_LDXR(isdw, src, reg), ctx);
912 		if (imm == (BPF_ADD | BPF_FETCH))
913 			emit(A64_ADD(isdw, tmp2, src, ax), ctx);
914 		else if (imm == (BPF_AND | BPF_FETCH))
915 			emit(A64_AND(isdw, tmp2, src, ax), ctx);
916 		else if (imm == (BPF_OR | BPF_FETCH))
917 			emit(A64_ORR(isdw, tmp2, src, ax), ctx);
918 		else
919 			emit(A64_EOR(isdw, tmp2, src, ax), ctx);
920 		emit(A64_STLXR(isdw, tmp2, reg, tmp3), ctx);
921 		jmp_offset = -3;
922 		check_imm19(jmp_offset);
923 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
924 		emit(A64_DMB_ISH, ctx);
925 	} else if (imm == BPF_XCHG) {
926 		/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
927 		emit(A64_MOV(isdw, tmp2, src), ctx);
928 		emit(A64_LDXR(isdw, src, reg), ctx);
929 		emit(A64_STLXR(isdw, tmp2, reg, tmp3), ctx);
930 		jmp_offset = -2;
931 		check_imm19(jmp_offset);
932 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
933 		emit(A64_DMB_ISH, ctx);
934 	} else if (imm == BPF_CMPXCHG) {
935 		/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
936 		const u8 r0 = bpf2a64[BPF_REG_0];
937 
938 		emit(A64_MOV(isdw, tmp2, r0), ctx);
939 		emit(A64_LDXR(isdw, r0, reg), ctx);
940 		emit(A64_EOR(isdw, tmp3, r0, tmp2), ctx);
941 		jmp_offset = 4;
942 		check_imm19(jmp_offset);
943 		emit(A64_CBNZ(isdw, tmp3, jmp_offset), ctx);
944 		emit(A64_STLXR(isdw, src, reg, tmp3), ctx);
945 		jmp_offset = -4;
946 		check_imm19(jmp_offset);
947 		emit(A64_CBNZ(0, tmp3, jmp_offset), ctx);
948 		emit(A64_DMB_ISH, ctx);
949 	} else {
950 		pr_err_once("unknown atomic op code %02x\n", imm);
951 		return -EINVAL;
952 	}
953 
954 	return 0;
955 }
956 
957 void dummy_tramp(void);
958 
959 asm (
960 "	.pushsection .text, \"ax\", @progbits\n"
961 "	.global dummy_tramp\n"
962 "	.type dummy_tramp, %function\n"
963 "dummy_tramp:"
964 #if IS_ENABLED(CONFIG_ARM64_BTI_KERNEL)
965 "	bti j\n" /* dummy_tramp is called via "br x10" */
966 #endif
967 "	mov x10, x30\n"
968 "	mov x30, x9\n"
969 "	ret x10\n"
970 "	.size dummy_tramp, .-dummy_tramp\n"
971 "	.popsection\n"
972 );
973 
974 /* build a plt initialized like this:
975  *
976  * plt:
977  *      ldr tmp, target
978  *      br tmp
979  * target:
980  *      .quad dummy_tramp
981  *
982  * when a long jump trampoline is attached, target is filled with the
983  * trampoline address, and when the trampoline is removed, target is
984  * restored to dummy_tramp address.
985  */
986 static void build_plt(struct jit_ctx *ctx)
987 {
988 	const u8 tmp = bpf2a64[TMP_REG_1];
989 	struct bpf_plt *plt = NULL;
990 
991 	/* make sure target is 64-bit aligned */
992 	if ((ctx->idx + PLT_TARGET_OFFSET / AARCH64_INSN_SIZE) % 2)
993 		emit(A64_NOP, ctx);
994 
995 	plt = (struct bpf_plt *)(ctx->image + ctx->idx);
996 	/* plt is called via bl, no BTI needed here */
997 	emit(A64_LDR64LIT(tmp, 2 * AARCH64_INSN_SIZE), ctx);
998 	emit(A64_BR(tmp), ctx);
999 
1000 	if (ctx->image)
1001 		plt->target = (u64)&dummy_tramp;
1002 }
1003 
1004 /* Clobbers BPF registers 1-4, aka x0-x3 */
1005 static void __maybe_unused build_bhb_mitigation(struct jit_ctx *ctx)
1006 {
1007 	const u8 r1 = bpf2a64[BPF_REG_1]; /* aka x0 */
1008 	u8 k = get_spectre_bhb_loop_value();
1009 
1010 	if (!IS_ENABLED(CONFIG_MITIGATE_SPECTRE_BRANCH_HISTORY) ||
1011 	    cpu_mitigations_off() || __nospectre_bhb ||
1012 	    arm64_get_spectre_v2_state() == SPECTRE_VULNERABLE)
1013 		return;
1014 
1015 	if (ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN))
1016 		return;
1017 
1018 	if (supports_clearbhb(SCOPE_SYSTEM)) {
1019 		emit(aarch64_insn_gen_hint(AARCH64_INSN_HINT_CLEARBHB), ctx);
1020 		return;
1021 	}
1022 
1023 	if (k) {
1024 		emit_a64_mov_i64(r1, k, ctx);
1025 		emit(A64_B(1), ctx);
1026 		emit(A64_SUBS_I(true, r1, r1, 1), ctx);
1027 		emit(A64_B_(A64_COND_NE, -2), ctx);
1028 		emit(aarch64_insn_gen_dsb(AARCH64_INSN_MB_ISH), ctx);
1029 		emit(aarch64_insn_get_isb_value(), ctx);
1030 	}
1031 
1032 	if (is_spectre_bhb_fw_mitigated()) {
1033 		emit(A64_ORR_I(false, r1, AARCH64_INSN_REG_ZR,
1034 			       ARM_SMCCC_ARCH_WORKAROUND_3), ctx);
1035 		switch (arm_smccc_1_1_get_conduit()) {
1036 		case SMCCC_CONDUIT_HVC:
1037 			emit(aarch64_insn_get_hvc_value(), ctx);
1038 			break;
1039 		case SMCCC_CONDUIT_SMC:
1040 			emit(aarch64_insn_get_smc_value(), ctx);
1041 			break;
1042 		default:
1043 			pr_err_once("Firmware mitigation enabled with unknown conduit\n");
1044 		}
1045 	}
1046 }
1047 
1048 static void build_epilogue(struct jit_ctx *ctx, bool was_classic, bool unwind)
1049 {
1050 	const u8 tmp = bpf2a64[TMP_REG_1];
1051 	const u8 r0 = bpf2a64[BPF_REG_0];
1052 	const u8 ptr = bpf2a64[TCCNT_PTR];
1053 
1054 	if (ctx->stack_arg_size)
1055 		emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_arg_size), ctx);
1056 
1057 	/* We're done with BPF stack */
1058 	if (ctx->stack_size && !ctx->priv_sp_used)
1059 		emit(A64_ADD_I(1, A64_SP, A64_SP, ctx->stack_size), ctx);
1060 
1061 	pop_callee_regs(ctx);
1062 
1063 	emit(A64_POP(A64_ZR, ptr, A64_SP), ctx);
1064 
1065 	if (was_classic)
1066 		build_bhb_mitigation(ctx);
1067 
1068 	/* Restore FP/LR registers */
1069 	emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
1070 
1071 	/* Move the return value from bpf:r0 (aka x8) to x0 */
1072 	emit(A64_MOV(1, A64_R(0), r0), ctx);
1073 
1074 	/* Authenticate lr */
1075 	if (IS_ENABLED(CONFIG_ARM64_PTR_AUTH_KERNEL))
1076 		emit(A64_AUTIASP, ctx);
1077 
1078 	/* tmp is the offset of the pad, see emit_unwind_exit() */
1079 	if (unwind)
1080 		emit(A64_ADD(1, A64_LR, A64_LR, tmp), ctx);
1081 
1082 	emit(A64_RET(A64_LR), ctx);
1083 }
1084 
1085 /*
1086  * Metadata encoding for exception handling in JITed code.
1087  *
1088  * Format of `fixup` field in `struct exception_table_entry`:
1089  *
1090  * Bit layout of `fixup` (32-bit):
1091  *
1092  * +-----------+--------+-------------+-----------+-----------+----------+
1093  * |   31-27   | 26-23  |      22     |     21    |   20-16   |   15-0   |
1094  * |           |        |             |           |           |          |
1095  * | FIXUP_REG | Unused | ARENA_WRITE | ARENA_ACC | ARENA_REG |  OFFSET  |
1096  * +-----------+--------+-------------+-----------+-----------+----------+
1097  *
1098  * - OFFSET (16 bits): Offset used to compute address for Load/Store instruction.
1099  * - ARENA_REG (5 bits): Register that is used to calculate the address for load/store when
1100  *                       accessing the arena region.
1101  * - ARENA_ACCESS (1 bit): This bit is set when the faulting instruction accessed the arena region.
1102  * - ARENA_WRITE (1 bit): This bit is set when the faulting instruction wrote to the arena region.
1103  *                        It is independent of FIXUP_REG, since a read-modify-write both writes to
1104  *                        memory and reads the old value into a register.
1105  * - FIXUP_REG (5 bits): Destination register for the load instruction (cleared on fault) or set to
1106  *                       DONT_CLEAR if the instruction does not read into a register.
1107  */
1108 
1109 #define BPF_FIXUP_OFFSET_MASK      GENMASK(15, 0)
1110 #define BPF_FIXUP_ARENA_REG_MASK   GENMASK(20, 16)
1111 #define BPF_ARENA_ACCESS           BIT(21)
1112 #define BPF_ARENA_WRITE            BIT(22)
1113 #define BPF_FIXUP_REG_MASK	GENMASK(31, 27)
1114 #define DONT_CLEAR 5 /* Unused ARM64 register from BPF's POV */
1115 
1116 bool ex_handler_bpf(const struct exception_table_entry *ex,
1117 		    struct pt_regs *regs)
1118 {
1119 	int dst_reg = FIELD_GET(BPF_FIXUP_REG_MASK, ex->fixup);
1120 	s16 off = FIELD_GET(BPF_FIXUP_OFFSET_MASK, ex->fixup);
1121 	int arena_reg = FIELD_GET(BPF_FIXUP_ARENA_REG_MASK, ex->fixup);
1122 	bool is_arena = !!(ex->fixup & BPF_ARENA_ACCESS);
1123 	bool is_write = !!(ex->fixup & BPF_ARENA_WRITE);
1124 	unsigned long addr;
1125 
1126 	if (is_arena) {
1127 		addr = regs->regs[arena_reg] + off;
1128 		bpf_prog_report_arena_violation(is_write, addr, regs->pc);
1129 	}
1130 
1131 	if (dst_reg != DONT_CLEAR)
1132 		regs->regs[dst_reg] = 0;
1133 	/* Skip the faulting instruction */
1134 	regs->pc += AARCH64_INSN_SIZE;
1135 
1136 	return true;
1137 }
1138 
1139 /* For accesses to BTF pointers, add an entry to the exception table */
1140 static int add_exception_handler(const struct bpf_insn *insn,
1141 				 struct jit_ctx *ctx,
1142 				 int dst_reg)
1143 {
1144 	off_t ins_offset;
1145 	s16 off = insn->off;
1146 	bool is_arena, is_write;
1147 	int arena_reg;
1148 	unsigned long pc;
1149 	struct exception_table_entry *ex;
1150 
1151 	if (!ctx->image)
1152 		/* First pass */
1153 		return 0;
1154 
1155 	if (BPF_MODE(insn->code) != BPF_PROBE_MEM &&
1156 	    BPF_MODE(insn->code) != BPF_PROBE_MEMSX &&
1157 	    BPF_MODE(insn->code) != BPF_PROBE_MEM32 &&
1158 	    BPF_MODE(insn->code) != BPF_PROBE_MEM32SX &&
1159 	    BPF_MODE(insn->code) != BPF_PROBE_ATOMIC)
1160 		return 0;
1161 
1162 	is_arena = (BPF_MODE(insn->code) == BPF_PROBE_MEM32) ||
1163 		   (BPF_MODE(insn->code) == BPF_PROBE_MEM32SX) ||
1164 		   (BPF_MODE(insn->code) == BPF_PROBE_ATOMIC);
1165 
1166 	if (!ctx->prog->aux->extable ||
1167 	    WARN_ON_ONCE(ctx->exentry_idx >= ctx->prog->aux->num_exentries))
1168 		return -EINVAL;
1169 
1170 	ex = &ctx->prog->aux->extable[ctx->exentry_idx];
1171 	pc = (unsigned long)&ctx->ro_image[ctx->idx - 1];
1172 
1173 	/*
1174 	 * This is the relative offset of the instruction that may fault from
1175 	 * the exception table itself. This will be written to the exception
1176 	 * table and if this instruction faults, the destination register will
1177 	 * be set to '0' and the execution will jump to the next instruction.
1178 	 */
1179 	ins_offset = pc - (long)&ex->insn;
1180 	if (WARN_ON_ONCE(ins_offset >= 0 || ins_offset < INT_MIN))
1181 		return -ERANGE;
1182 
1183 	/*
1184 	 * The offsets above have been calculated using the RO buffer but we
1185 	 * need to use the R/W buffer for writes.
1186 	 * switch ex to rw buffer for writing.
1187 	 */
1188 	ex = (void *)ctx->image + ((void *)ex - (void *)ctx->ro_image);
1189 
1190 	ex->insn = ins_offset;
1191 
1192 	/*
1193 	 * A load-acquire is of BPF_STX class, but reads from src_reg into
1194 	 * dst_reg like a BPF_LDX does, hence it must not be treated as a store
1195 	 * here. A read-modify-write carrying BPF_FETCH is reported as a write
1196 	 * even though it does have a register to clear, see the callers.
1197 	 */
1198 	is_write = BPF_CLASS(insn->code) != BPF_LDX &&
1199 		   !bpf_atomic_is_load_acq(insn);
1200 
1201 	ex->fixup = FIELD_PREP(BPF_FIXUP_REG_MASK, dst_reg);
1202 
1203 	if (is_arena) {
1204 		ex->fixup |= BPF_ARENA_ACCESS;
1205 		if (is_write)
1206 			ex->fixup |= BPF_ARENA_WRITE;
1207 		/*
1208 		 * insn->src_reg/dst_reg holds the address in the arena region with upper 32-bits
1209 		 * being zero because of a preceding addr_space_cast(r<n>, 0x0, 0x1) instruction.
1210 		 * This address is adjusted with the addition of arena_vm_start (see the
1211 		 * implementation of BPF_PROBE_MEM32 and BPF_PROBE_ATOMIC) before being used for the
1212 		 * memory access. Pass the reg holding the unmodified 32-bit address to
1213 		 * ex_handler_bpf.
1214 		 */
1215 		if (BPF_CLASS(insn->code) == BPF_LDX || bpf_atomic_is_load_acq(insn))
1216 			arena_reg = bpf2a64[insn->src_reg];
1217 		else
1218 			arena_reg = bpf2a64[insn->dst_reg];
1219 
1220 		ex->fixup |=  FIELD_PREP(BPF_FIXUP_OFFSET_MASK, off) |
1221 			      FIELD_PREP(BPF_FIXUP_ARENA_REG_MASK, arena_reg);
1222 	}
1223 
1224 	ex->type = EX_TYPE_BPF;
1225 
1226 	ctx->exentry_idx++;
1227 	return 0;
1228 }
1229 
1230 /*
1231  * There is no branch for unwind_goto, only an extable entry
1232  *   { .insn = ret_addr - 1, .fixup = pad - ret_addr }
1233  * where ret_addr is the return address of the call in front of it. unwind_exit
1234  * adds .fixup to its LR.
1235  * ret_addr - 1, because what follows the call can have an entry of its own.
1236  * No insn starts there, so a fault cannot hit the entry.
1237  * 'bl foo; mov x8, x0' is in front of unwind_goto. The pad doesn't miss the mov:
1238  * r0 is x8 and the epilogue of the callee copies it to x0 and leaves x8 as it is.
1239  */
1240 static int add_unwind_exentry(struct jit_ctx *ctx, int pad)
1241 {
1242 	int ret_addr = ctx->idx - 1;
1243 	struct exception_table_entry *ex;
1244 	off_t ins_offset;
1245 
1246 	if (!ctx->image)
1247 		/* First pass */
1248 		return 0;
1249 
1250 	if (!ctx->prog->aux->extable ||
1251 	    WARN_ON_ONCE(ctx->exentry_idx >= ctx->prog->aux->num_exentries))
1252 		return -EINVAL;
1253 
1254 	ex = &ctx->prog->aux->extable[ctx->exentry_idx];
1255 	ins_offset = (long)&ctx->ro_image[ret_addr] - 1 - (long)&ex->insn;
1256 	if (WARN_ON_ONCE(ins_offset >= 0 || ins_offset < INT_MIN))
1257 		return -ERANGE;
1258 
1259 	/* switch ex to rw buffer for writing */
1260 	ex = (void *)ctx->image + ((void *)ex - (void *)ctx->ro_image);
1261 	ex->insn = ins_offset;
1262 	ex->fixup = (ctx->offset[pad] - ret_addr) * AARCH64_INSN_SIZE;
1263 	ex->type = EX_TYPE_BPF;
1264 
1265 	ctx->exentry_idx++;
1266 	return 0;
1267 }
1268 
1269 static long bpf_unwind_fixup(u64 lr)
1270 {
1271 	const struct exception_table_entry *e;
1272 
1273 	e = search_bpf_extables(ptrauth_strip_kernel_insn_pac(lr) - 1);
1274 	/*
1275 	 * The verifier made sure that unwind_goto follows a call in a prog. When
1276 	 * the kernel called an async callback, it's exit.
1277 	 */
1278 	return e ? e->fixup : 0;
1279 }
1280 
1281 /*
1282  * unwind_exit: return to the pad. LR in the frame record is signed. Instead of
1283  * signing the address of the pad, let the epilogue authenticate LR as it is and
1284  * add the offset of the pad to it. r0 and r2 are returned.
1285  */
1286 static void emit_unwind_exit(struct jit_ctx *ctx)
1287 {
1288 	const u8 tmp = bpf2a64[TMP_REG_1];
1289 	const u8 r0 = bpf2a64[BPF_REG_0];
1290 	const u8 r2 = bpf2a64[BPF_REG_2];
1291 
1292 	emit(A64_PUSH(r0, r2, A64_SP), ctx);
1293 	emit(A64_LDR64I(A64_R(0), A64_FP, 8), ctx);
1294 	emit_call((u64)bpf_unwind_fixup, ctx);
1295 	emit(A64_MOV(1, tmp, A64_R(0)), ctx);
1296 	emit(A64_POP(r0, r2, A64_SP), ctx);
1297 	build_epilogue(ctx, false, true);
1298 }
1299 
1300 static const struct bpf_jit_arg_abi arm64_arg_abi = {
1301 	.nr_arg_regs		= 8,
1302 	.even_reg_align		= true,
1303 	.even_stack_align	= true,
1304 };
1305 
1306 static const u8 stack_arg_reg[] = { A64_R(5), A64_R(6), A64_R(7) };
1307 
1308 #define NR_STACK_ARG_REGS	ARRAY_SIZE(stack_arg_reg)
1309 
1310 static void emit_stack_arg_load(u8 dst, s16 bpf_off, struct jit_ctx *ctx)
1311 {
1312 	int idx = bpf_off / sizeof(u64) - 1;
1313 
1314 	if (idx < NR_STACK_ARG_REGS)
1315 		emit(A64_MOV(1, dst, stack_arg_reg[idx]), ctx);
1316 	else
1317 		emit(A64_LDR64I(dst, A64_FP, (idx - NR_STACK_ARG_REGS) * sizeof(u64) + 16), ctx);
1318 }
1319 
1320 static void emit_stack_arg_store(u8 src_a64, s16 bpf_off, struct jit_ctx *ctx)
1321 {
1322 	int idx = -bpf_off / sizeof(u64) - 1;
1323 
1324 	if (idx < NR_STACK_ARG_REGS)
1325 		emit(A64_MOV(1, stack_arg_reg[idx], src_a64), ctx);
1326 	else
1327 		emit(A64_STR64I(src_a64, A64_SP, (idx - NR_STACK_ARG_REGS) * sizeof(u64)), ctx);
1328 }
1329 
1330 static void emit_stack_arg_store_imm(s32 imm, s16 bpf_off, const u8 tmp, struct jit_ctx *ctx)
1331 {
1332 	int idx = -bpf_off / sizeof(u64) - 1;
1333 
1334 	if (idx < NR_STACK_ARG_REGS) {
1335 		emit_a64_mov_i(1, stack_arg_reg[idx], imm, ctx);
1336 	} else {
1337 		emit_a64_mov_i(1, tmp, imm, ctx);
1338 		emit(A64_STR64I(tmp, A64_SP, (idx - NR_STACK_ARG_REGS) * sizeof(u64)), ctx);
1339 	}
1340 }
1341 
1342 /*
1343  * Rebase the __arena args of a kfunc call to arena kernel addresses,
1344  * xN = kern_vm_start + (u32)xN, with the arena base register holding
1345  * kern_vm_start. A nullable arg preserves NULL by skipping the add, tested
1346  * on the truncated value as arena NULL is offset 0.
1347  */
1348 static int emit_kfunc_arena_args(struct jit_ctx *ctx, const struct btf_func_model *fm)
1349 {
1350 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
1351 	int i, slot;
1352 
1353 	for (i = 0, slot = 0; i < fm->nr_args; i++) {
1354 		u32 arg_regs = (fm->arg_size[i] + 7) / 8;
1355 		u8 flags = fm->arg_flags[i];
1356 		u8 reg;
1357 
1358 		if (slot + arg_regs > MAX_BPF_FUNC_REG_ARGS)
1359 			break;
1360 		reg = bpf2a64[BPF_REG_1 + slot];
1361 		slot += arg_regs;
1362 
1363 		if (!(flags & BTF_FMODEL_ARENA_ARG))
1364 			continue;
1365 		if (WARN_ON_ONCE(!ctx->arena_vm_start))
1366 			return -EINVAL;
1367 
1368 		if (flags & BTF_FMODEL_NULLABLE_ARG) {
1369 			/* 32-bit mov clears the upper 32 bits */
1370 			emit(A64_MOV(0, reg, reg), ctx);
1371 			/* skip the add so that NULL stays NULL */
1372 			emit(A64_CBZ(0, reg, 2), ctx);
1373 		}
1374 		emit(A64_ADD_UXTW(reg, arena_vm_base, reg), ctx);
1375 	}
1376 
1377 	return 0;
1378 }
1379 
1380 static bool a64_arg_on_stack(u8 slot)
1381 {
1382 	return slot >= arm64_arg_abi.nr_arg_regs;
1383 }
1384 
1385 static s32 a64_arg_stack_off(u8 slot)
1386 {
1387 	return (slot - arm64_arg_abi.nr_arg_regs) * sizeof(u64);
1388 }
1389 
1390 /*
1391  * Move the arguments AAPCS64 places somewhere other than the argument slot the
1392  * BPF calling convention gave them. Slot N is X(N) up to the eighth, and the
1393  * outgoing stack argument area from SP beyond it, both for the slot an
1394  * argument comes from and for the one it goes to.
1395  *
1396  * AAPCS64 only ever moves an argument to a higher slot, so no move here ever
1397  * takes BPF_JIT_ARG_TMP: bpf_jit_plan_arg_moves() hands out the scratch only
1398  * for a convention that moves one down, which needs a register to carry the
1399  * value past its own destination.
1400  */
1401 static void emit_kfunc_arg_moves(struct jit_ctx *ctx, const struct btf_func_model *fm)
1402 {
1403 	struct bpf_jit_arg_move moves[BPF_JIT_MAX_ARG_MOVES];
1404 	const u8 tmp = bpf2a64[TMP_REG_1];
1405 	u32 i, n;
1406 
1407 	n = bpf_jit_plan_arg_moves(&arm64_arg_abi, fm, moves);
1408 
1409 	for (i = 0; i < n; i++) {
1410 		u8 dst = moves[i].dst, src = moves[i].src, reg;
1411 
1412 		if (a64_arg_on_stack(src)) {
1413 			reg = tmp;
1414 			emit(A64_LDR64I(reg, A64_SP, a64_arg_stack_off(src)), ctx);
1415 		} else {
1416 			reg = src;
1417 		}
1418 
1419 		if (a64_arg_on_stack(dst))
1420 			emit(A64_STR64I(reg, A64_SP, a64_arg_stack_off(dst)), ctx);
1421 		else if (reg != dst)
1422 			emit(A64_MOV(1, dst, reg), ctx);
1423 	}
1424 }
1425 
1426 /* JITs an eBPF instruction.
1427  * Returns:
1428  * 0  - successfully JITed an 8-byte eBPF instruction.
1429  * >0 - successfully JITed a 16-byte eBPF instruction.
1430  * <0 - failed to JIT.
1431  */
1432 static int build_insn(const struct bpf_verifier_env *env, const struct bpf_insn *insn,
1433 		      struct jit_ctx *ctx, bool extra_pass)
1434 {
1435 	const u8 code = insn->code;
1436 	u8 dst = bpf2a64[insn->dst_reg];
1437 	u8 src = bpf2a64[insn->src_reg];
1438 	const u8 tmp = bpf2a64[TMP_REG_1];
1439 	const u8 tmp2 = bpf2a64[TMP_REG_2];
1440 	const u8 tmp3 = bpf2a64[TMP_REG_3];
1441 	const u8 fp = bpf2a64[BPF_REG_FP];
1442 	const u8 arena_vm_base = bpf2a64[ARENA_VM_START];
1443 	const u8 priv_sp = bpf2a64[PRIVATE_SP];
1444 	const s16 off = insn->off;
1445 	const s32 imm = insn->imm;
1446 	const int i = insn - ctx->prog->insnsi;
1447 	const bool is64 = BPF_CLASS(code) == BPF_ALU64 ||
1448 			  BPF_CLASS(code) == BPF_JMP;
1449 	u8 jmp_cond;
1450 	s32 jmp_offset;
1451 	u32 a64_insn;
1452 	u8 src_adj;
1453 	u8 dst_adj;
1454 	int off_adj;
1455 	int ret;
1456 	bool sign_extend;
1457 
1458 	if (bpf_insn_is_indirect_target(env, ctx->prog, i))
1459 		emit_bti(A64_BTI_J, ctx);
1460 
1461 	switch (code) {
1462 	/* dst = src */
1463 	case BPF_ALU | BPF_MOV | BPF_X:
1464 	case BPF_ALU64 | BPF_MOV | BPF_X:
1465 		if (insn_is_cast_user(insn)) {
1466 			u32 upper = ctx->user_vm_start >> 32;
1467 			u16 upper_low = upper & 0xffff;
1468 			u16 upper_high = upper >> 16;
1469 			int nr_movk = !!upper_low + !!upper_high;
1470 
1471 			/*
1472 			 * Build the user address: the low 32 bits are the arena
1473 			 * offset, the upper 32 bits come from user_vm_start. A
1474 			 * zero offset must stay NULL, so branch over the MOVKs
1475 			 * when it is zero.
1476 			 */
1477 			emit(A64_MOV(0, dst, src), ctx); /* 32-bit mov clears the upper 32 bits */
1478 			if (nr_movk) {
1479 				emit(A64_CBZ(0, dst, nr_movk + 1), ctx);
1480 				if (upper_low)
1481 					emit(A64_MOVK(1, dst, upper_low, 32), ctx);
1482 				if (upper_high)
1483 					emit(A64_MOVK(1, dst, upper_high, 48), ctx);
1484 			}
1485 			break;
1486 		} else if (insn_is_mov_percpu_addr(insn)) {
1487 			if (dst != src)
1488 				emit(A64_MOV(1, dst, src), ctx);
1489 			if (cpus_have_cap(ARM64_HAS_VIRT_HOST_EXTN))
1490 				emit(A64_MRS_TPIDR_EL2(tmp), ctx);
1491 			else
1492 				emit(A64_MRS_TPIDR_EL1(tmp), ctx);
1493 			emit(A64_ADD(1, dst, dst, tmp), ctx);
1494 			break;
1495 		}
1496 		switch (insn->off) {
1497 		case 0:
1498 			emit(A64_MOV(is64, dst, src), ctx);
1499 			break;
1500 		case 8:
1501 			emit(A64_SXTB(is64, dst, src), ctx);
1502 			break;
1503 		case 16:
1504 			emit(A64_SXTH(is64, dst, src), ctx);
1505 			break;
1506 		case 32:
1507 			emit(A64_SXTW(is64, dst, src), ctx);
1508 			break;
1509 		}
1510 		break;
1511 	/* dst = dst OP src */
1512 	case BPF_ALU | BPF_ADD | BPF_X:
1513 	case BPF_ALU64 | BPF_ADD | BPF_X:
1514 		emit(A64_ADD(is64, dst, dst, src), ctx);
1515 		break;
1516 	case BPF_ALU | BPF_SUB | BPF_X:
1517 	case BPF_ALU64 | BPF_SUB | BPF_X:
1518 		emit(A64_SUB(is64, dst, dst, src), ctx);
1519 		break;
1520 	case BPF_ALU | BPF_AND | BPF_X:
1521 	case BPF_ALU64 | BPF_AND | BPF_X:
1522 		emit(A64_AND(is64, dst, dst, src), ctx);
1523 		break;
1524 	case BPF_ALU | BPF_OR | BPF_X:
1525 	case BPF_ALU64 | BPF_OR | BPF_X:
1526 		emit(A64_ORR(is64, dst, dst, src), ctx);
1527 		break;
1528 	case BPF_ALU | BPF_XOR | BPF_X:
1529 	case BPF_ALU64 | BPF_XOR | BPF_X:
1530 		emit(A64_EOR(is64, dst, dst, src), ctx);
1531 		break;
1532 	case BPF_ALU | BPF_MUL | BPF_X:
1533 	case BPF_ALU64 | BPF_MUL | BPF_X:
1534 		emit(A64_MUL(is64, dst, dst, src), ctx);
1535 		break;
1536 	case BPF_ALU | BPF_DIV | BPF_X:
1537 	case BPF_ALU64 | BPF_DIV | BPF_X:
1538 		if (!off)
1539 			emit(A64_UDIV(is64, dst, dst, src), ctx);
1540 		else
1541 			emit(A64_SDIV(is64, dst, dst, src), ctx);
1542 		break;
1543 	case BPF_ALU | BPF_MOD | BPF_X:
1544 	case BPF_ALU64 | BPF_MOD | BPF_X:
1545 		if (!off)
1546 			emit(A64_UDIV(is64, tmp, dst, src), ctx);
1547 		else
1548 			emit(A64_SDIV(is64, tmp, dst, src), ctx);
1549 		emit(A64_MSUB(is64, dst, dst, tmp, src), ctx);
1550 		break;
1551 	case BPF_ALU | BPF_LSH | BPF_X:
1552 	case BPF_ALU64 | BPF_LSH | BPF_X:
1553 		emit(A64_LSLV(is64, dst, dst, src), ctx);
1554 		break;
1555 	case BPF_ALU | BPF_RSH | BPF_X:
1556 	case BPF_ALU64 | BPF_RSH | BPF_X:
1557 		emit(A64_LSRV(is64, dst, dst, src), ctx);
1558 		break;
1559 	case BPF_ALU | BPF_ARSH | BPF_X:
1560 	case BPF_ALU64 | BPF_ARSH | BPF_X:
1561 		emit(A64_ASRV(is64, dst, dst, src), ctx);
1562 		break;
1563 	/* dst = -dst */
1564 	case BPF_ALU | BPF_NEG:
1565 	case BPF_ALU64 | BPF_NEG:
1566 		emit(A64_NEG(is64, dst, dst), ctx);
1567 		break;
1568 	/* dst = BSWAP##imm(dst) */
1569 	case BPF_ALU | BPF_END | BPF_FROM_LE:
1570 	case BPF_ALU | BPF_END | BPF_FROM_BE:
1571 	case BPF_ALU64 | BPF_END | BPF_FROM_LE:
1572 		if (BPF_CLASS(code) == BPF_ALU && BPF_SRC(code) == BPF_FROM_LE)
1573 			goto emit_bswap_uxt;
1574 		switch (imm) {
1575 		case 16:
1576 			emit(A64_REV16(is64, dst, dst), ctx);
1577 			/* zero-extend 16 bits into 64 bits */
1578 			emit(A64_UXTH(is64, dst, dst), ctx);
1579 			break;
1580 		case 32:
1581 			emit(A64_REV32(0, dst, dst), ctx);
1582 			/* upper 32 bits already cleared */
1583 			break;
1584 		case 64:
1585 			emit(A64_REV64(dst, dst), ctx);
1586 			break;
1587 		}
1588 		break;
1589 emit_bswap_uxt:
1590 		switch (imm) {
1591 		case 16:
1592 			/* zero-extend 16 bits into 64 bits */
1593 			emit(A64_UXTH(is64, dst, dst), ctx);
1594 			break;
1595 		case 32:
1596 			/* zero-extend 32 bits into 64 bits */
1597 			emit(A64_UXTW(is64, dst, dst), ctx);
1598 			break;
1599 		case 64:
1600 			/* nop */
1601 			break;
1602 		}
1603 		break;
1604 	/* dst = imm */
1605 	case BPF_ALU | BPF_MOV | BPF_K:
1606 	case BPF_ALU64 | BPF_MOV | BPF_K:
1607 		emit_a64_mov_i(is64, dst, imm, ctx);
1608 		break;
1609 	/* dst = dst OP imm */
1610 	case BPF_ALU | BPF_ADD | BPF_K:
1611 	case BPF_ALU64 | BPF_ADD | BPF_K:
1612 		emit_a64_add_i(is64, dst, dst, tmp, imm, ctx);
1613 		break;
1614 	case BPF_ALU | BPF_SUB | BPF_K:
1615 	case BPF_ALU64 | BPF_SUB | BPF_K:
1616 		if (is_addsub_imm(imm)) {
1617 			emit(A64_SUB_I(is64, dst, dst, imm), ctx);
1618 		} else if (is_addsub_imm(-(u32)imm)) {
1619 			emit(A64_ADD_I(is64, dst, dst, -imm), ctx);
1620 		} else {
1621 			emit_a64_mov_i(is64, tmp, imm, ctx);
1622 			emit(A64_SUB(is64, dst, dst, tmp), ctx);
1623 		}
1624 		break;
1625 	case BPF_ALU | BPF_AND | BPF_K:
1626 	case BPF_ALU64 | BPF_AND | BPF_K:
1627 		a64_insn = A64_AND_I(is64, dst, dst, imm);
1628 		if (a64_insn != AARCH64_BREAK_FAULT) {
1629 			emit(a64_insn, ctx);
1630 		} else {
1631 			emit_a64_mov_i(is64, tmp, imm, ctx);
1632 			emit(A64_AND(is64, dst, dst, tmp), ctx);
1633 		}
1634 		break;
1635 	case BPF_ALU | BPF_OR | BPF_K:
1636 	case BPF_ALU64 | BPF_OR | BPF_K:
1637 		a64_insn = A64_ORR_I(is64, dst, dst, imm);
1638 		if (a64_insn != AARCH64_BREAK_FAULT) {
1639 			emit(a64_insn, ctx);
1640 		} else {
1641 			emit_a64_mov_i(is64, tmp, imm, ctx);
1642 			emit(A64_ORR(is64, dst, dst, tmp), ctx);
1643 		}
1644 		break;
1645 	case BPF_ALU | BPF_XOR | BPF_K:
1646 	case BPF_ALU64 | BPF_XOR | BPF_K:
1647 		a64_insn = A64_EOR_I(is64, dst, dst, imm);
1648 		if (a64_insn != AARCH64_BREAK_FAULT) {
1649 			emit(a64_insn, ctx);
1650 		} else {
1651 			emit_a64_mov_i(is64, tmp, imm, ctx);
1652 			emit(A64_EOR(is64, dst, dst, tmp), ctx);
1653 		}
1654 		break;
1655 	case BPF_ALU | BPF_MUL | BPF_K:
1656 	case BPF_ALU64 | BPF_MUL | BPF_K:
1657 		emit_a64_mov_i(is64, tmp, imm, ctx);
1658 		emit(A64_MUL(is64, dst, dst, tmp), ctx);
1659 		break;
1660 	case BPF_ALU | BPF_DIV | BPF_K:
1661 	case BPF_ALU64 | BPF_DIV | BPF_K:
1662 		emit_a64_mov_i(is64, tmp, imm, ctx);
1663 		if (!off)
1664 			emit(A64_UDIV(is64, dst, dst, tmp), ctx);
1665 		else
1666 			emit(A64_SDIV(is64, dst, dst, tmp), ctx);
1667 		break;
1668 	case BPF_ALU | BPF_MOD | BPF_K:
1669 	case BPF_ALU64 | BPF_MOD | BPF_K:
1670 		emit_a64_mov_i(is64, tmp2, imm, ctx);
1671 		if (!off)
1672 			emit(A64_UDIV(is64, tmp, dst, tmp2), ctx);
1673 		else
1674 			emit(A64_SDIV(is64, tmp, dst, tmp2), ctx);
1675 		emit(A64_MSUB(is64, dst, dst, tmp, tmp2), ctx);
1676 		break;
1677 	case BPF_ALU | BPF_LSH | BPF_K:
1678 	case BPF_ALU64 | BPF_LSH | BPF_K:
1679 		emit(A64_LSL(is64, dst, dst, imm), ctx);
1680 		break;
1681 	case BPF_ALU | BPF_RSH | BPF_K:
1682 	case BPF_ALU64 | BPF_RSH | BPF_K:
1683 		emit(A64_LSR(is64, dst, dst, imm), ctx);
1684 		break;
1685 	case BPF_ALU | BPF_ARSH | BPF_K:
1686 	case BPF_ALU64 | BPF_ARSH | BPF_K:
1687 		emit(A64_ASR(is64, dst, dst, imm), ctx);
1688 		break;
1689 
1690 	/* JUMP reg */
1691 	case BPF_JMP | BPF_JA | BPF_X:
1692 		emit(A64_BR(dst), ctx);
1693 		break;
1694 	/* JUMP off */
1695 	case BPF_JMP | BPF_JA:
1696 	case BPF_JMP32 | BPF_JA:
1697 		if (BPF_CLASS(code) == BPF_JMP)
1698 			jmp_offset = bpf2a64_offset(i, off, ctx);
1699 		else
1700 			jmp_offset = bpf2a64_offset(i, imm, ctx);
1701 		check_imm26(jmp_offset);
1702 		emit(A64_B(jmp_offset), ctx);
1703 		break;
1704 	/* IF (dst COND src) JUMP off */
1705 	case BPF_JMP | BPF_JEQ | BPF_X:
1706 	case BPF_JMP | BPF_JGT | BPF_X:
1707 	case BPF_JMP | BPF_JLT | BPF_X:
1708 	case BPF_JMP | BPF_JGE | BPF_X:
1709 	case BPF_JMP | BPF_JLE | BPF_X:
1710 	case BPF_JMP | BPF_JNE | BPF_X:
1711 	case BPF_JMP | BPF_JSGT | BPF_X:
1712 	case BPF_JMP | BPF_JSLT | BPF_X:
1713 	case BPF_JMP | BPF_JSGE | BPF_X:
1714 	case BPF_JMP | BPF_JSLE | BPF_X:
1715 	case BPF_JMP32 | BPF_JEQ | BPF_X:
1716 	case BPF_JMP32 | BPF_JGT | BPF_X:
1717 	case BPF_JMP32 | BPF_JLT | BPF_X:
1718 	case BPF_JMP32 | BPF_JGE | BPF_X:
1719 	case BPF_JMP32 | BPF_JLE | BPF_X:
1720 	case BPF_JMP32 | BPF_JNE | BPF_X:
1721 	case BPF_JMP32 | BPF_JSGT | BPF_X:
1722 	case BPF_JMP32 | BPF_JSLT | BPF_X:
1723 	case BPF_JMP32 | BPF_JSGE | BPF_X:
1724 	case BPF_JMP32 | BPF_JSLE | BPF_X:
1725 		emit(A64_CMP(is64, dst, src), ctx);
1726 emit_cond_jmp:
1727 		jmp_offset = bpf2a64_offset(i, off, ctx);
1728 		check_imm19(jmp_offset);
1729 		switch (BPF_OP(code)) {
1730 		case BPF_JEQ:
1731 			jmp_cond = A64_COND_EQ;
1732 			break;
1733 		case BPF_JGT:
1734 			jmp_cond = A64_COND_HI;
1735 			break;
1736 		case BPF_JLT:
1737 			jmp_cond = A64_COND_CC;
1738 			break;
1739 		case BPF_JGE:
1740 			jmp_cond = A64_COND_CS;
1741 			break;
1742 		case BPF_JLE:
1743 			jmp_cond = A64_COND_LS;
1744 			break;
1745 		case BPF_JSET:
1746 		case BPF_JNE:
1747 			jmp_cond = A64_COND_NE;
1748 			break;
1749 		case BPF_JSGT:
1750 			jmp_cond = A64_COND_GT;
1751 			break;
1752 		case BPF_JSLT:
1753 			jmp_cond = A64_COND_LT;
1754 			break;
1755 		case BPF_JSGE:
1756 			jmp_cond = A64_COND_GE;
1757 			break;
1758 		case BPF_JSLE:
1759 			jmp_cond = A64_COND_LE;
1760 			break;
1761 		default:
1762 			return -EFAULT;
1763 		}
1764 		emit(A64_B_(jmp_cond, jmp_offset), ctx);
1765 		break;
1766 	case BPF_JMP | BPF_JSET | BPF_X:
1767 	case BPF_JMP32 | BPF_JSET | BPF_X:
1768 		emit(A64_TST(is64, dst, src), ctx);
1769 		goto emit_cond_jmp;
1770 	/* IF (dst COND imm) JUMP off */
1771 	case BPF_JMP | BPF_JEQ | BPF_K:
1772 	case BPF_JMP | BPF_JGT | BPF_K:
1773 	case BPF_JMP | BPF_JLT | BPF_K:
1774 	case BPF_JMP | BPF_JGE | BPF_K:
1775 	case BPF_JMP | BPF_JLE | BPF_K:
1776 	case BPF_JMP | BPF_JNE | BPF_K:
1777 	case BPF_JMP | BPF_JSGT | BPF_K:
1778 	case BPF_JMP | BPF_JSLT | BPF_K:
1779 	case BPF_JMP | BPF_JSGE | BPF_K:
1780 	case BPF_JMP | BPF_JSLE | BPF_K:
1781 	case BPF_JMP32 | BPF_JEQ | BPF_K:
1782 	case BPF_JMP32 | BPF_JGT | BPF_K:
1783 	case BPF_JMP32 | BPF_JLT | BPF_K:
1784 	case BPF_JMP32 | BPF_JGE | BPF_K:
1785 	case BPF_JMP32 | BPF_JLE | BPF_K:
1786 	case BPF_JMP32 | BPF_JNE | BPF_K:
1787 	case BPF_JMP32 | BPF_JSGT | BPF_K:
1788 	case BPF_JMP32 | BPF_JSLT | BPF_K:
1789 	case BPF_JMP32 | BPF_JSGE | BPF_K:
1790 	case BPF_JMP32 | BPF_JSLE | BPF_K:
1791 		if (is_addsub_imm(imm)) {
1792 			emit(A64_CMP_I(is64, dst, imm), ctx);
1793 		} else if (is_addsub_imm(-(u32)imm)) {
1794 			emit(A64_CMN_I(is64, dst, -imm), ctx);
1795 		} else {
1796 			emit_a64_mov_i(is64, tmp, imm, ctx);
1797 			emit(A64_CMP(is64, dst, tmp), ctx);
1798 		}
1799 		goto emit_cond_jmp;
1800 	case BPF_JMP | BPF_JSET | BPF_K:
1801 	case BPF_JMP32 | BPF_JSET | BPF_K:
1802 		a64_insn = A64_TST_I(is64, dst, imm);
1803 		if (a64_insn != AARCH64_BREAK_FAULT) {
1804 			emit(a64_insn, ctx);
1805 		} else {
1806 			emit_a64_mov_i(is64, tmp, imm, ctx);
1807 			emit(A64_TST(is64, dst, tmp), ctx);
1808 		}
1809 		goto emit_cond_jmp;
1810 	/* function call */
1811 	case BPF_JMP | BPF_CALL:
1812 	{
1813 		const u8 r0 = bpf2a64[BPF_REG_0];
1814 		bool func_addr_fixed;
1815 		u64 func_addr;
1816 		u32 cpu_offset;
1817 
1818 		/* Implement helper call to bpf_get_smp_processor_id() inline */
1819 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_get_smp_processor_id) {
1820 			cpu_offset = offsetof(struct thread_info, cpu);
1821 
1822 			emit(A64_MRS_SP_EL0(tmp), ctx);
1823 			if (is_lsi_offset(cpu_offset, 2)) {
1824 				emit(A64_LDR32I(r0, tmp, cpu_offset), ctx);
1825 			} else {
1826 				emit_a64_mov_i(1, tmp2, cpu_offset, ctx);
1827 				emit(A64_LDR32(r0, tmp, tmp2), ctx);
1828 			}
1829 			break;
1830 		}
1831 
1832 		/* Implement helper call to bpf_get_current_task/_btf() inline */
1833 		if (insn->src_reg == 0 && (insn->imm == BPF_FUNC_get_current_task ||
1834 					   insn->imm == BPF_FUNC_get_current_task_btf)) {
1835 			emit(A64_MRS_SP_EL0(r0), ctx);
1836 			break;
1837 		}
1838 
1839 		ret = bpf_jit_get_func_addr(ctx->prog, insn, extra_pass,
1840 					    &func_addr, &func_addr_fixed);
1841 		if (ret < 0)
1842 			return ret;
1843 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
1844 			const struct btf_func_model *fm;
1845 
1846 			fm = bpf_jit_find_kfunc_model(ctx->prog, insn);
1847 			if (!fm)
1848 				return -EINVAL;
1849 			ret = emit_kfunc_arena_args(ctx, fm);
1850 			if (ret < 0)
1851 				return ret;
1852 			emit_kfunc_arg_moves(ctx, fm);
1853 		}
1854 		emit_call(func_addr, ctx);
1855 		/*
1856 		 * Call to arch_bpf_timed_may_goto() is emitted by the
1857 		 * verifier and called with custom calling convention with
1858 		 * first argument and return value in BPF_REG_AX (x9).
1859 		 */
1860 		if (func_addr != (u64)arch_bpf_timed_may_goto)
1861 			emit(A64_MOV(1, r0, A64_R(0)), ctx);
1862 		break;
1863 	}
1864 	/* indirect call of a bpf subprog, dst holds its address */
1865 	case BPF_JMP | BPF_CALL | BPF_X:
1866 		/*
1867 		 * It's the same as a direct call of a subprog that is out of
1868 		 * range of BL: the subprog starts with BTI JC, the arguments
1869 		 * are in place, and the registers that hold the tail call
1870 		 * counter and the private stack are callee saved.
1871 		 */
1872 		emit(A64_BLR(dst), ctx);
1873 		emit(A64_MOV(1, bpf2a64[BPF_REG_0], A64_R(0)), ctx);
1874 		break;
1875 	/* tail call */
1876 	case BPF_JMP | BPF_TAIL_CALL:
1877 		if (emit_bpf_tail_call(ctx))
1878 			return -EFAULT;
1879 		break;
1880 	/* unwind_goto. The verifier expanded may_goto. */
1881 	case BPF_JMP | BPF_JCOND:
1882 		ret = add_unwind_exentry(ctx, i + 1 + off);
1883 		if (ret)
1884 			return ret;
1885 		break;
1886 	/* function return */
1887 	case BPF_JMP | BPF_EXIT:
1888 		if (bpf_is_unwind_exit(insn) && bpf_prog_can_unwind(ctx->prog)) {
1889 			emit_unwind_exit(ctx);
1890 			break;
1891 		}
1892 		/* Optimization: when last instruction is EXIT,
1893 		   simply fallthrough to epilogue. */
1894 		if (i == ctx->prog->len - 1)
1895 			break;
1896 		jmp_offset = epilogue_offset(ctx);
1897 		check_imm26(jmp_offset);
1898 		emit(A64_B(jmp_offset), ctx);
1899 		break;
1900 
1901 	/* dst = imm64 */
1902 	case BPF_LD | BPF_IMM | BPF_DW:
1903 	{
1904 		const struct bpf_insn insn1 = insn[1];
1905 		u64 imm64;
1906 
1907 		imm64 = (u64)insn1.imm << 32 | (u32)imm;
1908 		if (bpf_pseudo_func(insn))
1909 			emit_addr_mov_i64(dst, imm64, ctx);
1910 		else
1911 			emit_a64_mov_i64(dst, imm64, ctx);
1912 
1913 		return 1;
1914 	}
1915 
1916 	/* LDX: dst = (u64)*(unsigned size *)(src + off) */
1917 	case BPF_LDX | BPF_MEM | BPF_W:
1918 	case BPF_LDX | BPF_MEM | BPF_H:
1919 	case BPF_LDX | BPF_MEM | BPF_B:
1920 	case BPF_LDX | BPF_MEM | BPF_DW:
1921 		if (insn->src_reg == BPF_REG_PARAMS) {
1922 			emit_stack_arg_load(dst, off, ctx);
1923 			break;
1924 		}
1925 		fallthrough;
1926 	case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
1927 	case BPF_LDX | BPF_PROBE_MEM | BPF_W:
1928 	case BPF_LDX | BPF_PROBE_MEM | BPF_H:
1929 	case BPF_LDX | BPF_PROBE_MEM | BPF_B:
1930 	/* LDXS: dst_reg = (s64)*(signed size *)(src_reg + off) */
1931 	case BPF_LDX | BPF_MEMSX | BPF_B:
1932 	case BPF_LDX | BPF_MEMSX | BPF_H:
1933 	case BPF_LDX | BPF_MEMSX | BPF_W:
1934 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
1935 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
1936 	case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
1937 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_B:
1938 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
1939 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
1940 	case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
1941 	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_B:
1942 	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_H:
1943 	case BPF_LDX | BPF_PROBE_MEM32SX | BPF_W:
1944 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
1945 		    BPF_MODE(insn->code) == BPF_PROBE_MEM32SX) {
1946 			emit(A64_ADD(1, tmp2, src, arena_vm_base), ctx);
1947 			src = tmp2;
1948 		}
1949 		if (src == fp) {
1950 			src_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
1951 			off_adj = off + ctx->stack_size;
1952 			if (!ctx->priv_sp_used)
1953 				off_adj += ctx->stack_arg_size;
1954 		} else {
1955 			src_adj = src;
1956 			off_adj = off;
1957 		}
1958 		sign_extend = (BPF_MODE(insn->code) == BPF_MEMSX ||
1959 				BPF_MODE(insn->code) == BPF_PROBE_MEMSX ||
1960 				 BPF_MODE(insn->code) == BPF_PROBE_MEM32SX);
1961 		switch (BPF_SIZE(code)) {
1962 		case BPF_W:
1963 			if (is_lsi_offset(off_adj, 2)) {
1964 				if (sign_extend)
1965 					emit(A64_LDRSWI(dst, src_adj, off_adj), ctx);
1966 				else
1967 					emit(A64_LDR32I(dst, src_adj, off_adj), ctx);
1968 			} else {
1969 				emit_a64_mov_i(1, tmp, off, ctx);
1970 				if (sign_extend)
1971 					emit(A64_LDRSW(dst, src, tmp), ctx);
1972 				else
1973 					emit(A64_LDR32(dst, src, tmp), ctx);
1974 			}
1975 			break;
1976 		case BPF_H:
1977 			if (is_lsi_offset(off_adj, 1)) {
1978 				if (sign_extend)
1979 					emit(A64_LDRSHI(dst, src_adj, off_adj), ctx);
1980 				else
1981 					emit(A64_LDRHI(dst, src_adj, off_adj), ctx);
1982 			} else {
1983 				emit_a64_mov_i(1, tmp, off, ctx);
1984 				if (sign_extend)
1985 					emit(A64_LDRSH(dst, src, tmp), ctx);
1986 				else
1987 					emit(A64_LDRH(dst, src, tmp), ctx);
1988 			}
1989 			break;
1990 		case BPF_B:
1991 			if (is_lsi_offset(off_adj, 0)) {
1992 				if (sign_extend)
1993 					emit(A64_LDRSBI(dst, src_adj, off_adj), ctx);
1994 				else
1995 					emit(A64_LDRBI(dst, src_adj, off_adj), ctx);
1996 			} else {
1997 				emit_a64_mov_i(1, tmp, off, ctx);
1998 				if (sign_extend)
1999 					emit(A64_LDRSB(dst, src, tmp), ctx);
2000 				else
2001 					emit(A64_LDRB(dst, src, tmp), ctx);
2002 			}
2003 			break;
2004 		case BPF_DW:
2005 			if (is_lsi_offset(off_adj, 3)) {
2006 				emit(A64_LDR64I(dst, src_adj, off_adj), ctx);
2007 			} else {
2008 				emit_a64_mov_i(1, tmp, off, ctx);
2009 				emit(A64_LDR64(dst, src, tmp), ctx);
2010 			}
2011 			break;
2012 		}
2013 
2014 		ret = add_exception_handler(insn, ctx, dst);
2015 		if (ret)
2016 			return ret;
2017 		break;
2018 
2019 	/* speculation barrier against v1 and v4 */
2020 	case BPF_ST | BPF_NOSPEC:
2021 		if (alternative_has_cap_likely(ARM64_HAS_SB)) {
2022 			emit(A64_SB, ctx);
2023 		} else {
2024 			emit(A64_DSB_NSH, ctx);
2025 			emit(A64_ISB, ctx);
2026 		}
2027 		break;
2028 
2029 	/* ST: *(size *)(dst + off) = imm */
2030 	case BPF_ST | BPF_MEM | BPF_W:
2031 	case BPF_ST | BPF_MEM | BPF_H:
2032 	case BPF_ST | BPF_MEM | BPF_B:
2033 	case BPF_ST | BPF_MEM | BPF_DW:
2034 		if (insn->dst_reg == BPF_REG_PARAMS) {
2035 			emit_stack_arg_store_imm(imm, off, tmp, ctx);
2036 			break;
2037 		}
2038 		fallthrough;
2039 	case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
2040 	case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
2041 	case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
2042 	case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
2043 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) {
2044 			emit(A64_ADD(1, tmp3, dst, arena_vm_base), ctx);
2045 			dst = tmp3;
2046 		}
2047 		if (dst == fp) {
2048 			dst_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
2049 			off_adj = off + ctx->stack_size;
2050 			if (!ctx->priv_sp_used)
2051 				off_adj += ctx->stack_arg_size;
2052 		} else {
2053 			dst_adj = dst;
2054 			off_adj = off;
2055 		}
2056 		/* Load imm to a register then store it */
2057 		emit_a64_mov_i(1, tmp, imm, ctx);
2058 		switch (BPF_SIZE(code)) {
2059 		case BPF_W:
2060 			if (is_lsi_offset(off_adj, 2)) {
2061 				emit(A64_STR32I(tmp, dst_adj, off_adj), ctx);
2062 			} else {
2063 				emit_a64_mov_i(1, tmp2, off, ctx);
2064 				emit(A64_STR32(tmp, dst, tmp2), ctx);
2065 			}
2066 			break;
2067 		case BPF_H:
2068 			if (is_lsi_offset(off_adj, 1)) {
2069 				emit(A64_STRHI(tmp, dst_adj, off_adj), ctx);
2070 			} else {
2071 				emit_a64_mov_i(1, tmp2, off, ctx);
2072 				emit(A64_STRH(tmp, dst, tmp2), ctx);
2073 			}
2074 			break;
2075 		case BPF_B:
2076 			if (is_lsi_offset(off_adj, 0)) {
2077 				emit(A64_STRBI(tmp, dst_adj, off_adj), ctx);
2078 			} else {
2079 				emit_a64_mov_i(1, tmp2, off, ctx);
2080 				emit(A64_STRB(tmp, dst, tmp2), ctx);
2081 			}
2082 			break;
2083 		case BPF_DW:
2084 			if (is_lsi_offset(off_adj, 3)) {
2085 				emit(A64_STR64I(tmp, dst_adj, off_adj), ctx);
2086 			} else {
2087 				emit_a64_mov_i(1, tmp2, off, ctx);
2088 				emit(A64_STR64(tmp, dst, tmp2), ctx);
2089 			}
2090 			break;
2091 		}
2092 
2093 		ret = add_exception_handler(insn, ctx, DONT_CLEAR);
2094 		if (ret)
2095 			return ret;
2096 		break;
2097 
2098 	/* STX: *(size *)(dst + off) = src */
2099 	case BPF_STX | BPF_MEM | BPF_W:
2100 	case BPF_STX | BPF_MEM | BPF_H:
2101 	case BPF_STX | BPF_MEM | BPF_B:
2102 	case BPF_STX | BPF_MEM | BPF_DW:
2103 		if (insn->dst_reg == BPF_REG_PARAMS) {
2104 			emit_stack_arg_store(src, off, ctx);
2105 			break;
2106 		}
2107 		fallthrough;
2108 	case BPF_STX | BPF_PROBE_MEM32 | BPF_B:
2109 	case BPF_STX | BPF_PROBE_MEM32 | BPF_H:
2110 	case BPF_STX | BPF_PROBE_MEM32 | BPF_W:
2111 	case BPF_STX | BPF_PROBE_MEM32 | BPF_DW:
2112 		if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) {
2113 			emit(A64_ADD(1, tmp2, dst, arena_vm_base), ctx);
2114 			dst = tmp2;
2115 		}
2116 		if (dst == fp) {
2117 			dst_adj = ctx->priv_sp_used ? priv_sp : A64_SP;
2118 			off_adj = off + ctx->stack_size;
2119 			if (!ctx->priv_sp_used)
2120 				off_adj += ctx->stack_arg_size;
2121 		} else {
2122 			dst_adj = dst;
2123 			off_adj = off;
2124 		}
2125 		switch (BPF_SIZE(code)) {
2126 		case BPF_W:
2127 			if (is_lsi_offset(off_adj, 2)) {
2128 				emit(A64_STR32I(src, dst_adj, off_adj), ctx);
2129 			} else {
2130 				emit_a64_mov_i(1, tmp, off, ctx);
2131 				emit(A64_STR32(src, dst, tmp), ctx);
2132 			}
2133 			break;
2134 		case BPF_H:
2135 			if (is_lsi_offset(off_adj, 1)) {
2136 				emit(A64_STRHI(src, dst_adj, off_adj), ctx);
2137 			} else {
2138 				emit_a64_mov_i(1, tmp, off, ctx);
2139 				emit(A64_STRH(src, dst, tmp), ctx);
2140 			}
2141 			break;
2142 		case BPF_B:
2143 			if (is_lsi_offset(off_adj, 0)) {
2144 				emit(A64_STRBI(src, dst_adj, off_adj), ctx);
2145 			} else {
2146 				emit_a64_mov_i(1, tmp, off, ctx);
2147 				emit(A64_STRB(src, dst, tmp), ctx);
2148 			}
2149 			break;
2150 		case BPF_DW:
2151 			if (is_lsi_offset(off_adj, 3)) {
2152 				emit(A64_STR64I(src, dst_adj, off_adj), ctx);
2153 			} else {
2154 				emit_a64_mov_i(1, tmp, off, ctx);
2155 				emit(A64_STR64(src, dst, tmp), ctx);
2156 			}
2157 			break;
2158 		}
2159 
2160 		ret = add_exception_handler(insn, ctx, DONT_CLEAR);
2161 		if (ret)
2162 			return ret;
2163 		break;
2164 
2165 	case BPF_STX | BPF_ATOMIC | BPF_B:
2166 	case BPF_STX | BPF_ATOMIC | BPF_H:
2167 	case BPF_STX | BPF_ATOMIC | BPF_W:
2168 	case BPF_STX | BPF_ATOMIC | BPF_DW:
2169 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_B:
2170 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_H:
2171 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_W:
2172 	case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
2173 		if (bpf_atomic_is_load_store(insn))
2174 			ret = emit_atomic_ld_st(insn, ctx);
2175 		else if (cpus_have_cap(ARM64_HAS_LSE_ATOMICS))
2176 			ret = emit_lse_atomic(insn, ctx);
2177 		else
2178 			ret = emit_ll_sc_atomic(insn, ctx);
2179 		if (ret)
2180 			return ret;
2181 
2182 		if (BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
2183 			/*
2184 			 * A load-acquire reads into dst_reg, and a read-modify-write
2185 			 * carrying BPF_FETCH reads the old value into src_reg, or into
2186 			 * r0 for a BPF_CMPXCHG. Clear that register on fault, the
2187 			 * remaining atomics have no destination register.
2188 			 */
2189 			int load_reg = bpf_atomic_load_reg(insn);
2190 
2191 			ret = add_exception_handler(insn, ctx, load_reg < 0 ?
2192 						    DONT_CLEAR : bpf2a64[load_reg]);
2193 			if (ret)
2194 				return ret;
2195 		}
2196 		break;
2197 
2198 	default:
2199 		pr_err_once("unknown opcode %02x\n", code);
2200 		return -EINVAL;
2201 	}
2202 
2203 	return 0;
2204 }
2205 
2206 static int build_body(struct bpf_verifier_env *env, struct jit_ctx *ctx, bool extra_pass)
2207 {
2208 	const struct bpf_prog *prog = ctx->prog;
2209 	int i;
2210 
2211 	/*
2212 	 * - offset[0] offset of the end of prologue,
2213 	 *   start of the 1st instruction.
2214 	 * - offset[1] - offset of the end of 1st instruction,
2215 	 *   start of the 2nd instruction
2216 	 * [....]
2217 	 * - offset[3] - offset of the end of 3rd instruction,
2218 	 *   start of 4th instruction
2219 	 */
2220 	for (i = 0; i < prog->len; i++) {
2221 		const struct bpf_insn *insn = &prog->insnsi[i];
2222 		int ret;
2223 
2224 		ctx->offset[i] = ctx->idx;
2225 		ret = build_insn(env, insn, ctx, extra_pass);
2226 		if (ret > 0) {
2227 			i++;
2228 			ctx->offset[i] = ctx->idx;
2229 			continue;
2230 		}
2231 		if (ret)
2232 			return ret;
2233 	}
2234 	/*
2235 	 * offset is allocated with prog->len + 1 so fill in
2236 	 * the last element with the offset after the last
2237 	 * instruction (end of program)
2238 	 */
2239 	ctx->offset[i] = ctx->idx;
2240 
2241 	return 0;
2242 }
2243 
2244 static int validate_code(struct jit_ctx *ctx)
2245 {
2246 	int i;
2247 
2248 	for (i = 0; i < ctx->idx; i++) {
2249 		u32 a64_insn = le32_to_cpu(ctx->image[i]);
2250 
2251 		if (a64_insn == AARCH64_BREAK_FAULT)
2252 			return -1;
2253 	}
2254 	return 0;
2255 }
2256 
2257 static int validate_ctx(struct jit_ctx *ctx)
2258 {
2259 	if (validate_code(ctx))
2260 		return -1;
2261 
2262 	if (WARN_ON_ONCE(ctx->exentry_idx != ctx->prog->aux->num_exentries))
2263 		return -1;
2264 
2265 	return 0;
2266 }
2267 
2268 static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
2269 {
2270 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
2271 	u64 *stack_ptr;
2272 
2273 	for_each_possible_cpu(cpu) {
2274 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
2275 		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
2276 		stack_ptr[1] = PRIV_STACK_GUARD_VAL;
2277 		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
2278 		stack_ptr[underflow_idx + 1] = PRIV_STACK_GUARD_VAL;
2279 	}
2280 }
2281 
2282 static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
2283 				   struct bpf_prog *prog)
2284 {
2285 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
2286 	u64 *stack_ptr;
2287 
2288 	for_each_possible_cpu(cpu) {
2289 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
2290 		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
2291 		    stack_ptr[1] != PRIV_STACK_GUARD_VAL ||
2292 		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL ||
2293 		    stack_ptr[underflow_idx + 1] != PRIV_STACK_GUARD_VAL) {
2294 			pr_err("BPF private stack overflow/underflow detected for prog %sx\n",
2295 			       bpf_jit_get_prog_name(prog));
2296 			break;
2297 		}
2298 	}
2299 }
2300 
2301 struct arm64_jit_data {
2302 	struct bpf_binary_header *header;
2303 	u8 *ro_image;
2304 	struct bpf_binary_header *ro_header;
2305 	struct jit_ctx ctx;
2306 };
2307 
2308 struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog)
2309 {
2310 	int image_size, prog_size, extable_size, extable_align, extable_offset;
2311 	struct bpf_binary_header *header;
2312 	struct bpf_binary_header *ro_header = NULL;
2313 	struct arm64_jit_data *jit_data;
2314 	void __percpu *priv_stack_ptr = NULL;
2315 	bool was_classic = bpf_prog_was_classic(prog);
2316 	int priv_stack_alloc_sz;
2317 	bool extra_pass = false;
2318 	struct jit_ctx ctx;
2319 	u8 *image_ptr;
2320 	u8 *ro_image_ptr;
2321 	int body_idx;
2322 	int exentry_idx;
2323 	int out_cnt;
2324 
2325 	if (!prog->jit_requested)
2326 		return prog;
2327 
2328 	jit_data = prog->aux->jit_data;
2329 	if (!jit_data) {
2330 		jit_data = kzalloc_obj(*jit_data);
2331 		if (!jit_data)
2332 			return prog;
2333 		prog->aux->jit_data = jit_data;
2334 	}
2335 	priv_stack_ptr = prog->aux->priv_stack_ptr;
2336 	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
2337 		/* Allocate actual private stack size with verifier-calculated
2338 		 * stack size plus two memory guards to protect overflow and
2339 		 * underflow.
2340 		 */
2341 		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
2342 				      2 * PRIV_STACK_GUARD_SZ;
2343 		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 16, GFP_KERNEL);
2344 		if (!priv_stack_ptr)
2345 			goto out_priv_stack;
2346 
2347 		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
2348 		prog->aux->priv_stack_ptr = priv_stack_ptr;
2349 	}
2350 	if (jit_data->ctx.offset) {
2351 		ctx = jit_data->ctx;
2352 		ro_image_ptr = jit_data->ro_image;
2353 		ro_header = jit_data->ro_header;
2354 		header = jit_data->header;
2355 		image_ptr = (void *)header + ((void *)ro_image_ptr
2356 						 - (void *)ro_header);
2357 		extra_pass = true;
2358 		prog_size = sizeof(u32) * ctx.idx;
2359 		goto skip_init_ctx;
2360 	}
2361 	memset(&ctx, 0, sizeof(ctx));
2362 	ctx.prog = prog;
2363 
2364 	ctx.offset = kvzalloc_objs(int, prog->len + 1);
2365 	if (ctx.offset == NULL)
2366 		goto out_off;
2367 
2368 	if (bpf_prog_uses_arena_insns(prog)) {
2369 		ctx.user_vm_start = bpf_arena_get_user_vm_start(prog->aux->arena);
2370 		ctx.arena_vm_start = bpf_arena_get_kern_vm_start(prog->aux->arena);
2371 	}
2372 
2373 	out_cnt = bpf_out_stack_arg_cnt(env, prog);
2374 	if (out_cnt) {
2375 		int nr_on_stack = out_cnt - NR_STACK_ARG_REGS;
2376 
2377 		if (nr_on_stack > 0)
2378 			ctx.stack_arg_size = round_up(nr_on_stack * sizeof(u64), 16);
2379 	}
2380 
2381 	if (priv_stack_ptr)
2382 		ctx.priv_sp_used = true;
2383 
2384 	/* Pass 1: Estimate the maximum image size.
2385 	 *
2386 	 * BPF line info needs ctx->offset[i] to be the offset of
2387 	 * instruction[i] in jited image, so build prologue first.
2388 	 */
2389 	if (build_prologue(&ctx, was_classic))
2390 		goto out_off;
2391 
2392 	if (build_body(env, &ctx, extra_pass))
2393 		goto out_off;
2394 
2395 	ctx.epilogue_offset = ctx.idx;
2396 	build_epilogue(&ctx, was_classic, false);
2397 	build_plt(&ctx);
2398 
2399 	extable_align = __alignof__(struct exception_table_entry);
2400 	extable_size = prog->aux->num_exentries *
2401 		sizeof(struct exception_table_entry);
2402 
2403 	/* Now we know the maximum image size. */
2404 	prog_size = sizeof(u32) * ctx.idx;
2405 	/* also allocate space for plt target */
2406 	extable_offset = round_up(prog_size + PLT_TARGET_SIZE, extable_align);
2407 	image_size = extable_offset + extable_size;
2408 	ro_header = bpf_jit_binary_pack_alloc(image_size, &ro_image_ptr,
2409 					      sizeof(u64), &header, &image_ptr,
2410 					      jit_fill_hole, was_classic);
2411 	if (!ro_header)
2412 		goto out_off;
2413 
2414 	/* Pass 2: Determine jited position and result for each instruction */
2415 
2416 	/*
2417 	 * Use the image(RW) for writing the JITed instructions. But also save
2418 	 * the ro_image(RX) for calculating the offsets in the image. The RW
2419 	 * image will be later copied to the RX image from where the program
2420 	 * will run. The bpf_jit_binary_pack_finalize() will do this copy in the
2421 	 * final step.
2422 	 */
2423 	ctx.image = (__le32 *)image_ptr;
2424 	ctx.ro_image = (__le32 *)ro_image_ptr;
2425 	if (extable_size)
2426 		prog->aux->extable = (void *)ro_image_ptr + extable_offset;
2427 skip_init_ctx:
2428 	ctx.idx = 0;
2429 	ctx.exentry_idx = 0;
2430 	ctx.write = true;
2431 
2432 	build_prologue(&ctx, was_classic);
2433 
2434 	/* Record exentry_idx and body_idx before first build_body */
2435 	exentry_idx = ctx.exentry_idx;
2436 	body_idx = ctx.idx;
2437 	/* Dont write body instructions to memory for now */
2438 	ctx.write = false;
2439 
2440 	if (build_body(env, &ctx, extra_pass))
2441 		goto out_free_hdr;
2442 
2443 	ctx.epilogue_offset = ctx.idx;
2444 	ctx.exentry_idx = exentry_idx;
2445 	ctx.idx = body_idx;
2446 	ctx.write = true;
2447 
2448 	/* Pass 3: Adjust jump offset and write final image */
2449 	if (build_body(env, &ctx, extra_pass) ||
2450 		WARN_ON_ONCE(ctx.idx != ctx.epilogue_offset))
2451 		goto out_free_hdr;
2452 
2453 	build_epilogue(&ctx, was_classic, false);
2454 	build_plt(&ctx);
2455 
2456 	/* Extra pass to validate JITed code. */
2457 	if (validate_ctx(&ctx))
2458 		goto out_free_hdr;
2459 
2460 	/* update the real prog size */
2461 	prog_size = sizeof(u32) * ctx.idx;
2462 
2463 	/* And we're done. */
2464 	if (bpf_jit_enable > 1)
2465 		bpf_jit_dump(prog->len, prog_size, 2, ctx.image);
2466 
2467 	if (!prog->is_func || extra_pass) {
2468 		/* The jited image may shrink since the jited result for
2469 		 * BPF_CALL to subprog may be changed from indirect call
2470 		 * to direct call.
2471 		 */
2472 		if (extra_pass && ctx.idx > jit_data->ctx.idx) {
2473 			pr_err_once("multi-func JIT bug %d > %d\n",
2474 				    ctx.idx, jit_data->ctx.idx);
2475 			goto out_free_hdr;
2476 		}
2477 		if (WARN_ON(bpf_jit_binary_pack_finalize(ro_header, header))) {
2478 			/* ro_header and header has been freed */
2479 			ro_header = NULL;
2480 			header = NULL;
2481 			goto out_free_hdr;
2482 		}
2483 	} else {
2484 		jit_data->ctx = ctx;
2485 		jit_data->ro_image = ro_image_ptr;
2486 		jit_data->header = header;
2487 		jit_data->ro_header = ro_header;
2488 	}
2489 
2490 	prog->bpf_func = (void *)ctx.ro_image + cfi_get_offset();
2491 	prog->jited = 1;
2492 	prog->jited_len = prog_size - cfi_get_offset();
2493 
2494 	if (!prog->is_func || extra_pass) {
2495 		int i;
2496 
2497 		/* offset[prog->len] is the size of program */
2498 		for (i = 0; i <= prog->len; i++)
2499 			ctx.offset[i] *= AARCH64_INSN_SIZE;
2500 		bpf_prog_fill_jited_linfo(prog, ctx.offset + 1);
2501 		/*
2502 		 * The bpf_prog_update_insn_ptrs function expects offsets to
2503 		 * point to the first byte of the jitted instruction (unlike
2504 		 * the bpf_prog_fill_jited_linfo above, which, for historical
2505 		 * reasons, expects to point to the next instruction)
2506 		 */
2507 		bpf_prog_update_insn_ptrs(prog, ctx.offset, ctx.ro_image);
2508 out_off:
2509 		if (!ro_header && priv_stack_ptr) {
2510 			free_percpu(priv_stack_ptr);
2511 			prog->aux->priv_stack_ptr = NULL;
2512 		}
2513 		kvfree(ctx.offset);
2514 out_priv_stack:
2515 		kfree(jit_data);
2516 		prog->aux->jit_data = NULL;
2517 	}
2518 
2519 	return prog;
2520 
2521 out_free_hdr:
2522 	if (extra_pass) {
2523 		prog->bpf_func = NULL;
2524 		prog->jited = 0;
2525 		prog->jited_len = 0;
2526 	}
2527 	if (header) {
2528 		bpf_arch_text_copy(&ro_header->size, &header->size,
2529 				   sizeof(header->size));
2530 		bpf_jit_binary_pack_free(ro_header, header);
2531 	}
2532 	goto out_off;
2533 }
2534 
2535 bool bpf_jit_supports_private_stack(void)
2536 {
2537 	return true;
2538 }
2539 
2540 bool bpf_jit_supports_kfunc_call(void)
2541 {
2542 	return true;
2543 }
2544 
2545 bool bpf_jit_supports_kfunc_ret_reg_pair(void)
2546 {
2547 	return true;
2548 }
2549 
2550 bool bpf_jit_supports_unwind(void)
2551 {
2552 	return true;
2553 }
2554 
2555 const struct bpf_jit_arg_abi *bpf_jit_arg_abi(void)
2556 {
2557 	return &arm64_arg_abi;
2558 }
2559 
2560 bool bpf_jit_supports_stack_args(void)
2561 {
2562 	return true;
2563 }
2564 
2565 bool bpf_jit_supports_arena_args(void)
2566 {
2567 	return true;
2568 }
2569 
2570 void *bpf_arch_text_copy(void *dst, void *src, size_t len)
2571 {
2572 	if (!aarch64_insn_copy(dst, src, len))
2573 		return ERR_PTR(-EINVAL);
2574 	return dst;
2575 }
2576 
2577 u64 bpf_jit_alloc_exec_limit(void)
2578 {
2579 	return VMALLOC_END - VMALLOC_START;
2580 }
2581 
2582 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
2583 bool bpf_jit_supports_subprog_tailcalls(void)
2584 {
2585 	return true;
2586 }
2587 
2588 bool bpf_jit_supports_callx(void)
2589 {
2590 	return true;
2591 }
2592 
2593 bool bpf_jit_supports_large_stack(void)
2594 {
2595 	return true;
2596 }
2597 
2598 static void invoke_bpf_prog(struct jit_ctx *ctx, struct bpf_tramp_image *im,
2599 			    struct bpf_tramp_node *node, int bargs_off,
2600 			    int retval_off, int run_ctx_off, bool save_ret)
2601 {
2602 	void *skip;
2603 	__le32 *branch;
2604 	u64 enter_prog;
2605 	u64 exit_prog;
2606 	struct bpf_prog *p = node->link->prog;
2607 	int cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
2608 
2609 	enter_prog = (u64)bpf_trampoline_enter(p);
2610 	exit_prog = (u64)bpf_trampoline_exit(p);
2611 
2612 	/* nop, patched to skip this prog when it is detached */
2613 	skip = ctx->ro_image + ctx->idx;
2614 	emit(A64_NOP, ctx);
2615 
2616 	if (node->cookie == 0) {
2617 		/* if cookie is zero, one instruction is enough to store it */
2618 		emit(A64_STR64I(A64_ZR, A64_SP, run_ctx_off + cookie_off), ctx);
2619 	} else {
2620 		emit_a64_mov_i64(A64_R(10), node->cookie, ctx);
2621 		emit(A64_STR64I(A64_R(10), A64_SP, run_ctx_off + cookie_off),
2622 		     ctx);
2623 	}
2624 
2625 	/* save p to callee saved register x19 to avoid loading p with mov_i64
2626 	 * each time.
2627 	 */
2628 	emit_addr_mov_i64(A64_R(19), (const u64)p, ctx);
2629 
2630 	/* arg1: prog */
2631 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
2632 	/* arg2: &run_ctx */
2633 	emit(A64_ADD_I(1, A64_R(1), A64_SP, run_ctx_off), ctx);
2634 
2635 	emit_call(enter_prog, ctx);
2636 
2637 	/* save return value to callee saved register x20 */
2638 	emit(A64_MOV(1, A64_R(20), A64_R(0)), ctx);
2639 
2640 	/* if (__bpf_prog_enter(prog) == 0)
2641 	 *         goto skip_exec_of_prog;
2642 	 */
2643 	branch = ctx->image + ctx->idx;
2644 	emit(A64_NOP, ctx);
2645 
2646 	emit(A64_ADD_I(1, A64_R(0), A64_SP, bargs_off), ctx);
2647 	if (!p->jited)
2648 		emit_addr_mov_i64(A64_R(1), (const u64)p->insnsi, ctx);
2649 
2650 	emit_call((const u64)p->bpf_func, ctx);
2651 
2652 	if (save_ret)
2653 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
2654 
2655 	if (ctx->image) {
2656 		int offset = &ctx->image[ctx->idx] - branch;
2657 		*branch = cpu_to_le32(A64_CBZ(1, A64_R(0), offset));
2658 	}
2659 
2660 	/* arg1: prog */
2661 	emit(A64_MOV(1, A64_R(0), A64_R(19)), ctx);
2662 	/* arg2: start time */
2663 	emit(A64_MOV(1, A64_R(1), A64_R(20)), ctx);
2664 	/* arg3: &run_ctx */
2665 	emit(A64_ADD_I(1, A64_R(2), A64_SP, run_ctx_off), ctx);
2666 
2667 	emit_call(exit_prog, ctx);
2668 
2669 	bpf_tramp_image_add_skip(im, p, skip, ctx->ro_image + ctx->idx);
2670 }
2671 
2672 static void invoke_bpf_mod_ret(struct jit_ctx *ctx, struct bpf_tramp_image *im,
2673 			       struct bpf_tramp_nodes *tn, int bargs_off,
2674 			       int retval_off, int run_ctx_off, __le32 **branches)
2675 {
2676 	int i;
2677 
2678 	/* The first fmod_ret program will receive a garbage return value.
2679 	 * Set this to 0 to avoid confusing the program.
2680 	 */
2681 	emit(A64_STR64I(A64_ZR, A64_SP, retval_off), ctx);
2682 	for (i = 0; i < tn->nr_nodes; i++) {
2683 		invoke_bpf_prog(ctx, im, tn->nodes[i], bargs_off, retval_off,
2684 				run_ctx_off, true);
2685 		/* if (*(u64 *)(sp + retval_off) !=  0)
2686 		 *	goto do_fexit;
2687 		 */
2688 		emit(A64_LDR64I(A64_R(10), A64_SP, retval_off), ctx);
2689 		/* Save the location of branch, and generate a nop.
2690 		 * This nop will be replaced with a cbnz later.
2691 		 */
2692 		branches[i] = ctx->image + ctx->idx;
2693 		emit(A64_NOP, ctx);
2694 	}
2695 }
2696 
2697 struct arg_aux {
2698 	/* how many args are passed through registers, the rest of the args are
2699 	 * passed through stack
2700 	 */
2701 	int args_in_regs;
2702 	/* how many registers are used to pass arguments */
2703 	int regs_for_args;
2704 	/* how much stack is used for additional args passed to bpf program
2705 	 * that did not fit in original function registers
2706 	 */
2707 	int bstack_for_args;
2708 	/* home much stack is used for additional args passed to the
2709 	 * original function when called from trampoline (this one needs
2710 	 * arguments to be properly aligned)
2711 	 */
2712 	int ostack_for_args;
2713 	/* where AAPCS64 puts each argument slot: an argument register below
2714 	 * the eighth, an on-stack argument slot from it up
2715 	 */
2716 	u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS];
2717 };
2718 
2719 static int calc_arg_aux(const struct btf_func_model *m,
2720 			 struct arg_aux *a)
2721 {
2722 	int slots, i, slot, total;
2723 
2724 	total = bpf_jit_place_args(&arm64_arg_abi, m, a->pos_of_slot);
2725 	if (total > MAX_BPF_FUNC_ARGS)
2726 		return -ENOTSUPP;
2727 
2728 	/* verifier ensures m->nr_args <= MAX_BPF_FUNC_ARGS */
2729 	for (i = 0, slot = 0; i < m->nr_args; i++) {
2730 		slots = (m->arg_size[i] + 7) / 8;
2731 		if (a64_arg_on_stack(a->pos_of_slot[slot])) /* passed through register ? */
2732 			break;
2733 		slot += slots;
2734 	}
2735 
2736 	a->args_in_regs = i;
2737 	a->regs_for_args = slot;
2738 	a->ostack_for_args = 0;
2739 	a->bstack_for_args = 0;
2740 
2741 	/* the rest arguments are passed through stack */
2742 	for (; i < m->nr_args; i++)
2743 		a->bstack_for_args += ((m->arg_size[i] + 7) / 8) * 8;
2744 
2745 	/* the outgoing area reaches the last slot, over any alignment hole */
2746 	if (a->bstack_for_args)
2747 		a->ostack_for_args = a64_arg_stack_off(a->pos_of_slot[total - 1]) + 8;
2748 
2749 	return 0;
2750 }
2751 
2752 static void clear_garbage(struct jit_ctx *ctx, int reg, int effective_bytes)
2753 {
2754 	if (effective_bytes) {
2755 		int garbage_bits = 64 - 8 * effective_bytes;
2756 		/* garbage bits are at the left end */
2757 		emit(A64_LSL(1, reg, reg, garbage_bits), ctx);
2758 		emit(A64_LSR(1, reg, reg, garbage_bits), ctx);
2759 	}
2760 }
2761 
2762 /*
2763  * Convert an arena kernel address into the arena pointer form on its way into
2764  * the BPF ctx, dst = (u32)(src - kern_vm_start), with @base_lo holding the low
2765  * 32 bits of kern_vm_start. A nullable arg preserves NULL, tested on the full
2766  * 64-bit kernel pointer. The 32-bit subtraction both truncates and clears the
2767  * upper half, so the stored value satisfies the JIT invariant for arena
2768  * pointer registers.
2769  */
2770 static void emit_arena_arg_conv(struct jit_ctx *ctx, u8 dst, u8 src, bool nullable, u8 base_lo)
2771 {
2772 	if (nullable) {
2773 		if (dst != src)
2774 			emit(A64_MOV(1, dst, src), ctx);
2775 		/* skip the subtraction so that NULL stays NULL */
2776 		emit(A64_CBZ(1, dst, 2), ctx);
2777 		src = dst;
2778 	}
2779 	emit(A64_SUB(0, dst, src, base_lo), ctx);
2780 }
2781 
2782 static void save_args(struct jit_ctx *ctx, int bargs_off, int oargs_off,
2783 		      const struct btf_func_model *m, const struct arg_aux *a,
2784 		      bool for_call_origin, bool is_struct_ops, u64 arena_base)
2785 {
2786 	u8 tmp = bpf2a64[TMP_REG_1];
2787 	u8 base_lo = bpf2a64[TMP_REG_2];
2788 	int i, reg, slot, soff, slots;
2789 
2790 	/* only the low 32 bits of the base take part in the subtraction */
2791 	if (arena_base)
2792 		emit_a64_mov_i(0, base_lo, (s32)(u32)arena_base, ctx);
2793 
2794 	/* store arguments to the stack for the bpf program, or restore
2795 	 * arguments from stack for the original function
2796 	 */
2797 	for (i = 0, slot = 0; i < a->args_in_regs; i++) {
2798 		bool arena_arg = arena_base && (m->arg_flags[i] & BTF_FMODEL_ARENA_ARG);
2799 		bool nullable = m->arg_flags[i] & BTF_FMODEL_NULLABLE_ARG;
2800 
2801 		slots = (m->arg_size[i] + 7) / 8;
2802 		while (slots-- > 0) {
2803 			reg = a->pos_of_slot[slot++];
2804 			if (for_call_origin) {
2805 				emit(A64_LDR64I(reg, A64_SP, bargs_off), ctx);
2806 			} else if (arena_arg) {
2807 				emit_arena_arg_conv(ctx, tmp, reg, nullable, base_lo);
2808 				emit(A64_STR64I(tmp, A64_SP, bargs_off), ctx);
2809 			} else {
2810 				emit(A64_STR64I(reg, A64_SP, bargs_off), ctx);
2811 			}
2812 			bargs_off += 8;
2813 		}
2814 	}
2815 
2816 	/*
2817 	 * On-stack arguments start above the frame(s) pushed by the trampoline
2818 	 * prologue. Entered through the fentry call from a traced function, the
2819 	 * prologue saves both the parent (FP/x9) and the traced function
2820 	 * (FP/LR) frames, so the arguments start at FP + 32. A struct_ops
2821 	 * callback is called indirectly and only the FP/LR frame is saved, so
2822 	 * they start at FP + 16.
2823 	 *
2824 	 * The outgoing area mirrors the incoming one, hole and all; only the
2825 	 * bpf program takes the arguments packed.
2826 	 */
2827 	soff = is_struct_ops ? 16 : 32;
2828 
2829 	/* save on stack arguments */
2830 	for (i = a->args_in_regs; i < m->nr_args; i++) {
2831 		bool arena_arg = arena_base && (m->arg_flags[i] & BTF_FMODEL_ARENA_ARG);
2832 		bool nullable = m->arg_flags[i] & BTF_FMODEL_NULLABLE_ARG;
2833 
2834 		slots = (m->arg_size[i] + 7) / 8;
2835 		/* verifier ensures arg_size <= 16, so slots equals 1 or 2 */
2836 		while (slots-- > 0) {
2837 			int off = a64_arg_stack_off(a->pos_of_slot[slot++]);
2838 
2839 			emit(A64_LDR64I(tmp, A64_FP, soff + off), ctx);
2840 			/* if there is unused space in the last slot, clear
2841 			 * the garbage contained in the space.
2842 			 */
2843 			if (slots == 0 && !for_call_origin)
2844 				clear_garbage(ctx, tmp, m->arg_size[i] % 8);
2845 			/*
2846 			 * No guard on for_call_origin here: only the indirect
2847 			 * trampoline is given a base, and it never calls the
2848 			 * original function, so arguments are never converted
2849 			 * on their way back out to it. See the WARN_ON_ONCE()
2850 			 * in prepare_trampoline().
2851 			 */
2852 			if (arena_arg)
2853 				emit_arena_arg_conv(ctx, tmp, tmp, nullable, base_lo);
2854 			if (for_call_origin)
2855 				emit(A64_STR64I(tmp, A64_SP, oargs_off + off), ctx);
2856 			else
2857 				emit(A64_STR64I(tmp, A64_SP, bargs_off), ctx);
2858 			bargs_off += 8;
2859 		}
2860 	}
2861 }
2862 
2863 static void restore_args(struct jit_ctx *ctx, int bargs_off, const struct arg_aux *a)
2864 {
2865 	int slot;
2866 
2867 	for (slot = 0; slot < a->regs_for_args; slot++) {
2868 		emit(A64_LDR64I(a->pos_of_slot[slot], A64_SP, bargs_off), ctx);
2869 		bargs_off += 8;
2870 	}
2871 }
2872 
2873 static void store_func_meta(struct jit_ctx *ctx, u64 func_meta, int func_meta_off)
2874 {
2875 	emit_a64_mov_i64(A64_R(10), func_meta, ctx);
2876 	emit(A64_STR64I(A64_R(10), A64_SP, func_meta_off), ctx);
2877 }
2878 
2879 /* Based on the x86's implementation of arch_prepare_bpf_trampoline().
2880  *
2881  * bpf prog and function entry before bpf trampoline hooked:
2882  *   mov x9, lr
2883  *   nop
2884  *
2885  * bpf prog and function entry after bpf trampoline hooked:
2886  *   mov x9, lr
2887  *   bl  <bpf_trampoline or plt>
2888  *
2889  */
2890 static int prepare_trampoline(struct jit_ctx *ctx, struct bpf_tramp_image *im,
2891 			      struct bpf_tramp_nodes *tnodes, void *func_addr,
2892 			      const struct btf_func_model *m,
2893 			      const struct arg_aux *a,
2894 			      u32 flags)
2895 {
2896 	int i;
2897 	int stack_size;
2898 	int retaddr_off;
2899 	int regs_off;
2900 	int retval_off;
2901 	int bargs_off;
2902 	int func_meta_off;
2903 	int ip_off;
2904 	int run_ctx_off;
2905 	int oargs_off;
2906 	int nfuncargs;
2907 	struct bpf_tramp_nodes *fentry = &tnodes[BPF_TRAMP_FENTRY];
2908 	struct bpf_tramp_nodes *fexit = &tnodes[BPF_TRAMP_FEXIT];
2909 	struct bpf_tramp_nodes *fmod_ret = &tnodes[BPF_TRAMP_MODIFY_RETURN];
2910 	bool save_ret;
2911 	__le32 **branches = NULL;
2912 	bool is_struct_ops = is_struct_ops_tramp(fentry);
2913 	int cookie_off, cookie_cnt, cookie_bargs_off;
2914 	int fsession_cnt = bpf_fsession_cnt(tnodes);
2915 	u64 arena_base;
2916 	u64 func_meta;
2917 
2918 	/*
2919 	 * F_INDIRECT is only compatible with F_RET_FENTRY_RET, it is explicitly
2920 	 * incompatible with F_CALL_ORIG | F_SKIP_FRAME | F_IP_ARG because
2921 	 * @func_addr. Arena conversion relies on this: bpf_tramp_arena_base()
2922 	 * only returns a base for the indirect trampoline, which therefore
2923 	 * never calls the original function with converted arguments.
2924 	 */
2925 	WARN_ON_ONCE((flags & BPF_TRAMP_F_INDIRECT) &&
2926 		     (flags & ~(BPF_TRAMP_F_INDIRECT | BPF_TRAMP_F_RET_FENTRY_RET)));
2927 
2928 	arena_base = bpf_tramp_arena_base(m, tnodes, flags);
2929 
2930 	/* trampoline stack layout:
2931 	 *                    [ parent ip         ]
2932 	 *                    [ FP                ]
2933 	 * SP + retaddr_off   [ self ip           ]
2934 	 *                    [ FP                ]
2935 	 *
2936 	 *                    [ padding           ] align SP to multiples of 16
2937 	 *
2938 	 *                    [ x20               ] callee saved reg x20
2939 	 * SP + regs_off      [ x19               ] callee saved reg x19
2940 	 *
2941 	 * SP + retval_off    [ return value      ] BPF_TRAMP_F_CALL_ORIG or
2942 	 *                                          BPF_TRAMP_F_RET_FENTRY_RET
2943 	 *                    [ arg reg N         ]
2944 	 *                    [ ...               ]
2945 	 * SP + bargs_off     [ arg reg 1         ] for bpf
2946 	 *
2947 	 * SP + func_meta_off [ regs count, etc   ]
2948 	 *
2949 	 * SP + ip_off        [ traced function   ] BPF_TRAMP_F_IP_ARG flag
2950 	 *
2951 	 *                    [ stack cookie N    ]
2952 	 *                    [ ...               ]
2953 	 * SP + cookie_off    [ stack cookie 1    ]
2954 	 *
2955 	 * SP + run_ctx_off   [ bpf_tramp_run_ctx ]
2956 	 *
2957 	 *                    [ stack arg N       ]
2958 	 *                    [ ...               ]
2959 	 * SP + oargs_off     [ stack arg 1       ] for original func
2960 	 */
2961 
2962 	stack_size = 0;
2963 	oargs_off = stack_size;
2964 	if (flags & BPF_TRAMP_F_CALL_ORIG)
2965 		stack_size +=  a->ostack_for_args;
2966 
2967 	run_ctx_off = stack_size;
2968 	/* room for bpf_tramp_run_ctx */
2969 	stack_size += round_up(sizeof(struct bpf_tramp_run_ctx), 8);
2970 
2971 	cookie_off = stack_size;
2972 	/* room for session cookies */
2973 	cookie_cnt = bpf_fsession_cookie_cnt(tnodes);
2974 	stack_size += cookie_cnt * 8;
2975 
2976 	ip_off = stack_size;
2977 	/* room for IP address argument */
2978 	if (flags & BPF_TRAMP_F_IP_ARG)
2979 		stack_size += 8;
2980 
2981 	func_meta_off = stack_size;
2982 	/* room for function metadata, such as regs count */
2983 	stack_size += 8;
2984 
2985 	bargs_off = stack_size;
2986 	/* room for args */
2987 	nfuncargs = a->regs_for_args + a->bstack_for_args / 8;
2988 	stack_size += 8 * nfuncargs;
2989 
2990 	/* room for return value */
2991 	retval_off = stack_size;
2992 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
2993 	if (save_ret)
2994 		stack_size += 8;
2995 
2996 	/* room for callee saved registers, currently x19 and x20 are used */
2997 	regs_off = stack_size;
2998 	stack_size += 16;
2999 
3000 	/* round up to multiples of 16 to avoid SPAlignmentFault */
3001 	stack_size = round_up(stack_size, 16);
3002 
3003 	/* return address locates above FP */
3004 	retaddr_off = stack_size + 8;
3005 
3006 	if (flags & BPF_TRAMP_F_INDIRECT) {
3007 		/*
3008 		 * Indirect call for bpf_struct_ops
3009 		 */
3010 		emit_kcfi(cfi_get_func_hash(func_addr), ctx);
3011 	}
3012 	/* bpf trampoline may be invoked by 3 instruction types:
3013 	 * 1. bl, attached to bpf prog or kernel function via short jump
3014 	 * 2. br, attached to bpf prog or kernel function via long jump
3015 	 * 3. blr, working as a function pointer, used by struct_ops.
3016 	 * So BTI_JC should used here to support both br and blr.
3017 	 */
3018 	emit_bti(A64_BTI_JC, ctx);
3019 
3020 	/* x9 is not set for struct_ops */
3021 	if (!is_struct_ops) {
3022 		/* frame for parent function */
3023 		emit(A64_PUSH(A64_FP, A64_R(9), A64_SP), ctx);
3024 		emit(A64_MOV(1, A64_FP, A64_SP), ctx);
3025 	}
3026 
3027 	/* frame for patched function for tracing, or caller for struct_ops */
3028 	emit(A64_PUSH(A64_FP, A64_LR, A64_SP), ctx);
3029 	emit(A64_MOV(1, A64_FP, A64_SP), ctx);
3030 
3031 	/* allocate stack space */
3032 	emit(A64_SUB_I(1, A64_SP, A64_SP, stack_size), ctx);
3033 
3034 	if (flags & BPF_TRAMP_F_IP_ARG) {
3035 		/* save ip address of the traced function */
3036 		emit_addr_mov_i64(A64_R(10), (const u64)func_addr, ctx);
3037 		emit(A64_STR64I(A64_R(10), A64_SP, ip_off), ctx);
3038 	}
3039 
3040 	/* save function metadata */
3041 	func_meta = nfuncargs;
3042 	store_func_meta(ctx, func_meta, func_meta_off);
3043 
3044 	/* save args for bpf */
3045 	save_args(ctx, bargs_off, oargs_off, m, a, false, is_struct_ops, arena_base);
3046 
3047 	/* save callee saved registers */
3048 	emit(A64_STR64I(A64_R(19), A64_SP, regs_off), ctx);
3049 	emit(A64_STR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
3050 
3051 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3052 		/* for the first pass, assume the worst case */
3053 		if (!ctx->image)
3054 			ctx->idx += 4;
3055 		else
3056 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
3057 		emit_call((const u64)__bpf_tramp_enter, ctx);
3058 	}
3059 
3060 	if (fsession_cnt) {
3061 		/* clear all the session cookies' value */
3062 		emit(A64_MOVZ(1, A64_R(10), 0, 0), ctx);
3063 		for (int i = 0; i < cookie_cnt; i++)
3064 			emit(A64_STR64I(A64_R(10), A64_SP, cookie_off + 8 * i), ctx);
3065 		/* clear the return value to make sure fentry always gets 0 */
3066 		emit(A64_STR64I(A64_R(10), A64_SP, retval_off), ctx);
3067 	}
3068 
3069 	cookie_bargs_off = (bargs_off - cookie_off) / 8;
3070 	for (i = 0; i < fentry->nr_nodes; i++) {
3071 		if (bpf_prog_calls_session_cookie(fentry->nodes[i])) {
3072 			u64 meta = func_meta | (cookie_bargs_off << BPF_TRAMP_COOKIE_INDEX_SHIFT);
3073 
3074 			store_func_meta(ctx, meta, func_meta_off);
3075 			cookie_bargs_off--;
3076 		}
3077 		invoke_bpf_prog(ctx, im, fentry->nodes[i], bargs_off,
3078 				retval_off, run_ctx_off,
3079 				flags & BPF_TRAMP_F_RET_FENTRY_RET);
3080 	}
3081 
3082 	if (fmod_ret->nr_nodes) {
3083 		branches = kcalloc(fmod_ret->nr_nodes, sizeof(__le32 *),
3084 				   GFP_KERNEL);
3085 		if (!branches)
3086 			return -ENOMEM;
3087 
3088 		invoke_bpf_mod_ret(ctx, im, fmod_ret, bargs_off, retval_off,
3089 				   run_ctx_off, branches);
3090 	}
3091 
3092 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3093 		/* the original func takes kernel addresses, never converted ones */
3094 		save_args(ctx, bargs_off, oargs_off, m, a, true, is_struct_ops, 0);
3095 		/* call original func */
3096 		emit(A64_LDR64I(A64_R(10), A64_SP, retaddr_off), ctx);
3097 		emit(A64_ADR(A64_LR, AARCH64_INSN_SIZE * 2), ctx);
3098 		emit(A64_RET(A64_R(10)), ctx);
3099 		/* store return value */
3100 		emit(A64_STR64I(A64_R(0), A64_SP, retval_off), ctx);
3101 	}
3102 
3103 	/* update the branches saved in invoke_bpf_mod_ret with cbnz */
3104 	for (i = 0; i < fmod_ret->nr_nodes && ctx->image != NULL; i++) {
3105 		int offset = &ctx->image[ctx->idx] - branches[i];
3106 		*branches[i] = cpu_to_le32(A64_CBNZ(1, A64_R(10), offset));
3107 	}
3108 
3109 	/* set the "is_return" flag for fsession */
3110 	func_meta |= (1ULL << BPF_TRAMP_IS_RETURN_SHIFT);
3111 	if (fsession_cnt)
3112 		store_func_meta(ctx, func_meta, func_meta_off);
3113 
3114 	cookie_bargs_off = (bargs_off - cookie_off) / 8;
3115 	for (i = 0; i < fexit->nr_nodes; i++) {
3116 		if (bpf_prog_calls_session_cookie(fexit->nodes[i])) {
3117 			u64 meta = func_meta | (cookie_bargs_off << BPF_TRAMP_COOKIE_INDEX_SHIFT);
3118 
3119 			store_func_meta(ctx, meta, func_meta_off);
3120 			cookie_bargs_off--;
3121 		}
3122 		invoke_bpf_prog(ctx, im, fexit->nodes[i], bargs_off, retval_off,
3123 				run_ctx_off, false);
3124 	}
3125 
3126 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3127 		/* for the first pass, assume the worst case */
3128 		if (!ctx->image)
3129 			ctx->idx += 4;
3130 		else
3131 			emit_a64_mov_i64(A64_R(0), (const u64)im, ctx);
3132 		emit_call((const u64)__bpf_tramp_exit, ctx);
3133 	}
3134 
3135 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
3136 		restore_args(ctx, bargs_off, a);
3137 
3138 	/* restore callee saved register x19 and x20 */
3139 	emit(A64_LDR64I(A64_R(19), A64_SP, regs_off), ctx);
3140 	emit(A64_LDR64I(A64_R(20), A64_SP, regs_off + 8), ctx);
3141 
3142 	if (save_ret)
3143 		emit(A64_LDR64I(A64_R(0), A64_SP, retval_off), ctx);
3144 
3145 	/* reset SP  */
3146 	emit(A64_MOV(1, A64_SP, A64_FP), ctx);
3147 
3148 	if (is_struct_ops) {
3149 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
3150 		emit(A64_RET(A64_LR), ctx);
3151 	} else {
3152 		/* pop frames */
3153 		emit(A64_POP(A64_FP, A64_LR, A64_SP), ctx);
3154 		emit(A64_POP(A64_FP, A64_R(9), A64_SP), ctx);
3155 
3156 		if (flags & BPF_TRAMP_F_SKIP_FRAME) {
3157 			/* skip patched function, return to parent */
3158 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
3159 			emit(A64_RET(A64_R(9)), ctx);
3160 		} else {
3161 			/* return to patched function */
3162 			emit(A64_MOV(1, A64_R(10), A64_LR), ctx);
3163 			emit(A64_MOV(1, A64_LR, A64_R(9)), ctx);
3164 			emit(A64_RET(A64_R(10)), ctx);
3165 		}
3166 	}
3167 
3168 	kfree(branches);
3169 
3170 	return ctx->idx;
3171 }
3172 
3173 bool bpf_jit_supports_fsession(void)
3174 {
3175 	return true;
3176 }
3177 
3178 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
3179 			     struct bpf_tramp_nodes *tnodes, void *func_addr)
3180 {
3181 	struct jit_ctx ctx = {
3182 		.image = NULL,
3183 		.idx = 0,
3184 	};
3185 	struct bpf_tramp_image im = {};
3186 	struct arg_aux aaux;
3187 	int ret;
3188 
3189 	ret = calc_arg_aux(m, &aaux);
3190 	if (ret < 0)
3191 		return ret;
3192 
3193 	ret = prepare_trampoline(&ctx, &im, tnodes, func_addr, m, &aaux, flags);
3194 	if (ret < 0)
3195 		return ret;
3196 
3197 	return ret < 0 ? ret : ret * AARCH64_INSN_SIZE;
3198 }
3199 
3200 void *arch_alloc_bpf_trampoline(unsigned int size)
3201 {
3202 	return bpf_prog_pack_alloc(size, jit_fill_hole, false);
3203 }
3204 
3205 void arch_free_bpf_trampoline(void *image, unsigned int size)
3206 {
3207 	bpf_prog_pack_free(image, size);
3208 }
3209 
3210 int arch_protect_bpf_trampoline(void *image, unsigned int size)
3211 {
3212 	return 0;
3213 }
3214 
3215 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *ro_image,
3216 				void *ro_image_end, const struct btf_func_model *m,
3217 				u32 flags, struct bpf_tramp_nodes *tnodes,
3218 				void *func_addr)
3219 {
3220 	u32 size = ro_image_end - ro_image;
3221 	struct arg_aux aaux;
3222 	void *image, *tmp;
3223 	int ret;
3224 
3225 	/* image doesn't need to be in module memory range, so we can
3226 	 * use kvmalloc.
3227 	 */
3228 	image = kvmalloc(size, GFP_KERNEL);
3229 	if (!image)
3230 		return -ENOMEM;
3231 
3232 	struct jit_ctx ctx = {
3233 		.image = image,
3234 		.ro_image = ro_image,
3235 		.idx = 0,
3236 		.write = true,
3237 	};
3238 
3239 
3240 	jit_fill_hole(image, (unsigned int)(ro_image_end - ro_image));
3241 	ret = calc_arg_aux(m, &aaux);
3242 	if (ret)
3243 		goto out;
3244 	ret = prepare_trampoline(&ctx, im, tnodes, func_addr, m, &aaux, flags);
3245 
3246 	if (ret > 0 && validate_code(&ctx) < 0) {
3247 		ret = -EINVAL;
3248 		goto out;
3249 	}
3250 
3251 	if (ret > 0)
3252 		ret *= AARCH64_INSN_SIZE;
3253 
3254 	tmp = bpf_arch_text_copy(ro_image, image, size);
3255 	if (IS_ERR(tmp)) {
3256 		ret = PTR_ERR(tmp);
3257 		goto out;
3258 	}
3259 
3260 out:
3261 	kvfree(image);
3262 	return ret;
3263 }
3264 
3265 static bool is_long_jump(void *ip, void *target)
3266 {
3267 	long offset;
3268 
3269 	/* NULL target means this is a NOP */
3270 	if (!target)
3271 		return false;
3272 
3273 	offset = (long)target - (long)ip;
3274 	return offset < -SZ_128M || offset >= SZ_128M;
3275 }
3276 
3277 static int gen_branch_or_nop(enum aarch64_insn_branch_type type, void *ip,
3278 			     void *addr, void *plt, u32 *insn)
3279 {
3280 	void *target;
3281 
3282 	if (!addr) {
3283 		*insn = aarch64_insn_gen_nop();
3284 		return 0;
3285 	}
3286 
3287 	if (is_long_jump(ip, addr))
3288 		target = plt;
3289 	else
3290 		target = addr;
3291 
3292 	*insn = aarch64_insn_gen_branch_imm((unsigned long)ip,
3293 					    (unsigned long)target,
3294 					    type);
3295 
3296 	return *insn != AARCH64_BREAK_FAULT ? 0 : -EFAULT;
3297 }
3298 
3299 /* Replace the branch instruction from @ip to @old_addr in a bpf prog or a bpf
3300  * trampoline with the branch instruction from @ip to @new_addr. If @old_addr
3301  * or @new_addr is NULL, the old or new instruction is NOP.
3302  *
3303  * When @ip is the bpf prog entry, a bpf trampoline is being attached or
3304  * detached. Since bpf trampoline and bpf prog are allocated separately with
3305  * vmalloc, the address distance may exceed 128MB, the maximum branch range.
3306  * So long jump should be handled.
3307  *
3308  * When a bpf prog is constructed, a plt pointing to empty trampoline
3309  * dummy_tramp is placed at the end:
3310  *
3311  *      bpf_prog:
3312  *              mov x9, lr
3313  *              nop // patchsite
3314  *              ...
3315  *              ret
3316  *
3317  *      plt:
3318  *              ldr x10, target
3319  *              br x10
3320  *      target:
3321  *              .quad dummy_tramp // plt target
3322  *
3323  * This is also the state when no trampoline is attached.
3324  *
3325  * When a short-jump bpf trampoline is attached, the patchsite is patched
3326  * to a bl instruction to the trampoline directly:
3327  *
3328  *      bpf_prog:
3329  *              mov x9, lr
3330  *              bl <short-jump bpf trampoline address> // patchsite
3331  *              ...
3332  *              ret
3333  *
3334  *      plt:
3335  *              ldr x10, target
3336  *              br x10
3337  *      target:
3338  *              .quad dummy_tramp // plt target
3339  *
3340  * When a long-jump bpf trampoline is attached, the plt target is filled with
3341  * the trampoline address and the patchsite is patched to a bl instruction to
3342  * the plt:
3343  *
3344  *      bpf_prog:
3345  *              mov x9, lr
3346  *              bl plt // patchsite
3347  *              ...
3348  *              ret
3349  *
3350  *      plt:
3351  *              ldr x10, target
3352  *              br x10
3353  *      target:
3354  *              .quad <long-jump bpf trampoline address> // plt target
3355  *
3356  * The dummy_tramp is used to prevent another CPU from jumping to unknown
3357  * locations during the patching process, making the patching process easier.
3358  */
3359 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t,
3360 		       enum bpf_text_poke_type new_t, void *old_addr,
3361 		       void *new_addr)
3362 {
3363 	int ret;
3364 	u32 old_insn;
3365 	u32 new_insn;
3366 	u32 replaced;
3367 	struct bpf_plt *plt = NULL;
3368 	unsigned long size = 0UL;
3369 	unsigned long offset = ~0UL;
3370 	enum aarch64_insn_branch_type branch_type;
3371 	char namebuf[KSYM_NAME_LEN];
3372 	void *image = NULL;
3373 	u64 plt_target = 0ULL;
3374 	bool poking_bpf_entry;
3375 
3376 	if (!bpf_address_lookup((unsigned long)ip, &size, &offset, namebuf))
3377 		/* Only poking bpf text is supported. Since kernel function
3378 		 * entry is set up by ftrace, we reply on ftrace to poke kernel
3379 		 * functions.
3380 		 */
3381 		return -ENOTSUPP;
3382 
3383 	image = ip - offset;
3384 	/* zero offset means we're poking bpf prog entry */
3385 	poking_bpf_entry = (offset == 0UL);
3386 
3387 	/* bpf prog entry, find plt and the real patchsite */
3388 	if (poking_bpf_entry) {
3389 		/* plt locates at the end of bpf prog */
3390 		plt = image + size - PLT_TARGET_OFFSET;
3391 
3392 		/* skip to the nop instruction in bpf prog entry:
3393 		 * bti c // if BTI enabled
3394 		 * mov x9, x30
3395 		 * nop
3396 		 */
3397 		ip = image + POKE_OFFSET * AARCH64_INSN_SIZE;
3398 	}
3399 
3400 	/* long jump is only possible at bpf prog entry */
3401 	if (WARN_ON((is_long_jump(ip, new_addr) || is_long_jump(ip, old_addr)) &&
3402 		    !poking_bpf_entry))
3403 		return -EINVAL;
3404 
3405 	branch_type = old_t == BPF_MOD_CALL ? AARCH64_INSN_BRANCH_LINK :
3406 					      AARCH64_INSN_BRANCH_NOLINK;
3407 	if (gen_branch_or_nop(branch_type, ip, old_addr, plt, &old_insn) < 0)
3408 		return -EFAULT;
3409 
3410 	branch_type = new_t == BPF_MOD_CALL ? AARCH64_INSN_BRANCH_LINK :
3411 					      AARCH64_INSN_BRANCH_NOLINK;
3412 	if (gen_branch_or_nop(branch_type, ip, new_addr, plt, &new_insn) < 0)
3413 		return -EFAULT;
3414 
3415 	if (is_long_jump(ip, new_addr))
3416 		plt_target = (u64)new_addr;
3417 	else if (is_long_jump(ip, old_addr))
3418 		/* if the old target is a long jump and the new target is not,
3419 		 * restore the plt target to dummy_tramp, so there is always a
3420 		 * legal and harmless address stored in plt target, and we'll
3421 		 * never jump from plt to an unknown place.
3422 		 */
3423 		plt_target = (u64)&dummy_tramp;
3424 
3425 	/*
3426 	 * non-zero plt_target indicates we're patching a bpf prog,
3427 	 * which is read only. The prog may share its page in the bpf
3428 	 * prog pack with other progs, so write the aligned target
3429 	 * through the text patching fixmap without flipping the
3430 	 * page permissions to avoid racing with concurrent pokers.
3431 	 *
3432 	 * since plt target points to either the new trampoline
3433 	 * or dummy_tramp, even if another CPU reads the old plt
3434 	 * target value before fetching the bl instruction to plt,
3435 	 * it will be brought back by dummy_tramp, so no barrier is
3436 	 * required here.
3437 	 */
3438 	if (plt_target &&
3439 	    aarch64_insn_write_literal_u64(&plt->target, plt_target))
3440 		return -EFAULT;
3441 
3442 	/* if the old target and the new target are both long jumps, no
3443 	 * patching is required
3444 	 */
3445 	if (old_insn == new_insn)
3446 		return 0;
3447 
3448 	mutex_lock(&text_mutex);
3449 	if (aarch64_insn_read(ip, &replaced)) {
3450 		ret = -EFAULT;
3451 		goto out;
3452 	}
3453 
3454 	if (replaced != old_insn) {
3455 		ret = -EFAULT;
3456 		goto out;
3457 	}
3458 
3459 	/* We call aarch64_insn_patch_text_nosync() to replace instruction
3460 	 * atomically, so no other CPUs will fetch a half-new and half-old
3461 	 * instruction. But there is chance that another CPU executes the
3462 	 * old instruction after the patching operation finishes (e.g.,
3463 	 * pipeline not flushed, or icache not synchronized yet).
3464 	 *
3465 	 * 1. when a new trampoline is attached, it is not a problem for
3466 	 *    different CPUs to jump to different trampolines temporarily.
3467 	 *
3468 	 * 2. when an old trampoline is freed, we should wait for all other
3469 	 *    CPUs to exit the trampoline and make sure the trampoline is no
3470 	 *    longer reachable, since bpf_tramp_image_put() function already
3471 	 *    uses percpu_ref and task-based rcu to do the sync, no need to call
3472 	 *    the sync version here, see bpf_tramp_image_put() for details.
3473 	 *
3474 	 * 3. when a detached prog is patched out of a trampoline, a CPU that
3475 	 *    still executes the old nop calls the prog before it went through
3476 	 *    a quiescent state, and the prog is freed after grace periods.
3477 	 */
3478 	ret = aarch64_insn_patch_text_nosync(ip, new_insn);
3479 out:
3480 	mutex_unlock(&text_mutex);
3481 
3482 	return ret;
3483 }
3484 
3485 bool bpf_jit_supports_ptr_xchg(void)
3486 {
3487 	return true;
3488 }
3489 
3490 bool bpf_jit_supports_exceptions(void)
3491 {
3492 	/* We unwind through both kernel frames starting from within bpf_throw
3493 	 * call and BPF frames. Therefore we require FP unwinder to be enabled
3494 	 * to walk kernel frames and reach BPF frames in the stack trace.
3495 	 * ARM64 kernel is always compiled with CONFIG_FRAME_POINTER=y
3496 	 */
3497 	return true;
3498 }
3499 
3500 bool bpf_jit_supports_arena(void)
3501 {
3502 	return true;
3503 }
3504 
3505 bool bpf_jit_supports_arena_scalar(void)
3506 {
3507 	return true;
3508 }
3509 
3510 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
3511 {
3512 	if (!in_arena)
3513 		return true;
3514 	switch (insn->code) {
3515 	case BPF_STX | BPF_ATOMIC | BPF_W:
3516 	case BPF_STX | BPF_ATOMIC | BPF_DW:
3517 		if (!bpf_atomic_is_load_store(insn) &&
3518 		    !cpus_have_cap(ARM64_HAS_LSE_ATOMICS))
3519 			return false;
3520 	}
3521 	return true;
3522 }
3523 
3524 bool bpf_jit_supports_percpu_insn(void)
3525 {
3526 	return true;
3527 }
3528 
3529 bool bpf_jit_bypass_spec_v4(void)
3530 {
3531 	/* In case of arm64, we rely on the firmware mitigation of Speculative
3532 	 * Store Bypass as controlled via the ssbd kernel parameter. Whenever
3533 	 * the mitigation is enabled, it works for all of the kernel code with
3534 	 * no need to provide any additional instructions. Therefore, skip
3535 	 * inserting nospec insns against Spectre v4.
3536 	 */
3537 	return true;
3538 }
3539 
3540 bool bpf_jit_supports_timed_may_goto(void)
3541 {
3542 	return true;
3543 }
3544 
3545 bool bpf_jit_inlines_helper_call(s32 imm)
3546 {
3547 	switch (imm) {
3548 	case BPF_FUNC_get_smp_processor_id:
3549 	case BPF_FUNC_get_current_task:
3550 	case BPF_FUNC_get_current_task_btf:
3551 		return true;
3552 	default:
3553 		return false;
3554 	}
3555 }
3556 
3557 void bpf_jit_free(struct bpf_prog *prog)
3558 {
3559 	if (prog->jited) {
3560 		struct arm64_jit_data *jit_data = prog->aux->jit_data;
3561 		struct bpf_binary_header *hdr;
3562 		void __percpu *priv_stack_ptr;
3563 		int priv_stack_alloc_sz;
3564 
3565 		/*
3566 		 * If we fail the final pass of JIT (from jit_subprogs),
3567 		 * the program may not be finalized yet. Call finalize here
3568 		 * before freeing it.
3569 		 */
3570 		if (jit_data) {
3571 			bpf_jit_binary_pack_finalize(jit_data->ro_header, jit_data->header);
3572 			kfree(jit_data);
3573 		}
3574 		prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset();
3575 		hdr = bpf_jit_binary_pack_hdr(prog);
3576 		bpf_jit_binary_pack_free(hdr, NULL);
3577 		priv_stack_ptr = prog->aux->priv_stack_ptr;
3578 		if (priv_stack_ptr) {
3579 			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 16) +
3580 					      2 * PRIV_STACK_GUARD_SZ;
3581 			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
3582 			free_percpu(prog->aux->priv_stack_ptr);
3583 		}
3584 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
3585 	}
3586 
3587 	bpf_prog_unlock_free(prog);
3588 }
3589