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