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