xref: /linux/arch/x86/net/bpf_jit_comp.c (revision 65499074efaf574fef6365ac63b785a3ec98913d)
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 	if (bpf_prog->aux->exception_boundary)
1793 		bpf_prog->aux->stack_arg_sp_adjust = outgoing_rsp;
1794 	emit_sub_rsp(&prog, outgoing_rsp);
1795 
1796 	if (arena_vm_start)
1797 		emit_mov_imm64(&prog, X86_REG_R12,
1798 			       arena_vm_start >> 32, (u32) arena_vm_start);
1799 
1800 	if (priv_frame_ptr)
1801 		emit_priv_frame_ptr(&prog, priv_frame_ptr);
1802 
1803 	ilen = prog - temp;
1804 	if (rw_image)
1805 		memcpy(rw_image + proglen, temp, ilen);
1806 	proglen += ilen;
1807 	addrs[0] = proglen;
1808 	prog = temp;
1809 
1810 	for (i = 1; i <= insn_cnt; i++, insn++) {
1811 		const s32 imm32 = insn->imm;
1812 		u32 dst_reg = insn->dst_reg;
1813 		u32 src_reg = insn->src_reg;
1814 		u8 b2 = 0, b3 = 0;
1815 		u8 *start_of_ldx;
1816 		s64 jmp_offset;
1817 		s32 insn_off;
1818 		u8 jmp_cond;
1819 		u8 *func;
1820 		int nops;
1821 
1822 		if (priv_frame_ptr) {
1823 			if (src_reg == BPF_REG_FP)
1824 				src_reg = X86_REG_R9;
1825 
1826 			if (dst_reg == BPF_REG_FP)
1827 				dst_reg = X86_REG_R9;
1828 		}
1829 
1830 		if (bpf_insn_is_indirect_target(env, bpf_prog, i - 1))
1831 			EMIT_ENDBR();
1832 
1833 		ip = image + addrs[i - 1] + (prog - temp);
1834 
1835 		switch (insn->code) {
1836 			/* ALU */
1837 		case BPF_ALU | BPF_ADD | BPF_X:
1838 		case BPF_ALU | BPF_SUB | BPF_X:
1839 		case BPF_ALU | BPF_AND | BPF_X:
1840 		case BPF_ALU | BPF_OR | BPF_X:
1841 		case BPF_ALU | BPF_XOR | BPF_X:
1842 		case BPF_ALU64 | BPF_ADD | BPF_X:
1843 		case BPF_ALU64 | BPF_SUB | BPF_X:
1844 		case BPF_ALU64 | BPF_AND | BPF_X:
1845 		case BPF_ALU64 | BPF_OR | BPF_X:
1846 		case BPF_ALU64 | BPF_XOR | BPF_X:
1847 			maybe_emit_mod(&prog, dst_reg, src_reg,
1848 				       BPF_CLASS(insn->code) == BPF_ALU64);
1849 			b2 = simple_alu_opcodes[BPF_OP(insn->code)];
1850 			EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg));
1851 			break;
1852 
1853 		case BPF_ALU64 | BPF_MOV | BPF_X:
1854 			if (insn_is_cast_user(insn)) {
1855 				if (dst_reg != src_reg)
1856 					/* 32-bit mov */
1857 					emit_mov_reg(&prog, false, dst_reg, src_reg);
1858 				/* shl dst_reg, 32 */
1859 				maybe_emit_1mod(&prog, dst_reg, true);
1860 				EMIT3(0xC1, add_1reg(0xE0, dst_reg), 32);
1861 
1862 				/* or dst_reg, user_vm_start */
1863 				maybe_emit_1mod(&prog, dst_reg, true);
1864 				if (is_axreg(dst_reg))
1865 					EMIT1_off32(0x0D,  user_vm_start >> 32);
1866 				else
1867 					EMIT2_off32(0x81, add_1reg(0xC8, dst_reg),  user_vm_start >> 32);
1868 
1869 				/* rol dst_reg, 32 */
1870 				maybe_emit_1mod(&prog, dst_reg, true);
1871 				EMIT3(0xC1, add_1reg(0xC0, dst_reg), 32);
1872 
1873 				/* xor r11, r11 */
1874 				EMIT3(0x4D, 0x31, 0xDB);
1875 
1876 				/* test dst_reg32, dst_reg32; check if lower 32-bit are zero */
1877 				maybe_emit_mod(&prog, dst_reg, dst_reg, false);
1878 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
1879 
1880 				/* cmove r11, dst_reg; if so, set dst_reg to zero */
1881 				/* WARNING: Intel swapped src/dst register encoding in CMOVcc !!! */
1882 				maybe_emit_mod(&prog, AUX_REG, dst_reg, true);
1883 				EMIT3(0x0F, 0x44, add_2reg(0xC0, AUX_REG, dst_reg));
1884 				break;
1885 			} else if (insn_is_mov_percpu_addr(insn)) {
1886 				/* mov <dst>, <src> (if necessary) */
1887 				EMIT_mov(dst_reg, src_reg);
1888 #ifdef CONFIG_SMP
1889 				/* add <dst>, gs:[<off>] */
1890 				EMIT2(0x65, add_1mod(0x48, dst_reg));
1891 				EMIT3(0x03, add_2reg(0x04, 0, dst_reg), 0x25);
1892 				EMIT((u32)(unsigned long)&this_cpu_off, 4);
1893 #endif
1894 				break;
1895 			}
1896 			fallthrough;
1897 		case BPF_ALU | BPF_MOV | BPF_X:
1898 			if (insn->off == 0)
1899 				emit_mov_reg(&prog,
1900 					     BPF_CLASS(insn->code) == BPF_ALU64,
1901 					     dst_reg, src_reg);
1902 			else
1903 				emit_movsx_reg(&prog, insn->off,
1904 					       BPF_CLASS(insn->code) == BPF_ALU64,
1905 					       dst_reg, src_reg);
1906 			break;
1907 
1908 			/* neg dst */
1909 		case BPF_ALU | BPF_NEG:
1910 		case BPF_ALU64 | BPF_NEG:
1911 			maybe_emit_1mod(&prog, dst_reg,
1912 					BPF_CLASS(insn->code) == BPF_ALU64);
1913 			EMIT2(0xF7, add_1reg(0xD8, dst_reg));
1914 			break;
1915 
1916 		case BPF_ALU | BPF_ADD | BPF_K:
1917 		case BPF_ALU | BPF_SUB | BPF_K:
1918 		case BPF_ALU | BPF_AND | BPF_K:
1919 		case BPF_ALU | BPF_OR | BPF_K:
1920 		case BPF_ALU | BPF_XOR | BPF_K:
1921 		case BPF_ALU64 | BPF_ADD | BPF_K:
1922 		case BPF_ALU64 | BPF_SUB | BPF_K:
1923 		case BPF_ALU64 | BPF_AND | BPF_K:
1924 		case BPF_ALU64 | BPF_OR | BPF_K:
1925 		case BPF_ALU64 | BPF_XOR | BPF_K:
1926 			maybe_emit_1mod(&prog, dst_reg,
1927 					BPF_CLASS(insn->code) == BPF_ALU64);
1928 
1929 			/*
1930 			 * b3 holds 'normal' opcode, b2 short form only valid
1931 			 * in case dst is eax/rax.
1932 			 */
1933 			switch (BPF_OP(insn->code)) {
1934 			case BPF_ADD:
1935 				b3 = 0xC0;
1936 				b2 = 0x05;
1937 				break;
1938 			case BPF_SUB:
1939 				b3 = 0xE8;
1940 				b2 = 0x2D;
1941 				break;
1942 			case BPF_AND:
1943 				b3 = 0xE0;
1944 				b2 = 0x25;
1945 				break;
1946 			case BPF_OR:
1947 				b3 = 0xC8;
1948 				b2 = 0x0D;
1949 				break;
1950 			case BPF_XOR:
1951 				b3 = 0xF0;
1952 				b2 = 0x35;
1953 				break;
1954 			}
1955 
1956 			if (is_imm8(imm32))
1957 				EMIT3(0x83, add_1reg(b3, dst_reg), imm32);
1958 			else if (is_axreg(dst_reg))
1959 				EMIT1_off32(b2, imm32);
1960 			else
1961 				EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32);
1962 			break;
1963 
1964 		case BPF_ALU64 | BPF_MOV | BPF_K:
1965 		case BPF_ALU | BPF_MOV | BPF_K:
1966 			emit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64,
1967 				       dst_reg, imm32);
1968 			break;
1969 
1970 		case BPF_LD | BPF_IMM | BPF_DW:
1971 			emit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm);
1972 			insn++;
1973 			i++;
1974 			break;
1975 
1976 			/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */
1977 		case BPF_ALU | BPF_MOD | BPF_X:
1978 		case BPF_ALU | BPF_DIV | BPF_X:
1979 		case BPF_ALU | BPF_MOD | BPF_K:
1980 		case BPF_ALU | BPF_DIV | BPF_K:
1981 		case BPF_ALU64 | BPF_MOD | BPF_X:
1982 		case BPF_ALU64 | BPF_DIV | BPF_X:
1983 		case BPF_ALU64 | BPF_MOD | BPF_K:
1984 		case BPF_ALU64 | BPF_DIV | BPF_K: {
1985 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
1986 
1987 			if (dst_reg != BPF_REG_0)
1988 				EMIT1(0x50); /* push rax */
1989 			if (dst_reg != BPF_REG_3)
1990 				EMIT1(0x52); /* push rdx */
1991 
1992 			if (BPF_SRC(insn->code) == BPF_X) {
1993 				if (src_reg == BPF_REG_0 ||
1994 				    src_reg == BPF_REG_3) {
1995 					/* mov r11, src_reg */
1996 					EMIT_mov(AUX_REG, src_reg);
1997 					src_reg = AUX_REG;
1998 				}
1999 			} else {
2000 				/* mov r11, imm32 */
2001 				EMIT3_off32(0x49, 0xC7, 0xC3, imm32);
2002 				src_reg = AUX_REG;
2003 			}
2004 
2005 			if (dst_reg != BPF_REG_0)
2006 				/* mov rax, dst_reg */
2007 				emit_mov_reg(&prog, is64, BPF_REG_0, dst_reg);
2008 
2009 			if (insn->off == 0) {
2010 				/*
2011 				 * xor edx, edx
2012 				 * equivalent to 'xor rdx, rdx', but one byte less
2013 				 */
2014 				EMIT2(0x31, 0xd2);
2015 
2016 				/* div src_reg */
2017 				maybe_emit_1mod(&prog, src_reg, is64);
2018 				EMIT2(0xF7, add_1reg(0xF0, src_reg));
2019 			} else {
2020 				if (BPF_CLASS(insn->code) == BPF_ALU)
2021 					EMIT1(0x99); /* cdq */
2022 				else
2023 					EMIT2(0x48, 0x99); /* cqo */
2024 
2025 				/* idiv src_reg */
2026 				maybe_emit_1mod(&prog, src_reg, is64);
2027 				EMIT2(0xF7, add_1reg(0xF8, src_reg));
2028 			}
2029 
2030 			if (BPF_OP(insn->code) == BPF_MOD &&
2031 			    dst_reg != BPF_REG_3)
2032 				/* mov dst_reg, rdx */
2033 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_3);
2034 			else if (BPF_OP(insn->code) == BPF_DIV &&
2035 				 dst_reg != BPF_REG_0)
2036 				/* mov dst_reg, rax */
2037 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_0);
2038 
2039 			if (dst_reg != BPF_REG_3)
2040 				EMIT1(0x5A); /* pop rdx */
2041 			if (dst_reg != BPF_REG_0)
2042 				EMIT1(0x58); /* pop rax */
2043 			break;
2044 		}
2045 
2046 		case BPF_ALU | BPF_MUL | BPF_K:
2047 		case BPF_ALU64 | BPF_MUL | BPF_K:
2048 			maybe_emit_mod(&prog, dst_reg, dst_reg,
2049 				       BPF_CLASS(insn->code) == BPF_ALU64);
2050 
2051 			if (is_imm8(imm32))
2052 				/* imul dst_reg, dst_reg, imm8 */
2053 				EMIT3(0x6B, add_2reg(0xC0, dst_reg, dst_reg),
2054 				      imm32);
2055 			else
2056 				/* imul dst_reg, dst_reg, imm32 */
2057 				EMIT2_off32(0x69,
2058 					    add_2reg(0xC0, dst_reg, dst_reg),
2059 					    imm32);
2060 			break;
2061 
2062 		case BPF_ALU | BPF_MUL | BPF_X:
2063 		case BPF_ALU64 | BPF_MUL | BPF_X:
2064 			maybe_emit_mod(&prog, src_reg, dst_reg,
2065 				       BPF_CLASS(insn->code) == BPF_ALU64);
2066 
2067 			/* imul dst_reg, src_reg */
2068 			EMIT3(0x0F, 0xAF, add_2reg(0xC0, src_reg, dst_reg));
2069 			break;
2070 
2071 			/* Shifts */
2072 		case BPF_ALU | BPF_LSH | BPF_K:
2073 		case BPF_ALU | BPF_RSH | BPF_K:
2074 		case BPF_ALU | BPF_ARSH | BPF_K:
2075 		case BPF_ALU64 | BPF_LSH | BPF_K:
2076 		case BPF_ALU64 | BPF_RSH | BPF_K:
2077 		case BPF_ALU64 | BPF_ARSH | BPF_K:
2078 			maybe_emit_1mod(&prog, dst_reg,
2079 					BPF_CLASS(insn->code) == BPF_ALU64);
2080 
2081 			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
2082 			if (imm32 == 1)
2083 				EMIT2(0xD1, add_1reg(b3, dst_reg));
2084 			else
2085 				EMIT3(0xC1, add_1reg(b3, dst_reg), imm32);
2086 			break;
2087 
2088 		case BPF_ALU | BPF_LSH | BPF_X:
2089 		case BPF_ALU | BPF_RSH | BPF_X:
2090 		case BPF_ALU | BPF_ARSH | BPF_X:
2091 		case BPF_ALU64 | BPF_LSH | BPF_X:
2092 		case BPF_ALU64 | BPF_RSH | BPF_X:
2093 		case BPF_ALU64 | BPF_ARSH | BPF_X:
2094 			/* BMI2 shifts aren't better when shift count is already in rcx */
2095 			if (boot_cpu_has(X86_FEATURE_BMI2) && src_reg != BPF_REG_4) {
2096 				/* shrx/sarx/shlx dst_reg, dst_reg, src_reg */
2097 				bool w = (BPF_CLASS(insn->code) == BPF_ALU64);
2098 				u8 op;
2099 
2100 				switch (BPF_OP(insn->code)) {
2101 				case BPF_LSH:
2102 					op = 1; /* prefix 0x66 */
2103 					break;
2104 				case BPF_RSH:
2105 					op = 3; /* prefix 0xf2 */
2106 					break;
2107 				case BPF_ARSH:
2108 					op = 2; /* prefix 0xf3 */
2109 					break;
2110 				}
2111 
2112 				emit_shiftx(&prog, dst_reg, src_reg, w, op);
2113 
2114 				break;
2115 			}
2116 
2117 			if (src_reg != BPF_REG_4) { /* common case */
2118 				/* Check for bad case when dst_reg == rcx */
2119 				if (dst_reg == BPF_REG_4) {
2120 					/* mov r11, dst_reg */
2121 					EMIT_mov(AUX_REG, dst_reg);
2122 					dst_reg = AUX_REG;
2123 				} else {
2124 					EMIT1(0x51); /* push rcx */
2125 				}
2126 				/* mov rcx, src_reg */
2127 				EMIT_mov(BPF_REG_4, src_reg);
2128 			}
2129 
2130 			/* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */
2131 			maybe_emit_1mod(&prog, dst_reg,
2132 					BPF_CLASS(insn->code) == BPF_ALU64);
2133 
2134 			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
2135 			EMIT2(0xD3, add_1reg(b3, dst_reg));
2136 
2137 			if (src_reg != BPF_REG_4) {
2138 				if (insn->dst_reg == BPF_REG_4)
2139 					/* mov dst_reg, r11 */
2140 					EMIT_mov(insn->dst_reg, AUX_REG);
2141 				else
2142 					EMIT1(0x59); /* pop rcx */
2143 			}
2144 
2145 			break;
2146 
2147 		case BPF_ALU | BPF_END | BPF_FROM_BE:
2148 		case BPF_ALU64 | BPF_END | BPF_FROM_LE:
2149 			switch (imm32) {
2150 			case 16:
2151 				/* Emit 'ror %ax, 8' to swap lower 2 bytes */
2152 				EMIT1(0x66);
2153 				if (is_ereg(dst_reg))
2154 					EMIT1(0x41);
2155 				EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8);
2156 
2157 				/* Emit 'movzwl eax, ax' */
2158 				if (is_ereg(dst_reg))
2159 					EMIT3(0x45, 0x0F, 0xB7);
2160 				else
2161 					EMIT2(0x0F, 0xB7);
2162 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
2163 				break;
2164 			case 32:
2165 				/* Emit 'bswap eax' to swap lower 4 bytes */
2166 				if (is_ereg(dst_reg))
2167 					EMIT2(0x41, 0x0F);
2168 				else
2169 					EMIT1(0x0F);
2170 				EMIT1(add_1reg(0xC8, dst_reg));
2171 				break;
2172 			case 64:
2173 				/* Emit 'bswap rax' to swap 8 bytes */
2174 				EMIT3(add_1mod(0x48, dst_reg), 0x0F,
2175 				      add_1reg(0xC8, dst_reg));
2176 				break;
2177 			}
2178 			break;
2179 
2180 		case BPF_ALU | BPF_END | BPF_FROM_LE:
2181 			switch (imm32) {
2182 			case 16:
2183 				/*
2184 				 * Emit 'movzwl eax, ax' to zero extend 16-bit
2185 				 * into 64 bit
2186 				 */
2187 				if (is_ereg(dst_reg))
2188 					EMIT3(0x45, 0x0F, 0xB7);
2189 				else
2190 					EMIT2(0x0F, 0xB7);
2191 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
2192 				break;
2193 			case 32:
2194 				/* Emit 'mov eax, eax' to clear upper 32-bits */
2195 				if (is_ereg(dst_reg))
2196 					EMIT1(0x45);
2197 				EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg));
2198 				break;
2199 			case 64:
2200 				/* nop */
2201 				break;
2202 			}
2203 			break;
2204 
2205 			/* speculation barrier */
2206 		case BPF_ST | BPF_NOSPEC:
2207 			EMIT_LFENCE();
2208 			break;
2209 
2210 			/* ST: *(u8*)(dst_reg + off) = imm */
2211 		case BPF_ST | BPF_MEM | BPF_B:
2212 			if (is_ereg(dst_reg))
2213 				EMIT2(0x41, 0xC6);
2214 			else
2215 				EMIT1(0xC6);
2216 			goto st;
2217 		case BPF_ST | BPF_MEM | BPF_H:
2218 			if (is_ereg(dst_reg))
2219 				EMIT3(0x66, 0x41, 0xC7);
2220 			else
2221 				EMIT2(0x66, 0xC7);
2222 			goto st;
2223 		case BPF_ST | BPF_MEM | BPF_W:
2224 			if (is_ereg(dst_reg))
2225 				EMIT2(0x41, 0xC7);
2226 			else
2227 				EMIT1(0xC7);
2228 			goto st;
2229 		case BPF_ST | BPF_MEM | BPF_DW:
2230 			if (dst_reg == BPF_REG_PARAMS && insn->off == -8) {
2231 				/* Arg 6: store immediate in r9 register */
2232 				emit_mov_imm64(&prog, X86_REG_R9, imm32 >> 31, (u32)imm32);
2233 				break;
2234 			}
2235 			EMIT2(add_1mod(0x48, dst_reg), 0xC7);
2236 
2237 st:			insn_off = insn->off;
2238 			if (dst_reg == BPF_REG_PARAMS) {
2239 				/*
2240 				 * Args 7+: reverse BPF negative offsets to
2241 				 * x86 positive rsp offsets.
2242 				 * BPF off=-16 → [rsp+0], off=-24 → [rsp+8], ...
2243 				 */
2244 				insn_off = outgoing_arg_base - outgoing_rsp - insn_off - 16;
2245 				dst_reg = BPF_REG_FP;
2246 			}
2247 			if (is_imm8(insn_off))
2248 				EMIT2(add_1reg(0x40, dst_reg), insn_off);
2249 			else
2250 				EMIT1_off32(add_1reg(0x80, dst_reg), insn_off);
2251 
2252 			EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));
2253 			break;
2254 
2255 			/* STX: *(u8*)(dst_reg + off) = src_reg */
2256 		case BPF_STX | BPF_MEM | BPF_B:
2257 		case BPF_STX | BPF_MEM | BPF_H:
2258 		case BPF_STX | BPF_MEM | BPF_W:
2259 		case BPF_STX | BPF_MEM | BPF_DW:
2260 			if (dst_reg == BPF_REG_PARAMS && insn->off == -8) {
2261 				/* Arg 6: store register value in r9 */
2262 				EMIT_mov(X86_REG_R9, src_reg);
2263 				break;
2264 			}
2265 			insn_off = insn->off;
2266 			if (dst_reg == BPF_REG_PARAMS) {
2267 				insn_off = outgoing_arg_base - outgoing_rsp - insn_off - 16;
2268 				dst_reg = BPF_REG_FP;
2269 			}
2270 			emit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
2271 			break;
2272 
2273 		case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
2274 		case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
2275 		case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
2276 		case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
2277 			start_of_ldx = prog;
2278 			emit_st_r12(&prog, BPF_SIZE(insn->code), dst_reg, insn->off, insn->imm);
2279 			goto populate_extable;
2280 
2281 			/* LDX: dst_reg = *(u8*)(src_reg + r12 + off) */
2282 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_B:
2283 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
2284 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
2285 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
2286 		case BPF_LDX | BPF_PROBE_MEM32SX | BPF_B:
2287 		case BPF_LDX | BPF_PROBE_MEM32SX | BPF_H:
2288 		case BPF_LDX | BPF_PROBE_MEM32SX | BPF_W:
2289 		case BPF_STX | BPF_PROBE_MEM32 | BPF_B:
2290 		case BPF_STX | BPF_PROBE_MEM32 | BPF_H:
2291 		case BPF_STX | BPF_PROBE_MEM32 | BPF_W:
2292 		case BPF_STX | BPF_PROBE_MEM32 | BPF_DW:
2293 			start_of_ldx = prog;
2294 			if (BPF_CLASS(insn->code) == BPF_LDX) {
2295 				if (BPF_MODE(insn->code) == BPF_PROBE_MEM32SX)
2296 					emit_ldsx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2297 				else
2298 					emit_ldx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2299 			} else {
2300 				emit_stx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2301 			}
2302 populate_extable:
2303 			{
2304 				struct exception_table_entry *ex;
2305 				u8 *_insn = image + proglen + (start_of_ldx - temp);
2306 				u32 arena_reg, fixup_reg;
2307 				s64 delta;
2308 
2309 				if (!bpf_prog->aux->extable)
2310 					break;
2311 
2312 				if (excnt >= bpf_prog->aux->num_exentries) {
2313 					pr_err("mem32 extable bug\n");
2314 					return -EFAULT;
2315 				}
2316 				ex = &bpf_prog->aux->extable[excnt++];
2317 
2318 				delta = _insn - (u8 *)&ex->insn;
2319 				/* switch ex to rw buffer for writes */
2320 				ex = (void *)rw_image + ((void *)ex - (void *)image);
2321 
2322 				ex->insn = delta;
2323 
2324 				ex->data = EX_TYPE_BPF;
2325 
2326 				/*
2327 				 * src_reg/dst_reg holds the address in the arena region with upper
2328 				 * 32-bits being zero because of a preceding addr_space_cast(r<n>,
2329 				 * 0x0, 0x1) instruction. This address is adjusted with the addition
2330 				 * of arena_vm_start (see the implementation of BPF_PROBE_MEM32 and
2331 				 * BPF_PROBE_ATOMIC) before being used for the memory access. Pass
2332 				 * the reg holding the unmodified 32-bit address to
2333 				 * ex_handler_bpf().
2334 				 */
2335 				if (BPF_CLASS(insn->code) == BPF_LDX) {
2336 					arena_reg = reg2pt_regs[src_reg];
2337 					fixup_reg = reg2pt_regs[dst_reg];
2338 				} else {
2339 					arena_reg = reg2pt_regs[dst_reg];
2340 					fixup_reg = DONT_CLEAR;
2341 				}
2342 
2343 				ex->fixup = FIELD_PREP(FIXUP_INSN_LEN_MASK, prog - start_of_ldx) |
2344 					    FIELD_PREP(FIXUP_ARENA_REG_MASK, arena_reg) |
2345 					    FIELD_PREP(FIXUP_REG_MASK, fixup_reg);
2346 				ex->fixup |= FIXUP_ARENA_ACCESS;
2347 
2348 				ex->data |= FIELD_PREP(DATA_ARENA_OFFSET_MASK, insn->off);
2349 			}
2350 			break;
2351 
2352 			/* LDX: dst_reg = *(u8*)(src_reg + off) */
2353 		case BPF_LDX | BPF_MEM | BPF_B:
2354 		case BPF_LDX | BPF_PROBE_MEM | BPF_B:
2355 		case BPF_LDX | BPF_MEM | BPF_H:
2356 		case BPF_LDX | BPF_PROBE_MEM | BPF_H:
2357 		case BPF_LDX | BPF_MEM | BPF_W:
2358 		case BPF_LDX | BPF_PROBE_MEM | BPF_W:
2359 		case BPF_LDX | BPF_MEM | BPF_DW:
2360 		case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
2361 			/* LDXS: dst_reg = *(s8*)(src_reg + off) */
2362 		case BPF_LDX | BPF_MEMSX | BPF_B:
2363 		case BPF_LDX | BPF_MEMSX | BPF_H:
2364 		case BPF_LDX | BPF_MEMSX | BPF_W:
2365 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
2366 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
2367 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
2368 			insn_off = insn->off;
2369 			if (src_reg == BPF_REG_PARAMS) {
2370 				if (insn_off == 8) {
2371 					/* Incoming arg 6: read from r9 */
2372 					EMIT_mov(dst_reg, X86_REG_R9);
2373 					break;
2374 				}
2375 				src_reg = BPF_REG_FP;
2376 				/*
2377 				 * Incoming args 7+: native_off == bpf_off
2378 				 * (r11+16 → [rbp+16], r11+24 → [rbp+24], ...)
2379 				 * No offset adjustment needed.
2380 				 */
2381 			}
2382 
2383 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
2384 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
2385 				/* Conservatively check that src_reg + insn->off is a kernel address:
2386 				 *   src_reg + insn->off > TASK_SIZE_MAX + PAGE_SIZE
2387 				 *   and
2388 				 *   src_reg + insn->off < VSYSCALL_ADDR
2389 				 */
2390 
2391 				u64 limit = TASK_SIZE_MAX + PAGE_SIZE - VSYSCALL_ADDR;
2392 				u8 *end_of_jmp;
2393 
2394 				/* movabsq r10, VSYSCALL_ADDR */
2395 				emit_mov_imm64(&prog, BPF_REG_AX, (long)VSYSCALL_ADDR >> 32,
2396 					       (u32)(long)VSYSCALL_ADDR);
2397 
2398 				/* mov src_reg, r11 */
2399 				EMIT_mov(AUX_REG, src_reg);
2400 
2401 				if (insn->off) {
2402 					/* add r11, insn->off */
2403 					maybe_emit_1mod(&prog, AUX_REG, true);
2404 					EMIT2_off32(0x81, add_1reg(0xC0, AUX_REG), insn->off);
2405 				}
2406 
2407 				/* sub r11, r10 */
2408 				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
2409 				EMIT2(0x29, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
2410 
2411 				/* movabsq r10, limit */
2412 				emit_mov_imm64(&prog, BPF_REG_AX, (long)limit >> 32,
2413 					       (u32)(long)limit);
2414 
2415 				/* cmp r10, r11 */
2416 				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
2417 				EMIT2(0x39, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
2418 
2419 				/* if unsigned '>', goto load */
2420 				EMIT2(X86_JA, 0);
2421 				end_of_jmp = prog;
2422 
2423 				/* xor dst_reg, dst_reg */
2424 				emit_mov_imm32(&prog, false, dst_reg, 0);
2425 				/* jmp byte_after_ldx */
2426 				EMIT2(0xEB, 0);
2427 
2428 				/* populate jmp_offset for JAE above to jump to start_of_ldx */
2429 				start_of_ldx = prog;
2430 				end_of_jmp[-1] = start_of_ldx - end_of_jmp;
2431 			}
2432 			if (BPF_MODE(insn->code) == BPF_PROBE_MEMSX ||
2433 			    BPF_MODE(insn->code) == BPF_MEMSX)
2434 				emit_ldsx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
2435 			else
2436 				emit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
2437 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
2438 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
2439 				struct exception_table_entry *ex;
2440 				u8 *_insn = image + proglen + (start_of_ldx - temp);
2441 				s64 delta;
2442 
2443 				/* populate jmp_offset for JMP above */
2444 				start_of_ldx[-1] = prog - start_of_ldx;
2445 
2446 				if (!bpf_prog->aux->extable)
2447 					break;
2448 
2449 				if (excnt >= bpf_prog->aux->num_exentries) {
2450 					pr_err("ex gen bug\n");
2451 					return -EFAULT;
2452 				}
2453 				ex = &bpf_prog->aux->extable[excnt++];
2454 
2455 				delta = _insn - (u8 *)&ex->insn;
2456 				if (!is_simm32(delta)) {
2457 					pr_err("extable->insn doesn't fit into 32-bit\n");
2458 					return -EFAULT;
2459 				}
2460 				/* switch ex to rw buffer for writes */
2461 				ex = (void *)rw_image + ((void *)ex - (void *)image);
2462 
2463 				ex->insn = delta;
2464 
2465 				ex->data = EX_TYPE_BPF;
2466 
2467 				if (dst_reg > BPF_REG_9) {
2468 					pr_err("verifier error\n");
2469 					return -EFAULT;
2470 				}
2471 				/*
2472 				 * Compute size of x86 insn and its target dest x86 register.
2473 				 * ex_handler_bpf() will use lower 8 bits to adjust
2474 				 * pt_regs->ip to jump over this x86 instruction
2475 				 * and upper bits to figure out which pt_regs to zero out.
2476 				 * End result: x86 insn "mov rbx, qword ptr [rax+0x14]"
2477 				 * of 4 bytes will be ignored and rbx will be zero inited.
2478 				 */
2479 				ex->fixup = FIELD_PREP(FIXUP_INSN_LEN_MASK, prog - start_of_ldx) |
2480 					    FIELD_PREP(FIXUP_REG_MASK, reg2pt_regs[dst_reg]);
2481 			}
2482 			break;
2483 
2484 		case BPF_STX | BPF_ATOMIC | BPF_B:
2485 		case BPF_STX | BPF_ATOMIC | BPF_H:
2486 			if (!bpf_atomic_is_load_store(insn)) {
2487 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
2488 				return -EFAULT;
2489 			}
2490 			fallthrough;
2491 		case BPF_STX | BPF_ATOMIC | BPF_W:
2492 		case BPF_STX | BPF_ATOMIC | BPF_DW:
2493 			if (insn->imm == (BPF_AND | BPF_FETCH) ||
2494 			    insn->imm == (BPF_OR | BPF_FETCH) ||
2495 			    insn->imm == (BPF_XOR | BPF_FETCH)) {
2496 				bool is64 = BPF_SIZE(insn->code) == BPF_DW;
2497 				u32 real_src_reg = src_reg;
2498 				u32 real_dst_reg = dst_reg;
2499 				u8 *branch_target;
2500 
2501 				/*
2502 				 * Can't be implemented with a single x86 insn.
2503 				 * Need to do a CMPXCHG loop.
2504 				 */
2505 
2506 				/* Will need RAX as a CMPXCHG operand so save R0 */
2507 				emit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0);
2508 				if (src_reg == BPF_REG_0)
2509 					real_src_reg = BPF_REG_AX;
2510 				if (dst_reg == BPF_REG_0)
2511 					real_dst_reg = BPF_REG_AX;
2512 
2513 				branch_target = prog;
2514 				/* Load old value */
2515 				emit_ldx(&prog, BPF_SIZE(insn->code),
2516 					 BPF_REG_0, real_dst_reg, insn->off);
2517 				/*
2518 				 * Perform the (commutative) operation locally,
2519 				 * put the result in the AUX_REG.
2520 				 */
2521 				emit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0);
2522 				maybe_emit_mod(&prog, AUX_REG, real_src_reg, is64);
2523 				EMIT2(simple_alu_opcodes[BPF_OP(insn->imm)],
2524 				      add_2reg(0xC0, AUX_REG, real_src_reg));
2525 				/* Attempt to swap in new value */
2526 				err = emit_atomic_rmw(&prog, BPF_CMPXCHG,
2527 						      real_dst_reg, AUX_REG,
2528 						      insn->off,
2529 						      BPF_SIZE(insn->code));
2530 				if (WARN_ON(err))
2531 					return err;
2532 				/*
2533 				 * ZF tells us whether we won the race. If it's
2534 				 * cleared we need to try again.
2535 				 */
2536 				EMIT2(X86_JNE, -(prog - branch_target) - 2);
2537 				/* Return the pre-modification value */
2538 				emit_mov_reg(&prog, is64, real_src_reg, BPF_REG_0);
2539 				/* Restore R0 after clobbering RAX */
2540 				emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX);
2541 				break;
2542 			}
2543 
2544 			if (bpf_atomic_is_load_store(insn))
2545 				err = emit_atomic_ld_st(&prog, insn->imm, dst_reg, src_reg,
2546 							insn->off, BPF_SIZE(insn->code));
2547 			else
2548 				err = emit_atomic_rmw(&prog, insn->imm, dst_reg, src_reg,
2549 						      insn->off, BPF_SIZE(insn->code));
2550 			if (err)
2551 				return err;
2552 			break;
2553 
2554 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_B:
2555 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_H:
2556 			if (!bpf_atomic_is_load_store(insn)) {
2557 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
2558 				return -EFAULT;
2559 			}
2560 			fallthrough;
2561 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_W:
2562 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
2563 			start_of_ldx = prog;
2564 
2565 			if (bpf_atomic_is_load_store(insn))
2566 				err = emit_atomic_ld_st_index(&prog, insn->imm,
2567 							      BPF_SIZE(insn->code), dst_reg,
2568 							      src_reg, X86_REG_R12, insn->off);
2569 			else
2570 				err = emit_atomic_rmw_index(&prog, insn->imm, BPF_SIZE(insn->code),
2571 							    dst_reg, src_reg, X86_REG_R12,
2572 							    insn->off);
2573 			if (err)
2574 				return err;
2575 			goto populate_extable;
2576 
2577 			/* call */
2578 		case BPF_JMP | BPF_CALL: {
2579 			func = (u8 *) __bpf_call_base + imm32;
2580 			if (src_reg == BPF_PSEUDO_CALL && tail_call_reachable) {
2581 				LOAD_TAIL_CALL_CNT_PTR(stack_depth);
2582 				ip += 7;
2583 			}
2584 			if (!imm32)
2585 				return -EINVAL;
2586 			if (priv_frame_ptr) {
2587 				push_r9(&prog);
2588 				ip += 2;
2589 			}
2590 			ip += x86_call_depth_emit_accounting(&prog, func, ip);
2591 			if (emit_call(&prog, func, ip))
2592 				return -EINVAL;
2593 			if (priv_frame_ptr)
2594 				pop_r9(&prog);
2595 			break;
2596 		}
2597 
2598 		case BPF_JMP | BPF_TAIL_CALL:
2599 			if (imm32)
2600 				emit_bpf_tail_call_direct(bpf_prog,
2601 							  &bpf_prog->aux->poke_tab[imm32 - 1],
2602 							  &prog,
2603 							  ip,
2604 							  callee_regs_used,
2605 							  stack_depth,
2606 							  ctx);
2607 			else
2608 				emit_bpf_tail_call_indirect(bpf_prog,
2609 							    &prog,
2610 							    callee_regs_used,
2611 							    stack_depth,
2612 							    ip,
2613 							    ctx);
2614 			break;
2615 
2616 			/* cond jump */
2617 		case BPF_JMP | BPF_JEQ | BPF_X:
2618 		case BPF_JMP | BPF_JNE | BPF_X:
2619 		case BPF_JMP | BPF_JGT | BPF_X:
2620 		case BPF_JMP | BPF_JLT | BPF_X:
2621 		case BPF_JMP | BPF_JGE | BPF_X:
2622 		case BPF_JMP | BPF_JLE | BPF_X:
2623 		case BPF_JMP | BPF_JSGT | BPF_X:
2624 		case BPF_JMP | BPF_JSLT | BPF_X:
2625 		case BPF_JMP | BPF_JSGE | BPF_X:
2626 		case BPF_JMP | BPF_JSLE | BPF_X:
2627 		case BPF_JMP32 | BPF_JEQ | BPF_X:
2628 		case BPF_JMP32 | BPF_JNE | BPF_X:
2629 		case BPF_JMP32 | BPF_JGT | BPF_X:
2630 		case BPF_JMP32 | BPF_JLT | BPF_X:
2631 		case BPF_JMP32 | BPF_JGE | BPF_X:
2632 		case BPF_JMP32 | BPF_JLE | BPF_X:
2633 		case BPF_JMP32 | BPF_JSGT | BPF_X:
2634 		case BPF_JMP32 | BPF_JSLT | BPF_X:
2635 		case BPF_JMP32 | BPF_JSGE | BPF_X:
2636 		case BPF_JMP32 | BPF_JSLE | BPF_X:
2637 			/* cmp dst_reg, src_reg */
2638 			maybe_emit_mod(&prog, dst_reg, src_reg,
2639 				       BPF_CLASS(insn->code) == BPF_JMP);
2640 			EMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg));
2641 			goto emit_cond_jmp;
2642 
2643 		case BPF_JMP | BPF_JSET | BPF_X:
2644 		case BPF_JMP32 | BPF_JSET | BPF_X:
2645 			/* test dst_reg, src_reg */
2646 			maybe_emit_mod(&prog, dst_reg, src_reg,
2647 				       BPF_CLASS(insn->code) == BPF_JMP);
2648 			EMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg));
2649 			goto emit_cond_jmp;
2650 
2651 		case BPF_JMP | BPF_JSET | BPF_K:
2652 		case BPF_JMP32 | BPF_JSET | BPF_K:
2653 			/* test dst_reg, imm32 */
2654 			maybe_emit_1mod(&prog, dst_reg,
2655 					BPF_CLASS(insn->code) == BPF_JMP);
2656 			EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);
2657 			goto emit_cond_jmp;
2658 
2659 		case BPF_JMP | BPF_JEQ | BPF_K:
2660 		case BPF_JMP | BPF_JNE | BPF_K:
2661 		case BPF_JMP | BPF_JGT | BPF_K:
2662 		case BPF_JMP | BPF_JLT | BPF_K:
2663 		case BPF_JMP | BPF_JGE | BPF_K:
2664 		case BPF_JMP | BPF_JLE | BPF_K:
2665 		case BPF_JMP | BPF_JSGT | BPF_K:
2666 		case BPF_JMP | BPF_JSLT | BPF_K:
2667 		case BPF_JMP | BPF_JSGE | BPF_K:
2668 		case BPF_JMP | BPF_JSLE | BPF_K:
2669 		case BPF_JMP32 | BPF_JEQ | BPF_K:
2670 		case BPF_JMP32 | BPF_JNE | BPF_K:
2671 		case BPF_JMP32 | BPF_JGT | BPF_K:
2672 		case BPF_JMP32 | BPF_JLT | BPF_K:
2673 		case BPF_JMP32 | BPF_JGE | BPF_K:
2674 		case BPF_JMP32 | BPF_JLE | BPF_K:
2675 		case BPF_JMP32 | BPF_JSGT | BPF_K:
2676 		case BPF_JMP32 | BPF_JSLT | BPF_K:
2677 		case BPF_JMP32 | BPF_JSGE | BPF_K:
2678 		case BPF_JMP32 | BPF_JSLE | BPF_K:
2679 			/* test dst_reg, dst_reg to save one extra byte */
2680 			if (imm32 == 0) {
2681 				maybe_emit_mod(&prog, dst_reg, dst_reg,
2682 					       BPF_CLASS(insn->code) == BPF_JMP);
2683 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
2684 				goto emit_cond_jmp;
2685 			}
2686 
2687 			/* cmp dst_reg, imm8/32 */
2688 			maybe_emit_1mod(&prog, dst_reg,
2689 					BPF_CLASS(insn->code) == BPF_JMP);
2690 
2691 			if (is_imm8(imm32))
2692 				EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);
2693 			else
2694 				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);
2695 
2696 emit_cond_jmp:		/* Convert BPF opcode to x86 */
2697 			switch (BPF_OP(insn->code)) {
2698 			case BPF_JEQ:
2699 				jmp_cond = X86_JE;
2700 				break;
2701 			case BPF_JSET:
2702 			case BPF_JNE:
2703 				jmp_cond = X86_JNE;
2704 				break;
2705 			case BPF_JGT:
2706 				/* GT is unsigned '>', JA in x86 */
2707 				jmp_cond = X86_JA;
2708 				break;
2709 			case BPF_JLT:
2710 				/* LT is unsigned '<', JB in x86 */
2711 				jmp_cond = X86_JB;
2712 				break;
2713 			case BPF_JGE:
2714 				/* GE is unsigned '>=', JAE in x86 */
2715 				jmp_cond = X86_JAE;
2716 				break;
2717 			case BPF_JLE:
2718 				/* LE is unsigned '<=', JBE in x86 */
2719 				jmp_cond = X86_JBE;
2720 				break;
2721 			case BPF_JSGT:
2722 				/* Signed '>', GT in x86 */
2723 				jmp_cond = X86_JG;
2724 				break;
2725 			case BPF_JSLT:
2726 				/* Signed '<', LT in x86 */
2727 				jmp_cond = X86_JL;
2728 				break;
2729 			case BPF_JSGE:
2730 				/* Signed '>=', GE in x86 */
2731 				jmp_cond = X86_JGE;
2732 				break;
2733 			case BPF_JSLE:
2734 				/* Signed '<=', LE in x86 */
2735 				jmp_cond = X86_JLE;
2736 				break;
2737 			default: /* to silence GCC warning */
2738 				return -EFAULT;
2739 			}
2740 			jmp_offset = addrs[i + insn->off] - addrs[i];
2741 			if (is_imm8_jmp_offset(jmp_offset)) {
2742 				if (jmp_padding) {
2743 					/* To keep the jmp_offset valid, the extra bytes are
2744 					 * padded before the jump insn, so we subtract the
2745 					 * 2 bytes of jmp_cond insn from INSN_SZ_DIFF.
2746 					 *
2747 					 * If the previous pass already emits an imm8
2748 					 * jmp_cond, then this BPF insn won't shrink, so
2749 					 * "nops" is 0.
2750 					 *
2751 					 * On the other hand, if the previous pass emits an
2752 					 * imm32 jmp_cond, the extra 4 bytes(*) is padded to
2753 					 * keep the image from shrinking further.
2754 					 *
2755 					 * (*) imm32 jmp_cond is 6 bytes, and imm8 jmp_cond
2756 					 *     is 2 bytes, so the size difference is 4 bytes.
2757 					 */
2758 					nops = INSN_SZ_DIFF - 2;
2759 					if (nops != 0 && nops != 4) {
2760 						pr_err("unexpected jmp_cond padding: %d bytes\n",
2761 						       nops);
2762 						return -EFAULT;
2763 					}
2764 					emit_nops(&prog, nops);
2765 				}
2766 				EMIT2(jmp_cond, jmp_offset);
2767 			} else if (is_simm32(jmp_offset)) {
2768 				EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset);
2769 			} else {
2770 				pr_err("cond_jmp gen bug %llx\n", jmp_offset);
2771 				return -EFAULT;
2772 			}
2773 
2774 			break;
2775 
2776 		case BPF_JMP | BPF_JA | BPF_X:
2777 			emit_indirect_jump(&prog, insn->dst_reg, ip);
2778 			break;
2779 		case BPF_JMP | BPF_JA:
2780 		case BPF_JMP32 | BPF_JA:
2781 			if (BPF_CLASS(insn->code) == BPF_JMP) {
2782 				if (insn->off == -1)
2783 					/* -1 jmp instructions will always jump
2784 					 * backwards two bytes. Explicitly handling
2785 					 * this case avoids wasting too many passes
2786 					 * when there are long sequences of replaced
2787 					 * dead code.
2788 					 */
2789 					jmp_offset = -2;
2790 				else
2791 					jmp_offset = addrs[i + insn->off] - addrs[i];
2792 			} else {
2793 				if (insn->imm == -1)
2794 					jmp_offset = -2;
2795 				else
2796 					jmp_offset = addrs[i + insn->imm] - addrs[i];
2797 			}
2798 
2799 			if (!jmp_offset) {
2800 				/*
2801 				 * If jmp_padding is enabled, the extra nops will
2802 				 * be inserted. Otherwise, optimize out nop jumps.
2803 				 */
2804 				if (jmp_padding) {
2805 					/* There are 3 possible conditions.
2806 					 * (1) This BPF_JA is already optimized out in
2807 					 *     the previous run, so there is no need
2808 					 *     to pad any extra byte (0 byte).
2809 					 * (2) The previous pass emits an imm8 jmp,
2810 					 *     so we pad 2 bytes to match the previous
2811 					 *     insn size.
2812 					 * (3) Similarly, the previous pass emits an
2813 					 *     imm32 jmp, and 5 bytes is padded.
2814 					 */
2815 					nops = INSN_SZ_DIFF;
2816 					if (nops != 0 && nops != 2 && nops != 5) {
2817 						pr_err("unexpected nop jump padding: %d bytes\n",
2818 						       nops);
2819 						return -EFAULT;
2820 					}
2821 					emit_nops(&prog, nops);
2822 				}
2823 				break;
2824 			}
2825 emit_jmp:
2826 			if (is_imm8_jmp_offset(jmp_offset)) {
2827 				if (jmp_padding) {
2828 					/* To avoid breaking jmp_offset, the extra bytes
2829 					 * are padded before the actual jmp insn, so
2830 					 * 2 bytes is subtracted from INSN_SZ_DIFF.
2831 					 *
2832 					 * If the previous pass already emits an imm8
2833 					 * jmp, there is nothing to pad (0 byte).
2834 					 *
2835 					 * If it emits an imm32 jmp (5 bytes) previously
2836 					 * and now an imm8 jmp (2 bytes), then we pad
2837 					 * (5 - 2 = 3) bytes to stop the image from
2838 					 * shrinking further.
2839 					 */
2840 					nops = INSN_SZ_DIFF - 2;
2841 					if (nops != 0 && nops != 3) {
2842 						pr_err("unexpected jump padding: %d bytes\n",
2843 						       nops);
2844 						return -EFAULT;
2845 					}
2846 					emit_nops(&prog, INSN_SZ_DIFF - 2);
2847 				}
2848 				EMIT2(0xEB, jmp_offset);
2849 			} else if (is_simm32(jmp_offset)) {
2850 				EMIT1_off32(0xE9, jmp_offset);
2851 			} else {
2852 				pr_err("jmp gen bug %llx\n", jmp_offset);
2853 				return -EFAULT;
2854 			}
2855 			break;
2856 
2857 		case BPF_JMP | BPF_EXIT:
2858 			if (seen_exit) {
2859 				jmp_offset = ctx->cleanup_addr - addrs[i];
2860 				goto emit_jmp;
2861 			}
2862 			seen_exit = true;
2863 			/* Update cleanup_addr */
2864 			ctx->cleanup_addr = proglen;
2865 			if (bpf_prog_was_classic(bpf_prog) &&
2866 			    !ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN)) {
2867 				if (emit_spectre_bhb_barrier(&prog, ip, bpf_prog))
2868 					return -EINVAL;
2869 			}
2870 			/* Deallocate outgoing args 7+ area. */
2871 			emit_add_rsp(&prog, outgoing_rsp);
2872 			if (bpf_prog->aux->exception_boundary) {
2873 				pop_callee_regs(&prog, all_callee_regs_used);
2874 				pop_r12(&prog);
2875 			} else {
2876 				pop_callee_regs(&prog, callee_regs_used);
2877 				if (arena_vm_start)
2878 					pop_r12(&prog);
2879 			}
2880 			EMIT1(0xC9);         /* leave */
2881 			bpf_prog->aux->ksym.fp_end = prog - temp;
2882 
2883 			emit_return(&prog, image + addrs[i - 1] + (prog - temp));
2884 			break;
2885 
2886 		default:
2887 			/*
2888 			 * By design x86-64 JIT should support all BPF instructions.
2889 			 * This error will be seen if new instruction was added
2890 			 * to the interpreter, but not to the JIT, or if there is
2891 			 * junk in bpf_prog.
2892 			 */
2893 			pr_err("bpf_jit: unknown opcode %02x\n", insn->code);
2894 			return -EINVAL;
2895 		}
2896 
2897 		ilen = prog - temp;
2898 		if (ilen > BPF_MAX_INSN_SIZE) {
2899 			pr_err("bpf_jit: fatal insn size error\n");
2900 			return -EFAULT;
2901 		}
2902 
2903 		if (image) {
2904 			/*
2905 			 * When populating the image, assert that:
2906 			 *
2907 			 *  i) We do not write beyond the allocated space, and
2908 			 * ii) addrs[i] did not change from the prior run, in order
2909 			 *     to validate assumptions made for computing branch
2910 			 *     displacements.
2911 			 */
2912 			if (unlikely(proglen + ilen > oldproglen ||
2913 				     proglen + ilen != addrs[i])) {
2914 				pr_err("bpf_jit: fatal error\n");
2915 				return -EFAULT;
2916 			}
2917 			memcpy(rw_image + proglen, temp, ilen);
2918 		}
2919 		proglen += ilen;
2920 		addrs[i] = proglen;
2921 		prog = temp;
2922 	}
2923 
2924 	if (image && excnt != bpf_prog->aux->num_exentries) {
2925 		pr_err("extable is not populated\n");
2926 		return -EFAULT;
2927 	}
2928 	return proglen;
2929 }
2930 
2931 static void clean_stack_garbage(const struct btf_func_model *m,
2932 				u8 **pprog, int nr_stack_slots,
2933 				int stack_size)
2934 {
2935 	int arg_size, off;
2936 	u8 *prog;
2937 
2938 	/* Generally speaking, the compiler will pass the arguments
2939 	 * on-stack with "push" instruction, which will take 8-byte
2940 	 * on the stack. In this case, there won't be garbage values
2941 	 * while we copy the arguments from origin stack frame to current
2942 	 * in BPF_DW.
2943 	 *
2944 	 * However, sometimes the compiler will only allocate 4-byte on
2945 	 * the stack for the arguments. For now, this case will only
2946 	 * happen if there is only one argument on-stack and its size
2947 	 * not more than 4 byte. In this case, there will be garbage
2948 	 * values on the upper 4-byte where we store the argument on
2949 	 * current stack frame.
2950 	 *
2951 	 * arguments on origin stack:
2952 	 *
2953 	 * stack_arg_1(4-byte) xxx(4-byte)
2954 	 *
2955 	 * what we copy:
2956 	 *
2957 	 * stack_arg_1(8-byte): stack_arg_1(origin) xxx
2958 	 *
2959 	 * and the xxx is the garbage values which we should clean here.
2960 	 */
2961 	if (nr_stack_slots != 1)
2962 		return;
2963 
2964 	/* the size of the last argument */
2965 	arg_size = m->arg_size[m->nr_args - 1];
2966 	if (arg_size <= 4) {
2967 		off = -(stack_size - 4);
2968 		prog = *pprog;
2969 		/* mov DWORD PTR [rbp + off], 0 */
2970 		if (!is_imm8(off))
2971 			EMIT2_off32(0xC7, 0x85, off);
2972 		else
2973 			EMIT3(0xC7, 0x45, off);
2974 		EMIT(0, 4);
2975 		*pprog = prog;
2976 	}
2977 }
2978 
2979 /* get the count of the regs that are used to pass arguments */
2980 static int get_nr_used_regs(const struct btf_func_model *m)
2981 {
2982 	int i, arg_regs, nr_used_regs = 0;
2983 
2984 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
2985 		arg_regs = (m->arg_size[i] + 7) / 8;
2986 		if (nr_used_regs + arg_regs <= 6)
2987 			nr_used_regs += arg_regs;
2988 
2989 		if (nr_used_regs >= 6)
2990 			break;
2991 	}
2992 
2993 	return nr_used_regs;
2994 }
2995 
2996 static void save_args(const struct btf_func_model *m, u8 **prog,
2997 		      int stack_size, bool for_call_origin, u32 flags)
2998 {
2999 	int arg_regs, first_off = 0, nr_regs = 0, nr_stack_slots = 0;
3000 	bool use_jmp = bpf_trampoline_use_jmp(flags);
3001 	int i, j;
3002 
3003 	/* Store function arguments to stack.
3004 	 * For a function that accepts two pointers the sequence will be:
3005 	 * mov QWORD PTR [rbp-0x10],rdi
3006 	 * mov QWORD PTR [rbp-0x8],rsi
3007 	 */
3008 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
3009 		arg_regs = (m->arg_size[i] + 7) / 8;
3010 
3011 		/* According to the research of Yonghong, struct members
3012 		 * should be all in register or all on the stack.
3013 		 * Meanwhile, the compiler will pass the argument on regs
3014 		 * if the remaining regs can hold the argument.
3015 		 *
3016 		 * Disorder of the args can happen. For example:
3017 		 *
3018 		 * struct foo_struct {
3019 		 *     long a;
3020 		 *     int b;
3021 		 * };
3022 		 * int foo(char, char, char, char, char, struct foo_struct,
3023 		 *         char);
3024 		 *
3025 		 * the arg1-5,arg7 will be passed by regs, and arg6 will
3026 		 * by stack.
3027 		 */
3028 		if (nr_regs + arg_regs > 6) {
3029 			/* copy function arguments from origin stack frame
3030 			 * into current stack frame.
3031 			 *
3032 			 * The starting address of the arguments on-stack
3033 			 * is:
3034 			 *   rbp + 8(push rbp) +
3035 			 *   8(return addr of origin call) +
3036 			 *   8(return addr of the caller)
3037 			 * which means: rbp + 24
3038 			 */
3039 			for (j = 0; j < arg_regs; j++) {
3040 				emit_ldx(prog, BPF_DW, BPF_REG_0, BPF_REG_FP,
3041 					 nr_stack_slots * 8 + 16 + (!use_jmp) * 8);
3042 				emit_stx(prog, BPF_DW, BPF_REG_FP, BPF_REG_0,
3043 					 -stack_size);
3044 
3045 				if (!nr_stack_slots)
3046 					first_off = stack_size;
3047 				stack_size -= 8;
3048 				nr_stack_slots++;
3049 			}
3050 		} else {
3051 			/* Only copy the arguments on-stack to current
3052 			 * 'stack_size' and ignore the regs, used to
3053 			 * prepare the arguments on-stack for origin call.
3054 			 */
3055 			if (for_call_origin) {
3056 				nr_regs += arg_regs;
3057 				continue;
3058 			}
3059 
3060 			/* copy the arguments from regs into stack */
3061 			for (j = 0; j < arg_regs; j++) {
3062 				emit_stx(prog, BPF_DW, BPF_REG_FP,
3063 					 nr_regs == 5 ? X86_REG_R9 : BPF_REG_1 + nr_regs,
3064 					 -stack_size);
3065 				stack_size -= 8;
3066 				nr_regs++;
3067 			}
3068 		}
3069 	}
3070 
3071 	clean_stack_garbage(m, prog, nr_stack_slots, first_off);
3072 }
3073 
3074 static void restore_regs(const struct btf_func_model *m, u8 **prog,
3075 			 int stack_size)
3076 {
3077 	int i, j, arg_regs, nr_regs = 0;
3078 
3079 	/* Restore function arguments from stack.
3080 	 * For a function that accepts two pointers the sequence will be:
3081 	 * EMIT4(0x48, 0x8B, 0x7D, 0xF0); mov rdi,QWORD PTR [rbp-0x10]
3082 	 * EMIT4(0x48, 0x8B, 0x75, 0xF8); mov rsi,QWORD PTR [rbp-0x8]
3083 	 *
3084 	 * The logic here is similar to what we do in save_args()
3085 	 */
3086 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
3087 		arg_regs = (m->arg_size[i] + 7) / 8;
3088 		if (nr_regs + arg_regs <= 6) {
3089 			for (j = 0; j < arg_regs; j++) {
3090 				emit_ldx(prog, BPF_DW,
3091 					 nr_regs == 5 ? X86_REG_R9 : BPF_REG_1 + nr_regs,
3092 					 BPF_REG_FP,
3093 					 -stack_size);
3094 				stack_size -= 8;
3095 				nr_regs++;
3096 			}
3097 		} else {
3098 			stack_size -= 8 * arg_regs;
3099 		}
3100 
3101 		if (nr_regs >= 6)
3102 			break;
3103 	}
3104 }
3105 
3106 static int invoke_bpf_prog(const struct btf_func_model *m, u8 **pprog,
3107 			   struct bpf_tramp_node *node, int stack_size,
3108 			   int run_ctx_off, bool save_ret,
3109 			   void *image, void *rw_image)
3110 {
3111 	u8 *prog = *pprog;
3112 	u8 *jmp_insn;
3113 	int ctx_cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
3114 	struct bpf_prog *p = node->link->prog;
3115 	u64 cookie = node->cookie;
3116 
3117 	/* mov rdi, cookie */
3118 	emit_mov_imm64(&prog, BPF_REG_1, (long) cookie >> 32, (u32) (long) cookie);
3119 
3120 	/* Prepare struct bpf_tramp_run_ctx.
3121 	 *
3122 	 * bpf_tramp_run_ctx is already preserved by
3123 	 * arch_prepare_bpf_trampoline().
3124 	 *
3125 	 * mov QWORD PTR [rbp - run_ctx_off + ctx_cookie_off], rdi
3126 	 */
3127 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_1, -run_ctx_off + ctx_cookie_off);
3128 
3129 	/* arg1: mov rdi, progs[i] */
3130 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
3131 	/* arg2: lea rsi, [rbp - ctx_cookie_off] */
3132 	if (!is_imm8(-run_ctx_off))
3133 		EMIT3_off32(0x48, 0x8D, 0xB5, -run_ctx_off);
3134 	else
3135 		EMIT4(0x48, 0x8D, 0x75, -run_ctx_off);
3136 
3137 	if (emit_rsb_call(&prog, bpf_trampoline_enter(p), image + (prog - (u8 *)rw_image)))
3138 		return -EINVAL;
3139 	/* remember prog start time returned by __bpf_prog_enter */
3140 	emit_mov_reg(&prog, true, BPF_REG_6, BPF_REG_0);
3141 
3142 	/* if (__bpf_prog_enter*(prog) == 0)
3143 	 *	goto skip_exec_of_prog;
3144 	 */
3145 	EMIT3(0x48, 0x85, 0xC0);  /* test rax,rax */
3146 	/* emit 2 nops that will be replaced with JE insn */
3147 	jmp_insn = prog;
3148 	emit_nops(&prog, 2);
3149 
3150 	/* arg1: lea rdi, [rbp - stack_size] */
3151 	if (!is_imm8(-stack_size))
3152 		EMIT3_off32(0x48, 0x8D, 0xBD, -stack_size);
3153 	else
3154 		EMIT4(0x48, 0x8D, 0x7D, -stack_size);
3155 	/* arg2: progs[i]->insnsi for interpreter */
3156 	if (!p->jited)
3157 		emit_mov_imm64(&prog, BPF_REG_2,
3158 			       (long) p->insnsi >> 32,
3159 			       (u32) (long) p->insnsi);
3160 	/* call JITed bpf program or interpreter */
3161 	if (emit_rsb_call(&prog, p->bpf_func, image + (prog - (u8 *)rw_image)))
3162 		return -EINVAL;
3163 
3164 	/*
3165 	 * BPF_TRAMP_MODIFY_RETURN trampolines can modify the return
3166 	 * of the previous call which is then passed on the stack to
3167 	 * the next BPF program.
3168 	 *
3169 	 * BPF_TRAMP_FENTRY trampoline may need to return the return
3170 	 * value of BPF_PROG_TYPE_STRUCT_OPS prog.
3171 	 */
3172 	if (save_ret)
3173 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
3174 
3175 	/* replace 2 nops with JE insn, since jmp target is known */
3176 	jmp_insn[0] = X86_JE;
3177 	jmp_insn[1] = prog - jmp_insn - 2;
3178 
3179 	/* arg1: mov rdi, progs[i] */
3180 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
3181 	/* arg2: mov rsi, rbx <- start time in nsec */
3182 	emit_mov_reg(&prog, true, BPF_REG_2, BPF_REG_6);
3183 	/* arg3: lea rdx, [rbp - run_ctx_off] */
3184 	if (!is_imm8(-run_ctx_off))
3185 		EMIT3_off32(0x48, 0x8D, 0x95, -run_ctx_off);
3186 	else
3187 		EMIT4(0x48, 0x8D, 0x55, -run_ctx_off);
3188 	if (emit_rsb_call(&prog, bpf_trampoline_exit(p), image + (prog - (u8 *)rw_image)))
3189 		return -EINVAL;
3190 
3191 	*pprog = prog;
3192 	return 0;
3193 }
3194 
3195 static void emit_align(u8 **pprog, u32 align)
3196 {
3197 	u8 *target, *prog = *pprog;
3198 
3199 	target = PTR_ALIGN(prog, align);
3200 	if (target != prog)
3201 		emit_nops(&prog, target - prog);
3202 
3203 	*pprog = prog;
3204 }
3205 
3206 static int emit_cond_near_jump(u8 **pprog, void *func, void *ip, u8 jmp_cond)
3207 {
3208 	u8 *prog = *pprog;
3209 	s64 offset;
3210 
3211 	offset = func - (ip + 2 + 4);
3212 	if (!is_simm32(offset)) {
3213 		pr_err("Target %p is out of range\n", func);
3214 		return -EINVAL;
3215 	}
3216 	EMIT2_off32(0x0F, jmp_cond + 0x10, offset);
3217 	*pprog = prog;
3218 	return 0;
3219 }
3220 
3221 static int invoke_bpf(const struct btf_func_model *m, u8 **pprog,
3222 		      struct bpf_tramp_nodes *tl, int stack_size,
3223 		      int run_ctx_off, int func_meta_off, bool save_ret,
3224 		      void *image, void *rw_image, u64 func_meta,
3225 		      int cookie_off)
3226 {
3227 	int i, cur_cookie = (cookie_off - stack_size) / 8;
3228 	u8 *prog = *pprog;
3229 
3230 	for (i = 0; i < tl->nr_nodes; i++) {
3231 		if (tl->nodes[i]->link->prog->call_session_cookie) {
3232 			emit_store_stack_imm64(&prog, BPF_REG_0, -func_meta_off,
3233 				func_meta | (cur_cookie << BPF_TRAMP_COOKIE_INDEX_SHIFT));
3234 			cur_cookie--;
3235 		}
3236 		if (invoke_bpf_prog(m, &prog, tl->nodes[i], stack_size,
3237 				    run_ctx_off, save_ret, image, rw_image))
3238 			return -EINVAL;
3239 	}
3240 	*pprog = prog;
3241 	return 0;
3242 }
3243 
3244 static int invoke_bpf_mod_ret(const struct btf_func_model *m, u8 **pprog,
3245 			      struct bpf_tramp_nodes *tl, int stack_size,
3246 			      int run_ctx_off, u8 **branches,
3247 			      void *image, void *rw_image)
3248 {
3249 	u8 *prog = *pprog;
3250 	int i;
3251 
3252 	/* The first fmod_ret program will receive a garbage return value.
3253 	 * Set this to 0 to avoid confusing the program.
3254 	 */
3255 	emit_mov_imm32(&prog, false, BPF_REG_0, 0);
3256 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
3257 	for (i = 0; i < tl->nr_nodes; i++) {
3258 		if (invoke_bpf_prog(m, &prog, tl->nodes[i], stack_size, run_ctx_off, true,
3259 				    image, rw_image))
3260 			return -EINVAL;
3261 
3262 		/* mod_ret prog stored return value into [rbp - 8]. Emit:
3263 		 * if (*(u64 *)(rbp - 8) !=  0)
3264 		 *	goto do_fexit;
3265 		 */
3266 		/* cmp QWORD PTR [rbp - 0x8], 0x0 */
3267 		EMIT4(0x48, 0x83, 0x7d, 0xf8); EMIT1(0x00);
3268 
3269 		/* Save the location of the branch and Generate 6 nops
3270 		 * (4 bytes for an offset and 2 bytes for the jump) These nops
3271 		 * are replaced with a conditional jump once do_fexit (i.e. the
3272 		 * start of the fexit invocation) is finalized.
3273 		 */
3274 		branches[i] = prog;
3275 		emit_nops(&prog, 4 + 2);
3276 	}
3277 
3278 	*pprog = prog;
3279 	return 0;
3280 }
3281 
3282 /* mov rax, qword ptr [rbp - rounded_stack_depth - 8] */
3283 #define LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack)	\
3284 	__LOAD_TCC_PTR(-round_up(stack, 8) - 8)
3285 
3286 /* Example:
3287  * __be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev);
3288  * its 'struct btf_func_model' will be nr_args=2
3289  * The assembly code when eth_type_trans is executing after trampoline:
3290  *
3291  * push rbp
3292  * mov rbp, rsp
3293  * sub rsp, 16                     // space for skb and dev
3294  * push rbx                        // temp regs to pass start time
3295  * mov qword ptr [rbp - 16], rdi   // save skb pointer to stack
3296  * mov qword ptr [rbp - 8], rsi    // save dev pointer to stack
3297  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
3298  * mov rbx, rax                    // remember start time in bpf stats are enabled
3299  * lea rdi, [rbp - 16]             // R1==ctx of bpf prog
3300  * call addr_of_jited_FENTRY_prog
3301  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
3302  * mov rsi, rbx                    // prog start time
3303  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
3304  * mov rdi, qword ptr [rbp - 16]   // restore skb pointer from stack
3305  * mov rsi, qword ptr [rbp - 8]    // restore dev pointer from stack
3306  * pop rbx
3307  * leave
3308  * ret
3309  *
3310  * eth_type_trans has 5 byte nop at the beginning. These 5 bytes will be
3311  * replaced with 'call generated_bpf_trampoline'. When it returns
3312  * eth_type_trans will continue executing with original skb and dev pointers.
3313  *
3314  * The assembly code when eth_type_trans is called from trampoline:
3315  *
3316  * push rbp
3317  * mov rbp, rsp
3318  * sub rsp, 24                     // space for skb, dev, return value
3319  * push rbx                        // temp regs to pass start time
3320  * mov qword ptr [rbp - 24], rdi   // save skb pointer to stack
3321  * mov qword ptr [rbp - 16], rsi   // save dev pointer to stack
3322  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
3323  * mov rbx, rax                    // remember start time if bpf stats are enabled
3324  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
3325  * call addr_of_jited_FENTRY_prog  // bpf prog can access skb and dev
3326  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
3327  * mov rsi, rbx                    // prog start time
3328  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
3329  * mov rdi, qword ptr [rbp - 24]   // restore skb pointer from stack
3330  * mov rsi, qword ptr [rbp - 16]   // restore dev pointer from stack
3331  * call eth_type_trans+5           // execute body of eth_type_trans
3332  * mov qword ptr [rbp - 8], rax    // save return value
3333  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
3334  * mov rbx, rax                    // remember start time in bpf stats are enabled
3335  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
3336  * call addr_of_jited_FEXIT_prog   // bpf prog can access skb, dev, return value
3337  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
3338  * mov rsi, rbx                    // prog start time
3339  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
3340  * mov rax, qword ptr [rbp - 8]    // restore eth_type_trans's return value
3341  * pop rbx
3342  * leave
3343  * add rsp, 8                      // skip eth_type_trans's frame
3344  * ret                             // return to its caller
3345  */
3346 static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_image,
3347 					 void *rw_image_end, void *image,
3348 					 const struct btf_func_model *m, u32 flags,
3349 					 struct bpf_tramp_nodes *tnodes,
3350 					 void *func_addr)
3351 {
3352 	int i, ret, nr_regs = m->nr_args, stack_size = 0;
3353 	int regs_off, func_meta_off, ip_off, run_ctx_off, arg_stack_off, rbx_off;
3354 	struct bpf_tramp_nodes *fentry = &tnodes[BPF_TRAMP_FENTRY];
3355 	struct bpf_tramp_nodes *fexit = &tnodes[BPF_TRAMP_FEXIT];
3356 	struct bpf_tramp_nodes *fmod_ret = &tnodes[BPF_TRAMP_MODIFY_RETURN];
3357 	void *orig_call = func_addr;
3358 	int cookie_off, cookie_cnt;
3359 	u8 **branches = NULL;
3360 	u64 func_meta;
3361 	u8 *prog;
3362 	bool save_ret;
3363 
3364 	/*
3365 	 * F_INDIRECT is only compatible with F_RET_FENTRY_RET, it is
3366 	 * explicitly incompatible with F_CALL_ORIG | F_SKIP_FRAME | F_IP_ARG
3367 	 * because @func_addr.
3368 	 */
3369 	WARN_ON_ONCE((flags & BPF_TRAMP_F_INDIRECT) &&
3370 		     (flags & ~(BPF_TRAMP_F_INDIRECT | BPF_TRAMP_F_RET_FENTRY_RET)));
3371 
3372 	/* extra registers for struct arguments */
3373 	for (i = 0; i < m->nr_args; i++) {
3374 		if (m->arg_flags[i] & BTF_FMODEL_STRUCT_ARG)
3375 			nr_regs += (m->arg_size[i] + 7) / 8 - 1;
3376 	}
3377 
3378 	/* x86-64 supports up to MAX_BPF_FUNC_ARGS arguments. 1-6
3379 	 * are passed through regs, the remains are through stack.
3380 	 */
3381 	if (nr_regs > MAX_BPF_FUNC_ARGS)
3382 		return -ENOTSUPP;
3383 
3384 	/* Generated trampoline stack layout:
3385 	 *
3386 	 * RBP + 8         [ return address  ]
3387 	 * RBP + 0         [ RBP             ]
3388 	 *
3389 	 * RBP - 8         [ return value    ]  BPF_TRAMP_F_CALL_ORIG or
3390 	 *                                      BPF_TRAMP_F_RET_FENTRY_RET flags
3391 	 *
3392 	 *                 [ reg_argN        ]  always
3393 	 *                 [ ...             ]
3394 	 * RBP - regs_off  [ reg_arg1        ]  program's ctx pointer
3395 	 *
3396 	 * RBP - func_meta_off [ regs count, etc ]  always
3397 	 *
3398 	 * RBP - ip_off    [ traced function ]  BPF_TRAMP_F_IP_ARG flag
3399 	 *
3400 	 * RBP - rbx_off   [ rbx value       ]  always
3401 	 *
3402 	 * RBP - run_ctx_off [ bpf_tramp_run_ctx ]
3403 	 *
3404 	 *                     [ stack_argN ]  BPF_TRAMP_F_CALL_ORIG
3405 	 *                     [ ...        ]
3406 	 *                     [ stack_arg2 ]
3407 	 * RBP - arg_stack_off [ stack_arg1 ]
3408 	 * RSP                 [ tail_call_cnt_ptr ] BPF_TRAMP_F_TAIL_CALL_CTX
3409 	 */
3410 
3411 	/* room for return value of orig_call or fentry prog */
3412 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
3413 	if (save_ret)
3414 		stack_size += 8;
3415 
3416 	stack_size += nr_regs * 8;
3417 	regs_off = stack_size;
3418 
3419 	/* function matedata, such as regs count  */
3420 	stack_size += 8;
3421 	func_meta_off = stack_size;
3422 
3423 	if (flags & BPF_TRAMP_F_IP_ARG)
3424 		stack_size += 8; /* room for IP address argument */
3425 
3426 	ip_off = stack_size;
3427 
3428 	cookie_cnt = bpf_fsession_cookie_cnt(tnodes);
3429 	/* room for session cookies */
3430 	stack_size += cookie_cnt * 8;
3431 	cookie_off = stack_size;
3432 
3433 	stack_size += 8;
3434 	rbx_off = stack_size;
3435 
3436 	stack_size += (sizeof(struct bpf_tramp_run_ctx) + 7) & ~0x7;
3437 	run_ctx_off = stack_size;
3438 
3439 	if (nr_regs > 6 && (flags & BPF_TRAMP_F_CALL_ORIG)) {
3440 		/* the space that used to pass arguments on-stack */
3441 		stack_size += (nr_regs - get_nr_used_regs(m)) * 8;
3442 		/* make sure the stack pointer is 16-byte aligned if we
3443 		 * need pass arguments on stack, which means
3444 		 *  [stack_size + 8(rbp) + 8(rip) + 8(origin rip)]
3445 		 * should be 16-byte aligned. Following code depend on
3446 		 * that stack_size is already 8-byte aligned.
3447 		 */
3448 		if (bpf_trampoline_use_jmp(flags)) {
3449 			/* no rip in the "jmp" case */
3450 			stack_size += (stack_size % 16) ? 8 : 0;
3451 		} else {
3452 			stack_size += (stack_size % 16) ? 0 : 8;
3453 		}
3454 	}
3455 
3456 	arg_stack_off = stack_size;
3457 
3458 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3459 		/* skip patched call instruction and point orig_call to actual
3460 		 * body of the kernel function.
3461 		 */
3462 		if (is_endbr(orig_call))
3463 			orig_call += ENDBR_INSN_SIZE;
3464 		orig_call += X86_PATCH_SIZE;
3465 	}
3466 
3467 	prog = rw_image;
3468 
3469 	if (flags & BPF_TRAMP_F_INDIRECT) {
3470 		/*
3471 		 * Indirect call for bpf_struct_ops
3472 		 */
3473 		emit_cfi(&prog, image,
3474 			 cfi_get_func_hash(func_addr),
3475 			 cfi_get_func_arity(func_addr));
3476 	} else {
3477 		/*
3478 		 * Direct-call fentry stub, as such it needs accounting for the
3479 		 * __fentry__ call.
3480 		 */
3481 		x86_call_depth_emit_accounting(&prog, NULL, image);
3482 	}
3483 	EMIT1(0x55);		 /* push rbp */
3484 	EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
3485 	if (im)
3486 		im->ksym.fp_start = prog - (u8 *)rw_image;
3487 
3488 	if (!is_imm8(stack_size)) {
3489 		/* sub rsp, stack_size */
3490 		EMIT3_off32(0x48, 0x81, 0xEC, stack_size);
3491 	} else {
3492 		/* sub rsp, stack_size */
3493 		EMIT4(0x48, 0x83, 0xEC, stack_size);
3494 	}
3495 	if (flags & BPF_TRAMP_F_TAIL_CALL_CTX)
3496 		EMIT1(0x50);		/* push rax */
3497 	/* mov QWORD PTR [rbp - rbx_off], rbx */
3498 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_6, -rbx_off);
3499 
3500 	func_meta = nr_regs;
3501 	/* Store number of argument registers of the traced function */
3502 	emit_store_stack_imm64(&prog, BPF_REG_0, -func_meta_off, func_meta);
3503 
3504 	if (flags & BPF_TRAMP_F_IP_ARG) {
3505 		/* Store IP address of the traced function */
3506 		emit_store_stack_imm64(&prog, BPF_REG_0, -ip_off, (long)func_addr);
3507 	}
3508 
3509 	save_args(m, &prog, regs_off, false, flags);
3510 
3511 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3512 		/* arg1: mov rdi, im */
3513 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
3514 		if (emit_rsb_call(&prog, __bpf_tramp_enter,
3515 				  image + (prog - (u8 *)rw_image))) {
3516 			ret = -EINVAL;
3517 			goto cleanup;
3518 		}
3519 	}
3520 
3521 	if (bpf_fsession_cnt(tnodes)) {
3522 		/* clear all the session cookies' value */
3523 		for (int i = 0; i < cookie_cnt; i++)
3524 			emit_store_stack_imm64(&prog, BPF_REG_0, -cookie_off + 8 * i, 0);
3525 		/* clear the return value to make sure fentry always get 0 */
3526 		emit_store_stack_imm64(&prog, BPF_REG_0, -8, 0);
3527 	}
3528 
3529 	if (fentry->nr_nodes) {
3530 		if (invoke_bpf(m, &prog, fentry, regs_off, run_ctx_off, func_meta_off,
3531 			       flags & BPF_TRAMP_F_RET_FENTRY_RET, image, rw_image,
3532 			       func_meta, cookie_off))
3533 			return -EINVAL;
3534 	}
3535 
3536 	if (fmod_ret->nr_nodes) {
3537 		branches = kcalloc(fmod_ret->nr_nodes, sizeof(u8 *),
3538 				   GFP_KERNEL);
3539 		if (!branches)
3540 			return -ENOMEM;
3541 
3542 		if (invoke_bpf_mod_ret(m, &prog, fmod_ret, regs_off,
3543 				       run_ctx_off, branches, image, rw_image)) {
3544 			ret = -EINVAL;
3545 			goto cleanup;
3546 		}
3547 	}
3548 
3549 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3550 		restore_regs(m, &prog, regs_off);
3551 		save_args(m, &prog, arg_stack_off, true, flags);
3552 
3553 		if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
3554 			/* Before calling the original function, load the
3555 			 * tail_call_cnt_ptr from stack to rax.
3556 			 */
3557 			LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size);
3558 		}
3559 
3560 		if (flags & BPF_TRAMP_F_ORIG_STACK) {
3561 			emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, 8);
3562 			EMIT2(0xff, 0xd3); /* call *rbx */
3563 		} else {
3564 			/* call original function */
3565 			if (emit_rsb_call(&prog, orig_call, image + (prog - (u8 *)rw_image))) {
3566 				ret = -EINVAL;
3567 				goto cleanup;
3568 			}
3569 		}
3570 		/* remember return value in a stack for bpf prog to access */
3571 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
3572 		im->ip_after_call = image + (prog - (u8 *)rw_image);
3573 		emit_nops(&prog, X86_PATCH_SIZE);
3574 	}
3575 
3576 	if (fmod_ret->nr_nodes) {
3577 		/* From Intel 64 and IA-32 Architectures Optimization
3578 		 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
3579 		 * Coding Rule 11: All branch targets should be 16-byte
3580 		 * aligned.
3581 		 */
3582 		emit_align(&prog, 16);
3583 		/* Update the branches saved in invoke_bpf_mod_ret with the
3584 		 * aligned address of do_fexit.
3585 		 */
3586 		for (i = 0; i < fmod_ret->nr_nodes; i++) {
3587 			emit_cond_near_jump(&branches[i], image + (prog - (u8 *)rw_image),
3588 					    image + (branches[i] - (u8 *)rw_image), X86_JNE);
3589 		}
3590 	}
3591 
3592 	/* set the "is_return" flag for fsession */
3593 	func_meta |= (1ULL << BPF_TRAMP_IS_RETURN_SHIFT);
3594 	if (bpf_fsession_cnt(tnodes))
3595 		emit_store_stack_imm64(&prog, BPF_REG_0, -func_meta_off, func_meta);
3596 
3597 	if (fexit->nr_nodes) {
3598 		if (invoke_bpf(m, &prog, fexit, regs_off, run_ctx_off, func_meta_off,
3599 			       false, image, rw_image, func_meta, cookie_off)) {
3600 			ret = -EINVAL;
3601 			goto cleanup;
3602 		}
3603 	}
3604 
3605 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
3606 		restore_regs(m, &prog, regs_off);
3607 
3608 	/* This needs to be done regardless. If there were fmod_ret programs,
3609 	 * the return value is only updated on the stack and still needs to be
3610 	 * restored to R0.
3611 	 */
3612 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3613 		im->ip_epilogue = image + (prog - (u8 *)rw_image);
3614 		/* arg1: mov rdi, im */
3615 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
3616 		if (emit_rsb_call(&prog, __bpf_tramp_exit, image + (prog - (u8 *)rw_image))) {
3617 			ret = -EINVAL;
3618 			goto cleanup;
3619 		}
3620 	} else if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
3621 		/* Before running the original function, load the
3622 		 * tail_call_cnt_ptr from stack to rax.
3623 		 */
3624 		LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size);
3625 	}
3626 
3627 	/* restore return value of orig_call or fentry prog back into RAX */
3628 	if (save_ret)
3629 		emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, -8);
3630 
3631 	emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, -rbx_off);
3632 
3633 	EMIT1(0xC9); /* leave */
3634 	if (im)
3635 		im->ksym.fp_end = prog - (u8 *)rw_image;
3636 
3637 	if (flags & BPF_TRAMP_F_SKIP_FRAME) {
3638 		/* skip our return address and return to parent */
3639 		EMIT4(0x48, 0x83, 0xC4, 8); /* add rsp, 8 */
3640 	}
3641 	emit_return(&prog, image + (prog - (u8 *)rw_image));
3642 	/* Make sure the trampoline generation logic doesn't overflow */
3643 	if (WARN_ON_ONCE(prog > (u8 *)rw_image_end - BPF_INSN_SAFETY)) {
3644 		ret = -EFAULT;
3645 		goto cleanup;
3646 	}
3647 	ret = prog - (u8 *)rw_image + BPF_INSN_SAFETY;
3648 
3649 cleanup:
3650 	kfree(branches);
3651 	return ret;
3652 }
3653 
3654 void *arch_alloc_bpf_trampoline(unsigned int size)
3655 {
3656 	return bpf_prog_pack_alloc(size, jit_fill_hole);
3657 }
3658 
3659 void arch_free_bpf_trampoline(void *image, unsigned int size)
3660 {
3661 	bpf_prog_pack_free(image, size);
3662 }
3663 
3664 int arch_protect_bpf_trampoline(void *image, unsigned int size)
3665 {
3666 	return 0;
3667 }
3668 
3669 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
3670 				const struct btf_func_model *m, u32 flags,
3671 				struct bpf_tramp_nodes *tnodes,
3672 				void *func_addr)
3673 {
3674 	void *rw_image, *tmp;
3675 	int ret;
3676 	u32 size = image_end - image;
3677 
3678 	/* rw_image doesn't need to be in module memory range, so we can
3679 	 * use kvmalloc.
3680 	 */
3681 	rw_image = kvmalloc(size, GFP_KERNEL);
3682 	if (!rw_image)
3683 		return -ENOMEM;
3684 
3685 	ret = __arch_prepare_bpf_trampoline(im, rw_image, rw_image + size, image, m,
3686 					    flags, tnodes, func_addr);
3687 	if (ret < 0)
3688 		goto out;
3689 
3690 	tmp = bpf_arch_text_copy(image, rw_image, size);
3691 	if (IS_ERR(tmp))
3692 		ret = PTR_ERR(tmp);
3693 out:
3694 	kvfree(rw_image);
3695 	return ret;
3696 }
3697 
3698 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
3699 			     struct bpf_tramp_nodes *tnodes, void *func_addr)
3700 {
3701 	struct bpf_tramp_image im;
3702 	void *image;
3703 	int ret;
3704 
3705 	/* Allocate a temporary buffer for __arch_prepare_bpf_trampoline().
3706 	 * This will NOT cause fragmentation in direct map, as we do not
3707 	 * call set_memory_*() on this buffer.
3708 	 *
3709 	 * We cannot use kvmalloc here, because we need image to be in
3710 	 * module memory range.
3711 	 */
3712 	image = bpf_jit_alloc_exec(PAGE_SIZE);
3713 	if (!image)
3714 		return -ENOMEM;
3715 
3716 	ret = __arch_prepare_bpf_trampoline(&im, image, image + PAGE_SIZE, image,
3717 					    m, flags, tnodes, func_addr);
3718 	bpf_jit_free_exec(image);
3719 	return ret;
3720 }
3721 
3722 static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf)
3723 {
3724 	u8 *jg_reloc, *prog = *pprog;
3725 	int pivot, err, jg_bytes = 1;
3726 	s64 jg_offset;
3727 
3728 	if (a == b) {
3729 		/* Leaf node of recursion, i.e. not a range of indices
3730 		 * anymore.
3731 		 */
3732 		EMIT1(add_1mod(0x48, BPF_REG_3));	/* cmp rdx,func */
3733 		if (!is_simm32(progs[a]))
3734 			return -1;
3735 		EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3),
3736 			    progs[a]);
3737 		err = emit_cond_near_jump(&prog,	/* je func */
3738 					  (void *)progs[a], image + (prog - buf),
3739 					  X86_JE);
3740 		if (err)
3741 			return err;
3742 
3743 		emit_indirect_jump(&prog, BPF_REG_3 /* R3 -> rdx */, image + (prog - buf));
3744 
3745 		*pprog = prog;
3746 		return 0;
3747 	}
3748 
3749 	/* Not a leaf node, so we pivot, and recursively descend into
3750 	 * the lower and upper ranges.
3751 	 */
3752 	pivot = (b - a) / 2;
3753 	EMIT1(add_1mod(0x48, BPF_REG_3));		/* cmp rdx,func */
3754 	if (!is_simm32(progs[a + pivot]))
3755 		return -1;
3756 	EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3), progs[a + pivot]);
3757 
3758 	if (pivot > 2) {				/* jg upper_part */
3759 		/* Require near jump. */
3760 		jg_bytes = 4;
3761 		EMIT2_off32(0x0F, X86_JG + 0x10, 0);
3762 	} else {
3763 		EMIT2(X86_JG, 0);
3764 	}
3765 	jg_reloc = prog;
3766 
3767 	err = emit_bpf_dispatcher(&prog, a, a + pivot,	/* emit lower_part */
3768 				  progs, image, buf);
3769 	if (err)
3770 		return err;
3771 
3772 	/* From Intel 64 and IA-32 Architectures Optimization
3773 	 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
3774 	 * Coding Rule 11: All branch targets should be 16-byte
3775 	 * aligned.
3776 	 */
3777 	emit_align(&prog, 16);
3778 	jg_offset = prog - jg_reloc;
3779 	emit_code(jg_reloc - jg_bytes, jg_offset, jg_bytes);
3780 
3781 	err = emit_bpf_dispatcher(&prog, a + pivot + 1,	/* emit upper_part */
3782 				  b, progs, image, buf);
3783 	if (err)
3784 		return err;
3785 
3786 	*pprog = prog;
3787 	return 0;
3788 }
3789 
3790 static int cmp_ips(const void *a, const void *b)
3791 {
3792 	const s64 *ipa = a;
3793 	const s64 *ipb = b;
3794 
3795 	if (*ipa > *ipb)
3796 		return 1;
3797 	if (*ipa < *ipb)
3798 		return -1;
3799 	return 0;
3800 }
3801 
3802 int arch_prepare_bpf_dispatcher(void *image, void *buf, s64 *funcs, int num_funcs)
3803 {
3804 	u8 *prog = buf;
3805 
3806 	sort(funcs, num_funcs, sizeof(funcs[0]), cmp_ips, NULL);
3807 	return emit_bpf_dispatcher(&prog, 0, num_funcs - 1, funcs, image, buf);
3808 }
3809 
3810 static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
3811 {
3812 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
3813 	u64 *stack_ptr;
3814 
3815 	for_each_possible_cpu(cpu) {
3816 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
3817 		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
3818 		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
3819 	}
3820 }
3821 
3822 static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
3823 				   struct bpf_prog *prog)
3824 {
3825 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
3826 	u64 *stack_ptr;
3827 
3828 	for_each_possible_cpu(cpu) {
3829 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
3830 		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
3831 		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL) {
3832 			pr_err("BPF private stack overflow/underflow detected for prog %sx\n",
3833 			       bpf_jit_get_prog_name(prog));
3834 			break;
3835 		}
3836 	}
3837 }
3838 
3839 struct x64_jit_data {
3840 	struct bpf_binary_header *rw_header;
3841 	struct bpf_binary_header *header;
3842 	int *addrs;
3843 	u8 *image;
3844 	int proglen;
3845 	struct jit_context ctx;
3846 };
3847 
3848 #define MAX_PASSES 20
3849 #define PADDING_PASSES (MAX_PASSES - 5)
3850 
3851 struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog)
3852 {
3853 	struct bpf_binary_header *rw_header = NULL;
3854 	struct bpf_binary_header *header = NULL;
3855 	void __percpu *priv_stack_ptr = NULL;
3856 	struct x64_jit_data *jit_data;
3857 	int priv_stack_alloc_sz;
3858 	int proglen, oldproglen = 0;
3859 	struct jit_context ctx = {};
3860 	bool extra_pass = false;
3861 	bool padding = false;
3862 	u8 *rw_image = NULL;
3863 	u8 *image = NULL;
3864 	int *addrs;
3865 	int pass;
3866 	int i;
3867 
3868 	if (!prog->jit_requested)
3869 		return prog;
3870 
3871 	jit_data = prog->aux->jit_data;
3872 	if (!jit_data) {
3873 		jit_data = kzalloc_obj(*jit_data);
3874 		if (!jit_data)
3875 			return prog;
3876 		prog->aux->jit_data = jit_data;
3877 	}
3878 	priv_stack_ptr = prog->aux->priv_stack_ptr;
3879 	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
3880 		/* Allocate actual private stack size with verifier-calculated
3881 		 * stack size plus two memory guards to protect overflow and
3882 		 * underflow.
3883 		 */
3884 		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
3885 				      2 * PRIV_STACK_GUARD_SZ;
3886 		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 8, GFP_KERNEL);
3887 		if (!priv_stack_ptr)
3888 			goto out_priv_stack;
3889 
3890 		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
3891 		prog->aux->priv_stack_ptr = priv_stack_ptr;
3892 	}
3893 	addrs = jit_data->addrs;
3894 	if (addrs) {
3895 		ctx = jit_data->ctx;
3896 		oldproglen = jit_data->proglen;
3897 		image = jit_data->image;
3898 		header = jit_data->header;
3899 		rw_header = jit_data->rw_header;
3900 		rw_image = (void *)rw_header + ((void *)image - (void *)header);
3901 		extra_pass = true;
3902 		padding = true;
3903 		goto skip_init_addrs;
3904 	}
3905 	addrs = kvmalloc_objs(*addrs, prog->len + 1);
3906 	if (!addrs)
3907 		goto out_addrs;
3908 
3909 	/*
3910 	 * Before first pass, make a rough estimation of addrs[]
3911 	 * each BPF instruction is translated to less than 64 bytes
3912 	 */
3913 	for (proglen = 0, i = 0; i <= prog->len; i++) {
3914 		proglen += 64;
3915 		addrs[i] = proglen;
3916 	}
3917 	ctx.cleanup_addr = proglen;
3918 skip_init_addrs:
3919 
3920 	/*
3921 	 * JITed image shrinks with every pass and the loop iterates
3922 	 * until the image stops shrinking. Very large BPF programs
3923 	 * may converge on the last pass. In such case do one more
3924 	 * pass to emit the final image.
3925 	 */
3926 	for (pass = 0; pass < MAX_PASSES || image; pass++) {
3927 		if (!padding && pass >= PADDING_PASSES)
3928 			padding = true;
3929 		proglen = do_jit(env, prog, addrs, image, rw_image, oldproglen,
3930 				 &ctx, padding);
3931 		if (proglen <= 0) {
3932 out_image:
3933 			image = NULL;
3934 			if (header) {
3935 				bpf_arch_text_copy(&header->size, &rw_header->size,
3936 						   sizeof(rw_header->size));
3937 				bpf_jit_binary_pack_free(header, rw_header);
3938 			}
3939 			if (extra_pass) {
3940 				prog->bpf_func = NULL;
3941 				prog->jited = 0;
3942 				prog->jited_len = 0;
3943 			}
3944 			goto out_addrs;
3945 		}
3946 		if (image) {
3947 			if (proglen != oldproglen) {
3948 				pr_err("bpf_jit: proglen=%d != oldproglen=%d\n",
3949 				       proglen, oldproglen);
3950 				goto out_image;
3951 			}
3952 			break;
3953 		}
3954 		if (proglen == oldproglen) {
3955 			/*
3956 			 * The number of entries in extable is the number of BPF_LDX
3957 			 * insns that access kernel memory via "pointer to BTF type".
3958 			 * The verifier changed their opcode from LDX|MEM|size
3959 			 * to LDX|PROBE_MEM|size to make JITing easier.
3960 			 */
3961 			u32 align = __alignof__(struct exception_table_entry);
3962 			u32 extable_size = prog->aux->num_exentries *
3963 				sizeof(struct exception_table_entry);
3964 
3965 			/* allocate module memory for x86 insns and extable */
3966 			header = bpf_jit_binary_pack_alloc(roundup(proglen, align) + extable_size,
3967 							   &image, align, &rw_header, &rw_image,
3968 							   jit_fill_hole);
3969 			if (!header)
3970 				goto out_addrs;
3971 			prog->aux->extable = (void *) image + roundup(proglen, align);
3972 		}
3973 		oldproglen = proglen;
3974 		cond_resched();
3975 	}
3976 
3977 	if (bpf_jit_enable > 1)
3978 		bpf_jit_dump(prog->len, proglen, pass + 1, rw_image);
3979 
3980 	if (image) {
3981 		if (!prog->is_func || extra_pass) {
3982 			/*
3983 			 * bpf_jit_binary_pack_finalize fails in two scenarios:
3984 			 *   1) header is not pointing to proper module memory;
3985 			 *   2) the arch doesn't support bpf_arch_text_copy().
3986 			 *
3987 			 * Both cases are serious bugs and justify WARN_ON.
3988 			 */
3989 			if (WARN_ON(bpf_jit_binary_pack_finalize(header, rw_header))) {
3990 				/* header has been freed */
3991 				header = NULL;
3992 				goto out_image;
3993 			}
3994 
3995 			bpf_tail_call_direct_fixup(prog);
3996 		} else {
3997 			jit_data->addrs = addrs;
3998 			jit_data->ctx = ctx;
3999 			jit_data->proglen = proglen;
4000 			jit_data->image = image;
4001 			jit_data->header = header;
4002 			jit_data->rw_header = rw_header;
4003 		}
4004 
4005 		/*
4006 		 * The bpf_prog_update_insn_ptrs function expects addrs to
4007 		 * point to the first byte of the jitted instruction (unlike
4008 		 * the bpf_prog_fill_jited_linfo below, which, for historical
4009 		 * reasons, expects to point to the next instruction)
4010 		 */
4011 		bpf_prog_update_insn_ptrs(prog, addrs, image);
4012 
4013 		/*
4014 		 * ctx.prog_offset is used when CFI preambles put code *before*
4015 		 * the function. See emit_cfi(). For FineIBT specifically this code
4016 		 * can also be executed and bpf_prog_kallsyms_add() will
4017 		 * generate an additional symbol to cover this, hence also
4018 		 * decrement proglen.
4019 		 */
4020 		prog->bpf_func = (void *)image + cfi_get_offset();
4021 		prog->jited = 1;
4022 		prog->jited_len = proglen - cfi_get_offset();
4023 	}
4024 
4025 	if (!image || !prog->is_func || extra_pass) {
4026 		if (image)
4027 			bpf_prog_fill_jited_linfo(prog, addrs + 1);
4028 out_addrs:
4029 		kvfree(addrs);
4030 		if (!image && priv_stack_ptr) {
4031 			free_percpu(priv_stack_ptr);
4032 			prog->aux->priv_stack_ptr = NULL;
4033 		}
4034 out_priv_stack:
4035 		kfree(jit_data);
4036 		prog->aux->jit_data = NULL;
4037 	}
4038 
4039 	return prog;
4040 }
4041 
4042 bool bpf_jit_supports_kfunc_call(void)
4043 {
4044 	return true;
4045 }
4046 
4047 bool bpf_jit_supports_stack_args(void)
4048 {
4049 	return true;
4050 }
4051 
4052 void *bpf_arch_text_copy(void *dst, void *src, size_t len)
4053 {
4054 	if (text_poke_copy(dst, src, len) == NULL)
4055 		return ERR_PTR(-EINVAL);
4056 	return dst;
4057 }
4058 
4059 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
4060 bool bpf_jit_supports_subprog_tailcalls(void)
4061 {
4062 	return true;
4063 }
4064 
4065 bool bpf_jit_supports_percpu_insn(void)
4066 {
4067 	return true;
4068 }
4069 
4070 void bpf_jit_free(struct bpf_prog *prog)
4071 {
4072 	if (prog->jited) {
4073 		struct x64_jit_data *jit_data = prog->aux->jit_data;
4074 		struct bpf_binary_header *hdr;
4075 		void __percpu *priv_stack_ptr;
4076 		int priv_stack_alloc_sz;
4077 
4078 		/*
4079 		 * If we fail the final pass of JIT (from jit_subprogs),
4080 		 * the program may not be finalized yet. Call finalize here
4081 		 * before freeing it.
4082 		 */
4083 		if (jit_data) {
4084 			bpf_jit_binary_pack_finalize(jit_data->header,
4085 						     jit_data->rw_header);
4086 			kvfree(jit_data->addrs);
4087 			kfree(jit_data);
4088 		}
4089 		prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset();
4090 		hdr = bpf_jit_binary_pack_hdr(prog);
4091 		bpf_jit_binary_pack_free(hdr, NULL);
4092 		priv_stack_ptr = prog->aux->priv_stack_ptr;
4093 		if (priv_stack_ptr) {
4094 			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
4095 					      2 * PRIV_STACK_GUARD_SZ;
4096 			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
4097 			free_percpu(prog->aux->priv_stack_ptr);
4098 		}
4099 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
4100 	}
4101 
4102 	bpf_prog_unlock_free(prog);
4103 }
4104 
4105 bool bpf_jit_supports_exceptions(void)
4106 {
4107 	/* We unwind through both kernel frames (starting from within bpf_throw
4108 	 * call) and BPF frames. Therefore we require ORC unwinder to be enabled
4109 	 * to walk kernel frames and reach BPF frames in the stack trace.
4110 	 */
4111 	return IS_ENABLED(CONFIG_UNWINDER_ORC);
4112 }
4113 
4114 bool bpf_jit_supports_private_stack(void)
4115 {
4116 	return true;
4117 }
4118 
4119 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
4120 {
4121 #if defined(CONFIG_UNWINDER_ORC)
4122 	struct unwind_state state;
4123 	unsigned long addr;
4124 
4125 	for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
4126 	     unwind_next_frame(&state)) {
4127 		addr = unwind_get_return_address(&state);
4128 		if (!addr || !consume_fn(cookie, (u64)addr, (u64)state.sp, (u64)state.bp))
4129 			break;
4130 	}
4131 	return;
4132 #endif
4133 }
4134 
4135 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
4136 			       struct bpf_prog *new, struct bpf_prog *old)
4137 {
4138 	u8 *old_addr, *new_addr, *old_bypass_addr;
4139 	enum bpf_text_poke_type t;
4140 	int ret;
4141 
4142 	old_bypass_addr = old ? NULL : poke->bypass_addr;
4143 	old_addr = old ? (u8 *)old->bpf_func + poke->adj_off : NULL;
4144 	new_addr = new ? (u8 *)new->bpf_func + poke->adj_off : NULL;
4145 
4146 	/*
4147 	 * On program loading or teardown, the program's kallsym entry
4148 	 * might not be in place, so we use __bpf_arch_text_poke to skip
4149 	 * the kallsyms check.
4150 	 */
4151 	if (new) {
4152 		t = old_addr ? BPF_MOD_JUMP : BPF_MOD_NOP;
4153 		ret = __bpf_arch_text_poke(poke->tailcall_target,
4154 					   t, BPF_MOD_JUMP,
4155 					   old_addr, new_addr);
4156 		BUG_ON(ret < 0);
4157 		if (!old) {
4158 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
4159 						   BPF_MOD_JUMP, BPF_MOD_NOP,
4160 						   poke->bypass_addr,
4161 						   NULL);
4162 			BUG_ON(ret < 0);
4163 		}
4164 	} else {
4165 		t = old_bypass_addr ? BPF_MOD_JUMP : BPF_MOD_NOP;
4166 		ret = __bpf_arch_text_poke(poke->tailcall_bypass,
4167 					   t, BPF_MOD_JUMP, old_bypass_addr,
4168 					   poke->bypass_addr);
4169 		BUG_ON(ret < 0);
4170 		/* let other CPUs finish the execution of program
4171 		 * so that it will not possible to expose them
4172 		 * to invalid nop, stack unwind, nop state
4173 		 */
4174 		if (!ret)
4175 			synchronize_rcu();
4176 		t = old_addr ? BPF_MOD_JUMP : BPF_MOD_NOP;
4177 		ret = __bpf_arch_text_poke(poke->tailcall_target,
4178 					   t, BPF_MOD_NOP, old_addr, NULL);
4179 		BUG_ON(ret < 0);
4180 	}
4181 }
4182 
4183 bool bpf_jit_supports_arena(void)
4184 {
4185 	return true;
4186 }
4187 
4188 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
4189 {
4190 	if (!in_arena)
4191 		return true;
4192 	switch (insn->code) {
4193 	case BPF_STX | BPF_ATOMIC | BPF_W:
4194 	case BPF_STX | BPF_ATOMIC | BPF_DW:
4195 		if (insn->imm == (BPF_AND | BPF_FETCH) ||
4196 		    insn->imm == (BPF_OR | BPF_FETCH) ||
4197 		    insn->imm == (BPF_XOR | BPF_FETCH))
4198 			return false;
4199 	}
4200 	return true;
4201 }
4202 
4203 bool bpf_jit_supports_ptr_xchg(void)
4204 {
4205 	return true;
4206 }
4207 
4208 /* x86-64 JIT emits its own code to filter user addresses so return 0 here */
4209 u64 bpf_arch_uaddress_limit(void)
4210 {
4211 	return 0;
4212 }
4213 
4214 bool bpf_jit_supports_timed_may_goto(void)
4215 {
4216 	return true;
4217 }
4218 
4219 bool bpf_jit_supports_fsession(void)
4220 {
4221 	return true;
4222 }
4223