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