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