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