xref: /linux/arch/x86/net/bpf_jit_comp.c (revision 40863f4d6ef2c34bb00dd1070dfaf9d5f27a497e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * BPF JIT compiler
4  *
5  * Copyright (C) 2011-2013 Eric Dumazet (eric.dumazet@gmail.com)
6  * Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
7  */
8 #include <linux/netdevice.h>
9 #include <linux/filter.h>
10 #include <linux/if_vlan.h>
11 #include <linux/bitfield.h>
12 #include <linux/bpf.h>
13 #include <linux/memory.h>
14 #include <linux/sort.h>
15 #include <asm/extable.h>
16 #include <asm/ftrace.h>
17 #include <asm/set_memory.h>
18 #include <asm/nospec-branch.h>
19 #include <asm/text-patching.h>
20 #include <asm/unwind.h>
21 #include <asm/cfi.h>
22 
23 static bool all_callee_regs_used[4] = {true, true, true, true};
24 
25 static u8 *emit_code(u8 *ptr, u32 bytes, unsigned int len)
26 {
27 	if (len == 1)
28 		*ptr = bytes;
29 	else if (len == 2)
30 		*(u16 *)ptr = bytes;
31 	else {
32 		*(u32 *)ptr = bytes;
33 		barrier();
34 	}
35 	return ptr + len;
36 }
37 
38 #define EMIT(bytes, len) \
39 	do { prog = emit_code(prog, bytes, len); } while (0)
40 
41 #define EMIT1(b1)		EMIT(b1, 1)
42 #define EMIT2(b1, b2)		EMIT((b1) + ((b2) << 8), 2)
43 #define EMIT3(b1, b2, b3)	EMIT((b1) + ((b2) << 8) + ((b3) << 16), 3)
44 #define EMIT4(b1, b2, b3, b4)   EMIT((b1) + ((b2) << 8) + ((b3) << 16) + ((b4) << 24), 4)
45 #define EMIT5(b1, b2, b3, b4, b5) \
46 	do { EMIT1(b1); EMIT4(b2, b3, b4, b5); } while (0)
47 
48 #define EMIT1_off32(b1, off) \
49 	do { EMIT1(b1); EMIT(off, 4); } while (0)
50 #define EMIT2_off32(b1, b2, off) \
51 	do { EMIT2(b1, b2); EMIT(off, 4); } while (0)
52 #define EMIT3_off32(b1, b2, b3, off) \
53 	do { EMIT3(b1, b2, b3); EMIT(off, 4); } while (0)
54 #define EMIT4_off32(b1, b2, b3, b4, off) \
55 	do { EMIT4(b1, b2, b3, b4); EMIT(off, 4); } while (0)
56 
57 #ifdef CONFIG_X86_KERNEL_IBT
58 #define EMIT_ENDBR()		EMIT(gen_endbr(), 4)
59 #define EMIT_ENDBR_POISON()	EMIT(gen_endbr_poison(), 4)
60 #else
61 #define EMIT_ENDBR()
62 #define EMIT_ENDBR_POISON()
63 #endif
64 
65 static bool is_imm8(int value)
66 {
67 	return value <= 127 && value >= -128;
68 }
69 
70 /*
71  * Let us limit the positive offset to be <= 123.
72  * This is to ensure eventual jit convergence For the following patterns:
73  * ...
74  * pass4, final_proglen=4391:
75  *   ...
76  *   20e:    48 85 ff                test   rdi,rdi
77  *   211:    74 7d                   je     0x290
78  *   213:    48 8b 77 00             mov    rsi,QWORD PTR [rdi+0x0]
79  *   ...
80  *   289:    48 85 ff                test   rdi,rdi
81  *   28c:    74 17                   je     0x2a5
82  *   28e:    e9 7f ff ff ff          jmp    0x212
83  *   293:    bf 03 00 00 00          mov    edi,0x3
84  * Note that insn at 0x211 is 2-byte cond jump insn for offset 0x7d (-125)
85  * and insn at 0x28e is 5-byte jmp insn with offset -129.
86  *
87  * pass5, final_proglen=4392:
88  *   ...
89  *   20e:    48 85 ff                test   rdi,rdi
90  *   211:    0f 84 80 00 00 00       je     0x297
91  *   217:    48 8b 77 00             mov    rsi,QWORD PTR [rdi+0x0]
92  *   ...
93  *   28d:    48 85 ff                test   rdi,rdi
94  *   290:    74 1a                   je     0x2ac
95  *   292:    eb 84                   jmp    0x218
96  *   294:    bf 03 00 00 00          mov    edi,0x3
97  * Note that insn at 0x211 is 6-byte cond jump insn now since its offset
98  * becomes 0x80 based on previous round (0x293 - 0x213 = 0x80).
99  * At the same time, insn at 0x292 is a 2-byte insn since its offset is
100  * -124.
101  *
102  * pass6 will repeat the same code as in pass4 and this will prevent
103  * eventual convergence.
104  *
105  * To fix this issue, we need to break je (2->6 bytes) <-> jmp (5->2 bytes)
106  * cycle in the above. In the above example je offset <= 0x7c should work.
107  *
108  * For other cases, je <-> je needs offset <= 0x7b to avoid no convergence
109  * issue. For jmp <-> je and jmp <-> jmp cases, jmp offset <= 0x7c should
110  * avoid no convergence issue.
111  *
112  * Overall, let us limit the positive offset for 8bit cond/uncond jmp insn
113  * to maximum 123 (0x7b). This way, the jit pass can eventually converge.
114  */
115 static bool is_imm8_jmp_offset(int value)
116 {
117 	return value <= 123 && value >= -128;
118 }
119 
120 static bool is_simm32(s64 value)
121 {
122 	return value == (s64)(s32)value;
123 }
124 
125 static bool is_uimm32(u64 value)
126 {
127 	return value == (u64)(u32)value;
128 }
129 
130 /* mov dst, src */
131 #define EMIT_mov(DST, SRC)								 \
132 	do {										 \
133 		if (DST != SRC)								 \
134 			EMIT3(add_2mod(0x48, DST, SRC), 0x89, add_2reg(0xC0, DST, SRC)); \
135 	} while (0)
136 
137 static int bpf_size_to_x86_bytes(int bpf_size)
138 {
139 	if (bpf_size == BPF_W)
140 		return 4;
141 	else if (bpf_size == BPF_H)
142 		return 2;
143 	else if (bpf_size == BPF_B)
144 		return 1;
145 	else if (bpf_size == BPF_DW)
146 		return 4; /* imm32 */
147 	else
148 		return 0;
149 }
150 
151 /*
152  * List of x86 cond jumps opcodes (. + s8)
153  * Add 0x10 (and an extra 0x0f) to generate far jumps (. + s32)
154  */
155 #define X86_JB  0x72
156 #define X86_JAE 0x73
157 #define X86_JE  0x74
158 #define X86_JNE 0x75
159 #define X86_JBE 0x76
160 #define X86_JA  0x77
161 #define X86_JL  0x7C
162 #define X86_JGE 0x7D
163 #define X86_JLE 0x7E
164 #define X86_JG  0x7F
165 
166 /* Pick a register outside of BPF range for JIT internal work */
167 #define AUX_REG (MAX_BPF_JIT_REG + 1)
168 #define X86_REG_R9 (MAX_BPF_JIT_REG + 2)
169 #define X86_REG_R12 (MAX_BPF_JIT_REG + 3)
170 
171 /*
172  * The following table maps BPF registers to x86-64 registers.
173  *
174  * x86-64 register R12 is unused, since if used as base address
175  * register in load/store instructions, it always needs an
176  * extra byte of encoding and is callee saved.
177  *
178  * x86-64 register R9 is not used by BPF programs, but can be used by BPF
179  * trampoline. x86-64 register R10 is used for blinding (if enabled).
180  */
181 static const int reg2hex[] = {
182 	[BPF_REG_0] = 0,  /* RAX */
183 	[BPF_REG_1] = 7,  /* RDI */
184 	[BPF_REG_2] = 6,  /* RSI */
185 	[BPF_REG_3] = 2,  /* RDX */
186 	[BPF_REG_4] = 1,  /* RCX */
187 	[BPF_REG_5] = 0,  /* R8  */
188 	[BPF_REG_6] = 3,  /* RBX callee saved */
189 	[BPF_REG_7] = 5,  /* R13 callee saved */
190 	[BPF_REG_8] = 6,  /* R14 callee saved */
191 	[BPF_REG_9] = 7,  /* R15 callee saved */
192 	[BPF_REG_FP] = 5, /* RBP readonly */
193 	[BPF_REG_AX] = 2, /* R10 temp register */
194 	[AUX_REG] = 3,    /* R11 temp register */
195 	[X86_REG_R9] = 1, /* R9 register, 6th function argument */
196 	[X86_REG_R12] = 4, /* R12 callee saved */
197 };
198 
199 static const int reg2pt_regs[] = {
200 	[BPF_REG_0] = offsetof(struct pt_regs, ax),
201 	[BPF_REG_1] = offsetof(struct pt_regs, di),
202 	[BPF_REG_2] = offsetof(struct pt_regs, si),
203 	[BPF_REG_3] = offsetof(struct pt_regs, dx),
204 	[BPF_REG_4] = offsetof(struct pt_regs, cx),
205 	[BPF_REG_5] = offsetof(struct pt_regs, r8),
206 	[BPF_REG_6] = offsetof(struct pt_regs, bx),
207 	[BPF_REG_7] = offsetof(struct pt_regs, r13),
208 	[BPF_REG_8] = offsetof(struct pt_regs, r14),
209 	[BPF_REG_9] = offsetof(struct pt_regs, r15),
210 };
211 
212 /*
213  * is_ereg() == true if BPF register 'reg' maps to x86-64 r8..r15
214  * which need extra byte of encoding.
215  * rax,rcx,...,rbp have simpler encoding
216  */
217 static bool is_ereg(u32 reg)
218 {
219 	return (1 << reg) & (BIT(BPF_REG_5) |
220 			     BIT(AUX_REG) |
221 			     BIT(BPF_REG_7) |
222 			     BIT(BPF_REG_8) |
223 			     BIT(BPF_REG_9) |
224 			     BIT(X86_REG_R9) |
225 			     BIT(X86_REG_R12) |
226 			     BIT(BPF_REG_AX));
227 }
228 
229 /*
230  * is_ereg_8l() == true if BPF register 'reg' is mapped to access x86-64
231  * lower 8-bit registers dil,sil,bpl,spl,r8b..r15b, which need extra byte
232  * of encoding. al,cl,dl,bl have simpler encoding.
233  */
234 static bool is_ereg_8l(u32 reg)
235 {
236 	return is_ereg(reg) ||
237 	    (1 << reg) & (BIT(BPF_REG_1) |
238 			  BIT(BPF_REG_2) |
239 			  BIT(BPF_REG_FP));
240 }
241 
242 static bool is_axreg(u32 reg)
243 {
244 	return reg == BPF_REG_0;
245 }
246 
247 /* Add modifiers if 'reg' maps to x86-64 registers R8..R15 */
248 static u8 add_1mod(u8 byte, u32 reg)
249 {
250 	if (is_ereg(reg))
251 		byte |= 1;
252 	return byte;
253 }
254 
255 static u8 add_2mod(u8 byte, u32 r1, u32 r2)
256 {
257 	if (is_ereg(r1))
258 		byte |= 1;
259 	if (is_ereg(r2))
260 		byte |= 4;
261 	return byte;
262 }
263 
264 static u8 add_3mod(u8 byte, u32 r1, u32 r2, u32 index)
265 {
266 	if (is_ereg(r1))
267 		byte |= 1;
268 	if (is_ereg(index))
269 		byte |= 2;
270 	if (is_ereg(r2))
271 		byte |= 4;
272 	return byte;
273 }
274 
275 /* Encode 'dst_reg' register into x86-64 opcode 'byte' */
276 static u8 add_1reg(u8 byte, u32 dst_reg)
277 {
278 	return byte + reg2hex[dst_reg];
279 }
280 
281 /* Encode 'dst_reg' and 'src_reg' registers into x86-64 opcode 'byte' */
282 static u8 add_2reg(u8 byte, u32 dst_reg, u32 src_reg)
283 {
284 	return byte + reg2hex[dst_reg] + (reg2hex[src_reg] << 3);
285 }
286 
287 /* Some 1-byte opcodes for binary ALU operations */
288 static u8 simple_alu_opcodes[] = {
289 	[BPF_ADD] = 0x01,
290 	[BPF_SUB] = 0x29,
291 	[BPF_AND] = 0x21,
292 	[BPF_OR] = 0x09,
293 	[BPF_XOR] = 0x31,
294 	[BPF_LSH] = 0xE0,
295 	[BPF_RSH] = 0xE8,
296 	[BPF_ARSH] = 0xF8,
297 };
298 
299 static void jit_fill_hole(void *area, unsigned int size)
300 {
301 	/* Fill whole space with INT3 instructions */
302 	memset(area, 0xcc, size);
303 }
304 
305 int bpf_arch_text_invalidate(void *dst, size_t len)
306 {
307 	return IS_ERR_OR_NULL(text_poke_set(dst, 0xcc, len));
308 }
309 
310 struct jit_context {
311 	int cleanup_addr; /* Epilogue code offset */
312 
313 	/*
314 	 * Program specific offsets of labels in the code; these rely on the
315 	 * JIT doing at least 2 passes, recording the position on the first
316 	 * pass, only to generate the correct offset on the second pass.
317 	 */
318 	int tail_call_direct_label;
319 	int tail_call_indirect_label;
320 };
321 
322 /* Maximum number of bytes emitted while JITing one eBPF insn */
323 #define BPF_MAX_INSN_SIZE	128
324 #define BPF_INSN_SAFETY		64
325 
326 /* Number of bytes emit_patch() needs to generate instructions */
327 #define X86_PATCH_SIZE		5
328 /* Number of bytes that will be skipped on tailcall */
329 #define X86_TAIL_CALL_OFFSET	(12 + ENDBR_INSN_SIZE)
330 
331 static void push_r9(u8 **pprog)
332 {
333 	u8 *prog = *pprog;
334 
335 	EMIT2(0x41, 0x51);   /* push r9 */
336 	*pprog = prog;
337 }
338 
339 static void pop_r9(u8 **pprog)
340 {
341 	u8 *prog = *pprog;
342 
343 	EMIT2(0x41, 0x59);   /* pop r9 */
344 	*pprog = prog;
345 }
346 
347 static void push_r12(u8 **pprog)
348 {
349 	u8 *prog = *pprog;
350 
351 	EMIT2(0x41, 0x54);   /* push r12 */
352 	*pprog = prog;
353 }
354 
355 static void push_callee_regs(u8 **pprog, bool *callee_regs_used)
356 {
357 	u8 *prog = *pprog;
358 
359 	if (callee_regs_used[0])
360 		EMIT1(0x53);         /* push rbx */
361 	if (callee_regs_used[1])
362 		EMIT2(0x41, 0x55);   /* push r13 */
363 	if (callee_regs_used[2])
364 		EMIT2(0x41, 0x56);   /* push r14 */
365 	if (callee_regs_used[3])
366 		EMIT2(0x41, 0x57);   /* push r15 */
367 	*pprog = prog;
368 }
369 
370 static void pop_r12(u8 **pprog)
371 {
372 	u8 *prog = *pprog;
373 
374 	EMIT2(0x41, 0x5C);   /* pop r12 */
375 	*pprog = prog;
376 }
377 
378 static void pop_callee_regs(u8 **pprog, bool *callee_regs_used)
379 {
380 	u8 *prog = *pprog;
381 
382 	if (callee_regs_used[3])
383 		EMIT2(0x41, 0x5F);   /* pop r15 */
384 	if (callee_regs_used[2])
385 		EMIT2(0x41, 0x5E);   /* pop r14 */
386 	if (callee_regs_used[1])
387 		EMIT2(0x41, 0x5D);   /* pop r13 */
388 	if (callee_regs_used[0])
389 		EMIT1(0x5B);         /* pop rbx */
390 	*pprog = prog;
391 }
392 
393 static void emit_nops(u8 **pprog, int len)
394 {
395 	u8 *prog = *pprog;
396 	int i, noplen;
397 
398 	while (len > 0) {
399 		noplen = len;
400 
401 		if (noplen > ASM_NOP_MAX)
402 			noplen = ASM_NOP_MAX;
403 
404 		for (i = 0; i < noplen; i++)
405 			EMIT1(x86_nops[noplen][i]);
406 		len -= noplen;
407 	}
408 
409 	*pprog = prog;
410 }
411 
412 /*
413  * Emit the various CFI preambles, see asm/cfi.h and the comments about FineIBT
414  * in arch/x86/kernel/alternative.c
415  */
416 static int emit_call(u8 **prog, void *func, void *ip);
417 
418 static void emit_fineibt(u8 **pprog, u8 *ip, u32 hash, int arity)
419 {
420 	u8 *prog = *pprog;
421 
422 	EMIT_ENDBR();
423 	EMIT3_off32(0x41, 0x81, 0xea, hash);		/* subl $hash, %r10d	*/
424 	if (cfi_bhi) {
425 		emit_call(&prog, __bhi_args[arity], ip + 11);
426 	} else {
427 		EMIT2(0x75, 0xf9);			/* jne.d8 .-7		*/
428 		EMIT3(0x0f, 0x1f, 0x00);		/* nop3			*/
429 	}
430 	EMIT_ENDBR_POISON();
431 
432 	*pprog = prog;
433 }
434 
435 static void emit_kcfi(u8 **pprog, u32 hash)
436 {
437 	u8 *prog = *pprog;
438 
439 	EMIT1_off32(0xb8, hash);			/* movl $hash, %eax	*/
440 #ifdef CONFIG_CALL_PADDING
441 	EMIT1(0x90);
442 	EMIT1(0x90);
443 	EMIT1(0x90);
444 	EMIT1(0x90);
445 	EMIT1(0x90);
446 	EMIT1(0x90);
447 	EMIT1(0x90);
448 	EMIT1(0x90);
449 	EMIT1(0x90);
450 	EMIT1(0x90);
451 	EMIT1(0x90);
452 #endif
453 	EMIT_ENDBR();
454 
455 	*pprog = prog;
456 }
457 
458 static void emit_cfi(u8 **pprog, u8 *ip, u32 hash, int arity)
459 {
460 	u8 *prog = *pprog;
461 
462 	switch (cfi_mode) {
463 	case CFI_FINEIBT:
464 		emit_fineibt(&prog, ip, hash, arity);
465 		break;
466 
467 	case CFI_KCFI:
468 		emit_kcfi(&prog, hash);
469 		break;
470 
471 	default:
472 		EMIT_ENDBR();
473 		break;
474 	}
475 
476 	*pprog = prog;
477 }
478 
479 static void emit_prologue_tail_call(u8 **pprog, bool is_subprog)
480 {
481 	u8 *prog = *pprog;
482 
483 	if (!is_subprog) {
484 		/* cmp rax, MAX_TAIL_CALL_CNT */
485 		EMIT4(0x48, 0x83, 0xF8, MAX_TAIL_CALL_CNT);
486 		EMIT2(X86_JA, 6);        /* ja 6 */
487 		/* rax is tail_call_cnt if <= MAX_TAIL_CALL_CNT.
488 		 * case1: entry of main prog.
489 		 * case2: tail callee of main prog.
490 		 */
491 		EMIT1(0x50);             /* push rax */
492 		/* Make rax as tail_call_cnt_ptr. */
493 		EMIT3(0x48, 0x89, 0xE0); /* mov rax, rsp */
494 		EMIT2(0xEB, 1);          /* jmp 1 */
495 		/* rax is tail_call_cnt_ptr if > MAX_TAIL_CALL_CNT.
496 		 * case: tail callee of subprog.
497 		 */
498 		EMIT1(0x50);             /* push rax */
499 		/* push tail_call_cnt_ptr */
500 		EMIT1(0x50);             /* push rax */
501 	} else { /* is_subprog */
502 		/* rax is tail_call_cnt_ptr. */
503 		EMIT1(0x50);             /* push rax */
504 		EMIT1(0x50);             /* push rax */
505 	}
506 
507 	*pprog = prog;
508 }
509 
510 /*
511  * Emit x86-64 prologue code for BPF program.
512  * bpf_tail_call helper will skip the first X86_TAIL_CALL_OFFSET bytes
513  * while jumping to another program
514  */
515 static void emit_prologue(u8 **pprog, u8 *ip, u32 stack_depth, bool ebpf_from_cbpf,
516 			  bool tail_call_reachable, bool is_subprog,
517 			  bool is_exception_cb)
518 {
519 	u8 *prog = *pprog;
520 
521 	if (is_subprog) {
522 		emit_cfi(&prog, ip, cfi_bpf_subprog_hash, 5);
523 	} else {
524 		emit_cfi(&prog, ip, cfi_bpf_hash, 1);
525 	}
526 	/* BPF trampoline can be made to work without these nops,
527 	 * but let's waste 5 bytes for now and optimize later
528 	 */
529 	emit_nops(&prog, X86_PATCH_SIZE);
530 	if (!ebpf_from_cbpf) {
531 		if (tail_call_reachable && !is_subprog)
532 			/* When it's the entry of the whole tailcall context,
533 			 * zeroing rax means initialising tail_call_cnt.
534 			 */
535 			EMIT3(0x48, 0x31, 0xC0); /* xor rax, rax */
536 		else
537 			/* Keep the same instruction layout. */
538 			emit_nops(&prog, 3);     /* nop3 */
539 	}
540 	/* Exception callback receives FP as third parameter */
541 	if (is_exception_cb) {
542 		EMIT3(0x48, 0x89, 0xF4); /* mov rsp, rsi */
543 		EMIT3(0x48, 0x89, 0xD5); /* mov rbp, rdx */
544 		/* The main frame must have exception_boundary as true, so we
545 		 * first restore those callee-saved regs from stack, before
546 		 * reusing the stack frame.
547 		 */
548 		pop_callee_regs(&prog, all_callee_regs_used);
549 		pop_r12(&prog);
550 		/* Reset the stack frame. */
551 		EMIT3(0x48, 0x89, 0xEC); /* mov rsp, rbp */
552 	} else {
553 		EMIT1(0x55);             /* push rbp */
554 		EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
555 	}
556 
557 	/* X86_TAIL_CALL_OFFSET is here */
558 	EMIT_ENDBR();
559 
560 	/* sub rsp, rounded_stack_depth */
561 	if (stack_depth)
562 		EMIT3_off32(0x48, 0x81, 0xEC, round_up(stack_depth, 8));
563 	if (tail_call_reachable)
564 		emit_prologue_tail_call(&prog, is_subprog);
565 	*pprog = prog;
566 }
567 
568 static int emit_patch(u8 **pprog, void *func, void *ip, u8 opcode)
569 {
570 	u8 *prog = *pprog;
571 	s64 offset;
572 
573 	offset = func - (ip + X86_PATCH_SIZE);
574 	if (!is_simm32(offset)) {
575 		pr_err("Target call %p is out of range\n", func);
576 		return -ERANGE;
577 	}
578 	EMIT1_off32(opcode, offset);
579 	*pprog = prog;
580 	return 0;
581 }
582 
583 static int emit_call(u8 **pprog, void *func, void *ip)
584 {
585 	return emit_patch(pprog, func, ip, 0xE8);
586 }
587 
588 static int emit_rsb_call(u8 **pprog, void *func, void *ip)
589 {
590 	OPTIMIZER_HIDE_VAR(func);
591 	ip += x86_call_depth_emit_accounting(pprog, func, ip);
592 	return emit_patch(pprog, func, ip, 0xE8);
593 }
594 
595 static int emit_jump(u8 **pprog, void *func, void *ip)
596 {
597 	return emit_patch(pprog, func, ip, 0xE9);
598 }
599 
600 static int __bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
601 				void *old_addr, void *new_addr)
602 {
603 	const u8 *nop_insn = x86_nops[5];
604 	u8 old_insn[X86_PATCH_SIZE];
605 	u8 new_insn[X86_PATCH_SIZE];
606 	u8 *prog;
607 	int ret;
608 
609 	memcpy(old_insn, nop_insn, X86_PATCH_SIZE);
610 	if (old_addr) {
611 		prog = old_insn;
612 		ret = t == BPF_MOD_CALL ?
613 		      emit_call(&prog, old_addr, ip) :
614 		      emit_jump(&prog, old_addr, ip);
615 		if (ret)
616 			return ret;
617 	}
618 
619 	memcpy(new_insn, nop_insn, X86_PATCH_SIZE);
620 	if (new_addr) {
621 		prog = new_insn;
622 		ret = t == BPF_MOD_CALL ?
623 		      emit_call(&prog, new_addr, ip) :
624 		      emit_jump(&prog, new_addr, ip);
625 		if (ret)
626 			return ret;
627 	}
628 
629 	ret = -EBUSY;
630 	mutex_lock(&text_mutex);
631 	if (memcmp(ip, old_insn, X86_PATCH_SIZE))
632 		goto out;
633 	ret = 1;
634 	if (memcmp(ip, new_insn, X86_PATCH_SIZE)) {
635 		smp_text_poke_single(ip, new_insn, X86_PATCH_SIZE, NULL);
636 		ret = 0;
637 	}
638 out:
639 	mutex_unlock(&text_mutex);
640 	return ret;
641 }
642 
643 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
644 		       void *old_addr, void *new_addr)
645 {
646 	if (!is_kernel_text((long)ip) &&
647 	    !is_bpf_text_address((long)ip))
648 		/* BPF poking in modules is not supported */
649 		return -EINVAL;
650 
651 	/*
652 	 * See emit_prologue(), for IBT builds the trampoline hook is preceded
653 	 * with an ENDBR instruction.
654 	 */
655 	if (is_endbr(ip))
656 		ip += ENDBR_INSN_SIZE;
657 
658 	return __bpf_arch_text_poke(ip, t, old_addr, new_addr);
659 }
660 
661 #define EMIT_LFENCE()	EMIT3(0x0F, 0xAE, 0xE8)
662 
663 static void emit_indirect_jump(u8 **pprog, int reg, u8 *ip)
664 {
665 	u8 *prog = *pprog;
666 
667 	if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) {
668 		OPTIMIZER_HIDE_VAR(reg);
669 		emit_jump(&prog, its_static_thunk(reg), ip);
670 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
671 		EMIT_LFENCE();
672 		EMIT2(0xFF, 0xE0 + reg);
673 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
674 		OPTIMIZER_HIDE_VAR(reg);
675 		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
676 			emit_jump(&prog, &__x86_indirect_jump_thunk_array[reg], ip);
677 		else
678 			emit_jump(&prog, &__x86_indirect_thunk_array[reg], ip);
679 	} else {
680 		EMIT2(0xFF, 0xE0 + reg);	/* jmp *%\reg */
681 		if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) || IS_ENABLED(CONFIG_MITIGATION_SLS))
682 			EMIT1(0xCC);		/* int3 */
683 	}
684 
685 	*pprog = prog;
686 }
687 
688 static void emit_return(u8 **pprog, u8 *ip)
689 {
690 	u8 *prog = *pprog;
691 
692 	if (cpu_wants_rethunk()) {
693 		emit_jump(&prog, x86_return_thunk, ip);
694 	} else {
695 		EMIT1(0xC3);		/* ret */
696 		if (IS_ENABLED(CONFIG_MITIGATION_SLS))
697 			EMIT1(0xCC);	/* int3 */
698 	}
699 
700 	*pprog = prog;
701 }
702 
703 #define BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack)	(-16 - round_up(stack, 8))
704 
705 /*
706  * Generate the following code:
707  *
708  * ... bpf_tail_call(void *ctx, struct bpf_array *array, u64 index) ...
709  *   if (index >= array->map.max_entries)
710  *     goto out;
711  *   if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
712  *     goto out;
713  *   prog = array->ptrs[index];
714  *   if (prog == NULL)
715  *     goto out;
716  *   goto *(prog->bpf_func + prologue_size);
717  * out:
718  */
719 static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
720 					u8 **pprog, bool *callee_regs_used,
721 					u32 stack_depth, u8 *ip,
722 					struct jit_context *ctx)
723 {
724 	int tcc_ptr_off = BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack_depth);
725 	u8 *prog = *pprog, *start = *pprog;
726 	int offset;
727 
728 	/*
729 	 * rdi - pointer to ctx
730 	 * rsi - pointer to bpf_array
731 	 * rdx - index in bpf_array
732 	 */
733 
734 	/*
735 	 * if (index >= array->map.max_entries)
736 	 *	goto out;
737 	 */
738 	EMIT2(0x89, 0xD2);                        /* mov edx, edx */
739 	EMIT3(0x39, 0x56,                         /* cmp dword ptr [rsi + 16], edx */
740 	      offsetof(struct bpf_array, map.max_entries));
741 
742 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
743 	EMIT2(X86_JBE, offset);                   /* jbe out */
744 
745 	/*
746 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
747 	 *	goto out;
748 	 */
749 	EMIT3_off32(0x48, 0x8B, 0x85, tcc_ptr_off); /* mov rax, qword ptr [rbp - tcc_ptr_off] */
750 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT); /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
751 
752 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
753 	EMIT2(X86_JAE, offset);                   /* jae out */
754 
755 	/* prog = array->ptrs[index]; */
756 	EMIT4_off32(0x48, 0x8B, 0x8C, 0xD6,       /* mov rcx, [rsi + rdx * 8 + offsetof(...)] */
757 		    offsetof(struct bpf_array, ptrs));
758 
759 	/*
760 	 * if (prog == NULL)
761 	 *	goto out;
762 	 */
763 	EMIT3(0x48, 0x85, 0xC9);                  /* test rcx,rcx */
764 
765 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
766 	EMIT2(X86_JE, offset);                    /* je out */
767 
768 	/* Inc tail_call_cnt if the slot is populated. */
769 	EMIT4(0x48, 0x83, 0x00, 0x01);            /* add qword ptr [rax], 1 */
770 
771 	if (bpf_prog->aux->exception_boundary) {
772 		pop_callee_regs(&prog, all_callee_regs_used);
773 		pop_r12(&prog);
774 	} else {
775 		pop_callee_regs(&prog, callee_regs_used);
776 		if (bpf_arena_get_kern_vm_start(bpf_prog->aux->arena))
777 			pop_r12(&prog);
778 	}
779 
780 	/* Pop tail_call_cnt_ptr. */
781 	EMIT1(0x58);                              /* pop rax */
782 	/* Pop tail_call_cnt, if it's main prog.
783 	 * Pop tail_call_cnt_ptr, if it's subprog.
784 	 */
785 	EMIT1(0x58);                              /* pop rax */
786 	if (stack_depth)
787 		EMIT3_off32(0x48, 0x81, 0xC4,     /* add rsp, sd */
788 			    round_up(stack_depth, 8));
789 
790 	/* goto *(prog->bpf_func + X86_TAIL_CALL_OFFSET); */
791 	EMIT4(0x48, 0x8B, 0x49,                   /* mov rcx, qword ptr [rcx + 32] */
792 	      offsetof(struct bpf_prog, bpf_func));
793 	EMIT4(0x48, 0x83, 0xC1,                   /* add rcx, X86_TAIL_CALL_OFFSET */
794 	      X86_TAIL_CALL_OFFSET);
795 	/*
796 	 * Now we're ready to jump into next BPF program
797 	 * rdi == ctx (1st arg)
798 	 * rcx == prog->bpf_func + X86_TAIL_CALL_OFFSET
799 	 */
800 	emit_indirect_jump(&prog, 1 /* rcx */, ip + (prog - start));
801 
802 	/* out: */
803 	ctx->tail_call_indirect_label = prog - start;
804 	*pprog = prog;
805 }
806 
807 static void emit_bpf_tail_call_direct(struct bpf_prog *bpf_prog,
808 				      struct bpf_jit_poke_descriptor *poke,
809 				      u8 **pprog, u8 *ip,
810 				      bool *callee_regs_used, u32 stack_depth,
811 				      struct jit_context *ctx)
812 {
813 	int tcc_ptr_off = BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack_depth);
814 	u8 *prog = *pprog, *start = *pprog;
815 	int offset;
816 
817 	/*
818 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
819 	 *	goto out;
820 	 */
821 	EMIT3_off32(0x48, 0x8B, 0x85, tcc_ptr_off);   /* mov rax, qword ptr [rbp - tcc_ptr_off] */
822 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT);   /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
823 
824 	offset = ctx->tail_call_direct_label - (prog + 2 - start);
825 	EMIT2(X86_JAE, offset);                       /* jae out */
826 
827 	poke->tailcall_bypass = ip + (prog - start);
828 	poke->adj_off = X86_TAIL_CALL_OFFSET;
829 	poke->tailcall_target = ip + ctx->tail_call_direct_label - X86_PATCH_SIZE;
830 	poke->bypass_addr = (u8 *)poke->tailcall_target + X86_PATCH_SIZE;
831 
832 	emit_jump(&prog, (u8 *)poke->tailcall_target + X86_PATCH_SIZE,
833 		  poke->tailcall_bypass);
834 
835 	/* Inc tail_call_cnt if the slot is populated. */
836 	EMIT4(0x48, 0x83, 0x00, 0x01);                /* add qword ptr [rax], 1 */
837 
838 	if (bpf_prog->aux->exception_boundary) {
839 		pop_callee_regs(&prog, all_callee_regs_used);
840 		pop_r12(&prog);
841 	} else {
842 		pop_callee_regs(&prog, callee_regs_used);
843 		if (bpf_arena_get_kern_vm_start(bpf_prog->aux->arena))
844 			pop_r12(&prog);
845 	}
846 
847 	/* Pop tail_call_cnt_ptr. */
848 	EMIT1(0x58);                                  /* pop rax */
849 	/* Pop tail_call_cnt, if it's main prog.
850 	 * Pop tail_call_cnt_ptr, if it's subprog.
851 	 */
852 	EMIT1(0x58);                                  /* pop rax */
853 	if (stack_depth)
854 		EMIT3_off32(0x48, 0x81, 0xC4, round_up(stack_depth, 8));
855 
856 	emit_nops(&prog, X86_PATCH_SIZE);
857 
858 	/* out: */
859 	ctx->tail_call_direct_label = prog - start;
860 
861 	*pprog = prog;
862 }
863 
864 static void bpf_tail_call_direct_fixup(struct bpf_prog *prog)
865 {
866 	struct bpf_jit_poke_descriptor *poke;
867 	struct bpf_array *array;
868 	struct bpf_prog *target;
869 	int i, ret;
870 
871 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
872 		poke = &prog->aux->poke_tab[i];
873 		if (poke->aux && poke->aux != prog->aux)
874 			continue;
875 
876 		WARN_ON_ONCE(READ_ONCE(poke->tailcall_target_stable));
877 
878 		if (poke->reason != BPF_POKE_REASON_TAIL_CALL)
879 			continue;
880 
881 		array = container_of(poke->tail_call.map, struct bpf_array, map);
882 		mutex_lock(&array->aux->poke_mutex);
883 		target = array->ptrs[poke->tail_call.key];
884 		if (target) {
885 			ret = __bpf_arch_text_poke(poke->tailcall_target,
886 						   BPF_MOD_JUMP, NULL,
887 						   (u8 *)target->bpf_func +
888 						   poke->adj_off);
889 			BUG_ON(ret < 0);
890 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
891 						   BPF_MOD_JUMP,
892 						   (u8 *)poke->tailcall_target +
893 						   X86_PATCH_SIZE, NULL);
894 			BUG_ON(ret < 0);
895 		}
896 		WRITE_ONCE(poke->tailcall_target_stable, true);
897 		mutex_unlock(&array->aux->poke_mutex);
898 	}
899 }
900 
901 static void emit_mov_imm32(u8 **pprog, bool sign_propagate,
902 			   u32 dst_reg, const u32 imm32)
903 {
904 	u8 *prog = *pprog;
905 	u8 b1, b2, b3;
906 
907 	/*
908 	 * Optimization: if imm32 is positive, use 'mov %eax, imm32'
909 	 * (which zero-extends imm32) to save 2 bytes.
910 	 */
911 	if (sign_propagate && (s32)imm32 < 0) {
912 		/* 'mov %rax, imm32' sign extends imm32 */
913 		b1 = add_1mod(0x48, dst_reg);
914 		b2 = 0xC7;
915 		b3 = 0xC0;
916 		EMIT3_off32(b1, b2, add_1reg(b3, dst_reg), imm32);
917 		goto done;
918 	}
919 
920 	/*
921 	 * Optimization: if imm32 is zero, use 'xor %eax, %eax'
922 	 * to save 3 bytes.
923 	 */
924 	if (imm32 == 0) {
925 		if (is_ereg(dst_reg))
926 			EMIT1(add_2mod(0x40, dst_reg, dst_reg));
927 		b2 = 0x31; /* xor */
928 		b3 = 0xC0;
929 		EMIT2(b2, add_2reg(b3, dst_reg, dst_reg));
930 		goto done;
931 	}
932 
933 	/* mov %eax, imm32 */
934 	if (is_ereg(dst_reg))
935 		EMIT1(add_1mod(0x40, dst_reg));
936 	EMIT1_off32(add_1reg(0xB8, dst_reg), imm32);
937 done:
938 	*pprog = prog;
939 }
940 
941 static void emit_mov_imm64(u8 **pprog, u32 dst_reg,
942 			   const u32 imm32_hi, const u32 imm32_lo)
943 {
944 	u64 imm64 = ((u64)imm32_hi << 32) | (u32)imm32_lo;
945 	u8 *prog = *pprog;
946 
947 	if (is_uimm32(imm64)) {
948 		/*
949 		 * For emitting plain u32, where sign bit must not be
950 		 * propagated LLVM tends to load imm64 over mov32
951 		 * directly, so save couple of bytes by just doing
952 		 * 'mov %eax, imm32' instead.
953 		 */
954 		emit_mov_imm32(&prog, false, dst_reg, imm32_lo);
955 	} else if (is_simm32(imm64)) {
956 		emit_mov_imm32(&prog, true, dst_reg, imm32_lo);
957 	} else {
958 		/* movabsq rax, imm64 */
959 		EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg));
960 		EMIT(imm32_lo, 4);
961 		EMIT(imm32_hi, 4);
962 	}
963 
964 	*pprog = prog;
965 }
966 
967 static void emit_mov_reg(u8 **pprog, bool is64, u32 dst_reg, u32 src_reg)
968 {
969 	u8 *prog = *pprog;
970 
971 	if (is64) {
972 		/* mov dst, src */
973 		EMIT_mov(dst_reg, src_reg);
974 	} else {
975 		/* mov32 dst, src */
976 		if (is_ereg(dst_reg) || is_ereg(src_reg))
977 			EMIT1(add_2mod(0x40, dst_reg, src_reg));
978 		EMIT2(0x89, add_2reg(0xC0, dst_reg, src_reg));
979 	}
980 
981 	*pprog = prog;
982 }
983 
984 static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg,
985 			   u32 src_reg)
986 {
987 	u8 *prog = *pprog;
988 
989 	if (is64) {
990 		/* movs[b,w,l]q dst, src */
991 		if (num_bits == 8)
992 			EMIT4(add_2mod(0x48, src_reg, dst_reg), 0x0f, 0xbe,
993 			      add_2reg(0xC0, src_reg, dst_reg));
994 		else if (num_bits == 16)
995 			EMIT4(add_2mod(0x48, src_reg, dst_reg), 0x0f, 0xbf,
996 			      add_2reg(0xC0, src_reg, dst_reg));
997 		else if (num_bits == 32)
998 			EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x63,
999 			      add_2reg(0xC0, src_reg, dst_reg));
1000 	} else {
1001 		/* movs[b,w]l dst, src */
1002 		if (num_bits == 8) {
1003 			EMIT4(add_2mod(0x40, src_reg, dst_reg), 0x0f, 0xbe,
1004 			      add_2reg(0xC0, src_reg, dst_reg));
1005 		} else if (num_bits == 16) {
1006 			if (is_ereg(dst_reg) || is_ereg(src_reg))
1007 				EMIT1(add_2mod(0x40, src_reg, dst_reg));
1008 			EMIT3(add_2mod(0x0f, src_reg, dst_reg), 0xbf,
1009 			      add_2reg(0xC0, src_reg, dst_reg));
1010 		}
1011 	}
1012 
1013 	*pprog = prog;
1014 }
1015 
1016 /* Emit the suffix (ModR/M etc) for addressing *(ptr_reg + off) and val_reg */
1017 static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
1018 {
1019 	u8 *prog = *pprog;
1020 
1021 	if (is_imm8(off)) {
1022 		/* 1-byte signed displacement.
1023 		 *
1024 		 * If off == 0 we could skip this and save one extra byte, but
1025 		 * special case of x86 R13 which always needs an offset is not
1026 		 * worth the hassle
1027 		 */
1028 		EMIT2(add_2reg(0x40, ptr_reg, val_reg), off);
1029 	} else {
1030 		/* 4-byte signed displacement */
1031 		EMIT1_off32(add_2reg(0x80, ptr_reg, val_reg), off);
1032 	}
1033 	*pprog = prog;
1034 }
1035 
1036 static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index_reg, int off)
1037 {
1038 	u8 *prog = *pprog;
1039 
1040 	if (is_imm8(off)) {
1041 		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
1042 	} else {
1043 		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
1044 	}
1045 	*pprog = prog;
1046 }
1047 
1048 /*
1049  * Emit a REX byte if it will be necessary to address these registers
1050  */
1051 static void maybe_emit_mod(u8 **pprog, u32 dst_reg, u32 src_reg, bool is64)
1052 {
1053 	u8 *prog = *pprog;
1054 
1055 	if (is64)
1056 		EMIT1(add_2mod(0x48, dst_reg, src_reg));
1057 	else if (is_ereg(dst_reg) || is_ereg(src_reg))
1058 		EMIT1(add_2mod(0x40, dst_reg, src_reg));
1059 	*pprog = prog;
1060 }
1061 
1062 /*
1063  * Similar version of maybe_emit_mod() for a single register
1064  */
1065 static void maybe_emit_1mod(u8 **pprog, u32 reg, bool is64)
1066 {
1067 	u8 *prog = *pprog;
1068 
1069 	if (is64)
1070 		EMIT1(add_1mod(0x48, reg));
1071 	else if (is_ereg(reg))
1072 		EMIT1(add_1mod(0x40, reg));
1073 	*pprog = prog;
1074 }
1075 
1076 /* LDX: dst_reg = *(u8*)(src_reg + off) */
1077 static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1078 {
1079 	u8 *prog = *pprog;
1080 
1081 	switch (size) {
1082 	case BPF_B:
1083 		/* Emit 'movzx rax, byte ptr [rax + off]' */
1084 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB6);
1085 		break;
1086 	case BPF_H:
1087 		/* Emit 'movzx rax, word ptr [rax + off]' */
1088 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB7);
1089 		break;
1090 	case BPF_W:
1091 		/* Emit 'mov eax, dword ptr [rax+0x14]' */
1092 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1093 			EMIT2(add_2mod(0x40, src_reg, dst_reg), 0x8B);
1094 		else
1095 			EMIT1(0x8B);
1096 		break;
1097 	case BPF_DW:
1098 		/* Emit 'mov rax, qword ptr [rax+0x14]' */
1099 		EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x8B);
1100 		break;
1101 	}
1102 	emit_insn_suffix(&prog, src_reg, dst_reg, off);
1103 	*pprog = prog;
1104 }
1105 
1106 /* LDSX: dst_reg = *(s8*)(src_reg + off) */
1107 static void emit_ldsx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1108 {
1109 	u8 *prog = *pprog;
1110 
1111 	switch (size) {
1112 	case BPF_B:
1113 		/* Emit 'movsx rax, byte ptr [rax + off]' */
1114 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xBE);
1115 		break;
1116 	case BPF_H:
1117 		/* Emit 'movsx rax, word ptr [rax + off]' */
1118 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xBF);
1119 		break;
1120 	case BPF_W:
1121 		/* Emit 'movsx rax, dword ptr [rax+0x14]' */
1122 		EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x63);
1123 		break;
1124 	}
1125 	emit_insn_suffix(&prog, src_reg, dst_reg, off);
1126 	*pprog = prog;
1127 }
1128 
1129 static void emit_ldx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 index_reg, int off)
1130 {
1131 	u8 *prog = *pprog;
1132 
1133 	switch (size) {
1134 	case BPF_B:
1135 		/* movzx rax, byte ptr [rax + r12 + off] */
1136 		EMIT3(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x0F, 0xB6);
1137 		break;
1138 	case BPF_H:
1139 		/* movzx rax, word ptr [rax + r12 + off] */
1140 		EMIT3(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x0F, 0xB7);
1141 		break;
1142 	case BPF_W:
1143 		/* mov eax, dword ptr [rax + r12 + off] */
1144 		EMIT2(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x8B);
1145 		break;
1146 	case BPF_DW:
1147 		/* mov rax, qword ptr [rax + r12 + off] */
1148 		EMIT2(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x8B);
1149 		break;
1150 	}
1151 	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off);
1152 	*pprog = prog;
1153 }
1154 
1155 static void emit_ldx_r12(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1156 {
1157 	emit_ldx_index(pprog, size, dst_reg, src_reg, X86_REG_R12, off);
1158 }
1159 
1160 /* STX: *(u8*)(dst_reg + off) = src_reg */
1161 static void emit_stx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1162 {
1163 	u8 *prog = *pprog;
1164 
1165 	switch (size) {
1166 	case BPF_B:
1167 		/* Emit 'mov byte ptr [rax + off], al' */
1168 		if (is_ereg(dst_reg) || is_ereg_8l(src_reg))
1169 			/* Add extra byte for eregs or SIL,DIL,BPL in src_reg */
1170 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x88);
1171 		else
1172 			EMIT1(0x88);
1173 		break;
1174 	case BPF_H:
1175 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1176 			EMIT3(0x66, add_2mod(0x40, dst_reg, src_reg), 0x89);
1177 		else
1178 			EMIT2(0x66, 0x89);
1179 		break;
1180 	case BPF_W:
1181 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1182 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x89);
1183 		else
1184 			EMIT1(0x89);
1185 		break;
1186 	case BPF_DW:
1187 		EMIT2(add_2mod(0x48, dst_reg, src_reg), 0x89);
1188 		break;
1189 	}
1190 	emit_insn_suffix(&prog, dst_reg, src_reg, off);
1191 	*pprog = prog;
1192 }
1193 
1194 /* STX: *(u8*)(dst_reg + index_reg + off) = src_reg */
1195 static void emit_stx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 index_reg, int off)
1196 {
1197 	u8 *prog = *pprog;
1198 
1199 	switch (size) {
1200 	case BPF_B:
1201 		/* mov byte ptr [rax + r12 + off], al */
1202 		EMIT2(add_3mod(0x40, dst_reg, src_reg, index_reg), 0x88);
1203 		break;
1204 	case BPF_H:
1205 		/* mov word ptr [rax + r12 + off], ax */
1206 		EMIT3(0x66, add_3mod(0x40, dst_reg, src_reg, index_reg), 0x89);
1207 		break;
1208 	case BPF_W:
1209 		/* mov dword ptr [rax + r12 + 1], eax */
1210 		EMIT2(add_3mod(0x40, dst_reg, src_reg, index_reg), 0x89);
1211 		break;
1212 	case BPF_DW:
1213 		/* mov qword ptr [rax + r12 + 1], rax */
1214 		EMIT2(add_3mod(0x48, dst_reg, src_reg, index_reg), 0x89);
1215 		break;
1216 	}
1217 	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off);
1218 	*pprog = prog;
1219 }
1220 
1221 static void emit_stx_r12(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1222 {
1223 	emit_stx_index(pprog, size, dst_reg, src_reg, X86_REG_R12, off);
1224 }
1225 
1226 /* ST: *(u8*)(dst_reg + index_reg + off) = imm32 */
1227 static void emit_st_index(u8 **pprog, u32 size, u32 dst_reg, u32 index_reg, int off, int imm)
1228 {
1229 	u8 *prog = *pprog;
1230 
1231 	switch (size) {
1232 	case BPF_B:
1233 		/* mov byte ptr [rax + r12 + off], imm8 */
1234 		EMIT2(add_3mod(0x40, dst_reg, 0, index_reg), 0xC6);
1235 		break;
1236 	case BPF_H:
1237 		/* mov word ptr [rax + r12 + off], imm16 */
1238 		EMIT3(0x66, add_3mod(0x40, dst_reg, 0, index_reg), 0xC7);
1239 		break;
1240 	case BPF_W:
1241 		/* mov dword ptr [rax + r12 + 1], imm32 */
1242 		EMIT2(add_3mod(0x40, dst_reg, 0, index_reg), 0xC7);
1243 		break;
1244 	case BPF_DW:
1245 		/* mov qword ptr [rax + r12 + 1], imm32 */
1246 		EMIT2(add_3mod(0x48, dst_reg, 0, index_reg), 0xC7);
1247 		break;
1248 	}
1249 	emit_insn_suffix_SIB(&prog, dst_reg, 0, index_reg, off);
1250 	EMIT(imm, bpf_size_to_x86_bytes(size));
1251 	*pprog = prog;
1252 }
1253 
1254 static void emit_st_r12(u8 **pprog, u32 size, u32 dst_reg, int off, int imm)
1255 {
1256 	emit_st_index(pprog, size, dst_reg, X86_REG_R12, off, imm);
1257 }
1258 
1259 static int emit_atomic_rmw(u8 **pprog, u32 atomic_op,
1260 			   u32 dst_reg, u32 src_reg, s16 off, u8 bpf_size)
1261 {
1262 	u8 *prog = *pprog;
1263 
1264 	EMIT1(0xF0); /* lock prefix */
1265 
1266 	maybe_emit_mod(&prog, dst_reg, src_reg, bpf_size == BPF_DW);
1267 
1268 	/* emit opcode */
1269 	switch (atomic_op) {
1270 	case BPF_ADD:
1271 	case BPF_AND:
1272 	case BPF_OR:
1273 	case BPF_XOR:
1274 		/* lock *(u32/u64*)(dst_reg + off) <op>= src_reg */
1275 		EMIT1(simple_alu_opcodes[atomic_op]);
1276 		break;
1277 	case BPF_ADD | BPF_FETCH:
1278 		/* src_reg = atomic_fetch_add(dst_reg + off, src_reg); */
1279 		EMIT2(0x0F, 0xC1);
1280 		break;
1281 	case BPF_XCHG:
1282 		/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
1283 		EMIT1(0x87);
1284 		break;
1285 	case BPF_CMPXCHG:
1286 		/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
1287 		EMIT2(0x0F, 0xB1);
1288 		break;
1289 	default:
1290 		pr_err("bpf_jit: unknown atomic opcode %02x\n", atomic_op);
1291 		return -EFAULT;
1292 	}
1293 
1294 	emit_insn_suffix(&prog, dst_reg, src_reg, off);
1295 
1296 	*pprog = prog;
1297 	return 0;
1298 }
1299 
1300 static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size,
1301 				 u32 dst_reg, u32 src_reg, u32 index_reg,
1302 				 int off)
1303 {
1304 	u8 *prog = *pprog;
1305 
1306 	EMIT1(0xF0); /* lock prefix */
1307 	switch (size) {
1308 	case BPF_W:
1309 		EMIT1(add_3mod(0x40, dst_reg, src_reg, index_reg));
1310 		break;
1311 	case BPF_DW:
1312 		EMIT1(add_3mod(0x48, dst_reg, src_reg, index_reg));
1313 		break;
1314 	default:
1315 		pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
1316 		return -EFAULT;
1317 	}
1318 
1319 	/* emit opcode */
1320 	switch (atomic_op) {
1321 	case BPF_ADD:
1322 	case BPF_AND:
1323 	case BPF_OR:
1324 	case BPF_XOR:
1325 		/* lock *(u32/u64*)(dst_reg + idx_reg + off) <op>= src_reg */
1326 		EMIT1(simple_alu_opcodes[atomic_op]);
1327 		break;
1328 	case BPF_ADD | BPF_FETCH:
1329 		/* src_reg = atomic_fetch_add(dst_reg + idx_reg + off, src_reg); */
1330 		EMIT2(0x0F, 0xC1);
1331 		break;
1332 	case BPF_XCHG:
1333 		/* src_reg = atomic_xchg(dst_reg + idx_reg + off, src_reg); */
1334 		EMIT1(0x87);
1335 		break;
1336 	case BPF_CMPXCHG:
1337 		/* r0 = atomic_cmpxchg(dst_reg + idx_reg + off, r0, src_reg); */
1338 		EMIT2(0x0F, 0xB1);
1339 		break;
1340 	default:
1341 		pr_err("bpf_jit: unknown atomic opcode %02x\n", atomic_op);
1342 		return -EFAULT;
1343 	}
1344 	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off);
1345 	*pprog = prog;
1346 	return 0;
1347 }
1348 
1349 static int emit_atomic_ld_st(u8 **pprog, u32 atomic_op, u32 dst_reg,
1350 			     u32 src_reg, s16 off, u8 bpf_size)
1351 {
1352 	switch (atomic_op) {
1353 	case BPF_LOAD_ACQ:
1354 		/* dst_reg = smp_load_acquire(src_reg + off16) */
1355 		emit_ldx(pprog, bpf_size, dst_reg, src_reg, off);
1356 		break;
1357 	case BPF_STORE_REL:
1358 		/* smp_store_release(dst_reg + off16, src_reg) */
1359 		emit_stx(pprog, bpf_size, dst_reg, src_reg, off);
1360 		break;
1361 	default:
1362 		pr_err("bpf_jit: unknown atomic load/store opcode %02x\n",
1363 		       atomic_op);
1364 		return -EFAULT;
1365 	}
1366 
1367 	return 0;
1368 }
1369 
1370 static int emit_atomic_ld_st_index(u8 **pprog, u32 atomic_op, u32 size,
1371 				   u32 dst_reg, u32 src_reg, u32 index_reg,
1372 				   int off)
1373 {
1374 	switch (atomic_op) {
1375 	case BPF_LOAD_ACQ:
1376 		/* dst_reg = smp_load_acquire(src_reg + idx_reg + off16) */
1377 		emit_ldx_index(pprog, size, dst_reg, src_reg, index_reg, off);
1378 		break;
1379 	case BPF_STORE_REL:
1380 		/* smp_store_release(dst_reg + idx_reg + off16, src_reg) */
1381 		emit_stx_index(pprog, size, dst_reg, src_reg, index_reg, off);
1382 		break;
1383 	default:
1384 		pr_err("bpf_jit: unknown atomic load/store opcode %02x\n",
1385 		       atomic_op);
1386 		return -EFAULT;
1387 	}
1388 
1389 	return 0;
1390 }
1391 
1392 /*
1393  * Metadata encoding for exception handling in JITed code.
1394  *
1395  * Format of `fixup` and `data` fields in `struct exception_table_entry`:
1396  *
1397  * Bit layout of `fixup` (32-bit):
1398  *
1399  * +-----------+--------+-----------+---------+----------+
1400  * | 31        | 30-24  |   23-16   |   15-8  |    7-0   |
1401  * |           |        |           |         |          |
1402  * | ARENA_ACC | Unused | ARENA_REG | DST_REG | INSN_LEN |
1403  * +-----------+--------+-----------+---------+----------+
1404  *
1405  * - INSN_LEN (8 bits): Length of faulting insn (max x86 insn = 15 bytes (fits in 8 bits)).
1406  * - DST_REG  (8 bits): Offset of dst_reg from reg2pt_regs[] (max offset = 112 (fits in 8 bits)).
1407  *                      This is set to DONT_CLEAR if the insn is a store.
1408  * - ARENA_REG (8 bits): Offset of the register that is used to calculate the
1409  *                       address for load/store when accessing the arena region.
1410  * - ARENA_ACCESS (1 bit): This bit is set when the faulting instruction accessed the arena region.
1411  *
1412  * Bit layout of `data` (32-bit):
1413  *
1414  * +--------------+--------+--------------+
1415  * |	31-16	  |  15-8  |     7-0      |
1416  * |              |	   |              |
1417  * | ARENA_OFFSET | Unused |  EX_TYPE_BPF |
1418  * +--------------+--------+--------------+
1419  *
1420  * - ARENA_OFFSET (16 bits): Offset used to calculate the address for load/store when
1421  *                           accessing the arena region.
1422  */
1423 
1424 #define DONT_CLEAR 1
1425 #define FIXUP_INSN_LEN_MASK	GENMASK(7, 0)
1426 #define FIXUP_REG_MASK		GENMASK(15, 8)
1427 #define FIXUP_ARENA_REG_MASK	GENMASK(23, 16)
1428 #define FIXUP_ARENA_ACCESS	BIT(31)
1429 #define DATA_ARENA_OFFSET_MASK	GENMASK(31, 16)
1430 
1431 bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
1432 {
1433 	u32 reg = FIELD_GET(FIXUP_REG_MASK, x->fixup);
1434 	u32 insn_len = FIELD_GET(FIXUP_INSN_LEN_MASK, x->fixup);
1435 	bool is_arena = !!(x->fixup & FIXUP_ARENA_ACCESS);
1436 	bool is_write = (reg == DONT_CLEAR);
1437 	unsigned long addr;
1438 	s16 off;
1439 	u32 arena_reg;
1440 
1441 	if (is_arena) {
1442 		arena_reg = FIELD_GET(FIXUP_ARENA_REG_MASK, x->fixup);
1443 		off = FIELD_GET(DATA_ARENA_OFFSET_MASK, x->data);
1444 		addr = *(unsigned long *)((void *)regs + arena_reg) + off;
1445 		bpf_prog_report_arena_violation(is_write, addr, regs->ip);
1446 	}
1447 
1448 	/* jump over faulting load and clear dest register */
1449 	if (reg != DONT_CLEAR)
1450 		*(unsigned long *)((void *)regs + reg) = 0;
1451 	regs->ip += insn_len;
1452 
1453 	return true;
1454 }
1455 
1456 static void detect_reg_usage(struct bpf_insn *insn, int insn_cnt,
1457 			     bool *regs_used)
1458 {
1459 	int i;
1460 
1461 	for (i = 1; i <= insn_cnt; i++, insn++) {
1462 		if (insn->dst_reg == BPF_REG_6 || insn->src_reg == BPF_REG_6)
1463 			regs_used[0] = true;
1464 		if (insn->dst_reg == BPF_REG_7 || insn->src_reg == BPF_REG_7)
1465 			regs_used[1] = true;
1466 		if (insn->dst_reg == BPF_REG_8 || insn->src_reg == BPF_REG_8)
1467 			regs_used[2] = true;
1468 		if (insn->dst_reg == BPF_REG_9 || insn->src_reg == BPF_REG_9)
1469 			regs_used[3] = true;
1470 	}
1471 }
1472 
1473 /* emit the 3-byte VEX prefix
1474  *
1475  * r: same as rex.r, extra bit for ModRM reg field
1476  * x: same as rex.x, extra bit for SIB index field
1477  * b: same as rex.b, extra bit for ModRM r/m, or SIB base
1478  * m: opcode map select, encoding escape bytes e.g. 0x0f38
1479  * w: same as rex.w (32 bit or 64 bit) or opcode specific
1480  * src_reg2: additional source reg (encoded as BPF reg)
1481  * l: vector length (128 bit or 256 bit) or reserved
1482  * pp: opcode prefix (none, 0x66, 0xf2 or 0xf3)
1483  */
1484 static void emit_3vex(u8 **pprog, bool r, bool x, bool b, u8 m,
1485 		      bool w, u8 src_reg2, bool l, u8 pp)
1486 {
1487 	u8 *prog = *pprog;
1488 	const u8 b0 = 0xc4; /* first byte of 3-byte VEX prefix */
1489 	u8 b1, b2;
1490 	u8 vvvv = reg2hex[src_reg2];
1491 
1492 	/* reg2hex gives only the lower 3 bit of vvvv */
1493 	if (is_ereg(src_reg2))
1494 		vvvv |= 1 << 3;
1495 
1496 	/*
1497 	 * 2nd byte of 3-byte VEX prefix
1498 	 * ~ means bit inverted encoding
1499 	 *
1500 	 *    7                           0
1501 	 *  +---+---+---+---+---+---+---+---+
1502 	 *  |~R |~X |~B |         m         |
1503 	 *  +---+---+---+---+---+---+---+---+
1504 	 */
1505 	b1 = (!r << 7) | (!x << 6) | (!b << 5) | (m & 0x1f);
1506 	/*
1507 	 * 3rd byte of 3-byte VEX prefix
1508 	 *
1509 	 *    7                           0
1510 	 *  +---+---+---+---+---+---+---+---+
1511 	 *  | W |     ~vvvv     | L |   pp  |
1512 	 *  +---+---+---+---+---+---+---+---+
1513 	 */
1514 	b2 = (w << 7) | ((~vvvv & 0xf) << 3) | (l << 2) | (pp & 3);
1515 
1516 	EMIT3(b0, b1, b2);
1517 	*pprog = prog;
1518 }
1519 
1520 /* emit BMI2 shift instruction */
1521 static void emit_shiftx(u8 **pprog, u32 dst_reg, u8 src_reg, bool is64, u8 op)
1522 {
1523 	u8 *prog = *pprog;
1524 	bool r = is_ereg(dst_reg);
1525 	u8 m = 2; /* escape code 0f38 */
1526 
1527 	emit_3vex(&prog, r, false, r, m, is64, src_reg, false, op);
1528 	EMIT2(0xf7, add_2reg(0xC0, dst_reg, dst_reg));
1529 	*pprog = prog;
1530 }
1531 
1532 static void emit_priv_frame_ptr(u8 **pprog, void __percpu *priv_frame_ptr)
1533 {
1534 	u8 *prog = *pprog;
1535 
1536 	/* movabs r9, priv_frame_ptr */
1537 	emit_mov_imm64(&prog, X86_REG_R9, (__force long) priv_frame_ptr >> 32,
1538 		       (u32) (__force long) priv_frame_ptr);
1539 
1540 #ifdef CONFIG_SMP
1541 	/* add <r9>, gs:[<off>] */
1542 	EMIT2(0x65, 0x4c);
1543 	EMIT3(0x03, 0x0c, 0x25);
1544 	EMIT((u32)(unsigned long)&this_cpu_off, 4);
1545 #endif
1546 
1547 	*pprog = prog;
1548 }
1549 
1550 #define INSN_SZ_DIFF (((addrs[i] - addrs[i - 1]) - (prog - temp)))
1551 
1552 #define __LOAD_TCC_PTR(off)			\
1553 	EMIT3_off32(0x48, 0x8B, 0x85, off)
1554 /* mov rax, qword ptr [rbp - rounded_stack_depth - 16] */
1555 #define LOAD_TAIL_CALL_CNT_PTR(stack)				\
1556 	__LOAD_TCC_PTR(BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack))
1557 
1558 /* Memory size/value to protect private stack overflow/underflow */
1559 #define PRIV_STACK_GUARD_SZ    8
1560 #define PRIV_STACK_GUARD_VAL   0xEB9F12345678eb9fULL
1561 
1562 static int emit_spectre_bhb_barrier(u8 **pprog, u8 *ip,
1563 				    struct bpf_prog *bpf_prog)
1564 {
1565 	u8 *prog = *pprog;
1566 	u8 *func;
1567 
1568 	if (cpu_feature_enabled(X86_FEATURE_CLEAR_BHB_LOOP)) {
1569 		/* The clearing sequence clobbers eax and ecx. */
1570 		EMIT1(0x50); /* push rax */
1571 		EMIT1(0x51); /* push rcx */
1572 		ip += 2;
1573 
1574 		func = (u8 *)clear_bhb_loop;
1575 		ip += x86_call_depth_emit_accounting(&prog, func, ip);
1576 
1577 		if (emit_call(&prog, func, ip))
1578 			return -EINVAL;
1579 		EMIT1(0x59); /* pop rcx */
1580 		EMIT1(0x58); /* pop rax */
1581 	}
1582 	/* Insert IBHF instruction */
1583 	if ((cpu_feature_enabled(X86_FEATURE_CLEAR_BHB_LOOP) &&
1584 	     cpu_feature_enabled(X86_FEATURE_HYPERVISOR)) ||
1585 	    cpu_feature_enabled(X86_FEATURE_CLEAR_BHB_HW)) {
1586 		/*
1587 		 * Add an Indirect Branch History Fence (IBHF). IBHF acts as a
1588 		 * fence preventing branch history from before the fence from
1589 		 * affecting indirect branches after the fence. This is
1590 		 * specifically used in cBPF jitted code to prevent Intra-mode
1591 		 * BHI attacks. The IBHF instruction is designed to be a NOP on
1592 		 * hardware that doesn't need or support it.  The REP and REX.W
1593 		 * prefixes are required by the microcode, and they also ensure
1594 		 * that the NOP is unlikely to be used in existing code.
1595 		 *
1596 		 * IBHF is not a valid instruction in 32-bit mode.
1597 		 */
1598 		EMIT5(0xF3, 0x48, 0x0F, 0x1E, 0xF8); /* ibhf */
1599 	}
1600 	*pprog = prog;
1601 	return 0;
1602 }
1603 
1604 static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image, u8 *rw_image,
1605 		  int oldproglen, struct jit_context *ctx, bool jmp_padding)
1606 {
1607 	bool tail_call_reachable = bpf_prog->aux->tail_call_reachable;
1608 	struct bpf_insn *insn = bpf_prog->insnsi;
1609 	bool callee_regs_used[4] = {};
1610 	int insn_cnt = bpf_prog->len;
1611 	bool seen_exit = false;
1612 	u8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY];
1613 	void __percpu *priv_frame_ptr = NULL;
1614 	u64 arena_vm_start, user_vm_start;
1615 	void __percpu *priv_stack_ptr;
1616 	int i, excnt = 0;
1617 	int ilen, proglen = 0;
1618 	u8 *prog = temp;
1619 	u32 stack_depth;
1620 	int err;
1621 
1622 	stack_depth = bpf_prog->aux->stack_depth;
1623 	priv_stack_ptr = bpf_prog->aux->priv_stack_ptr;
1624 	if (priv_stack_ptr) {
1625 		priv_frame_ptr = priv_stack_ptr + PRIV_STACK_GUARD_SZ + round_up(stack_depth, 8);
1626 		stack_depth = 0;
1627 	}
1628 
1629 	arena_vm_start = bpf_arena_get_kern_vm_start(bpf_prog->aux->arena);
1630 	user_vm_start = bpf_arena_get_user_vm_start(bpf_prog->aux->arena);
1631 
1632 	detect_reg_usage(insn, insn_cnt, callee_regs_used);
1633 
1634 	emit_prologue(&prog, image, stack_depth,
1635 		      bpf_prog_was_classic(bpf_prog), tail_call_reachable,
1636 		      bpf_is_subprog(bpf_prog), bpf_prog->aux->exception_cb);
1637 	/* Exception callback will clobber callee regs for its own use, and
1638 	 * restore the original callee regs from main prog's stack frame.
1639 	 */
1640 	if (bpf_prog->aux->exception_boundary) {
1641 		/* We also need to save r12, which is not mapped to any BPF
1642 		 * register, as we throw after entry into the kernel, which may
1643 		 * overwrite r12.
1644 		 */
1645 		push_r12(&prog);
1646 		push_callee_regs(&prog, all_callee_regs_used);
1647 	} else {
1648 		if (arena_vm_start)
1649 			push_r12(&prog);
1650 		push_callee_regs(&prog, callee_regs_used);
1651 	}
1652 	if (arena_vm_start)
1653 		emit_mov_imm64(&prog, X86_REG_R12,
1654 			       arena_vm_start >> 32, (u32) arena_vm_start);
1655 
1656 	if (priv_frame_ptr)
1657 		emit_priv_frame_ptr(&prog, priv_frame_ptr);
1658 
1659 	ilen = prog - temp;
1660 	if (rw_image)
1661 		memcpy(rw_image + proglen, temp, ilen);
1662 	proglen += ilen;
1663 	addrs[0] = proglen;
1664 	prog = temp;
1665 
1666 	for (i = 1; i <= insn_cnt; i++, insn++) {
1667 		const s32 imm32 = insn->imm;
1668 		u32 dst_reg = insn->dst_reg;
1669 		u32 src_reg = insn->src_reg;
1670 		u8 b2 = 0, b3 = 0;
1671 		u8 *start_of_ldx;
1672 		s64 jmp_offset;
1673 		s16 insn_off;
1674 		u8 jmp_cond;
1675 		u8 *func;
1676 		int nops;
1677 
1678 		if (priv_frame_ptr) {
1679 			if (src_reg == BPF_REG_FP)
1680 				src_reg = X86_REG_R9;
1681 
1682 			if (dst_reg == BPF_REG_FP)
1683 				dst_reg = X86_REG_R9;
1684 		}
1685 
1686 		switch (insn->code) {
1687 			/* ALU */
1688 		case BPF_ALU | BPF_ADD | BPF_X:
1689 		case BPF_ALU | BPF_SUB | BPF_X:
1690 		case BPF_ALU | BPF_AND | BPF_X:
1691 		case BPF_ALU | BPF_OR | BPF_X:
1692 		case BPF_ALU | BPF_XOR | BPF_X:
1693 		case BPF_ALU64 | BPF_ADD | BPF_X:
1694 		case BPF_ALU64 | BPF_SUB | BPF_X:
1695 		case BPF_ALU64 | BPF_AND | BPF_X:
1696 		case BPF_ALU64 | BPF_OR | BPF_X:
1697 		case BPF_ALU64 | BPF_XOR | BPF_X:
1698 			maybe_emit_mod(&prog, dst_reg, src_reg,
1699 				       BPF_CLASS(insn->code) == BPF_ALU64);
1700 			b2 = simple_alu_opcodes[BPF_OP(insn->code)];
1701 			EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg));
1702 			break;
1703 
1704 		case BPF_ALU64 | BPF_MOV | BPF_X:
1705 			if (insn_is_cast_user(insn)) {
1706 				if (dst_reg != src_reg)
1707 					/* 32-bit mov */
1708 					emit_mov_reg(&prog, false, dst_reg, src_reg);
1709 				/* shl dst_reg, 32 */
1710 				maybe_emit_1mod(&prog, dst_reg, true);
1711 				EMIT3(0xC1, add_1reg(0xE0, dst_reg), 32);
1712 
1713 				/* or dst_reg, user_vm_start */
1714 				maybe_emit_1mod(&prog, dst_reg, true);
1715 				if (is_axreg(dst_reg))
1716 					EMIT1_off32(0x0D,  user_vm_start >> 32);
1717 				else
1718 					EMIT2_off32(0x81, add_1reg(0xC8, dst_reg),  user_vm_start >> 32);
1719 
1720 				/* rol dst_reg, 32 */
1721 				maybe_emit_1mod(&prog, dst_reg, true);
1722 				EMIT3(0xC1, add_1reg(0xC0, dst_reg), 32);
1723 
1724 				/* xor r11, r11 */
1725 				EMIT3(0x4D, 0x31, 0xDB);
1726 
1727 				/* test dst_reg32, dst_reg32; check if lower 32-bit are zero */
1728 				maybe_emit_mod(&prog, dst_reg, dst_reg, false);
1729 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
1730 
1731 				/* cmove r11, dst_reg; if so, set dst_reg to zero */
1732 				/* WARNING: Intel swapped src/dst register encoding in CMOVcc !!! */
1733 				maybe_emit_mod(&prog, AUX_REG, dst_reg, true);
1734 				EMIT3(0x0F, 0x44, add_2reg(0xC0, AUX_REG, dst_reg));
1735 				break;
1736 			} else if (insn_is_mov_percpu_addr(insn)) {
1737 				/* mov <dst>, <src> (if necessary) */
1738 				EMIT_mov(dst_reg, src_reg);
1739 #ifdef CONFIG_SMP
1740 				/* add <dst>, gs:[<off>] */
1741 				EMIT2(0x65, add_1mod(0x48, dst_reg));
1742 				EMIT3(0x03, add_2reg(0x04, 0, dst_reg), 0x25);
1743 				EMIT((u32)(unsigned long)&this_cpu_off, 4);
1744 #endif
1745 				break;
1746 			}
1747 			fallthrough;
1748 		case BPF_ALU | BPF_MOV | BPF_X:
1749 			if (insn->off == 0)
1750 				emit_mov_reg(&prog,
1751 					     BPF_CLASS(insn->code) == BPF_ALU64,
1752 					     dst_reg, src_reg);
1753 			else
1754 				emit_movsx_reg(&prog, insn->off,
1755 					       BPF_CLASS(insn->code) == BPF_ALU64,
1756 					       dst_reg, src_reg);
1757 			break;
1758 
1759 			/* neg dst */
1760 		case BPF_ALU | BPF_NEG:
1761 		case BPF_ALU64 | BPF_NEG:
1762 			maybe_emit_1mod(&prog, dst_reg,
1763 					BPF_CLASS(insn->code) == BPF_ALU64);
1764 			EMIT2(0xF7, add_1reg(0xD8, dst_reg));
1765 			break;
1766 
1767 		case BPF_ALU | BPF_ADD | BPF_K:
1768 		case BPF_ALU | BPF_SUB | BPF_K:
1769 		case BPF_ALU | BPF_AND | BPF_K:
1770 		case BPF_ALU | BPF_OR | BPF_K:
1771 		case BPF_ALU | BPF_XOR | BPF_K:
1772 		case BPF_ALU64 | BPF_ADD | BPF_K:
1773 		case BPF_ALU64 | BPF_SUB | BPF_K:
1774 		case BPF_ALU64 | BPF_AND | BPF_K:
1775 		case BPF_ALU64 | BPF_OR | BPF_K:
1776 		case BPF_ALU64 | BPF_XOR | BPF_K:
1777 			maybe_emit_1mod(&prog, dst_reg,
1778 					BPF_CLASS(insn->code) == BPF_ALU64);
1779 
1780 			/*
1781 			 * b3 holds 'normal' opcode, b2 short form only valid
1782 			 * in case dst is eax/rax.
1783 			 */
1784 			switch (BPF_OP(insn->code)) {
1785 			case BPF_ADD:
1786 				b3 = 0xC0;
1787 				b2 = 0x05;
1788 				break;
1789 			case BPF_SUB:
1790 				b3 = 0xE8;
1791 				b2 = 0x2D;
1792 				break;
1793 			case BPF_AND:
1794 				b3 = 0xE0;
1795 				b2 = 0x25;
1796 				break;
1797 			case BPF_OR:
1798 				b3 = 0xC8;
1799 				b2 = 0x0D;
1800 				break;
1801 			case BPF_XOR:
1802 				b3 = 0xF0;
1803 				b2 = 0x35;
1804 				break;
1805 			}
1806 
1807 			if (is_imm8(imm32))
1808 				EMIT3(0x83, add_1reg(b3, dst_reg), imm32);
1809 			else if (is_axreg(dst_reg))
1810 				EMIT1_off32(b2, imm32);
1811 			else
1812 				EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32);
1813 			break;
1814 
1815 		case BPF_ALU64 | BPF_MOV | BPF_K:
1816 		case BPF_ALU | BPF_MOV | BPF_K:
1817 			emit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64,
1818 				       dst_reg, imm32);
1819 			break;
1820 
1821 		case BPF_LD | BPF_IMM | BPF_DW:
1822 			emit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm);
1823 			insn++;
1824 			i++;
1825 			break;
1826 
1827 			/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */
1828 		case BPF_ALU | BPF_MOD | BPF_X:
1829 		case BPF_ALU | BPF_DIV | BPF_X:
1830 		case BPF_ALU | BPF_MOD | BPF_K:
1831 		case BPF_ALU | BPF_DIV | BPF_K:
1832 		case BPF_ALU64 | BPF_MOD | BPF_X:
1833 		case BPF_ALU64 | BPF_DIV | BPF_X:
1834 		case BPF_ALU64 | BPF_MOD | BPF_K:
1835 		case BPF_ALU64 | BPF_DIV | BPF_K: {
1836 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
1837 
1838 			if (dst_reg != BPF_REG_0)
1839 				EMIT1(0x50); /* push rax */
1840 			if (dst_reg != BPF_REG_3)
1841 				EMIT1(0x52); /* push rdx */
1842 
1843 			if (BPF_SRC(insn->code) == BPF_X) {
1844 				if (src_reg == BPF_REG_0 ||
1845 				    src_reg == BPF_REG_3) {
1846 					/* mov r11, src_reg */
1847 					EMIT_mov(AUX_REG, src_reg);
1848 					src_reg = AUX_REG;
1849 				}
1850 			} else {
1851 				/* mov r11, imm32 */
1852 				EMIT3_off32(0x49, 0xC7, 0xC3, imm32);
1853 				src_reg = AUX_REG;
1854 			}
1855 
1856 			if (dst_reg != BPF_REG_0)
1857 				/* mov rax, dst_reg */
1858 				emit_mov_reg(&prog, is64, BPF_REG_0, dst_reg);
1859 
1860 			if (insn->off == 0) {
1861 				/*
1862 				 * xor edx, edx
1863 				 * equivalent to 'xor rdx, rdx', but one byte less
1864 				 */
1865 				EMIT2(0x31, 0xd2);
1866 
1867 				/* div src_reg */
1868 				maybe_emit_1mod(&prog, src_reg, is64);
1869 				EMIT2(0xF7, add_1reg(0xF0, src_reg));
1870 			} else {
1871 				if (BPF_CLASS(insn->code) == BPF_ALU)
1872 					EMIT1(0x99); /* cdq */
1873 				else
1874 					EMIT2(0x48, 0x99); /* cqo */
1875 
1876 				/* idiv src_reg */
1877 				maybe_emit_1mod(&prog, src_reg, is64);
1878 				EMIT2(0xF7, add_1reg(0xF8, src_reg));
1879 			}
1880 
1881 			if (BPF_OP(insn->code) == BPF_MOD &&
1882 			    dst_reg != BPF_REG_3)
1883 				/* mov dst_reg, rdx */
1884 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_3);
1885 			else if (BPF_OP(insn->code) == BPF_DIV &&
1886 				 dst_reg != BPF_REG_0)
1887 				/* mov dst_reg, rax */
1888 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_0);
1889 
1890 			if (dst_reg != BPF_REG_3)
1891 				EMIT1(0x5A); /* pop rdx */
1892 			if (dst_reg != BPF_REG_0)
1893 				EMIT1(0x58); /* pop rax */
1894 			break;
1895 		}
1896 
1897 		case BPF_ALU | BPF_MUL | BPF_K:
1898 		case BPF_ALU64 | BPF_MUL | BPF_K:
1899 			maybe_emit_mod(&prog, dst_reg, dst_reg,
1900 				       BPF_CLASS(insn->code) == BPF_ALU64);
1901 
1902 			if (is_imm8(imm32))
1903 				/* imul dst_reg, dst_reg, imm8 */
1904 				EMIT3(0x6B, add_2reg(0xC0, dst_reg, dst_reg),
1905 				      imm32);
1906 			else
1907 				/* imul dst_reg, dst_reg, imm32 */
1908 				EMIT2_off32(0x69,
1909 					    add_2reg(0xC0, dst_reg, dst_reg),
1910 					    imm32);
1911 			break;
1912 
1913 		case BPF_ALU | BPF_MUL | BPF_X:
1914 		case BPF_ALU64 | BPF_MUL | BPF_X:
1915 			maybe_emit_mod(&prog, src_reg, dst_reg,
1916 				       BPF_CLASS(insn->code) == BPF_ALU64);
1917 
1918 			/* imul dst_reg, src_reg */
1919 			EMIT3(0x0F, 0xAF, add_2reg(0xC0, src_reg, dst_reg));
1920 			break;
1921 
1922 			/* Shifts */
1923 		case BPF_ALU | BPF_LSH | BPF_K:
1924 		case BPF_ALU | BPF_RSH | BPF_K:
1925 		case BPF_ALU | BPF_ARSH | BPF_K:
1926 		case BPF_ALU64 | BPF_LSH | BPF_K:
1927 		case BPF_ALU64 | BPF_RSH | BPF_K:
1928 		case BPF_ALU64 | BPF_ARSH | BPF_K:
1929 			maybe_emit_1mod(&prog, dst_reg,
1930 					BPF_CLASS(insn->code) == BPF_ALU64);
1931 
1932 			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
1933 			if (imm32 == 1)
1934 				EMIT2(0xD1, add_1reg(b3, dst_reg));
1935 			else
1936 				EMIT3(0xC1, add_1reg(b3, dst_reg), imm32);
1937 			break;
1938 
1939 		case BPF_ALU | BPF_LSH | BPF_X:
1940 		case BPF_ALU | BPF_RSH | BPF_X:
1941 		case BPF_ALU | BPF_ARSH | BPF_X:
1942 		case BPF_ALU64 | BPF_LSH | BPF_X:
1943 		case BPF_ALU64 | BPF_RSH | BPF_X:
1944 		case BPF_ALU64 | BPF_ARSH | BPF_X:
1945 			/* BMI2 shifts aren't better when shift count is already in rcx */
1946 			if (boot_cpu_has(X86_FEATURE_BMI2) && src_reg != BPF_REG_4) {
1947 				/* shrx/sarx/shlx dst_reg, dst_reg, src_reg */
1948 				bool w = (BPF_CLASS(insn->code) == BPF_ALU64);
1949 				u8 op;
1950 
1951 				switch (BPF_OP(insn->code)) {
1952 				case BPF_LSH:
1953 					op = 1; /* prefix 0x66 */
1954 					break;
1955 				case BPF_RSH:
1956 					op = 3; /* prefix 0xf2 */
1957 					break;
1958 				case BPF_ARSH:
1959 					op = 2; /* prefix 0xf3 */
1960 					break;
1961 				}
1962 
1963 				emit_shiftx(&prog, dst_reg, src_reg, w, op);
1964 
1965 				break;
1966 			}
1967 
1968 			if (src_reg != BPF_REG_4) { /* common case */
1969 				/* Check for bad case when dst_reg == rcx */
1970 				if (dst_reg == BPF_REG_4) {
1971 					/* mov r11, dst_reg */
1972 					EMIT_mov(AUX_REG, dst_reg);
1973 					dst_reg = AUX_REG;
1974 				} else {
1975 					EMIT1(0x51); /* push rcx */
1976 				}
1977 				/* mov rcx, src_reg */
1978 				EMIT_mov(BPF_REG_4, src_reg);
1979 			}
1980 
1981 			/* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */
1982 			maybe_emit_1mod(&prog, dst_reg,
1983 					BPF_CLASS(insn->code) == BPF_ALU64);
1984 
1985 			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
1986 			EMIT2(0xD3, add_1reg(b3, dst_reg));
1987 
1988 			if (src_reg != BPF_REG_4) {
1989 				if (insn->dst_reg == BPF_REG_4)
1990 					/* mov dst_reg, r11 */
1991 					EMIT_mov(insn->dst_reg, AUX_REG);
1992 				else
1993 					EMIT1(0x59); /* pop rcx */
1994 			}
1995 
1996 			break;
1997 
1998 		case BPF_ALU | BPF_END | BPF_FROM_BE:
1999 		case BPF_ALU64 | BPF_END | BPF_FROM_LE:
2000 			switch (imm32) {
2001 			case 16:
2002 				/* Emit 'ror %ax, 8' to swap lower 2 bytes */
2003 				EMIT1(0x66);
2004 				if (is_ereg(dst_reg))
2005 					EMIT1(0x41);
2006 				EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8);
2007 
2008 				/* Emit 'movzwl eax, ax' */
2009 				if (is_ereg(dst_reg))
2010 					EMIT3(0x45, 0x0F, 0xB7);
2011 				else
2012 					EMIT2(0x0F, 0xB7);
2013 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
2014 				break;
2015 			case 32:
2016 				/* Emit 'bswap eax' to swap lower 4 bytes */
2017 				if (is_ereg(dst_reg))
2018 					EMIT2(0x41, 0x0F);
2019 				else
2020 					EMIT1(0x0F);
2021 				EMIT1(add_1reg(0xC8, dst_reg));
2022 				break;
2023 			case 64:
2024 				/* Emit 'bswap rax' to swap 8 bytes */
2025 				EMIT3(add_1mod(0x48, dst_reg), 0x0F,
2026 				      add_1reg(0xC8, dst_reg));
2027 				break;
2028 			}
2029 			break;
2030 
2031 		case BPF_ALU | BPF_END | BPF_FROM_LE:
2032 			switch (imm32) {
2033 			case 16:
2034 				/*
2035 				 * Emit 'movzwl eax, ax' to zero extend 16-bit
2036 				 * into 64 bit
2037 				 */
2038 				if (is_ereg(dst_reg))
2039 					EMIT3(0x45, 0x0F, 0xB7);
2040 				else
2041 					EMIT2(0x0F, 0xB7);
2042 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
2043 				break;
2044 			case 32:
2045 				/* Emit 'mov eax, eax' to clear upper 32-bits */
2046 				if (is_ereg(dst_reg))
2047 					EMIT1(0x45);
2048 				EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg));
2049 				break;
2050 			case 64:
2051 				/* nop */
2052 				break;
2053 			}
2054 			break;
2055 
2056 			/* speculation barrier */
2057 		case BPF_ST | BPF_NOSPEC:
2058 			EMIT_LFENCE();
2059 			break;
2060 
2061 			/* ST: *(u8*)(dst_reg + off) = imm */
2062 		case BPF_ST | BPF_MEM | BPF_B:
2063 			if (is_ereg(dst_reg))
2064 				EMIT2(0x41, 0xC6);
2065 			else
2066 				EMIT1(0xC6);
2067 			goto st;
2068 		case BPF_ST | BPF_MEM | BPF_H:
2069 			if (is_ereg(dst_reg))
2070 				EMIT3(0x66, 0x41, 0xC7);
2071 			else
2072 				EMIT2(0x66, 0xC7);
2073 			goto st;
2074 		case BPF_ST | BPF_MEM | BPF_W:
2075 			if (is_ereg(dst_reg))
2076 				EMIT2(0x41, 0xC7);
2077 			else
2078 				EMIT1(0xC7);
2079 			goto st;
2080 		case BPF_ST | BPF_MEM | BPF_DW:
2081 			EMIT2(add_1mod(0x48, dst_reg), 0xC7);
2082 
2083 st:			if (is_imm8(insn->off))
2084 				EMIT2(add_1reg(0x40, dst_reg), insn->off);
2085 			else
2086 				EMIT1_off32(add_1reg(0x80, dst_reg), insn->off);
2087 
2088 			EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));
2089 			break;
2090 
2091 			/* STX: *(u8*)(dst_reg + off) = src_reg */
2092 		case BPF_STX | BPF_MEM | BPF_B:
2093 		case BPF_STX | BPF_MEM | BPF_H:
2094 		case BPF_STX | BPF_MEM | BPF_W:
2095 		case BPF_STX | BPF_MEM | BPF_DW:
2096 			emit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2097 			break;
2098 
2099 		case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
2100 		case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
2101 		case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
2102 		case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
2103 			start_of_ldx = prog;
2104 			emit_st_r12(&prog, BPF_SIZE(insn->code), dst_reg, insn->off, insn->imm);
2105 			goto populate_extable;
2106 
2107 			/* LDX: dst_reg = *(u8*)(src_reg + r12 + off) */
2108 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_B:
2109 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
2110 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
2111 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
2112 		case BPF_STX | BPF_PROBE_MEM32 | BPF_B:
2113 		case BPF_STX | BPF_PROBE_MEM32 | BPF_H:
2114 		case BPF_STX | BPF_PROBE_MEM32 | BPF_W:
2115 		case BPF_STX | BPF_PROBE_MEM32 | BPF_DW:
2116 			start_of_ldx = prog;
2117 			if (BPF_CLASS(insn->code) == BPF_LDX)
2118 				emit_ldx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2119 			else
2120 				emit_stx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2121 populate_extable:
2122 			{
2123 				struct exception_table_entry *ex;
2124 				u8 *_insn = image + proglen + (start_of_ldx - temp);
2125 				u32 arena_reg, fixup_reg;
2126 				s64 delta;
2127 
2128 				if (!bpf_prog->aux->extable)
2129 					break;
2130 
2131 				if (excnt >= bpf_prog->aux->num_exentries) {
2132 					pr_err("mem32 extable bug\n");
2133 					return -EFAULT;
2134 				}
2135 				ex = &bpf_prog->aux->extable[excnt++];
2136 
2137 				delta = _insn - (u8 *)&ex->insn;
2138 				/* switch ex to rw buffer for writes */
2139 				ex = (void *)rw_image + ((void *)ex - (void *)image);
2140 
2141 				ex->insn = delta;
2142 
2143 				ex->data = EX_TYPE_BPF;
2144 
2145 				/*
2146 				 * src_reg/dst_reg holds the address in the arena region with upper
2147 				 * 32-bits being zero because of a preceding addr_space_cast(r<n>,
2148 				 * 0x0, 0x1) instruction. This address is adjusted with the addition
2149 				 * of arena_vm_start (see the implementation of BPF_PROBE_MEM32 and
2150 				 * BPF_PROBE_ATOMIC) before being used for the memory access. Pass
2151 				 * the reg holding the unmodified 32-bit address to
2152 				 * ex_handler_bpf().
2153 				 */
2154 				if (BPF_CLASS(insn->code) == BPF_LDX) {
2155 					arena_reg = reg2pt_regs[src_reg];
2156 					fixup_reg = reg2pt_regs[dst_reg];
2157 				} else {
2158 					arena_reg = reg2pt_regs[dst_reg];
2159 					fixup_reg = DONT_CLEAR;
2160 				}
2161 
2162 				ex->fixup = FIELD_PREP(FIXUP_INSN_LEN_MASK, prog - start_of_ldx) |
2163 					    FIELD_PREP(FIXUP_ARENA_REG_MASK, arena_reg) |
2164 					    FIELD_PREP(FIXUP_REG_MASK, fixup_reg);
2165 				ex->fixup |= FIXUP_ARENA_ACCESS;
2166 
2167 				ex->data |= FIELD_PREP(DATA_ARENA_OFFSET_MASK, insn->off);
2168 			}
2169 			break;
2170 
2171 			/* LDX: dst_reg = *(u8*)(src_reg + off) */
2172 		case BPF_LDX | BPF_MEM | BPF_B:
2173 		case BPF_LDX | BPF_PROBE_MEM | BPF_B:
2174 		case BPF_LDX | BPF_MEM | BPF_H:
2175 		case BPF_LDX | BPF_PROBE_MEM | BPF_H:
2176 		case BPF_LDX | BPF_MEM | BPF_W:
2177 		case BPF_LDX | BPF_PROBE_MEM | BPF_W:
2178 		case BPF_LDX | BPF_MEM | BPF_DW:
2179 		case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
2180 			/* LDXS: dst_reg = *(s8*)(src_reg + off) */
2181 		case BPF_LDX | BPF_MEMSX | BPF_B:
2182 		case BPF_LDX | BPF_MEMSX | BPF_H:
2183 		case BPF_LDX | BPF_MEMSX | BPF_W:
2184 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
2185 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
2186 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
2187 			insn_off = insn->off;
2188 
2189 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
2190 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
2191 				/* Conservatively check that src_reg + insn->off is a kernel address:
2192 				 *   src_reg + insn->off > TASK_SIZE_MAX + PAGE_SIZE
2193 				 *   and
2194 				 *   src_reg + insn->off < VSYSCALL_ADDR
2195 				 */
2196 
2197 				u64 limit = TASK_SIZE_MAX + PAGE_SIZE - VSYSCALL_ADDR;
2198 				u8 *end_of_jmp;
2199 
2200 				/* movabsq r10, VSYSCALL_ADDR */
2201 				emit_mov_imm64(&prog, BPF_REG_AX, (long)VSYSCALL_ADDR >> 32,
2202 					       (u32)(long)VSYSCALL_ADDR);
2203 
2204 				/* mov src_reg, r11 */
2205 				EMIT_mov(AUX_REG, src_reg);
2206 
2207 				if (insn->off) {
2208 					/* add r11, insn->off */
2209 					maybe_emit_1mod(&prog, AUX_REG, true);
2210 					EMIT2_off32(0x81, add_1reg(0xC0, AUX_REG), insn->off);
2211 				}
2212 
2213 				/* sub r11, r10 */
2214 				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
2215 				EMIT2(0x29, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
2216 
2217 				/* movabsq r10, limit */
2218 				emit_mov_imm64(&prog, BPF_REG_AX, (long)limit >> 32,
2219 					       (u32)(long)limit);
2220 
2221 				/* cmp r10, r11 */
2222 				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
2223 				EMIT2(0x39, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
2224 
2225 				/* if unsigned '>', goto load */
2226 				EMIT2(X86_JA, 0);
2227 				end_of_jmp = prog;
2228 
2229 				/* xor dst_reg, dst_reg */
2230 				emit_mov_imm32(&prog, false, dst_reg, 0);
2231 				/* jmp byte_after_ldx */
2232 				EMIT2(0xEB, 0);
2233 
2234 				/* populate jmp_offset for JAE above to jump to start_of_ldx */
2235 				start_of_ldx = prog;
2236 				end_of_jmp[-1] = start_of_ldx - end_of_jmp;
2237 			}
2238 			if (BPF_MODE(insn->code) == BPF_PROBE_MEMSX ||
2239 			    BPF_MODE(insn->code) == BPF_MEMSX)
2240 				emit_ldsx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
2241 			else
2242 				emit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
2243 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
2244 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
2245 				struct exception_table_entry *ex;
2246 				u8 *_insn = image + proglen + (start_of_ldx - temp);
2247 				s64 delta;
2248 
2249 				/* populate jmp_offset for JMP above */
2250 				start_of_ldx[-1] = prog - start_of_ldx;
2251 
2252 				if (!bpf_prog->aux->extable)
2253 					break;
2254 
2255 				if (excnt >= bpf_prog->aux->num_exentries) {
2256 					pr_err("ex gen bug\n");
2257 					return -EFAULT;
2258 				}
2259 				ex = &bpf_prog->aux->extable[excnt++];
2260 
2261 				delta = _insn - (u8 *)&ex->insn;
2262 				if (!is_simm32(delta)) {
2263 					pr_err("extable->insn doesn't fit into 32-bit\n");
2264 					return -EFAULT;
2265 				}
2266 				/* switch ex to rw buffer for writes */
2267 				ex = (void *)rw_image + ((void *)ex - (void *)image);
2268 
2269 				ex->insn = delta;
2270 
2271 				ex->data = EX_TYPE_BPF;
2272 
2273 				if (dst_reg > BPF_REG_9) {
2274 					pr_err("verifier error\n");
2275 					return -EFAULT;
2276 				}
2277 				/*
2278 				 * Compute size of x86 insn and its target dest x86 register.
2279 				 * ex_handler_bpf() will use lower 8 bits to adjust
2280 				 * pt_regs->ip to jump over this x86 instruction
2281 				 * and upper bits to figure out which pt_regs to zero out.
2282 				 * End result: x86 insn "mov rbx, qword ptr [rax+0x14]"
2283 				 * of 4 bytes will be ignored and rbx will be zero inited.
2284 				 */
2285 				ex->fixup = FIELD_PREP(FIXUP_INSN_LEN_MASK, prog - start_of_ldx) |
2286 					    FIELD_PREP(FIXUP_REG_MASK, reg2pt_regs[dst_reg]);
2287 			}
2288 			break;
2289 
2290 		case BPF_STX | BPF_ATOMIC | BPF_B:
2291 		case BPF_STX | BPF_ATOMIC | BPF_H:
2292 			if (!bpf_atomic_is_load_store(insn)) {
2293 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
2294 				return -EFAULT;
2295 			}
2296 			fallthrough;
2297 		case BPF_STX | BPF_ATOMIC | BPF_W:
2298 		case BPF_STX | BPF_ATOMIC | BPF_DW:
2299 			if (insn->imm == (BPF_AND | BPF_FETCH) ||
2300 			    insn->imm == (BPF_OR | BPF_FETCH) ||
2301 			    insn->imm == (BPF_XOR | BPF_FETCH)) {
2302 				bool is64 = BPF_SIZE(insn->code) == BPF_DW;
2303 				u32 real_src_reg = src_reg;
2304 				u32 real_dst_reg = dst_reg;
2305 				u8 *branch_target;
2306 
2307 				/*
2308 				 * Can't be implemented with a single x86 insn.
2309 				 * Need to do a CMPXCHG loop.
2310 				 */
2311 
2312 				/* Will need RAX as a CMPXCHG operand so save R0 */
2313 				emit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0);
2314 				if (src_reg == BPF_REG_0)
2315 					real_src_reg = BPF_REG_AX;
2316 				if (dst_reg == BPF_REG_0)
2317 					real_dst_reg = BPF_REG_AX;
2318 
2319 				branch_target = prog;
2320 				/* Load old value */
2321 				emit_ldx(&prog, BPF_SIZE(insn->code),
2322 					 BPF_REG_0, real_dst_reg, insn->off);
2323 				/*
2324 				 * Perform the (commutative) operation locally,
2325 				 * put the result in the AUX_REG.
2326 				 */
2327 				emit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0);
2328 				maybe_emit_mod(&prog, AUX_REG, real_src_reg, is64);
2329 				EMIT2(simple_alu_opcodes[BPF_OP(insn->imm)],
2330 				      add_2reg(0xC0, AUX_REG, real_src_reg));
2331 				/* Attempt to swap in new value */
2332 				err = emit_atomic_rmw(&prog, BPF_CMPXCHG,
2333 						      real_dst_reg, AUX_REG,
2334 						      insn->off,
2335 						      BPF_SIZE(insn->code));
2336 				if (WARN_ON(err))
2337 					return err;
2338 				/*
2339 				 * ZF tells us whether we won the race. If it's
2340 				 * cleared we need to try again.
2341 				 */
2342 				EMIT2(X86_JNE, -(prog - branch_target) - 2);
2343 				/* Return the pre-modification value */
2344 				emit_mov_reg(&prog, is64, real_src_reg, BPF_REG_0);
2345 				/* Restore R0 after clobbering RAX */
2346 				emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX);
2347 				break;
2348 			}
2349 
2350 			if (bpf_atomic_is_load_store(insn))
2351 				err = emit_atomic_ld_st(&prog, insn->imm, dst_reg, src_reg,
2352 							insn->off, BPF_SIZE(insn->code));
2353 			else
2354 				err = emit_atomic_rmw(&prog, insn->imm, dst_reg, src_reg,
2355 						      insn->off, BPF_SIZE(insn->code));
2356 			if (err)
2357 				return err;
2358 			break;
2359 
2360 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_B:
2361 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_H:
2362 			if (!bpf_atomic_is_load_store(insn)) {
2363 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
2364 				return -EFAULT;
2365 			}
2366 			fallthrough;
2367 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_W:
2368 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
2369 			start_of_ldx = prog;
2370 
2371 			if (bpf_atomic_is_load_store(insn))
2372 				err = emit_atomic_ld_st_index(&prog, insn->imm,
2373 							      BPF_SIZE(insn->code), dst_reg,
2374 							      src_reg, X86_REG_R12, insn->off);
2375 			else
2376 				err = emit_atomic_rmw_index(&prog, insn->imm, BPF_SIZE(insn->code),
2377 							    dst_reg, src_reg, X86_REG_R12,
2378 							    insn->off);
2379 			if (err)
2380 				return err;
2381 			goto populate_extable;
2382 
2383 			/* call */
2384 		case BPF_JMP | BPF_CALL: {
2385 			u8 *ip = image + addrs[i - 1];
2386 
2387 			func = (u8 *) __bpf_call_base + imm32;
2388 			if (src_reg == BPF_PSEUDO_CALL && tail_call_reachable) {
2389 				LOAD_TAIL_CALL_CNT_PTR(stack_depth);
2390 				ip += 7;
2391 			}
2392 			if (!imm32)
2393 				return -EINVAL;
2394 			if (priv_frame_ptr) {
2395 				push_r9(&prog);
2396 				ip += 2;
2397 			}
2398 			ip += x86_call_depth_emit_accounting(&prog, func, ip);
2399 			if (emit_call(&prog, func, ip))
2400 				return -EINVAL;
2401 			if (priv_frame_ptr)
2402 				pop_r9(&prog);
2403 			break;
2404 		}
2405 
2406 		case BPF_JMP | BPF_TAIL_CALL:
2407 			if (imm32)
2408 				emit_bpf_tail_call_direct(bpf_prog,
2409 							  &bpf_prog->aux->poke_tab[imm32 - 1],
2410 							  &prog, image + addrs[i - 1],
2411 							  callee_regs_used,
2412 							  stack_depth,
2413 							  ctx);
2414 			else
2415 				emit_bpf_tail_call_indirect(bpf_prog,
2416 							    &prog,
2417 							    callee_regs_used,
2418 							    stack_depth,
2419 							    image + addrs[i - 1],
2420 							    ctx);
2421 			break;
2422 
2423 			/* cond jump */
2424 		case BPF_JMP | BPF_JEQ | BPF_X:
2425 		case BPF_JMP | BPF_JNE | BPF_X:
2426 		case BPF_JMP | BPF_JGT | BPF_X:
2427 		case BPF_JMP | BPF_JLT | BPF_X:
2428 		case BPF_JMP | BPF_JGE | BPF_X:
2429 		case BPF_JMP | BPF_JLE | BPF_X:
2430 		case BPF_JMP | BPF_JSGT | BPF_X:
2431 		case BPF_JMP | BPF_JSLT | BPF_X:
2432 		case BPF_JMP | BPF_JSGE | BPF_X:
2433 		case BPF_JMP | BPF_JSLE | BPF_X:
2434 		case BPF_JMP32 | BPF_JEQ | BPF_X:
2435 		case BPF_JMP32 | BPF_JNE | BPF_X:
2436 		case BPF_JMP32 | BPF_JGT | BPF_X:
2437 		case BPF_JMP32 | BPF_JLT | BPF_X:
2438 		case BPF_JMP32 | BPF_JGE | BPF_X:
2439 		case BPF_JMP32 | BPF_JLE | BPF_X:
2440 		case BPF_JMP32 | BPF_JSGT | BPF_X:
2441 		case BPF_JMP32 | BPF_JSLT | BPF_X:
2442 		case BPF_JMP32 | BPF_JSGE | BPF_X:
2443 		case BPF_JMP32 | BPF_JSLE | BPF_X:
2444 			/* cmp dst_reg, src_reg */
2445 			maybe_emit_mod(&prog, dst_reg, src_reg,
2446 				       BPF_CLASS(insn->code) == BPF_JMP);
2447 			EMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg));
2448 			goto emit_cond_jmp;
2449 
2450 		case BPF_JMP | BPF_JSET | BPF_X:
2451 		case BPF_JMP32 | BPF_JSET | BPF_X:
2452 			/* test dst_reg, src_reg */
2453 			maybe_emit_mod(&prog, dst_reg, src_reg,
2454 				       BPF_CLASS(insn->code) == BPF_JMP);
2455 			EMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg));
2456 			goto emit_cond_jmp;
2457 
2458 		case BPF_JMP | BPF_JSET | BPF_K:
2459 		case BPF_JMP32 | BPF_JSET | BPF_K:
2460 			/* test dst_reg, imm32 */
2461 			maybe_emit_1mod(&prog, dst_reg,
2462 					BPF_CLASS(insn->code) == BPF_JMP);
2463 			EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);
2464 			goto emit_cond_jmp;
2465 
2466 		case BPF_JMP | BPF_JEQ | BPF_K:
2467 		case BPF_JMP | BPF_JNE | BPF_K:
2468 		case BPF_JMP | BPF_JGT | BPF_K:
2469 		case BPF_JMP | BPF_JLT | BPF_K:
2470 		case BPF_JMP | BPF_JGE | BPF_K:
2471 		case BPF_JMP | BPF_JLE | BPF_K:
2472 		case BPF_JMP | BPF_JSGT | BPF_K:
2473 		case BPF_JMP | BPF_JSLT | BPF_K:
2474 		case BPF_JMP | BPF_JSGE | BPF_K:
2475 		case BPF_JMP | BPF_JSLE | BPF_K:
2476 		case BPF_JMP32 | BPF_JEQ | BPF_K:
2477 		case BPF_JMP32 | BPF_JNE | BPF_K:
2478 		case BPF_JMP32 | BPF_JGT | BPF_K:
2479 		case BPF_JMP32 | BPF_JLT | BPF_K:
2480 		case BPF_JMP32 | BPF_JGE | BPF_K:
2481 		case BPF_JMP32 | BPF_JLE | BPF_K:
2482 		case BPF_JMP32 | BPF_JSGT | BPF_K:
2483 		case BPF_JMP32 | BPF_JSLT | BPF_K:
2484 		case BPF_JMP32 | BPF_JSGE | BPF_K:
2485 		case BPF_JMP32 | BPF_JSLE | BPF_K:
2486 			/* test dst_reg, dst_reg to save one extra byte */
2487 			if (imm32 == 0) {
2488 				maybe_emit_mod(&prog, dst_reg, dst_reg,
2489 					       BPF_CLASS(insn->code) == BPF_JMP);
2490 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
2491 				goto emit_cond_jmp;
2492 			}
2493 
2494 			/* cmp dst_reg, imm8/32 */
2495 			maybe_emit_1mod(&prog, dst_reg,
2496 					BPF_CLASS(insn->code) == BPF_JMP);
2497 
2498 			if (is_imm8(imm32))
2499 				EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);
2500 			else
2501 				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);
2502 
2503 emit_cond_jmp:		/* Convert BPF opcode to x86 */
2504 			switch (BPF_OP(insn->code)) {
2505 			case BPF_JEQ:
2506 				jmp_cond = X86_JE;
2507 				break;
2508 			case BPF_JSET:
2509 			case BPF_JNE:
2510 				jmp_cond = X86_JNE;
2511 				break;
2512 			case BPF_JGT:
2513 				/* GT is unsigned '>', JA in x86 */
2514 				jmp_cond = X86_JA;
2515 				break;
2516 			case BPF_JLT:
2517 				/* LT is unsigned '<', JB in x86 */
2518 				jmp_cond = X86_JB;
2519 				break;
2520 			case BPF_JGE:
2521 				/* GE is unsigned '>=', JAE in x86 */
2522 				jmp_cond = X86_JAE;
2523 				break;
2524 			case BPF_JLE:
2525 				/* LE is unsigned '<=', JBE in x86 */
2526 				jmp_cond = X86_JBE;
2527 				break;
2528 			case BPF_JSGT:
2529 				/* Signed '>', GT in x86 */
2530 				jmp_cond = X86_JG;
2531 				break;
2532 			case BPF_JSLT:
2533 				/* Signed '<', LT in x86 */
2534 				jmp_cond = X86_JL;
2535 				break;
2536 			case BPF_JSGE:
2537 				/* Signed '>=', GE in x86 */
2538 				jmp_cond = X86_JGE;
2539 				break;
2540 			case BPF_JSLE:
2541 				/* Signed '<=', LE in x86 */
2542 				jmp_cond = X86_JLE;
2543 				break;
2544 			default: /* to silence GCC warning */
2545 				return -EFAULT;
2546 			}
2547 			jmp_offset = addrs[i + insn->off] - addrs[i];
2548 			if (is_imm8_jmp_offset(jmp_offset)) {
2549 				if (jmp_padding) {
2550 					/* To keep the jmp_offset valid, the extra bytes are
2551 					 * padded before the jump insn, so we subtract the
2552 					 * 2 bytes of jmp_cond insn from INSN_SZ_DIFF.
2553 					 *
2554 					 * If the previous pass already emits an imm8
2555 					 * jmp_cond, then this BPF insn won't shrink, so
2556 					 * "nops" is 0.
2557 					 *
2558 					 * On the other hand, if the previous pass emits an
2559 					 * imm32 jmp_cond, the extra 4 bytes(*) is padded to
2560 					 * keep the image from shrinking further.
2561 					 *
2562 					 * (*) imm32 jmp_cond is 6 bytes, and imm8 jmp_cond
2563 					 *     is 2 bytes, so the size difference is 4 bytes.
2564 					 */
2565 					nops = INSN_SZ_DIFF - 2;
2566 					if (nops != 0 && nops != 4) {
2567 						pr_err("unexpected jmp_cond padding: %d bytes\n",
2568 						       nops);
2569 						return -EFAULT;
2570 					}
2571 					emit_nops(&prog, nops);
2572 				}
2573 				EMIT2(jmp_cond, jmp_offset);
2574 			} else if (is_simm32(jmp_offset)) {
2575 				EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset);
2576 			} else {
2577 				pr_err("cond_jmp gen bug %llx\n", jmp_offset);
2578 				return -EFAULT;
2579 			}
2580 
2581 			break;
2582 
2583 		case BPF_JMP | BPF_JA:
2584 		case BPF_JMP32 | BPF_JA:
2585 			if (BPF_CLASS(insn->code) == BPF_JMP) {
2586 				if (insn->off == -1)
2587 					/* -1 jmp instructions will always jump
2588 					 * backwards two bytes. Explicitly handling
2589 					 * this case avoids wasting too many passes
2590 					 * when there are long sequences of replaced
2591 					 * dead code.
2592 					 */
2593 					jmp_offset = -2;
2594 				else
2595 					jmp_offset = addrs[i + insn->off] - addrs[i];
2596 			} else {
2597 				if (insn->imm == -1)
2598 					jmp_offset = -2;
2599 				else
2600 					jmp_offset = addrs[i + insn->imm] - addrs[i];
2601 			}
2602 
2603 			if (!jmp_offset) {
2604 				/*
2605 				 * If jmp_padding is enabled, the extra nops will
2606 				 * be inserted. Otherwise, optimize out nop jumps.
2607 				 */
2608 				if (jmp_padding) {
2609 					/* There are 3 possible conditions.
2610 					 * (1) This BPF_JA is already optimized out in
2611 					 *     the previous run, so there is no need
2612 					 *     to pad any extra byte (0 byte).
2613 					 * (2) The previous pass emits an imm8 jmp,
2614 					 *     so we pad 2 bytes to match the previous
2615 					 *     insn size.
2616 					 * (3) Similarly, the previous pass emits an
2617 					 *     imm32 jmp, and 5 bytes is padded.
2618 					 */
2619 					nops = INSN_SZ_DIFF;
2620 					if (nops != 0 && nops != 2 && nops != 5) {
2621 						pr_err("unexpected nop jump padding: %d bytes\n",
2622 						       nops);
2623 						return -EFAULT;
2624 					}
2625 					emit_nops(&prog, nops);
2626 				}
2627 				break;
2628 			}
2629 emit_jmp:
2630 			if (is_imm8_jmp_offset(jmp_offset)) {
2631 				if (jmp_padding) {
2632 					/* To avoid breaking jmp_offset, the extra bytes
2633 					 * are padded before the actual jmp insn, so
2634 					 * 2 bytes is subtracted from INSN_SZ_DIFF.
2635 					 *
2636 					 * If the previous pass already emits an imm8
2637 					 * jmp, there is nothing to pad (0 byte).
2638 					 *
2639 					 * If it emits an imm32 jmp (5 bytes) previously
2640 					 * and now an imm8 jmp (2 bytes), then we pad
2641 					 * (5 - 2 = 3) bytes to stop the image from
2642 					 * shrinking further.
2643 					 */
2644 					nops = INSN_SZ_DIFF - 2;
2645 					if (nops != 0 && nops != 3) {
2646 						pr_err("unexpected jump padding: %d bytes\n",
2647 						       nops);
2648 						return -EFAULT;
2649 					}
2650 					emit_nops(&prog, INSN_SZ_DIFF - 2);
2651 				}
2652 				EMIT2(0xEB, jmp_offset);
2653 			} else if (is_simm32(jmp_offset)) {
2654 				EMIT1_off32(0xE9, jmp_offset);
2655 			} else {
2656 				pr_err("jmp gen bug %llx\n", jmp_offset);
2657 				return -EFAULT;
2658 			}
2659 			break;
2660 
2661 		case BPF_JMP | BPF_EXIT:
2662 			if (seen_exit) {
2663 				jmp_offset = ctx->cleanup_addr - addrs[i];
2664 				goto emit_jmp;
2665 			}
2666 			seen_exit = true;
2667 			/* Update cleanup_addr */
2668 			ctx->cleanup_addr = proglen;
2669 			if (bpf_prog_was_classic(bpf_prog) &&
2670 			    !capable(CAP_SYS_ADMIN)) {
2671 				u8 *ip = image + addrs[i - 1];
2672 
2673 				if (emit_spectre_bhb_barrier(&prog, ip, bpf_prog))
2674 					return -EINVAL;
2675 			}
2676 			if (bpf_prog->aux->exception_boundary) {
2677 				pop_callee_regs(&prog, all_callee_regs_used);
2678 				pop_r12(&prog);
2679 			} else {
2680 				pop_callee_regs(&prog, callee_regs_used);
2681 				if (arena_vm_start)
2682 					pop_r12(&prog);
2683 			}
2684 			EMIT1(0xC9);         /* leave */
2685 			emit_return(&prog, image + addrs[i - 1] + (prog - temp));
2686 			break;
2687 
2688 		default:
2689 			/*
2690 			 * By design x86-64 JIT should support all BPF instructions.
2691 			 * This error will be seen if new instruction was added
2692 			 * to the interpreter, but not to the JIT, or if there is
2693 			 * junk in bpf_prog.
2694 			 */
2695 			pr_err("bpf_jit: unknown opcode %02x\n", insn->code);
2696 			return -EINVAL;
2697 		}
2698 
2699 		ilen = prog - temp;
2700 		if (ilen > BPF_MAX_INSN_SIZE) {
2701 			pr_err("bpf_jit: fatal insn size error\n");
2702 			return -EFAULT;
2703 		}
2704 
2705 		if (image) {
2706 			/*
2707 			 * When populating the image, assert that:
2708 			 *
2709 			 *  i) We do not write beyond the allocated space, and
2710 			 * ii) addrs[i] did not change from the prior run, in order
2711 			 *     to validate assumptions made for computing branch
2712 			 *     displacements.
2713 			 */
2714 			if (unlikely(proglen + ilen > oldproglen ||
2715 				     proglen + ilen != addrs[i])) {
2716 				pr_err("bpf_jit: fatal error\n");
2717 				return -EFAULT;
2718 			}
2719 			memcpy(rw_image + proglen, temp, ilen);
2720 		}
2721 		proglen += ilen;
2722 		addrs[i] = proglen;
2723 		prog = temp;
2724 	}
2725 
2726 	if (image && excnt != bpf_prog->aux->num_exentries) {
2727 		pr_err("extable is not populated\n");
2728 		return -EFAULT;
2729 	}
2730 	return proglen;
2731 }
2732 
2733 static void clean_stack_garbage(const struct btf_func_model *m,
2734 				u8 **pprog, int nr_stack_slots,
2735 				int stack_size)
2736 {
2737 	int arg_size, off;
2738 	u8 *prog;
2739 
2740 	/* Generally speaking, the compiler will pass the arguments
2741 	 * on-stack with "push" instruction, which will take 8-byte
2742 	 * on the stack. In this case, there won't be garbage values
2743 	 * while we copy the arguments from origin stack frame to current
2744 	 * in BPF_DW.
2745 	 *
2746 	 * However, sometimes the compiler will only allocate 4-byte on
2747 	 * the stack for the arguments. For now, this case will only
2748 	 * happen if there is only one argument on-stack and its size
2749 	 * not more than 4 byte. In this case, there will be garbage
2750 	 * values on the upper 4-byte where we store the argument on
2751 	 * current stack frame.
2752 	 *
2753 	 * arguments on origin stack:
2754 	 *
2755 	 * stack_arg_1(4-byte) xxx(4-byte)
2756 	 *
2757 	 * what we copy:
2758 	 *
2759 	 * stack_arg_1(8-byte): stack_arg_1(origin) xxx
2760 	 *
2761 	 * and the xxx is the garbage values which we should clean here.
2762 	 */
2763 	if (nr_stack_slots != 1)
2764 		return;
2765 
2766 	/* the size of the last argument */
2767 	arg_size = m->arg_size[m->nr_args - 1];
2768 	if (arg_size <= 4) {
2769 		off = -(stack_size - 4);
2770 		prog = *pprog;
2771 		/* mov DWORD PTR [rbp + off], 0 */
2772 		if (!is_imm8(off))
2773 			EMIT2_off32(0xC7, 0x85, off);
2774 		else
2775 			EMIT3(0xC7, 0x45, off);
2776 		EMIT(0, 4);
2777 		*pprog = prog;
2778 	}
2779 }
2780 
2781 /* get the count of the regs that are used to pass arguments */
2782 static int get_nr_used_regs(const struct btf_func_model *m)
2783 {
2784 	int i, arg_regs, nr_used_regs = 0;
2785 
2786 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
2787 		arg_regs = (m->arg_size[i] + 7) / 8;
2788 		if (nr_used_regs + arg_regs <= 6)
2789 			nr_used_regs += arg_regs;
2790 
2791 		if (nr_used_regs >= 6)
2792 			break;
2793 	}
2794 
2795 	return nr_used_regs;
2796 }
2797 
2798 static void save_args(const struct btf_func_model *m, u8 **prog,
2799 		      int stack_size, bool for_call_origin)
2800 {
2801 	int arg_regs, first_off = 0, nr_regs = 0, nr_stack_slots = 0;
2802 	int i, j;
2803 
2804 	/* Store function arguments to stack.
2805 	 * For a function that accepts two pointers the sequence will be:
2806 	 * mov QWORD PTR [rbp-0x10],rdi
2807 	 * mov QWORD PTR [rbp-0x8],rsi
2808 	 */
2809 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
2810 		arg_regs = (m->arg_size[i] + 7) / 8;
2811 
2812 		/* According to the research of Yonghong, struct members
2813 		 * should be all in register or all on the stack.
2814 		 * Meanwhile, the compiler will pass the argument on regs
2815 		 * if the remaining regs can hold the argument.
2816 		 *
2817 		 * Disorder of the args can happen. For example:
2818 		 *
2819 		 * struct foo_struct {
2820 		 *     long a;
2821 		 *     int b;
2822 		 * };
2823 		 * int foo(char, char, char, char, char, struct foo_struct,
2824 		 *         char);
2825 		 *
2826 		 * the arg1-5,arg7 will be passed by regs, and arg6 will
2827 		 * by stack.
2828 		 */
2829 		if (nr_regs + arg_regs > 6) {
2830 			/* copy function arguments from origin stack frame
2831 			 * into current stack frame.
2832 			 *
2833 			 * The starting address of the arguments on-stack
2834 			 * is:
2835 			 *   rbp + 8(push rbp) +
2836 			 *   8(return addr of origin call) +
2837 			 *   8(return addr of the caller)
2838 			 * which means: rbp + 24
2839 			 */
2840 			for (j = 0; j < arg_regs; j++) {
2841 				emit_ldx(prog, BPF_DW, BPF_REG_0, BPF_REG_FP,
2842 					 nr_stack_slots * 8 + 0x18);
2843 				emit_stx(prog, BPF_DW, BPF_REG_FP, BPF_REG_0,
2844 					 -stack_size);
2845 
2846 				if (!nr_stack_slots)
2847 					first_off = stack_size;
2848 				stack_size -= 8;
2849 				nr_stack_slots++;
2850 			}
2851 		} else {
2852 			/* Only copy the arguments on-stack to current
2853 			 * 'stack_size' and ignore the regs, used to
2854 			 * prepare the arguments on-stack for origin call.
2855 			 */
2856 			if (for_call_origin) {
2857 				nr_regs += arg_regs;
2858 				continue;
2859 			}
2860 
2861 			/* copy the arguments from regs into stack */
2862 			for (j = 0; j < arg_regs; j++) {
2863 				emit_stx(prog, BPF_DW, BPF_REG_FP,
2864 					 nr_regs == 5 ? X86_REG_R9 : BPF_REG_1 + nr_regs,
2865 					 -stack_size);
2866 				stack_size -= 8;
2867 				nr_regs++;
2868 			}
2869 		}
2870 	}
2871 
2872 	clean_stack_garbage(m, prog, nr_stack_slots, first_off);
2873 }
2874 
2875 static void restore_regs(const struct btf_func_model *m, u8 **prog,
2876 			 int stack_size)
2877 {
2878 	int i, j, arg_regs, nr_regs = 0;
2879 
2880 	/* Restore function arguments from stack.
2881 	 * For a function that accepts two pointers the sequence will be:
2882 	 * EMIT4(0x48, 0x8B, 0x7D, 0xF0); mov rdi,QWORD PTR [rbp-0x10]
2883 	 * EMIT4(0x48, 0x8B, 0x75, 0xF8); mov rsi,QWORD PTR [rbp-0x8]
2884 	 *
2885 	 * The logic here is similar to what we do in save_args()
2886 	 */
2887 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
2888 		arg_regs = (m->arg_size[i] + 7) / 8;
2889 		if (nr_regs + arg_regs <= 6) {
2890 			for (j = 0; j < arg_regs; j++) {
2891 				emit_ldx(prog, BPF_DW,
2892 					 nr_regs == 5 ? X86_REG_R9 : BPF_REG_1 + nr_regs,
2893 					 BPF_REG_FP,
2894 					 -stack_size);
2895 				stack_size -= 8;
2896 				nr_regs++;
2897 			}
2898 		} else {
2899 			stack_size -= 8 * arg_regs;
2900 		}
2901 
2902 		if (nr_regs >= 6)
2903 			break;
2904 	}
2905 }
2906 
2907 static int invoke_bpf_prog(const struct btf_func_model *m, u8 **pprog,
2908 			   struct bpf_tramp_link *l, int stack_size,
2909 			   int run_ctx_off, bool save_ret,
2910 			   void *image, void *rw_image)
2911 {
2912 	u8 *prog = *pprog;
2913 	u8 *jmp_insn;
2914 	int ctx_cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
2915 	struct bpf_prog *p = l->link.prog;
2916 	u64 cookie = l->cookie;
2917 
2918 	/* mov rdi, cookie */
2919 	emit_mov_imm64(&prog, BPF_REG_1, (long) cookie >> 32, (u32) (long) cookie);
2920 
2921 	/* Prepare struct bpf_tramp_run_ctx.
2922 	 *
2923 	 * bpf_tramp_run_ctx is already preserved by
2924 	 * arch_prepare_bpf_trampoline().
2925 	 *
2926 	 * mov QWORD PTR [rbp - run_ctx_off + ctx_cookie_off], rdi
2927 	 */
2928 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_1, -run_ctx_off + ctx_cookie_off);
2929 
2930 	/* arg1: mov rdi, progs[i] */
2931 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
2932 	/* arg2: lea rsi, [rbp - ctx_cookie_off] */
2933 	if (!is_imm8(-run_ctx_off))
2934 		EMIT3_off32(0x48, 0x8D, 0xB5, -run_ctx_off);
2935 	else
2936 		EMIT4(0x48, 0x8D, 0x75, -run_ctx_off);
2937 
2938 	if (emit_rsb_call(&prog, bpf_trampoline_enter(p), image + (prog - (u8 *)rw_image)))
2939 		return -EINVAL;
2940 	/* remember prog start time returned by __bpf_prog_enter */
2941 	emit_mov_reg(&prog, true, BPF_REG_6, BPF_REG_0);
2942 
2943 	/* if (__bpf_prog_enter*(prog) == 0)
2944 	 *	goto skip_exec_of_prog;
2945 	 */
2946 	EMIT3(0x48, 0x85, 0xC0);  /* test rax,rax */
2947 	/* emit 2 nops that will be replaced with JE insn */
2948 	jmp_insn = prog;
2949 	emit_nops(&prog, 2);
2950 
2951 	/* arg1: lea rdi, [rbp - stack_size] */
2952 	if (!is_imm8(-stack_size))
2953 		EMIT3_off32(0x48, 0x8D, 0xBD, -stack_size);
2954 	else
2955 		EMIT4(0x48, 0x8D, 0x7D, -stack_size);
2956 	/* arg2: progs[i]->insnsi for interpreter */
2957 	if (!p->jited)
2958 		emit_mov_imm64(&prog, BPF_REG_2,
2959 			       (long) p->insnsi >> 32,
2960 			       (u32) (long) p->insnsi);
2961 	/* call JITed bpf program or interpreter */
2962 	if (emit_rsb_call(&prog, p->bpf_func, image + (prog - (u8 *)rw_image)))
2963 		return -EINVAL;
2964 
2965 	/*
2966 	 * BPF_TRAMP_MODIFY_RETURN trampolines can modify the return
2967 	 * of the previous call which is then passed on the stack to
2968 	 * the next BPF program.
2969 	 *
2970 	 * BPF_TRAMP_FENTRY trampoline may need to return the return
2971 	 * value of BPF_PROG_TYPE_STRUCT_OPS prog.
2972 	 */
2973 	if (save_ret)
2974 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
2975 
2976 	/* replace 2 nops with JE insn, since jmp target is known */
2977 	jmp_insn[0] = X86_JE;
2978 	jmp_insn[1] = prog - jmp_insn - 2;
2979 
2980 	/* arg1: mov rdi, progs[i] */
2981 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
2982 	/* arg2: mov rsi, rbx <- start time in nsec */
2983 	emit_mov_reg(&prog, true, BPF_REG_2, BPF_REG_6);
2984 	/* arg3: lea rdx, [rbp - run_ctx_off] */
2985 	if (!is_imm8(-run_ctx_off))
2986 		EMIT3_off32(0x48, 0x8D, 0x95, -run_ctx_off);
2987 	else
2988 		EMIT4(0x48, 0x8D, 0x55, -run_ctx_off);
2989 	if (emit_rsb_call(&prog, bpf_trampoline_exit(p), image + (prog - (u8 *)rw_image)))
2990 		return -EINVAL;
2991 
2992 	*pprog = prog;
2993 	return 0;
2994 }
2995 
2996 static void emit_align(u8 **pprog, u32 align)
2997 {
2998 	u8 *target, *prog = *pprog;
2999 
3000 	target = PTR_ALIGN(prog, align);
3001 	if (target != prog)
3002 		emit_nops(&prog, target - prog);
3003 
3004 	*pprog = prog;
3005 }
3006 
3007 static int emit_cond_near_jump(u8 **pprog, void *func, void *ip, u8 jmp_cond)
3008 {
3009 	u8 *prog = *pprog;
3010 	s64 offset;
3011 
3012 	offset = func - (ip + 2 + 4);
3013 	if (!is_simm32(offset)) {
3014 		pr_err("Target %p is out of range\n", func);
3015 		return -EINVAL;
3016 	}
3017 	EMIT2_off32(0x0F, jmp_cond + 0x10, offset);
3018 	*pprog = prog;
3019 	return 0;
3020 }
3021 
3022 static int invoke_bpf(const struct btf_func_model *m, u8 **pprog,
3023 		      struct bpf_tramp_links *tl, int stack_size,
3024 		      int run_ctx_off, bool save_ret,
3025 		      void *image, void *rw_image)
3026 {
3027 	int i;
3028 	u8 *prog = *pprog;
3029 
3030 	for (i = 0; i < tl->nr_links; i++) {
3031 		if (invoke_bpf_prog(m, &prog, tl->links[i], stack_size,
3032 				    run_ctx_off, save_ret, image, rw_image))
3033 			return -EINVAL;
3034 	}
3035 	*pprog = prog;
3036 	return 0;
3037 }
3038 
3039 static int invoke_bpf_mod_ret(const struct btf_func_model *m, u8 **pprog,
3040 			      struct bpf_tramp_links *tl, int stack_size,
3041 			      int run_ctx_off, u8 **branches,
3042 			      void *image, void *rw_image)
3043 {
3044 	u8 *prog = *pprog;
3045 	int i;
3046 
3047 	/* The first fmod_ret program will receive a garbage return value.
3048 	 * Set this to 0 to avoid confusing the program.
3049 	 */
3050 	emit_mov_imm32(&prog, false, BPF_REG_0, 0);
3051 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
3052 	for (i = 0; i < tl->nr_links; i++) {
3053 		if (invoke_bpf_prog(m, &prog, tl->links[i], stack_size, run_ctx_off, true,
3054 				    image, rw_image))
3055 			return -EINVAL;
3056 
3057 		/* mod_ret prog stored return value into [rbp - 8]. Emit:
3058 		 * if (*(u64 *)(rbp - 8) !=  0)
3059 		 *	goto do_fexit;
3060 		 */
3061 		/* cmp QWORD PTR [rbp - 0x8], 0x0 */
3062 		EMIT4(0x48, 0x83, 0x7d, 0xf8); EMIT1(0x00);
3063 
3064 		/* Save the location of the branch and Generate 6 nops
3065 		 * (4 bytes for an offset and 2 bytes for the jump) These nops
3066 		 * are replaced with a conditional jump once do_fexit (i.e. the
3067 		 * start of the fexit invocation) is finalized.
3068 		 */
3069 		branches[i] = prog;
3070 		emit_nops(&prog, 4 + 2);
3071 	}
3072 
3073 	*pprog = prog;
3074 	return 0;
3075 }
3076 
3077 /* mov rax, qword ptr [rbp - rounded_stack_depth - 8] */
3078 #define LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack)	\
3079 	__LOAD_TCC_PTR(-round_up(stack, 8) - 8)
3080 
3081 /* Example:
3082  * __be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev);
3083  * its 'struct btf_func_model' will be nr_args=2
3084  * The assembly code when eth_type_trans is executing after trampoline:
3085  *
3086  * push rbp
3087  * mov rbp, rsp
3088  * sub rsp, 16                     // space for skb and dev
3089  * push rbx                        // temp regs to pass start time
3090  * mov qword ptr [rbp - 16], rdi   // save skb pointer to stack
3091  * mov qword ptr [rbp - 8], rsi    // save dev pointer to stack
3092  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
3093  * mov rbx, rax                    // remember start time in bpf stats are enabled
3094  * lea rdi, [rbp - 16]             // R1==ctx of bpf prog
3095  * call addr_of_jited_FENTRY_prog
3096  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
3097  * mov rsi, rbx                    // prog start time
3098  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
3099  * mov rdi, qword ptr [rbp - 16]   // restore skb pointer from stack
3100  * mov rsi, qword ptr [rbp - 8]    // restore dev pointer from stack
3101  * pop rbx
3102  * leave
3103  * ret
3104  *
3105  * eth_type_trans has 5 byte nop at the beginning. These 5 bytes will be
3106  * replaced with 'call generated_bpf_trampoline'. When it returns
3107  * eth_type_trans will continue executing with original skb and dev pointers.
3108  *
3109  * The assembly code when eth_type_trans is called from trampoline:
3110  *
3111  * push rbp
3112  * mov rbp, rsp
3113  * sub rsp, 24                     // space for skb, dev, return value
3114  * push rbx                        // temp regs to pass start time
3115  * mov qword ptr [rbp - 24], rdi   // save skb pointer to stack
3116  * mov qword ptr [rbp - 16], rsi   // save dev pointer to stack
3117  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
3118  * mov rbx, rax                    // remember start time if bpf stats are enabled
3119  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
3120  * call addr_of_jited_FENTRY_prog  // bpf prog can access skb and dev
3121  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
3122  * mov rsi, rbx                    // prog start time
3123  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
3124  * mov rdi, qword ptr [rbp - 24]   // restore skb pointer from stack
3125  * mov rsi, qword ptr [rbp - 16]   // restore dev pointer from stack
3126  * call eth_type_trans+5           // execute body of eth_type_trans
3127  * mov qword ptr [rbp - 8], rax    // save return value
3128  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
3129  * mov rbx, rax                    // remember start time in bpf stats are enabled
3130  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
3131  * call addr_of_jited_FEXIT_prog   // bpf prog can access skb, dev, return value
3132  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
3133  * mov rsi, rbx                    // prog start time
3134  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
3135  * mov rax, qword ptr [rbp - 8]    // restore eth_type_trans's return value
3136  * pop rbx
3137  * leave
3138  * add rsp, 8                      // skip eth_type_trans's frame
3139  * ret                             // return to its caller
3140  */
3141 static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_image,
3142 					 void *rw_image_end, void *image,
3143 					 const struct btf_func_model *m, u32 flags,
3144 					 struct bpf_tramp_links *tlinks,
3145 					 void *func_addr)
3146 {
3147 	int i, ret, nr_regs = m->nr_args, stack_size = 0;
3148 	int regs_off, nregs_off, ip_off, run_ctx_off, arg_stack_off, rbx_off;
3149 	struct bpf_tramp_links *fentry = &tlinks[BPF_TRAMP_FENTRY];
3150 	struct bpf_tramp_links *fexit = &tlinks[BPF_TRAMP_FEXIT];
3151 	struct bpf_tramp_links *fmod_ret = &tlinks[BPF_TRAMP_MODIFY_RETURN];
3152 	void *orig_call = func_addr;
3153 	u8 **branches = NULL;
3154 	u8 *prog;
3155 	bool save_ret;
3156 
3157 	/*
3158 	 * F_INDIRECT is only compatible with F_RET_FENTRY_RET, it is
3159 	 * explicitly incompatible with F_CALL_ORIG | F_SKIP_FRAME | F_IP_ARG
3160 	 * because @func_addr.
3161 	 */
3162 	WARN_ON_ONCE((flags & BPF_TRAMP_F_INDIRECT) &&
3163 		     (flags & ~(BPF_TRAMP_F_INDIRECT | BPF_TRAMP_F_RET_FENTRY_RET)));
3164 
3165 	/* extra registers for struct arguments */
3166 	for (i = 0; i < m->nr_args; i++) {
3167 		if (m->arg_flags[i] & BTF_FMODEL_STRUCT_ARG)
3168 			nr_regs += (m->arg_size[i] + 7) / 8 - 1;
3169 	}
3170 
3171 	/* x86-64 supports up to MAX_BPF_FUNC_ARGS arguments. 1-6
3172 	 * are passed through regs, the remains are through stack.
3173 	 */
3174 	if (nr_regs > MAX_BPF_FUNC_ARGS)
3175 		return -ENOTSUPP;
3176 
3177 	/* Generated trampoline stack layout:
3178 	 *
3179 	 * RBP + 8         [ return address  ]
3180 	 * RBP + 0         [ RBP             ]
3181 	 *
3182 	 * RBP - 8         [ return value    ]  BPF_TRAMP_F_CALL_ORIG or
3183 	 *                                      BPF_TRAMP_F_RET_FENTRY_RET flags
3184 	 *
3185 	 *                 [ reg_argN        ]  always
3186 	 *                 [ ...             ]
3187 	 * RBP - regs_off  [ reg_arg1        ]  program's ctx pointer
3188 	 *
3189 	 * RBP - nregs_off [ regs count	     ]  always
3190 	 *
3191 	 * RBP - ip_off    [ traced function ]  BPF_TRAMP_F_IP_ARG flag
3192 	 *
3193 	 * RBP - rbx_off   [ rbx value       ]  always
3194 	 *
3195 	 * RBP - run_ctx_off [ bpf_tramp_run_ctx ]
3196 	 *
3197 	 *                     [ stack_argN ]  BPF_TRAMP_F_CALL_ORIG
3198 	 *                     [ ...        ]
3199 	 *                     [ stack_arg2 ]
3200 	 * RBP - arg_stack_off [ stack_arg1 ]
3201 	 * RSP                 [ tail_call_cnt_ptr ] BPF_TRAMP_F_TAIL_CALL_CTX
3202 	 */
3203 
3204 	/* room for return value of orig_call or fentry prog */
3205 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
3206 	if (save_ret)
3207 		stack_size += 8;
3208 
3209 	stack_size += nr_regs * 8;
3210 	regs_off = stack_size;
3211 
3212 	/* regs count  */
3213 	stack_size += 8;
3214 	nregs_off = stack_size;
3215 
3216 	if (flags & BPF_TRAMP_F_IP_ARG)
3217 		stack_size += 8; /* room for IP address argument */
3218 
3219 	ip_off = stack_size;
3220 
3221 	stack_size += 8;
3222 	rbx_off = stack_size;
3223 
3224 	stack_size += (sizeof(struct bpf_tramp_run_ctx) + 7) & ~0x7;
3225 	run_ctx_off = stack_size;
3226 
3227 	if (nr_regs > 6 && (flags & BPF_TRAMP_F_CALL_ORIG)) {
3228 		/* the space that used to pass arguments on-stack */
3229 		stack_size += (nr_regs - get_nr_used_regs(m)) * 8;
3230 		/* make sure the stack pointer is 16-byte aligned if we
3231 		 * need pass arguments on stack, which means
3232 		 *  [stack_size + 8(rbp) + 8(rip) + 8(origin rip)]
3233 		 * should be 16-byte aligned. Following code depend on
3234 		 * that stack_size is already 8-byte aligned.
3235 		 */
3236 		stack_size += (stack_size % 16) ? 0 : 8;
3237 	}
3238 
3239 	arg_stack_off = stack_size;
3240 
3241 	if (flags & BPF_TRAMP_F_SKIP_FRAME) {
3242 		/* skip patched call instruction and point orig_call to actual
3243 		 * body of the kernel function.
3244 		 */
3245 		if (is_endbr(orig_call))
3246 			orig_call += ENDBR_INSN_SIZE;
3247 		orig_call += X86_PATCH_SIZE;
3248 	}
3249 
3250 	prog = rw_image;
3251 
3252 	if (flags & BPF_TRAMP_F_INDIRECT) {
3253 		/*
3254 		 * Indirect call for bpf_struct_ops
3255 		 */
3256 		emit_cfi(&prog, image,
3257 			 cfi_get_func_hash(func_addr),
3258 			 cfi_get_func_arity(func_addr));
3259 	} else {
3260 		/*
3261 		 * Direct-call fentry stub, as such it needs accounting for the
3262 		 * __fentry__ call.
3263 		 */
3264 		x86_call_depth_emit_accounting(&prog, NULL, image);
3265 	}
3266 	EMIT1(0x55);		 /* push rbp */
3267 	EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
3268 	if (!is_imm8(stack_size)) {
3269 		/* sub rsp, stack_size */
3270 		EMIT3_off32(0x48, 0x81, 0xEC, stack_size);
3271 	} else {
3272 		/* sub rsp, stack_size */
3273 		EMIT4(0x48, 0x83, 0xEC, stack_size);
3274 	}
3275 	if (flags & BPF_TRAMP_F_TAIL_CALL_CTX)
3276 		EMIT1(0x50);		/* push rax */
3277 	/* mov QWORD PTR [rbp - rbx_off], rbx */
3278 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_6, -rbx_off);
3279 
3280 	/* Store number of argument registers of the traced function:
3281 	 *   mov rax, nr_regs
3282 	 *   mov QWORD PTR [rbp - nregs_off], rax
3283 	 */
3284 	emit_mov_imm64(&prog, BPF_REG_0, 0, (u32) nr_regs);
3285 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -nregs_off);
3286 
3287 	if (flags & BPF_TRAMP_F_IP_ARG) {
3288 		/* Store IP address of the traced function:
3289 		 * movabsq rax, func_addr
3290 		 * mov QWORD PTR [rbp - ip_off], rax
3291 		 */
3292 		emit_mov_imm64(&prog, BPF_REG_0, (long) func_addr >> 32, (u32) (long) func_addr);
3293 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -ip_off);
3294 	}
3295 
3296 	save_args(m, &prog, regs_off, false);
3297 
3298 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3299 		/* arg1: mov rdi, im */
3300 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
3301 		if (emit_rsb_call(&prog, __bpf_tramp_enter,
3302 				  image + (prog - (u8 *)rw_image))) {
3303 			ret = -EINVAL;
3304 			goto cleanup;
3305 		}
3306 	}
3307 
3308 	if (fentry->nr_links) {
3309 		if (invoke_bpf(m, &prog, fentry, regs_off, run_ctx_off,
3310 			       flags & BPF_TRAMP_F_RET_FENTRY_RET, image, rw_image))
3311 			return -EINVAL;
3312 	}
3313 
3314 	if (fmod_ret->nr_links) {
3315 		branches = kcalloc(fmod_ret->nr_links, sizeof(u8 *),
3316 				   GFP_KERNEL);
3317 		if (!branches)
3318 			return -ENOMEM;
3319 
3320 		if (invoke_bpf_mod_ret(m, &prog, fmod_ret, regs_off,
3321 				       run_ctx_off, branches, image, rw_image)) {
3322 			ret = -EINVAL;
3323 			goto cleanup;
3324 		}
3325 	}
3326 
3327 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3328 		restore_regs(m, &prog, regs_off);
3329 		save_args(m, &prog, arg_stack_off, true);
3330 
3331 		if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
3332 			/* Before calling the original function, load the
3333 			 * tail_call_cnt_ptr from stack to rax.
3334 			 */
3335 			LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size);
3336 		}
3337 
3338 		if (flags & BPF_TRAMP_F_ORIG_STACK) {
3339 			emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, 8);
3340 			EMIT2(0xff, 0xd3); /* call *rbx */
3341 		} else {
3342 			/* call original function */
3343 			if (emit_rsb_call(&prog, orig_call, image + (prog - (u8 *)rw_image))) {
3344 				ret = -EINVAL;
3345 				goto cleanup;
3346 			}
3347 		}
3348 		/* remember return value in a stack for bpf prog to access */
3349 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
3350 		im->ip_after_call = image + (prog - (u8 *)rw_image);
3351 		emit_nops(&prog, X86_PATCH_SIZE);
3352 	}
3353 
3354 	if (fmod_ret->nr_links) {
3355 		/* From Intel 64 and IA-32 Architectures Optimization
3356 		 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
3357 		 * Coding Rule 11: All branch targets should be 16-byte
3358 		 * aligned.
3359 		 */
3360 		emit_align(&prog, 16);
3361 		/* Update the branches saved in invoke_bpf_mod_ret with the
3362 		 * aligned address of do_fexit.
3363 		 */
3364 		for (i = 0; i < fmod_ret->nr_links; i++) {
3365 			emit_cond_near_jump(&branches[i], image + (prog - (u8 *)rw_image),
3366 					    image + (branches[i] - (u8 *)rw_image), X86_JNE);
3367 		}
3368 	}
3369 
3370 	if (fexit->nr_links) {
3371 		if (invoke_bpf(m, &prog, fexit, regs_off, run_ctx_off,
3372 			       false, image, rw_image)) {
3373 			ret = -EINVAL;
3374 			goto cleanup;
3375 		}
3376 	}
3377 
3378 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
3379 		restore_regs(m, &prog, regs_off);
3380 
3381 	/* This needs to be done regardless. If there were fmod_ret programs,
3382 	 * the return value is only updated on the stack and still needs to be
3383 	 * restored to R0.
3384 	 */
3385 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3386 		im->ip_epilogue = image + (prog - (u8 *)rw_image);
3387 		/* arg1: mov rdi, im */
3388 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
3389 		if (emit_rsb_call(&prog, __bpf_tramp_exit, image + (prog - (u8 *)rw_image))) {
3390 			ret = -EINVAL;
3391 			goto cleanup;
3392 		}
3393 	} else if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
3394 		/* Before running the original function, load the
3395 		 * tail_call_cnt_ptr from stack to rax.
3396 		 */
3397 		LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size);
3398 	}
3399 
3400 	/* restore return value of orig_call or fentry prog back into RAX */
3401 	if (save_ret)
3402 		emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, -8);
3403 
3404 	emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, -rbx_off);
3405 	EMIT1(0xC9); /* leave */
3406 	if (flags & BPF_TRAMP_F_SKIP_FRAME) {
3407 		/* skip our return address and return to parent */
3408 		EMIT4(0x48, 0x83, 0xC4, 8); /* add rsp, 8 */
3409 	}
3410 	emit_return(&prog, image + (prog - (u8 *)rw_image));
3411 	/* Make sure the trampoline generation logic doesn't overflow */
3412 	if (WARN_ON_ONCE(prog > (u8 *)rw_image_end - BPF_INSN_SAFETY)) {
3413 		ret = -EFAULT;
3414 		goto cleanup;
3415 	}
3416 	ret = prog - (u8 *)rw_image + BPF_INSN_SAFETY;
3417 
3418 cleanup:
3419 	kfree(branches);
3420 	return ret;
3421 }
3422 
3423 void *arch_alloc_bpf_trampoline(unsigned int size)
3424 {
3425 	return bpf_prog_pack_alloc(size, jit_fill_hole);
3426 }
3427 
3428 void arch_free_bpf_trampoline(void *image, unsigned int size)
3429 {
3430 	bpf_prog_pack_free(image, size);
3431 }
3432 
3433 int arch_protect_bpf_trampoline(void *image, unsigned int size)
3434 {
3435 	return 0;
3436 }
3437 
3438 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
3439 				const struct btf_func_model *m, u32 flags,
3440 				struct bpf_tramp_links *tlinks,
3441 				void *func_addr)
3442 {
3443 	void *rw_image, *tmp;
3444 	int ret;
3445 	u32 size = image_end - image;
3446 
3447 	/* rw_image doesn't need to be in module memory range, so we can
3448 	 * use kvmalloc.
3449 	 */
3450 	rw_image = kvmalloc(size, GFP_KERNEL);
3451 	if (!rw_image)
3452 		return -ENOMEM;
3453 
3454 	ret = __arch_prepare_bpf_trampoline(im, rw_image, rw_image + size, image, m,
3455 					    flags, tlinks, func_addr);
3456 	if (ret < 0)
3457 		goto out;
3458 
3459 	tmp = bpf_arch_text_copy(image, rw_image, size);
3460 	if (IS_ERR(tmp))
3461 		ret = PTR_ERR(tmp);
3462 out:
3463 	kvfree(rw_image);
3464 	return ret;
3465 }
3466 
3467 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
3468 			     struct bpf_tramp_links *tlinks, void *func_addr)
3469 {
3470 	struct bpf_tramp_image im;
3471 	void *image;
3472 	int ret;
3473 
3474 	/* Allocate a temporary buffer for __arch_prepare_bpf_trampoline().
3475 	 * This will NOT cause fragmentation in direct map, as we do not
3476 	 * call set_memory_*() on this buffer.
3477 	 *
3478 	 * We cannot use kvmalloc here, because we need image to be in
3479 	 * module memory range.
3480 	 */
3481 	image = bpf_jit_alloc_exec(PAGE_SIZE);
3482 	if (!image)
3483 		return -ENOMEM;
3484 
3485 	ret = __arch_prepare_bpf_trampoline(&im, image, image + PAGE_SIZE, image,
3486 					    m, flags, tlinks, func_addr);
3487 	bpf_jit_free_exec(image);
3488 	return ret;
3489 }
3490 
3491 static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf)
3492 {
3493 	u8 *jg_reloc, *prog = *pprog;
3494 	int pivot, err, jg_bytes = 1;
3495 	s64 jg_offset;
3496 
3497 	if (a == b) {
3498 		/* Leaf node of recursion, i.e. not a range of indices
3499 		 * anymore.
3500 		 */
3501 		EMIT1(add_1mod(0x48, BPF_REG_3));	/* cmp rdx,func */
3502 		if (!is_simm32(progs[a]))
3503 			return -1;
3504 		EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3),
3505 			    progs[a]);
3506 		err = emit_cond_near_jump(&prog,	/* je func */
3507 					  (void *)progs[a], image + (prog - buf),
3508 					  X86_JE);
3509 		if (err)
3510 			return err;
3511 
3512 		emit_indirect_jump(&prog, 2 /* rdx */, image + (prog - buf));
3513 
3514 		*pprog = prog;
3515 		return 0;
3516 	}
3517 
3518 	/* Not a leaf node, so we pivot, and recursively descend into
3519 	 * the lower and upper ranges.
3520 	 */
3521 	pivot = (b - a) / 2;
3522 	EMIT1(add_1mod(0x48, BPF_REG_3));		/* cmp rdx,func */
3523 	if (!is_simm32(progs[a + pivot]))
3524 		return -1;
3525 	EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3), progs[a + pivot]);
3526 
3527 	if (pivot > 2) {				/* jg upper_part */
3528 		/* Require near jump. */
3529 		jg_bytes = 4;
3530 		EMIT2_off32(0x0F, X86_JG + 0x10, 0);
3531 	} else {
3532 		EMIT2(X86_JG, 0);
3533 	}
3534 	jg_reloc = prog;
3535 
3536 	err = emit_bpf_dispatcher(&prog, a, a + pivot,	/* emit lower_part */
3537 				  progs, image, buf);
3538 	if (err)
3539 		return err;
3540 
3541 	/* From Intel 64 and IA-32 Architectures Optimization
3542 	 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
3543 	 * Coding Rule 11: All branch targets should be 16-byte
3544 	 * aligned.
3545 	 */
3546 	emit_align(&prog, 16);
3547 	jg_offset = prog - jg_reloc;
3548 	emit_code(jg_reloc - jg_bytes, jg_offset, jg_bytes);
3549 
3550 	err = emit_bpf_dispatcher(&prog, a + pivot + 1,	/* emit upper_part */
3551 				  b, progs, image, buf);
3552 	if (err)
3553 		return err;
3554 
3555 	*pprog = prog;
3556 	return 0;
3557 }
3558 
3559 static int cmp_ips(const void *a, const void *b)
3560 {
3561 	const s64 *ipa = a;
3562 	const s64 *ipb = b;
3563 
3564 	if (*ipa > *ipb)
3565 		return 1;
3566 	if (*ipa < *ipb)
3567 		return -1;
3568 	return 0;
3569 }
3570 
3571 int arch_prepare_bpf_dispatcher(void *image, void *buf, s64 *funcs, int num_funcs)
3572 {
3573 	u8 *prog = buf;
3574 
3575 	sort(funcs, num_funcs, sizeof(funcs[0]), cmp_ips, NULL);
3576 	return emit_bpf_dispatcher(&prog, 0, num_funcs - 1, funcs, image, buf);
3577 }
3578 
3579 static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
3580 {
3581 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
3582 	u64 *stack_ptr;
3583 
3584 	for_each_possible_cpu(cpu) {
3585 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
3586 		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
3587 		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
3588 	}
3589 }
3590 
3591 static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
3592 				   struct bpf_prog *prog)
3593 {
3594 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
3595 	u64 *stack_ptr;
3596 
3597 	for_each_possible_cpu(cpu) {
3598 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
3599 		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
3600 		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL) {
3601 			pr_err("BPF private stack overflow/underflow detected for prog %sx\n",
3602 			       bpf_jit_get_prog_name(prog));
3603 			break;
3604 		}
3605 	}
3606 }
3607 
3608 struct x64_jit_data {
3609 	struct bpf_binary_header *rw_header;
3610 	struct bpf_binary_header *header;
3611 	int *addrs;
3612 	u8 *image;
3613 	int proglen;
3614 	struct jit_context ctx;
3615 };
3616 
3617 #define MAX_PASSES 20
3618 #define PADDING_PASSES (MAX_PASSES - 5)
3619 
3620 struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
3621 {
3622 	struct bpf_binary_header *rw_header = NULL;
3623 	struct bpf_binary_header *header = NULL;
3624 	struct bpf_prog *tmp, *orig_prog = prog;
3625 	void __percpu *priv_stack_ptr = NULL;
3626 	struct x64_jit_data *jit_data;
3627 	int priv_stack_alloc_sz;
3628 	int proglen, oldproglen = 0;
3629 	struct jit_context ctx = {};
3630 	bool tmp_blinded = false;
3631 	bool extra_pass = false;
3632 	bool padding = false;
3633 	u8 *rw_image = NULL;
3634 	u8 *image = NULL;
3635 	int *addrs;
3636 	int pass;
3637 	int i;
3638 
3639 	if (!prog->jit_requested)
3640 		return orig_prog;
3641 
3642 	tmp = bpf_jit_blind_constants(prog);
3643 	/*
3644 	 * If blinding was requested and we failed during blinding,
3645 	 * we must fall back to the interpreter.
3646 	 */
3647 	if (IS_ERR(tmp))
3648 		return orig_prog;
3649 	if (tmp != prog) {
3650 		tmp_blinded = true;
3651 		prog = tmp;
3652 	}
3653 
3654 	jit_data = prog->aux->jit_data;
3655 	if (!jit_data) {
3656 		jit_data = kzalloc(sizeof(*jit_data), GFP_KERNEL);
3657 		if (!jit_data) {
3658 			prog = orig_prog;
3659 			goto out;
3660 		}
3661 		prog->aux->jit_data = jit_data;
3662 	}
3663 	priv_stack_ptr = prog->aux->priv_stack_ptr;
3664 	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
3665 		/* Allocate actual private stack size with verifier-calculated
3666 		 * stack size plus two memory guards to protect overflow and
3667 		 * underflow.
3668 		 */
3669 		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
3670 				      2 * PRIV_STACK_GUARD_SZ;
3671 		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 8, GFP_KERNEL);
3672 		if (!priv_stack_ptr) {
3673 			prog = orig_prog;
3674 			goto out_priv_stack;
3675 		}
3676 
3677 		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
3678 		prog->aux->priv_stack_ptr = priv_stack_ptr;
3679 	}
3680 	addrs = jit_data->addrs;
3681 	if (addrs) {
3682 		ctx = jit_data->ctx;
3683 		oldproglen = jit_data->proglen;
3684 		image = jit_data->image;
3685 		header = jit_data->header;
3686 		rw_header = jit_data->rw_header;
3687 		rw_image = (void *)rw_header + ((void *)image - (void *)header);
3688 		extra_pass = true;
3689 		padding = true;
3690 		goto skip_init_addrs;
3691 	}
3692 	addrs = kvmalloc_array(prog->len + 1, sizeof(*addrs), GFP_KERNEL);
3693 	if (!addrs) {
3694 		prog = orig_prog;
3695 		goto out_addrs;
3696 	}
3697 
3698 	/*
3699 	 * Before first pass, make a rough estimation of addrs[]
3700 	 * each BPF instruction is translated to less than 64 bytes
3701 	 */
3702 	for (proglen = 0, i = 0; i <= prog->len; i++) {
3703 		proglen += 64;
3704 		addrs[i] = proglen;
3705 	}
3706 	ctx.cleanup_addr = proglen;
3707 skip_init_addrs:
3708 
3709 	/*
3710 	 * JITed image shrinks with every pass and the loop iterates
3711 	 * until the image stops shrinking. Very large BPF programs
3712 	 * may converge on the last pass. In such case do one more
3713 	 * pass to emit the final image.
3714 	 */
3715 	for (pass = 0; pass < MAX_PASSES || image; pass++) {
3716 		if (!padding && pass >= PADDING_PASSES)
3717 			padding = true;
3718 		proglen = do_jit(prog, addrs, image, rw_image, oldproglen, &ctx, padding);
3719 		if (proglen <= 0) {
3720 out_image:
3721 			image = NULL;
3722 			if (header) {
3723 				bpf_arch_text_copy(&header->size, &rw_header->size,
3724 						   sizeof(rw_header->size));
3725 				bpf_jit_binary_pack_free(header, rw_header);
3726 			}
3727 			/* Fall back to interpreter mode */
3728 			prog = orig_prog;
3729 			if (extra_pass) {
3730 				prog->bpf_func = NULL;
3731 				prog->jited = 0;
3732 				prog->jited_len = 0;
3733 			}
3734 			goto out_addrs;
3735 		}
3736 		if (image) {
3737 			if (proglen != oldproglen) {
3738 				pr_err("bpf_jit: proglen=%d != oldproglen=%d\n",
3739 				       proglen, oldproglen);
3740 				goto out_image;
3741 			}
3742 			break;
3743 		}
3744 		if (proglen == oldproglen) {
3745 			/*
3746 			 * The number of entries in extable is the number of BPF_LDX
3747 			 * insns that access kernel memory via "pointer to BTF type".
3748 			 * The verifier changed their opcode from LDX|MEM|size
3749 			 * to LDX|PROBE_MEM|size to make JITing easier.
3750 			 */
3751 			u32 align = __alignof__(struct exception_table_entry);
3752 			u32 extable_size = prog->aux->num_exentries *
3753 				sizeof(struct exception_table_entry);
3754 
3755 			/* allocate module memory for x86 insns and extable */
3756 			header = bpf_jit_binary_pack_alloc(roundup(proglen, align) + extable_size,
3757 							   &image, align, &rw_header, &rw_image,
3758 							   jit_fill_hole);
3759 			if (!header) {
3760 				prog = orig_prog;
3761 				goto out_addrs;
3762 			}
3763 			prog->aux->extable = (void *) image + roundup(proglen, align);
3764 		}
3765 		oldproglen = proglen;
3766 		cond_resched();
3767 	}
3768 
3769 	if (bpf_jit_enable > 1)
3770 		bpf_jit_dump(prog->len, proglen, pass + 1, rw_image);
3771 
3772 	if (image) {
3773 		if (!prog->is_func || extra_pass) {
3774 			/*
3775 			 * bpf_jit_binary_pack_finalize fails in two scenarios:
3776 			 *   1) header is not pointing to proper module memory;
3777 			 *   2) the arch doesn't support bpf_arch_text_copy().
3778 			 *
3779 			 * Both cases are serious bugs and justify WARN_ON.
3780 			 */
3781 			if (WARN_ON(bpf_jit_binary_pack_finalize(header, rw_header))) {
3782 				/* header has been freed */
3783 				header = NULL;
3784 				goto out_image;
3785 			}
3786 
3787 			bpf_tail_call_direct_fixup(prog);
3788 		} else {
3789 			jit_data->addrs = addrs;
3790 			jit_data->ctx = ctx;
3791 			jit_data->proglen = proglen;
3792 			jit_data->image = image;
3793 			jit_data->header = header;
3794 			jit_data->rw_header = rw_header;
3795 		}
3796 		/*
3797 		 * ctx.prog_offset is used when CFI preambles put code *before*
3798 		 * the function. See emit_cfi(). For FineIBT specifically this code
3799 		 * can also be executed and bpf_prog_kallsyms_add() will
3800 		 * generate an additional symbol to cover this, hence also
3801 		 * decrement proglen.
3802 		 */
3803 		prog->bpf_func = (void *)image + cfi_get_offset();
3804 		prog->jited = 1;
3805 		prog->jited_len = proglen - cfi_get_offset();
3806 	} else {
3807 		prog = orig_prog;
3808 	}
3809 
3810 	if (!image || !prog->is_func || extra_pass) {
3811 		if (image)
3812 			bpf_prog_fill_jited_linfo(prog, addrs + 1);
3813 out_addrs:
3814 		kvfree(addrs);
3815 		if (!image && priv_stack_ptr) {
3816 			free_percpu(priv_stack_ptr);
3817 			prog->aux->priv_stack_ptr = NULL;
3818 		}
3819 out_priv_stack:
3820 		kfree(jit_data);
3821 		prog->aux->jit_data = NULL;
3822 	}
3823 out:
3824 	if (tmp_blinded)
3825 		bpf_jit_prog_release_other(prog, prog == orig_prog ?
3826 					   tmp : orig_prog);
3827 	return prog;
3828 }
3829 
3830 bool bpf_jit_supports_kfunc_call(void)
3831 {
3832 	return true;
3833 }
3834 
3835 void *bpf_arch_text_copy(void *dst, void *src, size_t len)
3836 {
3837 	if (text_poke_copy(dst, src, len) == NULL)
3838 		return ERR_PTR(-EINVAL);
3839 	return dst;
3840 }
3841 
3842 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
3843 bool bpf_jit_supports_subprog_tailcalls(void)
3844 {
3845 	return true;
3846 }
3847 
3848 bool bpf_jit_supports_percpu_insn(void)
3849 {
3850 	return true;
3851 }
3852 
3853 void bpf_jit_free(struct bpf_prog *prog)
3854 {
3855 	if (prog->jited) {
3856 		struct x64_jit_data *jit_data = prog->aux->jit_data;
3857 		struct bpf_binary_header *hdr;
3858 		void __percpu *priv_stack_ptr;
3859 		int priv_stack_alloc_sz;
3860 
3861 		/*
3862 		 * If we fail the final pass of JIT (from jit_subprogs),
3863 		 * the program may not be finalized yet. Call finalize here
3864 		 * before freeing it.
3865 		 */
3866 		if (jit_data) {
3867 			bpf_jit_binary_pack_finalize(jit_data->header,
3868 						     jit_data->rw_header);
3869 			kvfree(jit_data->addrs);
3870 			kfree(jit_data);
3871 		}
3872 		prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset();
3873 		hdr = bpf_jit_binary_pack_hdr(prog);
3874 		bpf_jit_binary_pack_free(hdr, NULL);
3875 		priv_stack_ptr = prog->aux->priv_stack_ptr;
3876 		if (priv_stack_ptr) {
3877 			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
3878 					      2 * PRIV_STACK_GUARD_SZ;
3879 			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
3880 			free_percpu(prog->aux->priv_stack_ptr);
3881 		}
3882 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
3883 	}
3884 
3885 	bpf_prog_unlock_free(prog);
3886 }
3887 
3888 bool bpf_jit_supports_exceptions(void)
3889 {
3890 	/* We unwind through both kernel frames (starting from within bpf_throw
3891 	 * call) and BPF frames. Therefore we require ORC unwinder to be enabled
3892 	 * to walk kernel frames and reach BPF frames in the stack trace.
3893 	 */
3894 	return IS_ENABLED(CONFIG_UNWINDER_ORC);
3895 }
3896 
3897 bool bpf_jit_supports_private_stack(void)
3898 {
3899 	return true;
3900 }
3901 
3902 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
3903 {
3904 #if defined(CONFIG_UNWINDER_ORC)
3905 	struct unwind_state state;
3906 	unsigned long addr;
3907 
3908 	for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
3909 	     unwind_next_frame(&state)) {
3910 		addr = unwind_get_return_address(&state);
3911 		if (!addr || !consume_fn(cookie, (u64)addr, (u64)state.sp, (u64)state.bp))
3912 			break;
3913 	}
3914 	return;
3915 #endif
3916 }
3917 
3918 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
3919 			       struct bpf_prog *new, struct bpf_prog *old)
3920 {
3921 	u8 *old_addr, *new_addr, *old_bypass_addr;
3922 	int ret;
3923 
3924 	old_bypass_addr = old ? NULL : poke->bypass_addr;
3925 	old_addr = old ? (u8 *)old->bpf_func + poke->adj_off : NULL;
3926 	new_addr = new ? (u8 *)new->bpf_func + poke->adj_off : NULL;
3927 
3928 	/*
3929 	 * On program loading or teardown, the program's kallsym entry
3930 	 * might not be in place, so we use __bpf_arch_text_poke to skip
3931 	 * the kallsyms check.
3932 	 */
3933 	if (new) {
3934 		ret = __bpf_arch_text_poke(poke->tailcall_target,
3935 					   BPF_MOD_JUMP,
3936 					   old_addr, new_addr);
3937 		BUG_ON(ret < 0);
3938 		if (!old) {
3939 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
3940 						   BPF_MOD_JUMP,
3941 						   poke->bypass_addr,
3942 						   NULL);
3943 			BUG_ON(ret < 0);
3944 		}
3945 	} else {
3946 		ret = __bpf_arch_text_poke(poke->tailcall_bypass,
3947 					   BPF_MOD_JUMP,
3948 					   old_bypass_addr,
3949 					   poke->bypass_addr);
3950 		BUG_ON(ret < 0);
3951 		/* let other CPUs finish the execution of program
3952 		 * so that it will not possible to expose them
3953 		 * to invalid nop, stack unwind, nop state
3954 		 */
3955 		if (!ret)
3956 			synchronize_rcu();
3957 		ret = __bpf_arch_text_poke(poke->tailcall_target,
3958 					   BPF_MOD_JUMP,
3959 					   old_addr, NULL);
3960 		BUG_ON(ret < 0);
3961 	}
3962 }
3963 
3964 bool bpf_jit_supports_arena(void)
3965 {
3966 	return true;
3967 }
3968 
3969 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
3970 {
3971 	if (!in_arena)
3972 		return true;
3973 	switch (insn->code) {
3974 	case BPF_STX | BPF_ATOMIC | BPF_W:
3975 	case BPF_STX | BPF_ATOMIC | BPF_DW:
3976 		if (insn->imm == (BPF_AND | BPF_FETCH) ||
3977 		    insn->imm == (BPF_OR | BPF_FETCH) ||
3978 		    insn->imm == (BPF_XOR | BPF_FETCH))
3979 			return false;
3980 	}
3981 	return true;
3982 }
3983 
3984 bool bpf_jit_supports_ptr_xchg(void)
3985 {
3986 	return true;
3987 }
3988 
3989 /* x86-64 JIT emits its own code to filter user addresses so return 0 here */
3990 u64 bpf_arch_uaddress_limit(void)
3991 {
3992 	return 0;
3993 }
3994 
3995 bool bpf_jit_supports_timed_may_goto(void)
3996 {
3997 	return true;
3998 }
3999