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