xref: /linux/arch/x86/net/bpf_jit_comp.c (revision 2e320ea9a883b307bed2a7a54af96ca0b902f902)
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/init.h>
13 #include <linux/bpf.h>
14 #include <linux/bpf_verifier.h>
15 #include <linux/memory.h>
16 #include <linux/sort.h>
17 #include <linux/execmem.h>
18 #include <linux/extable.h>
19 #include <asm/extable.h>
20 #include <asm/ftrace.h>
21 #include <asm/set_memory.h>
22 #include <asm/nospec-branch.h>
23 #include <asm/text-patching.h>
24 #include <asm/unwind.h>
25 #include <asm/cfi.h>
26 
27 #if IS_ENABLED(CONFIG_BPF_JIT_KASAN)
28 void __asan_load1(void *p);
29 void __asan_store1(void *p);
30 void __asan_load2(void *p);
31 void __asan_store2(void *p);
32 void __asan_load4(void *p);
33 void __asan_store4(void *p);
34 void __asan_load8(void *p);
35 void __asan_store8(void *p);
36 #endif
37 
38 static bool all_callee_regs_used[4] = {true, true, true, true};
39 
40 static void *trampoline_size_image;
41 
42 static int __init init_trampoline_size_image(void)
43 {
44 	/*
45 	 * The generated trampoline contains calls and jumps with 32bit relative
46 	 * offsets, so the scratch image must be in the execmem range.
47 	 * On x86, module data and executable memory share the same address range,
48 	 * so using EXECMEM_MODULE_DATA to get writable memory.
49 	 */
50 	trampoline_size_image = execmem_alloc(EXECMEM_MODULE_DATA, PAGE_SIZE);
51 	return trampoline_size_image ? 0 : -ENOMEM;
52 }
53 late_initcall(init_trampoline_size_image);
54 
55 static u8 *emit_code(u8 *ptr, u32 bytes, unsigned int len)
56 {
57 	if (len == 1)
58 		*ptr = bytes;
59 	else if (len == 2)
60 		*(u16 *)ptr = bytes;
61 	else {
62 		*(u32 *)ptr = bytes;
63 		barrier();
64 	}
65 	return ptr + len;
66 }
67 
68 #define EMIT(bytes, len) \
69 	do { prog = emit_code(prog, bytes, len); } while (0)
70 
71 #define EMIT1(b1)		EMIT(b1, 1)
72 #define EMIT2(b1, b2)		EMIT((b1) + ((b2) << 8), 2)
73 #define EMIT3(b1, b2, b3)	EMIT((b1) + ((b2) << 8) + ((b3) << 16), 3)
74 #define EMIT4(b1, b2, b3, b4)   EMIT((b1) + ((b2) << 8) + ((b3) << 16) + ((b4) << 24), 4)
75 #define EMIT5(b1, b2, b3, b4, b5) \
76 	do { EMIT1(b1); EMIT4(b2, b3, b4, b5); } while (0)
77 
78 #define EMIT1_off32(b1, off) \
79 	do { EMIT1(b1); EMIT(off, 4); } while (0)
80 #define EMIT2_off32(b1, b2, off) \
81 	do { EMIT2(b1, b2); EMIT(off, 4); } while (0)
82 #define EMIT3_off32(b1, b2, b3, off) \
83 	do { EMIT3(b1, b2, b3); EMIT(off, 4); } while (0)
84 #define EMIT4_off32(b1, b2, b3, b4, off) \
85 	do { EMIT4(b1, b2, b3, b4); EMIT(off, 4); } while (0)
86 
87 #ifdef CONFIG_X86_KERNEL_IBT
88 #define EMIT_ENDBR()		EMIT(gen_endbr(), 4)
89 #define EMIT_ENDBR_POISON()	EMIT(gen_endbr_poison(), 4)
90 #else
91 #define EMIT_ENDBR()		do { } while (0)
92 #define EMIT_ENDBR_POISON()	do { } while (0)
93 #endif
94 
95 static bool is_imm8(int value)
96 {
97 	return value <= 127 && value >= -128;
98 }
99 
100 /*
101  * Let us limit the positive offset to be <= 123.
102  * This is to ensure eventual jit convergence For the following patterns:
103  * ...
104  * pass4, final_proglen=4391:
105  *   ...
106  *   20e:    48 85 ff                test   rdi,rdi
107  *   211:    74 7d                   je     0x290
108  *   213:    48 8b 77 00             mov    rsi,QWORD PTR [rdi+0x0]
109  *   ...
110  *   289:    48 85 ff                test   rdi,rdi
111  *   28c:    74 17                   je     0x2a5
112  *   28e:    e9 7f ff ff ff          jmp    0x212
113  *   293:    bf 03 00 00 00          mov    edi,0x3
114  * Note that insn at 0x211 is 2-byte cond jump insn for offset 0x7d (-125)
115  * and insn at 0x28e is 5-byte jmp insn with offset -129.
116  *
117  * pass5, final_proglen=4392:
118  *   ...
119  *   20e:    48 85 ff                test   rdi,rdi
120  *   211:    0f 84 80 00 00 00       je     0x297
121  *   217:    48 8b 77 00             mov    rsi,QWORD PTR [rdi+0x0]
122  *   ...
123  *   28d:    48 85 ff                test   rdi,rdi
124  *   290:    74 1a                   je     0x2ac
125  *   292:    eb 84                   jmp    0x218
126  *   294:    bf 03 00 00 00          mov    edi,0x3
127  * Note that insn at 0x211 is 6-byte cond jump insn now since its offset
128  * becomes 0x80 based on previous round (0x293 - 0x213 = 0x80).
129  * At the same time, insn at 0x292 is a 2-byte insn since its offset is
130  * -124.
131  *
132  * pass6 will repeat the same code as in pass4 and this will prevent
133  * eventual convergence.
134  *
135  * To fix this issue, we need to break je (2->6 bytes) <-> jmp (5->2 bytes)
136  * cycle in the above. In the above example je offset <= 0x7c should work.
137  *
138  * For other cases, je <-> je needs offset <= 0x7b to avoid no convergence
139  * issue. For jmp <-> je and jmp <-> jmp cases, jmp offset <= 0x7c should
140  * avoid no convergence issue.
141  *
142  * Overall, let us limit the positive offset for 8bit cond/uncond jmp insn
143  * to maximum 123 (0x7b). This way, the jit pass can eventually converge.
144  */
145 static bool is_imm8_jmp_offset(int value)
146 {
147 	return value <= 123 && value >= -128;
148 }
149 
150 static bool is_simm32(s64 value)
151 {
152 	return value == (s64)(s32)value;
153 }
154 
155 static bool is_uimm32(u64 value)
156 {
157 	return value == (u64)(u32)value;
158 }
159 
160 /* mov dst, src */
161 #define EMIT_mov(DST, SRC)								 \
162 	do {										 \
163 		if (DST != SRC)								 \
164 			EMIT3(add_2mod(0x48, DST, SRC), 0x89, add_2reg(0xC0, DST, SRC)); \
165 	} while (0)
166 
167 static int bpf_size_to_x86_bytes(int bpf_size)
168 {
169 	if (bpf_size == BPF_W)
170 		return 4;
171 	else if (bpf_size == BPF_H)
172 		return 2;
173 	else if (bpf_size == BPF_B)
174 		return 1;
175 	else if (bpf_size == BPF_DW)
176 		return 4; /* imm32 */
177 	else
178 		return 0;
179 }
180 
181 /*
182  * List of x86 cond jumps opcodes (. + s8)
183  * Add 0x10 (and an extra 0x0f) to generate far jumps (. + s32)
184  */
185 #define X86_JB  0x72
186 #define X86_JAE 0x73
187 #define X86_JE  0x74
188 #define X86_JNE 0x75
189 #define X86_JBE 0x76
190 #define X86_JA  0x77
191 #define X86_JL  0x7C
192 #define X86_JGE 0x7D
193 #define X86_JLE 0x7E
194 #define X86_JG  0x7F
195 
196 /* Pick a register outside of BPF range for JIT internal work */
197 #define AUX_REG (MAX_BPF_JIT_REG + 1)
198 #define X86_REG_R9 (MAX_BPF_JIT_REG + 2)
199 #define X86_REG_R12 (MAX_BPF_JIT_REG + 3)
200 
201 /*
202  * The following table maps BPF registers to x86-64 registers.
203  *
204  * x86-64 register R12 is unused, since if used as base address
205  * register in load/store instructions, it always needs an
206  * extra byte of encoding and is callee saved.
207  *
208  * x86-64 register R9 is not used by BPF programs, but can be used by BPF
209  * trampoline. x86-64 register R10 is used for blinding (if enabled).
210  */
211 static const int reg2hex[] = {
212 	[BPF_REG_0] = 0,  /* RAX */
213 	[BPF_REG_1] = 7,  /* RDI */
214 	[BPF_REG_2] = 6,  /* RSI */
215 	[BPF_REG_3] = 2,  /* RDX */
216 	[BPF_REG_4] = 1,  /* RCX */
217 	[BPF_REG_5] = 0,  /* R8  */
218 	[BPF_REG_6] = 3,  /* RBX callee saved */
219 	[BPF_REG_7] = 5,  /* R13 callee saved */
220 	[BPF_REG_8] = 6,  /* R14 callee saved */
221 	[BPF_REG_9] = 7,  /* R15 callee saved */
222 	[BPF_REG_FP] = 5, /* RBP readonly */
223 	[BPF_REG_AX] = 2, /* R10 temp register */
224 	[AUX_REG] = 3,    /* R11 temp register */
225 	[X86_REG_R9] = 1, /* R9 register, 6th function argument */
226 	[X86_REG_R12] = 4, /* R12 callee saved */
227 };
228 
229 static const int reg2pt_regs[] = {
230 	[BPF_REG_0] = offsetof(struct pt_regs, ax),
231 	[BPF_REG_1] = offsetof(struct pt_regs, di),
232 	[BPF_REG_2] = offsetof(struct pt_regs, si),
233 	[BPF_REG_3] = offsetof(struct pt_regs, dx),
234 	[BPF_REG_4] = offsetof(struct pt_regs, cx),
235 	[BPF_REG_5] = offsetof(struct pt_regs, r8),
236 	[BPF_REG_6] = offsetof(struct pt_regs, bx),
237 	[BPF_REG_7] = offsetof(struct pt_regs, r13),
238 	[BPF_REG_8] = offsetof(struct pt_regs, r14),
239 	[BPF_REG_9] = offsetof(struct pt_regs, r15),
240 	[BPF_REG_AX] = offsetof(struct pt_regs, r10),
241 };
242 
243 static bool is_atomic_fetch_op(const struct bpf_insn *insn)
244 {
245 	return insn->imm == (BPF_AND | BPF_FETCH) ||
246 	       insn->imm == (BPF_OR | BPF_FETCH) ||
247 	       insn->imm == (BPF_XOR | BPF_FETCH);
248 }
249 
250 /*
251  * is_ereg() == true if BPF register 'reg' maps to x86-64 r8..r15
252  * which need extra byte of encoding.
253  * rax,rcx,...,rbp have simpler encoding
254  */
255 static bool is_ereg(u32 reg)
256 {
257 	return (1 << reg) & (BIT(BPF_REG_5) |
258 			     BIT(AUX_REG) |
259 			     BIT(BPF_REG_7) |
260 			     BIT(BPF_REG_8) |
261 			     BIT(BPF_REG_9) |
262 			     BIT(X86_REG_R9) |
263 			     BIT(X86_REG_R12) |
264 			     BIT(BPF_REG_AX));
265 }
266 
267 /*
268  * is_ereg_8l() == true if BPF register 'reg' is mapped to access x86-64
269  * lower 8-bit registers dil,sil,bpl,spl,r8b..r15b, which need extra byte
270  * of encoding. al,cl,dl,bl have simpler encoding.
271  */
272 static bool is_ereg_8l(u32 reg)
273 {
274 	return is_ereg(reg) ||
275 	    (1 << reg) & (BIT(BPF_REG_1) |
276 			  BIT(BPF_REG_2) |
277 			  BIT(BPF_REG_FP));
278 }
279 
280 static bool is_axreg(u32 reg)
281 {
282 	return reg == BPF_REG_0;
283 }
284 
285 /* Add modifiers if 'reg' maps to x86-64 registers R8..R15 */
286 static u8 add_1mod(u8 byte, u32 reg)
287 {
288 	if (is_ereg(reg))
289 		byte |= 1;
290 	return byte;
291 }
292 
293 static u8 add_2mod(u8 byte, u32 r1, u32 r2)
294 {
295 	if (is_ereg(r1))
296 		byte |= 1;
297 	if (is_ereg(r2))
298 		byte |= 4;
299 	return byte;
300 }
301 
302 static u8 add_3mod(u8 byte, u32 r1, u32 r2, u32 index)
303 {
304 	if (is_ereg(r1))
305 		byte |= 1;
306 	if (is_ereg(index))
307 		byte |= 2;
308 	if (is_ereg(r2))
309 		byte |= 4;
310 	return byte;
311 }
312 
313 /* Encode 'dst_reg' register into x86-64 opcode 'byte' */
314 static u8 add_1reg(u8 byte, u32 dst_reg)
315 {
316 	return byte + reg2hex[dst_reg];
317 }
318 
319 /* Encode 'dst_reg' and 'src_reg' registers into x86-64 opcode 'byte' */
320 static u8 add_2reg(u8 byte, u32 dst_reg, u32 src_reg)
321 {
322 	return byte + reg2hex[dst_reg] + (reg2hex[src_reg] << 3);
323 }
324 
325 /* Some 1-byte opcodes for binary ALU operations */
326 static u8 simple_alu_opcodes[] = {
327 	[BPF_ADD] = 0x01,
328 	[BPF_SUB] = 0x29,
329 	[BPF_AND] = 0x21,
330 	[BPF_OR] = 0x09,
331 	[BPF_XOR] = 0x31,
332 	[BPF_LSH] = 0xE0,
333 	[BPF_RSH] = 0xE8,
334 	[BPF_ARSH] = 0xF8,
335 };
336 
337 static void jit_fill_hole(void *area, unsigned int size)
338 {
339 	/* Fill whole space with INT3 instructions */
340 	memset(area, 0xcc, size);
341 }
342 
343 int bpf_arch_text_invalidate(void *dst, size_t len)
344 {
345 	return IS_ERR_OR_NULL(text_poke_set(dst, 0xcc, len));
346 }
347 
348 struct jit_context {
349 	int cleanup_addr; /* Epilogue code offset */
350 
351 	/*
352 	 * Program specific offsets of labels in the code; these rely on the
353 	 * JIT doing at least 2 passes, recording the position on the first
354 	 * pass, only to generate the correct offset on the second pass.
355 	 */
356 	int tail_call_direct_label;
357 	int tail_call_indirect_label;
358 };
359 
360 /* Maximum number of bytes emitted while JITing one eBPF insn */
361 #define BPF_MAX_INSN_SIZE	128
362 #define BPF_INSN_SAFETY		64
363 
364 /* Number of bytes emit_patch() needs to generate instructions */
365 #define X86_PATCH_SIZE		5
366 /* Number of bytes that will be skipped on tailcall */
367 #define X86_TAIL_CALL_OFFSET	(12 + ENDBR_INSN_SIZE)
368 
369 static void push_r9(u8 **pprog)
370 {
371 	u8 *prog = *pprog;
372 
373 	EMIT2(0x41, 0x51);   /* push r9 */
374 	*pprog = prog;
375 }
376 
377 static void pop_r9(u8 **pprog)
378 {
379 	u8 *prog = *pprog;
380 
381 	EMIT2(0x41, 0x59);   /* pop r9 */
382 	*pprog = prog;
383 }
384 
385 static void push_r12(u8 **pprog)
386 {
387 	u8 *prog = *pprog;
388 
389 	EMIT2(0x41, 0x54);   /* push r12 */
390 	*pprog = prog;
391 }
392 
393 static void push_callee_regs(u8 **pprog, bool *callee_regs_used)
394 {
395 	u8 *prog = *pprog;
396 
397 	if (callee_regs_used[0])
398 		EMIT1(0x53);         /* push rbx */
399 	if (callee_regs_used[1])
400 		EMIT2(0x41, 0x55);   /* push r13 */
401 	if (callee_regs_used[2])
402 		EMIT2(0x41, 0x56);   /* push r14 */
403 	if (callee_regs_used[3])
404 		EMIT2(0x41, 0x57);   /* push r15 */
405 	*pprog = prog;
406 }
407 
408 static void pop_r12(u8 **pprog)
409 {
410 	u8 *prog = *pprog;
411 
412 	EMIT2(0x41, 0x5C);   /* pop r12 */
413 	*pprog = prog;
414 }
415 
416 static void pop_callee_regs(u8 **pprog, bool *callee_regs_used)
417 {
418 	u8 *prog = *pprog;
419 
420 	if (callee_regs_used[3])
421 		EMIT2(0x41, 0x5F);   /* pop r15 */
422 	if (callee_regs_used[2])
423 		EMIT2(0x41, 0x5E);   /* pop r14 */
424 	if (callee_regs_used[1])
425 		EMIT2(0x41, 0x5D);   /* pop r13 */
426 	if (callee_regs_used[0])
427 		EMIT1(0x5B);         /* pop rbx */
428 	*pprog = prog;
429 }
430 
431 /* add rsp, depth */
432 static void emit_add_rsp(u8 **pprog, u32 depth)
433 {
434 	u8 *prog = *pprog;
435 
436 	if (!depth)
437 		return;
438 	if (is_imm8(depth))
439 		EMIT4(0x48, 0x83, 0xC4, depth); /* add rsp, imm8 */
440 	else
441 		EMIT3_off32(0x48, 0x81, 0xC4, depth); /* add rsp, imm32 */
442 	*pprog = prog;
443 }
444 
445 /* sub rsp, depth */
446 static void emit_sub_rsp(u8 **pprog, u32 depth)
447 {
448 	u8 *prog = *pprog;
449 
450 	if (!depth)
451 		return;
452 	if (is_imm8(depth))
453 		EMIT4(0x48, 0x83, 0xEC, depth); /* sub rsp, imm8 */
454 	else
455 		EMIT3_off32(0x48, 0x81, 0xEC, depth); /* sub rsp, imm32 */
456 	*pprog = prog;
457 }
458 
459 static void emit_nops(u8 **pprog, int len)
460 {
461 	u8 *prog = *pprog;
462 	int i, noplen;
463 
464 	while (len > 0) {
465 		noplen = len;
466 
467 		if (noplen > ASM_NOP_MAX)
468 			noplen = ASM_NOP_MAX;
469 
470 		for (i = 0; i < noplen; i++)
471 			EMIT1(x86_nops[noplen][i]);
472 		len -= noplen;
473 	}
474 
475 	*pprog = prog;
476 }
477 
478 /*
479  * Emit the various CFI preambles, see asm/cfi.h and the comments about FineIBT
480  * in arch/x86/kernel/alternative.c
481  */
482 static int emit_call(u8 **prog, void *func, void *ip);
483 static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off);
484 static void emit_mov_reg(u8 **pprog, bool is64, u32 dst_reg, u32 src_reg);
485 static void emit_alu_imm(u8 **pprog, u32 op, u32 dst_reg, s32 imm, bool is64);
486 
487 static void emit_fineibt(u8 **pprog, u8 *ip, u32 hash, int arity)
488 {
489 	u8 *prog = *pprog;
490 
491 	EMIT_ENDBR();
492 	EMIT1_off32(0x2d, hash);			/* subl $hash, %eax	*/
493 	if (cfi_bhi) {
494 		EMIT2(0x2e, 0x2e);			/* cs cs */
495 		emit_call(&prog, __bhi_args[arity], ip + 11);
496 	} else {
497 		EMIT3_off32(0x2e, 0x0f, 0x85, 3);	/* jne.d32,pn 3		*/
498 	}
499 	EMIT_ENDBR_POISON();
500 
501 	*pprog = prog;
502 }
503 
504 static void emit_kcfi(u8 **pprog, u32 hash)
505 {
506 	u8 *prog = *pprog;
507 
508 	EMIT1_off32(0xb8, hash);			/* movl $hash, %eax	*/
509 #ifdef CONFIG_CALL_PADDING
510 	for (int i = 0; i < CONFIG_FUNCTION_PADDING_CFI; i++)
511 		EMIT1(0x90);
512 #endif
513 	EMIT_ENDBR();
514 
515 	*pprog = prog;
516 }
517 
518 static void emit_cfi(u8 **pprog, u8 *ip, u32 hash, int arity)
519 {
520 	u8 *prog = *pprog;
521 
522 	switch (cfi_mode) {
523 	case CFI_FINEIBT:
524 		emit_fineibt(&prog, ip, hash, arity);
525 		break;
526 
527 	case CFI_KCFI:
528 		emit_kcfi(&prog, hash);
529 		break;
530 
531 	default:
532 		EMIT_ENDBR();
533 		break;
534 	}
535 
536 	*pprog = prog;
537 }
538 
539 static void emit_prologue_tail_call(u8 **pprog, bool is_subprog)
540 {
541 	u8 *prog = *pprog;
542 
543 	if (!is_subprog) {
544 		/* cmp rax, MAX_TAIL_CALL_CNT */
545 		EMIT4(0x48, 0x83, 0xF8, MAX_TAIL_CALL_CNT);
546 		EMIT2(X86_JA, 6);        /* ja 6 */
547 		/* rax is tail_call_cnt if <= MAX_TAIL_CALL_CNT.
548 		 * case1: entry of main prog.
549 		 * case2: tail callee of main prog.
550 		 */
551 		EMIT1(0x50);             /* push rax */
552 		/* Make rax as tail_call_cnt_ptr. */
553 		EMIT3(0x48, 0x89, 0xE0); /* mov rax, rsp */
554 		EMIT2(0xEB, 1);          /* jmp 1 */
555 		/* rax is tail_call_cnt_ptr if > MAX_TAIL_CALL_CNT.
556 		 * case: tail callee of subprog.
557 		 */
558 		EMIT1(0x50);             /* push rax */
559 		/* push tail_call_cnt_ptr */
560 		EMIT1(0x50);             /* push rax */
561 	} else { /* is_subprog */
562 		/* rax is tail_call_cnt_ptr. */
563 		EMIT1(0x50);             /* push rax */
564 		EMIT1(0x50);             /* push rax */
565 	}
566 
567 	*pprog = prog;
568 }
569 
570 /*
571  * Emit x86-64 prologue code for BPF program.
572  * bpf_tail_call helper will skip the first X86_TAIL_CALL_OFFSET bytes
573  * while jumping to another program
574  */
575 static void emit_prologue(u8 **pprog, u8 *ip, u32 stack_depth, bool ebpf_from_cbpf,
576 			  bool tail_call_reachable, bool is_subprog,
577 			  bool is_exception_cb)
578 {
579 	u8 *prog = *pprog;
580 
581 	if (is_subprog) {
582 		emit_cfi(&prog, ip, cfi_bpf_subprog_hash, 5);
583 	} else {
584 		emit_cfi(&prog, ip, cfi_bpf_hash, 1);
585 	}
586 	/* BPF trampoline can be made to work without these nops,
587 	 * but let's waste 5 bytes for now and optimize later
588 	 */
589 	emit_nops(&prog, X86_PATCH_SIZE);
590 	if (!ebpf_from_cbpf) {
591 		if (tail_call_reachable && !is_subprog)
592 			/* When it's the entry of the whole tailcall context,
593 			 * zeroing rax means initialising tail_call_cnt.
594 			 */
595 			EMIT3(0x48, 0x31, 0xC0); /* xor rax, rax */
596 		else
597 			/* Keep the same instruction layout. */
598 			emit_nops(&prog, 3);     /* nop3 */
599 	}
600 	/* Exception callback receives FP as third parameter */
601 	if (is_exception_cb) {
602 		EMIT3(0x48, 0x89, 0xF4); /* mov rsp, rsi */
603 		EMIT3(0x48, 0x89, 0xD5); /* mov rbp, rdx */
604 		/* The main frame must have exception_boundary as true, so we
605 		 * first restore those callee-saved regs from stack, before
606 		 * reusing the stack frame.
607 		 */
608 		pop_callee_regs(&prog, all_callee_regs_used);
609 		pop_r12(&prog);
610 		/* Reset the stack frame. */
611 		EMIT3(0x48, 0x89, 0xEC); /* mov rsp, rbp */
612 	} else {
613 		EMIT1(0x55);             /* push rbp */
614 		EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
615 	}
616 
617 	/* X86_TAIL_CALL_OFFSET is here */
618 	EMIT_ENDBR();
619 
620 	/* sub rsp, rounded_stack_depth */
621 	emit_sub_rsp(&prog, round_up(stack_depth, 8));
622 	if (tail_call_reachable)
623 		emit_prologue_tail_call(&prog, is_subprog);
624 	*pprog = prog;
625 }
626 
627 static int emit_patch(u8 **pprog, void *func, void *ip, u8 opcode)
628 {
629 	u8 *prog = *pprog;
630 	s64 offset;
631 
632 	offset = func - (ip + X86_PATCH_SIZE);
633 	if (!is_simm32(offset)) {
634 		pr_err("Target call %p is out of range\n", func);
635 		return -ERANGE;
636 	}
637 	EMIT1_off32(opcode, offset);
638 	*pprog = prog;
639 	return 0;
640 }
641 
642 static int emit_call(u8 **pprog, void *func, void *ip)
643 {
644 	return emit_patch(pprog, func, ip, 0xE8);
645 }
646 
647 static int emit_rsb_call(u8 **pprog, void *func, void *ip)
648 {
649 	OPTIMIZER_HIDE_VAR(func);
650 	ip += x86_call_depth_emit_accounting(pprog, func, ip);
651 	return emit_patch(pprog, func, ip, 0xE8);
652 }
653 
654 static int emit_jump(u8 **pprog, void *func, void *ip)
655 {
656 	return emit_patch(pprog, func, ip, 0xE9);
657 }
658 
659 static int __bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t,
660 				enum bpf_text_poke_type new_t,
661 				void *old_addr, void *new_addr)
662 {
663 	const u8 *nop_insn = x86_nops[5];
664 	u8 old_insn[X86_PATCH_SIZE];
665 	u8 new_insn[X86_PATCH_SIZE];
666 	u8 *prog;
667 	int ret;
668 
669 	memcpy(old_insn, nop_insn, X86_PATCH_SIZE);
670 	if (old_t != BPF_MOD_NOP && old_addr) {
671 		prog = old_insn;
672 		ret = old_t == BPF_MOD_CALL ?
673 		      emit_call(&prog, old_addr, ip) :
674 		      emit_jump(&prog, old_addr, ip);
675 		if (ret)
676 			return ret;
677 	}
678 
679 	memcpy(new_insn, nop_insn, X86_PATCH_SIZE);
680 	if (new_t != BPF_MOD_NOP && new_addr) {
681 		prog = new_insn;
682 		ret = new_t == BPF_MOD_CALL ?
683 		      emit_call(&prog, new_addr, ip) :
684 		      emit_jump(&prog, new_addr, ip);
685 		if (ret)
686 			return ret;
687 	}
688 
689 	ret = -EBUSY;
690 	mutex_lock(&text_mutex);
691 	if (memcmp(ip, old_insn, X86_PATCH_SIZE))
692 		goto out;
693 	ret = 1;
694 	if (memcmp(ip, new_insn, X86_PATCH_SIZE)) {
695 		smp_text_poke_single(ip, new_insn, X86_PATCH_SIZE, NULL);
696 		ret = 0;
697 	}
698 out:
699 	mutex_unlock(&text_mutex);
700 	return ret;
701 }
702 
703 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t,
704 		       enum bpf_text_poke_type new_t, void *old_addr,
705 		       void *new_addr)
706 {
707 	if (!is_kernel_text((long)ip) &&
708 	    !is_bpf_text_address((long)ip))
709 		/* BPF poking in modules is not supported */
710 		return -EINVAL;
711 
712 	/*
713 	 * See emit_prologue(), for IBT builds the trampoline hook is preceded
714 	 * with an ENDBR instruction.
715 	 */
716 	if (is_endbr(ip))
717 		ip += ENDBR_INSN_SIZE;
718 
719 	return __bpf_arch_text_poke(ip, old_t, new_t, old_addr, new_addr);
720 }
721 
722 #define EMIT_LFENCE()	EMIT3(0x0F, 0xAE, 0xE8)
723 
724 static void __emit_indirect_jump(u8 **pprog, int reg, bool ereg)
725 {
726 	u8 *prog = *pprog;
727 
728 	if (ereg)
729 		EMIT1(0x41);
730 
731 	EMIT2(0xFF, 0xE0 + reg);
732 
733 	*pprog = prog;
734 }
735 
736 static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip)
737 {
738 	u8 *prog = *pprog;
739 	int reg = reg2hex[bpf_reg];
740 	bool ereg = is_ereg(bpf_reg);
741 
742 	if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) {
743 		OPTIMIZER_HIDE_VAR(reg);
744 		emit_jump(&prog, its_static_thunk(reg + 8*ereg), ip);
745 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
746 		EMIT_LFENCE();
747 		__emit_indirect_jump(&prog, reg, ereg);
748 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
749 		OPTIMIZER_HIDE_VAR(reg);
750 		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
751 			emit_jump(&prog, &__x86_indirect_jump_thunk_array[reg + 8*ereg], ip);
752 		else
753 			emit_jump(&prog, &__x86_indirect_thunk_array[reg + 8*ereg], ip);
754 	} else {
755 		__emit_indirect_jump(&prog, reg, ereg);
756 		if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) || IS_ENABLED(CONFIG_MITIGATION_SLS))
757 			EMIT1(0xCC);		/* int3 */
758 	}
759 
760 	*pprog = prog;
761 }
762 
763 static void __emit_indirect_call(u8 **pprog, int reg, bool ereg)
764 {
765 	u8 *prog = *pprog;
766 
767 	if (ereg)
768 		EMIT1(0x41);
769 
770 	EMIT2(0xFF, 0xD0 + reg);
771 
772 	*pprog = prog;
773 }
774 
775 /* call *bpf_reg */
776 static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)
777 {
778 	u8 *prog = *pprog;
779 	int reg = reg2hex[bpf_reg];
780 	bool ereg = is_ereg(bpf_reg);
781 	int err = 0;
782 
783 	if (cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS)) {
784 		OPTIMIZER_HIDE_VAR(reg);
785 		err = emit_call(&prog, its_static_thunk(reg + 8*ereg), ip);
786 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
787 		EMIT_LFENCE();
788 		__emit_indirect_call(&prog, reg, ereg);
789 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
790 		OPTIMIZER_HIDE_VAR(reg);
791 		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
792 			err = emit_call(&prog, &__x86_indirect_call_thunk_array[reg + 8*ereg], ip);
793 		else
794 			err = emit_call(&prog, &__x86_indirect_thunk_array[reg + 8*ereg], ip);
795 	} else {
796 		__emit_indirect_call(&prog, reg, ereg);
797 	}
798 
799 	*pprog = prog;
800 	return err;
801 }
802 
803 static void emit_return(u8 **pprog, u8 *ip)
804 {
805 	u8 *prog = *pprog;
806 
807 	if (cpu_wants_rethunk()) {
808 		emit_jump(&prog, x86_return_thunk, ip);
809 	} else {
810 		EMIT1(0xC3);		/* ret */
811 		if (IS_ENABLED(CONFIG_MITIGATION_SLS))
812 			EMIT1(0xCC);	/* int3 */
813 	}
814 
815 	*pprog = prog;
816 }
817 
818 #define BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack)	(-16 - round_up(stack, 8))
819 
820 /*
821  * Generate the following code:
822  *
823  * ... bpf_tail_call(void *ctx, struct bpf_array *array, u64 index) ...
824  *   if (index >= array->map.max_entries)
825  *     goto out;
826  *   if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
827  *     goto out;
828  *   prog = array->ptrs[index];
829  *   if (prog == NULL)
830  *     goto out;
831  *   goto *(prog->bpf_func + prologue_size);
832  * out:
833  */
834 static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
835 					u8 **pprog, bool *callee_regs_used,
836 					u32 stack_depth, u8 *ip,
837 					struct jit_context *ctx)
838 {
839 	int tcc_ptr_off = BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack_depth);
840 	u8 *prog = *pprog, *start = *pprog;
841 	int offset;
842 
843 	/*
844 	 * rdi - pointer to ctx
845 	 * rsi - pointer to bpf_array
846 	 * rdx - index in bpf_array
847 	 */
848 
849 	/*
850 	 * if (index >= array->map.max_entries)
851 	 *	goto out;
852 	 */
853 	emit_mov_reg(&prog, false, BPF_REG_3, BPF_REG_3); /* mov edx, edx */
854 	EMIT3(0x39, 0x56,                         /* cmp dword ptr [rsi + 16], edx */
855 	      offsetof(struct bpf_array, map.max_entries));
856 
857 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
858 	EMIT2(X86_JBE, offset);                   /* jbe out */
859 
860 	/*
861 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
862 	 *	goto out;
863 	 */
864 	/* mov rax, qword ptr [rbp - tcc_ptr_off] */
865 	emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, tcc_ptr_off);
866 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT); /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
867 
868 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
869 	EMIT2(X86_JAE, offset);                   /* jae out */
870 
871 	/* prog = array->ptrs[index]; */
872 	EMIT4_off32(0x48, 0x8B, 0x8C, 0xD6,       /* mov rcx, [rsi + rdx * 8 + offsetof(...)] */
873 		    offsetof(struct bpf_array, ptrs));
874 
875 	/*
876 	 * if (prog == NULL)
877 	 *	goto out;
878 	 */
879 	EMIT3(0x48, 0x85, 0xC9);                  /* test rcx,rcx */
880 
881 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
882 	EMIT2(X86_JE, offset);                    /* je out */
883 
884 	/* Inc tail_call_cnt if the slot is populated. */
885 	EMIT4(0x48, 0x83, 0x00, 0x01);            /* add qword ptr [rax], 1 */
886 
887 	if (bpf_prog->aux->exception_boundary) {
888 		pop_callee_regs(&prog, all_callee_regs_used);
889 		pop_r12(&prog);
890 	} else {
891 		pop_callee_regs(&prog, callee_regs_used);
892 		if (bpf_prog_uses_arena_insns(bpf_prog))
893 			pop_r12(&prog);
894 	}
895 
896 	/* Pop tail_call_cnt_ptr. */
897 	EMIT1(0x58);                              /* pop rax */
898 	/* Pop tail_call_cnt, if it's main prog.
899 	 * Pop tail_call_cnt_ptr, if it's subprog.
900 	 */
901 	EMIT1(0x58);                              /* pop rax */
902 	emit_add_rsp(&prog, round_up(stack_depth, 8)); /* add rsp, sd */
903 
904 	/* goto *(prog->bpf_func + X86_TAIL_CALL_OFFSET); */
905 	EMIT4(0x48, 0x8B, 0x49,                   /* mov rcx, qword ptr [rcx + 32] */
906 	      offsetof(struct bpf_prog, bpf_func));
907 	/* add rcx, X86_TAIL_CALL_OFFSET */
908 	emit_alu_imm(&prog, BPF_ADD, BPF_REG_4, X86_TAIL_CALL_OFFSET, true);
909 	/*
910 	 * Now we're ready to jump into next BPF program
911 	 * rdi == ctx (1st arg)
912 	 * rcx == prog->bpf_func + X86_TAIL_CALL_OFFSET
913 	 */
914 	emit_indirect_jump(&prog, BPF_REG_4 /* R4 -> rcx */, ip + (prog - start));
915 
916 	/* out: */
917 	ctx->tail_call_indirect_label = prog - start;
918 	*pprog = prog;
919 }
920 
921 static void emit_bpf_tail_call_direct(struct bpf_prog *bpf_prog,
922 				      struct bpf_jit_poke_descriptor *poke,
923 				      u8 **pprog, u8 *ip,
924 				      bool *callee_regs_used, u32 stack_depth,
925 				      struct jit_context *ctx)
926 {
927 	int tcc_ptr_off = BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack_depth);
928 	u8 *prog = *pprog, *start = *pprog;
929 	int offset;
930 
931 	/*
932 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
933 	 *	goto out;
934 	 */
935 	/* mov rax, qword ptr [rbp - tcc_ptr_off] */
936 	emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, tcc_ptr_off);
937 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT);   /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
938 
939 	offset = ctx->tail_call_direct_label - (prog + 2 - start);
940 	EMIT2(X86_JAE, offset);                       /* jae out */
941 
942 	poke->tailcall_bypass = ip + (prog - start);
943 	poke->adj_off = X86_TAIL_CALL_OFFSET;
944 	poke->tailcall_target = ip + ctx->tail_call_direct_label - X86_PATCH_SIZE;
945 	poke->bypass_addr = (u8 *)poke->tailcall_target + X86_PATCH_SIZE;
946 
947 	emit_jump(&prog, (u8 *)poke->tailcall_target + X86_PATCH_SIZE,
948 		  poke->tailcall_bypass);
949 
950 	/* Inc tail_call_cnt if the slot is populated. */
951 	EMIT4(0x48, 0x83, 0x00, 0x01);                /* add qword ptr [rax], 1 */
952 
953 	if (bpf_prog->aux->exception_boundary) {
954 		pop_callee_regs(&prog, all_callee_regs_used);
955 		pop_r12(&prog);
956 	} else {
957 		pop_callee_regs(&prog, callee_regs_used);
958 		if (bpf_prog_uses_arena_insns(bpf_prog))
959 			pop_r12(&prog);
960 	}
961 
962 	/* Pop tail_call_cnt_ptr. */
963 	EMIT1(0x58);                                  /* pop rax */
964 	/* Pop tail_call_cnt, if it's main prog.
965 	 * Pop tail_call_cnt_ptr, if it's subprog.
966 	 */
967 	EMIT1(0x58);                                  /* pop rax */
968 	emit_add_rsp(&prog, round_up(stack_depth, 8));
969 
970 	emit_nops(&prog, X86_PATCH_SIZE);
971 
972 	/* out: */
973 	ctx->tail_call_direct_label = prog - start;
974 
975 	*pprog = prog;
976 }
977 
978 static void bpf_tail_call_direct_fixup(struct bpf_prog *prog)
979 {
980 	struct bpf_jit_poke_descriptor *poke;
981 	struct bpf_array *array;
982 	struct bpf_prog *target;
983 	int i, ret;
984 
985 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
986 		poke = &prog->aux->poke_tab[i];
987 		if (poke->aux && poke->aux != prog->aux)
988 			continue;
989 
990 		WARN_ON_ONCE(READ_ONCE(poke->tailcall_target_stable));
991 
992 		if (poke->reason != BPF_POKE_REASON_TAIL_CALL)
993 			continue;
994 
995 		array = container_of(poke->tail_call.map, struct bpf_array, map);
996 		mutex_lock(&array->aux->poke_mutex);
997 		target = array->ptrs[poke->tail_call.key];
998 		if (target) {
999 			ret = __bpf_arch_text_poke(poke->tailcall_target,
1000 						   BPF_MOD_NOP, BPF_MOD_JUMP,
1001 						   NULL,
1002 						   (u8 *)target->bpf_func +
1003 						   poke->adj_off);
1004 			BUG_ON(ret < 0);
1005 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
1006 						   BPF_MOD_JUMP, BPF_MOD_NOP,
1007 						   (u8 *)poke->tailcall_target +
1008 						   X86_PATCH_SIZE, NULL);
1009 			BUG_ON(ret < 0);
1010 		}
1011 		WRITE_ONCE(poke->tailcall_target_stable, true);
1012 		mutex_unlock(&array->aux->poke_mutex);
1013 	}
1014 }
1015 
1016 static void emit_mov_imm32(u8 **pprog, bool sign_propagate,
1017 			   u32 dst_reg, const u32 imm32)
1018 {
1019 	u8 *prog = *pprog;
1020 	u8 b1, b2, b3;
1021 
1022 	/*
1023 	 * Optimization: if imm32 is positive, use 'mov %eax, imm32'
1024 	 * (which zero-extends imm32) to save 2 bytes.
1025 	 */
1026 	if (sign_propagate && (s32)imm32 < 0) {
1027 		/* 'mov %rax, imm32' sign extends imm32 */
1028 		b1 = add_1mod(0x48, dst_reg);
1029 		b2 = 0xC7;
1030 		b3 = 0xC0;
1031 		EMIT3_off32(b1, b2, add_1reg(b3, dst_reg), imm32);
1032 		goto done;
1033 	}
1034 
1035 	/*
1036 	 * Optimization: if imm32 is zero, use 'xor %eax, %eax'
1037 	 * to save 3 bytes.
1038 	 */
1039 	if (imm32 == 0) {
1040 		if (is_ereg(dst_reg))
1041 			EMIT1(add_2mod(0x40, dst_reg, dst_reg));
1042 		b2 = 0x31; /* xor */
1043 		b3 = 0xC0;
1044 		EMIT2(b2, add_2reg(b3, dst_reg, dst_reg));
1045 		goto done;
1046 	}
1047 
1048 	/* mov %eax, imm32 */
1049 	if (is_ereg(dst_reg))
1050 		EMIT1(add_1mod(0x40, dst_reg));
1051 	EMIT1_off32(add_1reg(0xB8, dst_reg), imm32);
1052 done:
1053 	*pprog = prog;
1054 }
1055 
1056 static void emit_mov_imm64(u8 **pprog, u32 dst_reg,
1057 			   const u32 imm32_hi, const u32 imm32_lo)
1058 {
1059 	u64 imm64 = ((u64)imm32_hi << 32) | (u32)imm32_lo;
1060 	u8 *prog = *pprog;
1061 
1062 	if (is_uimm32(imm64)) {
1063 		/*
1064 		 * For emitting plain u32, where sign bit must not be
1065 		 * propagated LLVM tends to load imm64 over mov32
1066 		 * directly, so save couple of bytes by just doing
1067 		 * 'mov %eax, imm32' instead.
1068 		 */
1069 		emit_mov_imm32(&prog, false, dst_reg, imm32_lo);
1070 	} else if (is_simm32(imm64)) {
1071 		emit_mov_imm32(&prog, true, dst_reg, imm32_lo);
1072 	} else {
1073 		/* movabsq rax, imm64 */
1074 		EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg));
1075 		EMIT(imm32_lo, 4);
1076 		EMIT(imm32_hi, 4);
1077 	}
1078 
1079 	*pprog = prog;
1080 }
1081 
1082 static void emit_mov_reg(u8 **pprog, bool is64, u32 dst_reg, u32 src_reg)
1083 {
1084 	u8 *prog = *pprog;
1085 
1086 	if (is64) {
1087 		/* mov dst, src */
1088 		EMIT_mov(dst_reg, src_reg);
1089 	} else {
1090 		/* mov32 dst, src */
1091 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1092 			EMIT1(add_2mod(0x40, dst_reg, src_reg));
1093 		EMIT2(0x89, add_2reg(0xC0, dst_reg, src_reg));
1094 	}
1095 
1096 	*pprog = prog;
1097 }
1098 
1099 static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg,
1100 			   u32 src_reg)
1101 {
1102 	u8 *prog = *pprog;
1103 
1104 	if (is64) {
1105 		/* movs[b,w,l]q dst, src */
1106 		if (num_bits == 8)
1107 			EMIT4(add_2mod(0x48, src_reg, dst_reg), 0x0f, 0xbe,
1108 			      add_2reg(0xC0, src_reg, dst_reg));
1109 		else if (num_bits == 16)
1110 			EMIT4(add_2mod(0x48, src_reg, dst_reg), 0x0f, 0xbf,
1111 			      add_2reg(0xC0, src_reg, dst_reg));
1112 		else if (num_bits == 32)
1113 			EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x63,
1114 			      add_2reg(0xC0, src_reg, dst_reg));
1115 	} else {
1116 		/* movs[b,w]l dst, src */
1117 		if (num_bits == 8) {
1118 			if (is_ereg(dst_reg) || is_ereg_8l(src_reg))
1119 				EMIT1(add_2mod(0x40, src_reg, dst_reg));
1120 			EMIT3(0x0f, 0xbe, add_2reg(0xC0, src_reg, dst_reg));
1121 		} else if (num_bits == 16) {
1122 			if (is_ereg(dst_reg) || is_ereg(src_reg))
1123 				EMIT1(add_2mod(0x40, src_reg, dst_reg));
1124 			EMIT3(add_2mod(0x0f, src_reg, dst_reg), 0xbf,
1125 			      add_2reg(0xC0, src_reg, dst_reg));
1126 		}
1127 	}
1128 
1129 	*pprog = prog;
1130 }
1131 
1132 /*
1133  * rbp and r13 as base register always need a displacement, since mod 00
1134  * with r/m 101 encodes a RIP-relative disp32 and with SIB base 101 a
1135  * disp32 without base instead.
1136  */
1137 static bool base_needs_disp(u32 reg)
1138 {
1139 	return reg2hex[reg] == 5;
1140 }
1141 
1142 static void emit_movzx_reg(u8 **pprog, int num_bits, u32 dst_reg, u32 src_reg)
1143 {
1144 	u8 *prog = *pprog;
1145 
1146 	/* movz[b,w]l dst, src */
1147 	if (is_ereg(dst_reg) ||
1148 	    (num_bits == 8 ? is_ereg_8l(src_reg) : is_ereg(src_reg)))
1149 		EMIT1(add_2mod(0x40, src_reg, dst_reg));
1150 	EMIT3(0x0F, num_bits == 8 ? 0xB6 : 0xB7,
1151 	      add_2reg(0xC0, src_reg, dst_reg));
1152 
1153 	*pprog = prog;
1154 }
1155 
1156 /* Emit the suffix (ModR/M etc) for addressing *(ptr_reg + off) and val_reg */
1157 static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
1158 {
1159 	u8 *prog = *pprog;
1160 
1161 	if (!off && !base_needs_disp(ptr_reg)) {
1162 		/* No displacement */
1163 		EMIT1(add_2reg(0x00, ptr_reg, val_reg));
1164 	} else if (is_imm8(off)) {
1165 		/* 1-byte signed displacement */
1166 		EMIT2(add_2reg(0x40, ptr_reg, val_reg), off);
1167 	} else {
1168 		/* 4-byte signed displacement */
1169 		EMIT1_off32(add_2reg(0x80, ptr_reg, val_reg), off);
1170 	}
1171 	*pprog = prog;
1172 }
1173 
1174 /*
1175  * Emit the suffix for addressing *(ptr_reg + (index_reg << scale) + off)
1176  * and val_reg, with a SIB byte
1177  */
1178 static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index_reg, int off,
1179 				 u8 scale)
1180 {
1181 	u8 sib = (scale << 6) | add_2reg(0, ptr_reg, index_reg);
1182 	u8 *prog = *pprog;
1183 
1184 	if (!off && !base_needs_disp(ptr_reg)) {
1185 		EMIT2(add_2reg(0x04, BPF_REG_0, val_reg), sib);
1186 	} else if (is_imm8(off)) {
1187 		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), sib, off);
1188 	} else {
1189 		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), sib, off);
1190 	}
1191 	*pprog = prog;
1192 }
1193 
1194 /*
1195  * Emit a REX byte if it will be necessary to address these registers
1196  */
1197 static void maybe_emit_mod(u8 **pprog, u32 dst_reg, u32 src_reg, bool is64)
1198 {
1199 	u8 *prog = *pprog;
1200 
1201 	if (is64)
1202 		EMIT1(add_2mod(0x48, dst_reg, src_reg));
1203 	else if (is_ereg(dst_reg) || is_ereg(src_reg))
1204 		EMIT1(add_2mod(0x40, dst_reg, src_reg));
1205 	*pprog = prog;
1206 }
1207 
1208 /*
1209  * Similar version of maybe_emit_mod() for a single register
1210  */
1211 static void maybe_emit_1mod(u8 **pprog, u32 reg, bool is64)
1212 {
1213 	u8 *prog = *pprog;
1214 
1215 	if (is64)
1216 		EMIT1(add_1mod(0x48, reg));
1217 	else if (is_ereg(reg))
1218 		EMIT1(add_1mod(0x40, reg));
1219 	*pprog = prog;
1220 }
1221 
1222 /* add/sub/and/or/xor dst_reg, imm with the imm8 and the rax short forms */
1223 static void emit_alu_imm(u8 **pprog, u32 op, u32 dst_reg, s32 imm, bool is64)
1224 {
1225 	/* ModR/M opcode extension and rax short form per operation */
1226 	static const u8 modrm[] = {
1227 		[BPF_ADD] = 0xC0, [BPF_SUB] = 0xE8, [BPF_AND] = 0xE0,
1228 		[BPF_OR] = 0xC8, [BPF_XOR] = 0xF0,
1229 	};
1230 	static const u8 short_op[] = {
1231 		[BPF_ADD] = 0x05, [BPF_SUB] = 0x2D, [BPF_AND] = 0x25,
1232 		[BPF_OR] = 0x0D, [BPF_XOR] = 0x35,
1233 	};
1234 	u8 *prog = *pprog;
1235 	bool inc;
1236 
1237 	/* A non-negative mask clears the upper half like the 32-bit and does */
1238 	if (op == BPF_AND && imm >= 0)
1239 		is64 = false;
1240 	/* add 128 is sub -128 and the other way round, which fit into an imm8 */
1241 	if ((op == BPF_ADD || op == BPF_SUB) && imm == 128) {
1242 		op = op == BPF_ADD ? BPF_SUB : BPF_ADD;
1243 		imm = -128;
1244 	}
1245 	inc = op == BPF_ADD ? imm == 1 : imm == -1;
1246 	maybe_emit_1mod(&prog, dst_reg, is64);
1247 	/* inc or dec for +-1, the flags are not read across instructions */
1248 	if ((op == BPF_ADD || op == BPF_SUB) && (imm == 1 || imm == -1))
1249 		EMIT2(0xFF, add_1reg(inc ? 0xC0 : 0xC8, dst_reg));
1250 	else if (is_imm8(imm))
1251 		EMIT3(0x83, add_1reg(modrm[op], dst_reg), imm);
1252 	else if (is_axreg(dst_reg))
1253 		EMIT1_off32(short_op[op], imm);
1254 	else
1255 		EMIT2_off32(0x81, add_1reg(modrm[op], dst_reg), imm);
1256 
1257 	*pprog = prog;
1258 }
1259 
1260 /* add/sub/and/or/xor dst_reg, src_reg */
1261 static void emit_alu_reg(u8 **pprog, u32 op, u32 dst_reg, u32 src_reg, bool is64)
1262 {
1263 	u8 *prog = *pprog;
1264 
1265 	maybe_emit_mod(&prog, dst_reg, src_reg, is64);
1266 	EMIT2(simple_alu_opcodes[op], add_2reg(0xC0, dst_reg, src_reg));
1267 
1268 	*pprog = prog;
1269 }
1270 
1271 /* shl/shr/sar reg, imm */
1272 static void emit_shift_imm(u8 **pprog, u32 op, u32 reg, u8 imm, bool is64)
1273 {
1274 	u8 *prog = *pprog;
1275 
1276 	/* The shift left by one is an add of the register to itself */
1277 	if (op == BPF_LSH && imm == 1) {
1278 		emit_alu_reg(&prog, BPF_ADD, reg, reg, is64);
1279 	} else {
1280 		maybe_emit_1mod(&prog, reg, is64);
1281 		if (imm == 1)
1282 			EMIT2(0xD1, add_1reg(simple_alu_opcodes[op], reg));
1283 		else
1284 			EMIT3(0xC1, add_1reg(simple_alu_opcodes[op], reg), imm);
1285 	}
1286 
1287 	*pprog = prog;
1288 }
1289 
1290 /* neg dst_reg */
1291 static void emit_neg(u8 **pprog, u32 dst_reg, bool is64)
1292 {
1293 	u8 *prog = *pprog;
1294 
1295 	maybe_emit_1mod(&prog, dst_reg, is64);
1296 	EMIT2(0xF7, add_1reg(0xD8, dst_reg));
1297 
1298 	*pprog = prog;
1299 }
1300 
1301 static int emit_kasan_check(struct bpf_verifier_env *env, u8 **pprog,
1302 			    u32 addr_reg, s32 off, u32 bpf_size, u8 *ip,
1303 			    bool is_write)
1304 {
1305 #ifdef CONFIG_BPF_JIT_KASAN
1306 	u8 *prog = *pprog;
1307 	void *kasan_func;
1308 
1309 	if (!env)
1310 		return 0;
1311 
1312 	if (addr_reg == BPF_REG_FP || addr_reg == BPF_REG_PARAMS)
1313 		return 0;
1314 
1315 	/* Derive KASAN check function from access type and size */
1316 	switch (bpf_size) {
1317 	case BPF_B:
1318 		kasan_func = is_write ? __asan_store1 : __asan_load1;
1319 		break;
1320 	case BPF_H:
1321 		kasan_func = is_write ? __asan_store2 : __asan_load2;
1322 		break;
1323 	case BPF_W:
1324 		kasan_func = is_write ? __asan_store4 : __asan_load4;
1325 		break;
1326 	case BPF_DW:
1327 		kasan_func = is_write ? __asan_store8 : __asan_load8;
1328 		break;
1329 	default:
1330 		return -EINVAL;
1331 	}
1332 
1333 	/* Save rax */
1334 	EMIT1(0x50);
1335 	/* Save rcx */
1336 	EMIT1(0x51);
1337 	/* Save rdx */
1338 	EMIT1(0x52);
1339 	/* Save rsi */
1340 	EMIT1(0x56);
1341 	/* Save rdi */
1342 	EMIT1(0x57);
1343 	/* Save r8 */
1344 	EMIT2(0x41, 0x50);
1345 	/* Save r9 */
1346 	EMIT2(0x41, 0x51);
1347 	/* Save r10 */
1348 	EMIT2(0x41, 0x52);
1349 	/* Save r11 */
1350 	EMIT2(0x41, 0x53);
1351 	/* mov rdi, addr_reg */
1352 	EMIT_mov(BPF_REG_1, addr_reg);
1353 
1354 	/* add rdi, off (if offset is non-zero) */
1355 	if (off)
1356 		emit_alu_imm(&prog, BPF_ADD, BPF_REG_1, off, true);
1357 
1358 	/* Adjust ip to account for the instrumentation generated so far */
1359 	ip += (prog - *pprog);
1360 	/* We emit a call, so update call depth counting */
1361 	ip += x86_call_depth_emit_accounting(&prog, kasan_func, ip);
1362 	/* call kasan_func */
1363 	if (emit_call(&prog, kasan_func, ip))
1364 		return -ERANGE;
1365 
1366 	EMIT2(0x41, 0x5B);
1367 	EMIT2(0x41, 0x5A);
1368 	EMIT2(0x41, 0x59);
1369 	EMIT2(0x41, 0x58);
1370 	EMIT1(0x5F);
1371 	EMIT1(0x5E);
1372 	EMIT1(0x5A);
1373 	EMIT1(0x59);
1374 	EMIT1(0x58);
1375 
1376 	*pprog = prog;
1377 #endif /* CONFIG_BPF_JIT_KASAN */
1378 	return 0;
1379 }
1380 
1381 /* LDX: dst_reg = *(u8*)(src_reg + off) */
1382 static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1383 {
1384 	u8 *prog = *pprog;
1385 
1386 	switch (size) {
1387 	case BPF_B:
1388 		/* Emit 'movzx eax, byte ptr [rax + off]' */
1389 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1390 			EMIT1(add_2mod(0x40, src_reg, dst_reg));
1391 		EMIT2(0x0F, 0xB6);
1392 		break;
1393 	case BPF_H:
1394 		/* Emit 'movzx eax, word ptr [rax + off]' */
1395 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1396 			EMIT1(add_2mod(0x40, src_reg, dst_reg));
1397 		EMIT2(0x0F, 0xB7);
1398 		break;
1399 	case BPF_W:
1400 		/* Emit 'mov eax, dword ptr [rax+0x14]' */
1401 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1402 			EMIT2(add_2mod(0x40, src_reg, dst_reg), 0x8B);
1403 		else
1404 			EMIT1(0x8B);
1405 		break;
1406 	case BPF_DW:
1407 		/* Emit 'mov rax, qword ptr [rax+0x14]' */
1408 		EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x8B);
1409 		break;
1410 	}
1411 	emit_insn_suffix(&prog, src_reg, dst_reg, off);
1412 	*pprog = prog;
1413 }
1414 
1415 /* LDSX: dst_reg = *(s8*)(src_reg + off) */
1416 static void emit_ldsx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1417 {
1418 	u8 *prog = *pprog;
1419 
1420 	switch (size) {
1421 	case BPF_B:
1422 		/* Emit 'movsx rax, byte ptr [rax + off]' */
1423 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xBE);
1424 		break;
1425 	case BPF_H:
1426 		/* Emit 'movsx rax, word ptr [rax + off]' */
1427 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xBF);
1428 		break;
1429 	case BPF_W:
1430 		/* Emit 'movsx rax, dword ptr [rax+0x14]' */
1431 		EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x63);
1432 		break;
1433 	}
1434 	emit_insn_suffix(&prog, src_reg, dst_reg, off);
1435 	*pprog = prog;
1436 }
1437 
1438 static void emit_ldx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 index_reg, int off)
1439 {
1440 	u8 *prog = *pprog;
1441 
1442 	switch (size) {
1443 	case BPF_B:
1444 		/* movzx rax, byte ptr [rax + r12 + off] */
1445 		EMIT3(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x0F, 0xB6);
1446 		break;
1447 	case BPF_H:
1448 		/* movzx rax, word ptr [rax + r12 + off] */
1449 		EMIT3(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x0F, 0xB7);
1450 		break;
1451 	case BPF_W:
1452 		/* mov eax, dword ptr [rax + r12 + off] */
1453 		EMIT2(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x8B);
1454 		break;
1455 	case BPF_DW:
1456 		/* mov rax, qword ptr [rax + r12 + off] */
1457 		EMIT2(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x8B);
1458 		break;
1459 	}
1460 	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off, 0);
1461 	*pprog = prog;
1462 }
1463 
1464 static void emit_ldsx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 index_reg, int off)
1465 {
1466 	u8 *prog = *pprog;
1467 
1468 	switch (size) {
1469 	case BPF_B:
1470 		/* movsx rax, byte ptr [rax + r12 + off] */
1471 		EMIT3(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x0F, 0xBE);
1472 		break;
1473 	case BPF_H:
1474 		/* movsx rax, word ptr [rax + r12 + off] */
1475 		EMIT3(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x0F, 0xBF);
1476 		break;
1477 	case BPF_W:
1478 		/* movsx rax, dword ptr [rax + r12 + off] */
1479 		EMIT2(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x63);
1480 		break;
1481 	}
1482 	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off, 0);
1483 	*pprog = prog;
1484 }
1485 
1486 static void emit_ldx_r12(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1487 {
1488 	emit_ldx_index(pprog, size, dst_reg, src_reg, X86_REG_R12, off);
1489 }
1490 
1491 static void emit_ldsx_r12(u8 **prog, u32 size, u32 dst_reg, u32 src_reg, int off)
1492 {
1493 	emit_ldsx_index(prog, size, dst_reg, src_reg, X86_REG_R12, off);
1494 }
1495 
1496 /* STX: *(u8*)(dst_reg + off) = src_reg */
1497 static void emit_stx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1498 {
1499 	u8 *prog = *pprog;
1500 
1501 	switch (size) {
1502 	case BPF_B:
1503 		/* Emit 'mov byte ptr [rax + off], al' */
1504 		if (is_ereg(dst_reg) || is_ereg_8l(src_reg))
1505 			/* Add extra byte for eregs or SIL,DIL,BPL in src_reg */
1506 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x88);
1507 		else
1508 			EMIT1(0x88);
1509 		break;
1510 	case BPF_H:
1511 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1512 			EMIT3(0x66, add_2mod(0x40, dst_reg, src_reg), 0x89);
1513 		else
1514 			EMIT2(0x66, 0x89);
1515 		break;
1516 	case BPF_W:
1517 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1518 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x89);
1519 		else
1520 			EMIT1(0x89);
1521 		break;
1522 	case BPF_DW:
1523 		EMIT2(add_2mod(0x48, dst_reg, src_reg), 0x89);
1524 		break;
1525 	}
1526 	emit_insn_suffix(&prog, dst_reg, src_reg, off);
1527 	*pprog = prog;
1528 }
1529 
1530 /* STX: *(u8*)(dst_reg + index_reg + off) = src_reg */
1531 static void emit_stx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 index_reg, int off)
1532 {
1533 	u8 *prog = *pprog;
1534 
1535 	switch (size) {
1536 	case BPF_B:
1537 		/* mov byte ptr [rax + r12 + off], al */
1538 		EMIT2(add_3mod(0x40, dst_reg, src_reg, index_reg), 0x88);
1539 		break;
1540 	case BPF_H:
1541 		/* mov word ptr [rax + r12 + off], ax */
1542 		EMIT3(0x66, add_3mod(0x40, dst_reg, src_reg, index_reg), 0x89);
1543 		break;
1544 	case BPF_W:
1545 		/* mov dword ptr [rax + r12 + 1], eax */
1546 		EMIT2(add_3mod(0x40, dst_reg, src_reg, index_reg), 0x89);
1547 		break;
1548 	case BPF_DW:
1549 		/* mov qword ptr [rax + r12 + 1], rax */
1550 		EMIT2(add_3mod(0x48, dst_reg, src_reg, index_reg), 0x89);
1551 		break;
1552 	}
1553 	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off, 0);
1554 	*pprog = prog;
1555 }
1556 
1557 static void emit_stx_r12(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1558 {
1559 	emit_stx_index(pprog, size, dst_reg, src_reg, X86_REG_R12, off);
1560 }
1561 
1562 /* ST: *(u8*)(dst_reg + index_reg + off) = imm32 */
1563 static void emit_st_index(u8 **pprog, u32 size, u32 dst_reg, u32 index_reg, int off, int imm)
1564 {
1565 	u8 *prog = *pprog;
1566 
1567 	switch (size) {
1568 	case BPF_B:
1569 		/* mov byte ptr [rax + r12 + off], imm8 */
1570 		EMIT2(add_3mod(0x40, dst_reg, 0, index_reg), 0xC6);
1571 		break;
1572 	case BPF_H:
1573 		/* mov word ptr [rax + r12 + off], imm16 */
1574 		EMIT3(0x66, add_3mod(0x40, dst_reg, 0, index_reg), 0xC7);
1575 		break;
1576 	case BPF_W:
1577 		/* mov dword ptr [rax + r12 + 1], imm32 */
1578 		EMIT2(add_3mod(0x40, dst_reg, 0, index_reg), 0xC7);
1579 		break;
1580 	case BPF_DW:
1581 		/* mov qword ptr [rax + r12 + 1], imm32 */
1582 		EMIT2(add_3mod(0x48, dst_reg, 0, index_reg), 0xC7);
1583 		break;
1584 	}
1585 	emit_insn_suffix_SIB(&prog, dst_reg, 0, index_reg, off, 0);
1586 	EMIT(imm, bpf_size_to_x86_bytes(size));
1587 	*pprog = prog;
1588 }
1589 
1590 /* ST: *(u8*)(dst_reg + off) = imm */
1591 static void emit_st(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
1592 		    s32 insn_off)
1593 {
1594 	s32 imm32 = insn->imm;
1595 	u8 *prog = *pprog;
1596 
1597 	switch (BPF_SIZE(insn->code)) {
1598 	case BPF_B:
1599 		if (is_ereg(dst_reg))
1600 			EMIT2(0x41, 0xC6);
1601 		else
1602 			EMIT1(0xC6);
1603 		break;
1604 	case BPF_H:
1605 		if (is_ereg(dst_reg))
1606 			EMIT3(0x66, 0x41, 0xC7);
1607 		else
1608 			EMIT2(0x66, 0xC7);
1609 		break;
1610 	case BPF_W:
1611 		if (is_ereg(dst_reg))
1612 			EMIT2(0x41, 0xC7);
1613 		else
1614 			EMIT1(0xC7);
1615 		break;
1616 	case BPF_DW:
1617 		EMIT2(add_1mod(0x48, dst_reg), 0xC7);
1618 		break;
1619 	}
1620 
1621 	emit_insn_suffix(&prog, dst_reg, BPF_REG_0, insn_off);
1622 	EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));
1623 	*pprog = prog;
1624 }
1625 
1626 static void emit_st_r12(u8 **pprog, u32 size, u32 dst_reg, int off, int imm)
1627 {
1628 	emit_st_index(pprog, size, dst_reg, X86_REG_R12, off, imm);
1629 }
1630 
1631 static void emit_store_stack_imm64(u8 **pprog, int reg, int stack_off, u64 imm64)
1632 {
1633 	/*
1634 	 * mov reg, imm64
1635 	 * mov QWORD PTR [rbp + stack_off], reg
1636 	 */
1637 	emit_mov_imm64(pprog, reg, imm64 >> 32, (u32) imm64);
1638 	emit_stx(pprog, BPF_DW, BPF_REG_FP, reg, stack_off);
1639 }
1640 
1641 static int emit_atomic_rmw(u8 **pprog, u32 atomic_op,
1642 			   u32 dst_reg, u32 src_reg, s16 off, u8 bpf_size)
1643 {
1644 	u8 *prog = *pprog;
1645 
1646 	if (atomic_op != BPF_XCHG)
1647 		EMIT1(0xF0); /* lock prefix */
1648 
1649 	maybe_emit_mod(&prog, dst_reg, src_reg, bpf_size == BPF_DW);
1650 
1651 	/* emit opcode */
1652 	switch (atomic_op) {
1653 	case BPF_ADD:
1654 	case BPF_AND:
1655 	case BPF_OR:
1656 	case BPF_XOR:
1657 		/* lock *(u32/u64*)(dst_reg + off) <op>= src_reg */
1658 		EMIT1(simple_alu_opcodes[atomic_op]);
1659 		break;
1660 	case BPF_ADD | BPF_FETCH:
1661 		/* src_reg = atomic_fetch_add(dst_reg + off, src_reg); */
1662 		EMIT2(0x0F, 0xC1);
1663 		break;
1664 	case BPF_XCHG:
1665 		/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
1666 		EMIT1(0x87);
1667 		break;
1668 	case BPF_CMPXCHG:
1669 		/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
1670 		EMIT2(0x0F, 0xB1);
1671 		break;
1672 	default:
1673 		pr_err("bpf_jit: unknown atomic opcode %02x\n", atomic_op);
1674 		return -EFAULT;
1675 	}
1676 
1677 	emit_insn_suffix(&prog, dst_reg, src_reg, off);
1678 
1679 	*pprog = prog;
1680 	return 0;
1681 }
1682 
1683 static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size,
1684 				 u32 dst_reg, u32 src_reg, u32 index_reg,
1685 				 int off)
1686 {
1687 	u8 *prog = *pprog;
1688 
1689 	if (atomic_op != BPF_XCHG)
1690 		EMIT1(0xF0); /* lock prefix */
1691 
1692 	switch (size) {
1693 	case BPF_W:
1694 		EMIT1(add_3mod(0x40, dst_reg, src_reg, index_reg));
1695 		break;
1696 	case BPF_DW:
1697 		EMIT1(add_3mod(0x48, dst_reg, src_reg, index_reg));
1698 		break;
1699 	default:
1700 		pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
1701 		return -EFAULT;
1702 	}
1703 
1704 	/* emit opcode */
1705 	switch (atomic_op) {
1706 	case BPF_ADD:
1707 	case BPF_AND:
1708 	case BPF_OR:
1709 	case BPF_XOR:
1710 		/* lock *(u32/u64*)(dst_reg + idx_reg + off) <op>= src_reg */
1711 		EMIT1(simple_alu_opcodes[atomic_op]);
1712 		break;
1713 	case BPF_ADD | BPF_FETCH:
1714 		/* src_reg = atomic_fetch_add(dst_reg + idx_reg + off, src_reg); */
1715 		EMIT2(0x0F, 0xC1);
1716 		break;
1717 	case BPF_XCHG:
1718 		/* src_reg = atomic_xchg(dst_reg + idx_reg + off, src_reg); */
1719 		EMIT1(0x87);
1720 		break;
1721 	case BPF_CMPXCHG:
1722 		/* r0 = atomic_cmpxchg(dst_reg + idx_reg + off, r0, src_reg); */
1723 		EMIT2(0x0F, 0xB1);
1724 		break;
1725 	default:
1726 		pr_err("bpf_jit: unknown atomic opcode %02x\n", atomic_op);
1727 		return -EFAULT;
1728 	}
1729 	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off, 0);
1730 	*pprog = prog;
1731 	return 0;
1732 }
1733 
1734 static int emit_atomic_ld_st(struct bpf_verifier_env *env, u8 **pprog,
1735 			     struct bpf_insn *insn, u8 *ip, u32 dst_reg,
1736 			     u32 src_reg, bool accesses_stack_only)
1737 {
1738 	u32 atomic_op = insn->imm;
1739 	int err;
1740 
1741 	switch (atomic_op) {
1742 	case BPF_LOAD_ACQ:
1743 		if (!accesses_stack_only) {
1744 			err = emit_kasan_check(env, pprog, src_reg, insn->off,
1745 					       BPF_SIZE(insn->code), ip, false);
1746 			if (err)
1747 				return err;
1748 		}
1749 		/* dst_reg = smp_load_acquire(src_reg + off16) */
1750 		emit_ldx(pprog, BPF_SIZE(insn->code), dst_reg, src_reg,
1751 			 insn->off);
1752 		break;
1753 	case BPF_STORE_REL:
1754 		if (!accesses_stack_only) {
1755 			err = emit_kasan_check(env, pprog, dst_reg, insn->off,
1756 					       BPF_SIZE(insn->code), ip, true);
1757 			if (err)
1758 				return err;
1759 		}
1760 		/* smp_store_release(dst_reg + off16, src_reg) */
1761 		emit_stx(pprog, BPF_SIZE(insn->code), dst_reg, src_reg,
1762 			 insn->off);
1763 		break;
1764 	default:
1765 		pr_err("bpf_jit: unknown atomic load/store opcode %02x\n",
1766 		       atomic_op);
1767 		return -EFAULT;
1768 	}
1769 
1770 	return 0;
1771 }
1772 
1773 static int emit_atomic_ld_st_index(u8 **pprog, u32 atomic_op, u32 size,
1774 				   u32 dst_reg, u32 src_reg, u32 index_reg,
1775 				   int off)
1776 {
1777 	switch (atomic_op) {
1778 	case BPF_LOAD_ACQ:
1779 		/* dst_reg = smp_load_acquire(src_reg + idx_reg + off16) */
1780 		emit_ldx_index(pprog, size, dst_reg, src_reg, index_reg, off);
1781 		break;
1782 	case BPF_STORE_REL:
1783 		/* smp_store_release(dst_reg + idx_reg + off16, src_reg) */
1784 		emit_stx_index(pprog, size, dst_reg, src_reg, index_reg, off);
1785 		break;
1786 	default:
1787 		pr_err("bpf_jit: unknown atomic load/store opcode %02x\n",
1788 		       atomic_op);
1789 		return -EFAULT;
1790 	}
1791 
1792 	return 0;
1793 }
1794 
1795 /*
1796  * A fetching AND/OR/XOR can't be implemented with a single x86 insn, so do a
1797  * CMPXCHG loop. @index_reg is X86_REG_R12 for an arena access or -1 otherwise.
1798  * Unless @r0_on_stack, the caller has substituted BPF_REG_AX for R0 in
1799  * @dst_reg and @src_reg.
1800  *
1801  * Both the load and the CMPXCHG can fault when accessing the arena, so their
1802  * addresses are handed back in @fault[0] and @fault[1]. A fault has to resume
1803  * at @resume, which is past the loop and past the move that delivers the old
1804  * value, but before R0 is restored. Both are NULL for the non-arena case,
1805  * which needs no fixup.
1806  *
1807  * R0 is expected to be saved in BPF_REG_AX by the caller, or pushed on the
1808  * stack if @r0_on_stack. In that case an R0 operand stays in the stack slot,
1809  * RAX ends up holding the old value that R0 is to return, and the slot is
1810  * dropped rather than popped.
1811  */
1812 static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
1813 				 u32 src_reg, int index_reg, bool r0_on_stack,
1814 				 u8 **fault, u8 **resume)
1815 {
1816 	bool is64 = BPF_SIZE(insn->code) == BPF_DW;
1817 	bool operand_on_stack = r0_on_stack && src_reg == BPF_REG_0;
1818 	u8 *branch_target, *prog = *pprog;
1819 	int err;
1820 
1821 	branch_target = prog;
1822 
1823 	/* Load old value */
1824 	if (fault)
1825 		fault[0] = prog;
1826 	if (index_reg < 0)
1827 		emit_ldx(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg, insn->off);
1828 	else
1829 		emit_ldx_index(&prog, BPF_SIZE(insn->code), BPF_REG_0, dst_reg,
1830 			       index_reg, insn->off);
1831 
1832 	/*
1833 	 * Perform the (commutative) operation locally, put the result in
1834 	 * the AUX_REG.
1835 	 */
1836 	if (operand_on_stack) {
1837 		/* mov r11, [rsp]: the operand is the R0 saved there, RAX is the old value */
1838 		if (is64)
1839 			EMIT4(0x4C, 0x8B, 0x1C, 0x24);
1840 		else
1841 			EMIT4(0x44, 0x8B, 0x1C, 0x24);
1842 	} else {
1843 		emit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0);
1844 	}
1845 	maybe_emit_mod(&prog, AUX_REG, src_reg, is64);
1846 	EMIT2(simple_alu_opcodes[BPF_OP(insn->imm)],
1847 	      add_2reg(0xC0, AUX_REG, src_reg));
1848 
1849 	/* Attempt to swap in new value */
1850 	if (fault)
1851 		fault[1] = prog;
1852 	if (index_reg < 0)
1853 		err = emit_atomic_rmw(&prog, BPF_CMPXCHG, dst_reg, AUX_REG,
1854 				      insn->off, BPF_SIZE(insn->code));
1855 	else
1856 		err = emit_atomic_rmw_index(&prog, BPF_CMPXCHG, BPF_SIZE(insn->code),
1857 					    dst_reg, AUX_REG, index_reg, insn->off);
1858 	if (WARN_ON(err))
1859 		return err;
1860 
1861 	/* ZF tells us whether we won the race. If it's cleared we need to try again. */
1862 	EMIT2(X86_JNE, -(prog - branch_target) - 2);
1863 	/* Return the pre-modification value, which RAX already is for R0 */
1864 	if (!operand_on_stack)
1865 		emit_mov_reg(&prog, is64, src_reg, BPF_REG_0);
1866 
1867 	if (resume)
1868 		*resume = prog;
1869 
1870 	/* Restore R0 after clobbering RAX */
1871 	if (!r0_on_stack)
1872 		emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX);
1873 	else if (operand_on_stack)
1874 		EMIT2(0x41, 0x5B); /* pop r11, dropping the operand */
1875 	else
1876 		EMIT1(0x58); /* pop rax */
1877 
1878 	*pprog = prog;
1879 	return 0;
1880 }
1881 
1882 /*
1883  * Metadata encoding for exception handling in JITed code.
1884  *
1885  * Format of `fixup` and `data` fields in `struct exception_table_entry`:
1886  *
1887  * Bit layout of `fixup` (32-bit):
1888  *
1889  * +-----------+-------------+--------+-----------+---------+----------+
1890  * | 31        | 30          | 29-24  |   23-16   |   15-8  |    7-0   |
1891  * |           |             |        |           |         |          |
1892  * | ARENA_ACC | ARENA_WRITE | Unused | ARENA_REG | DST_REG | INSN_LEN |
1893  * +-----------+-------------+--------+-----------+---------+----------+
1894  *
1895  * - INSN_LEN (8 bits): How far past the faulting insn to resume. That is its own length
1896  *                      for a single-insn access, but the distance to the end of the whole
1897  *                      sequence where one BPF insn became several, as for the CMPXCHG loop
1898  *                      of a fetching AND/OR/XOR. A sequence long enough to overflow this
1899  *                      field would first have to exceed BPF_MAX_INSN_SIZE, which do_jit()
1900  *                      rejects with -EFAULT before the image is used.
1901  * - DST_REG  (8 bits): Offset of dst_reg from reg2pt_regs[] (max offset = 112 (fits in 8 bits)).
1902  *                      This is set to DONT_CLEAR if the insn does not read into a register.
1903  * - ARENA_REG (8 bits): Offset of the register that is used to calculate the
1904  *                       address for load/store when accessing the arena region.
1905  * - ARENA_WRITE (1 bit): This bit is set when the faulting instruction wrote to the arena region.
1906  *                        It is independent of DST_REG, since a read-modify-write both writes to
1907  *                        memory and reads the old value into a register.
1908  * - ARENA_ACCESS (1 bit): This bit is set when the faulting instruction accessed the arena region.
1909  *
1910  * Bit layout of `data` (32-bit):
1911  *
1912  * +--------------+--------+--------------+
1913  * |	31-16	  |  15-8  |     7-0      |
1914  * |              |	   |              |
1915  * | ARENA_OFFSET | Unused |  EX_TYPE_BPF |
1916  * +--------------+--------+--------------+
1917  *
1918  * - ARENA_OFFSET (16 bits): Offset used to calculate the address for load/store when
1919  *                           accessing the arena region.
1920  */
1921 
1922 #define DONT_CLEAR 1
1923 #define FIXUP_INSN_LEN_MASK	GENMASK(7, 0)
1924 #define FIXUP_REG_MASK		GENMASK(15, 8)
1925 #define FIXUP_ARENA_REG_MASK	GENMASK(23, 16)
1926 #define FIXUP_ARENA_WRITE	BIT(30)
1927 #define FIXUP_ARENA_ACCESS	BIT(31)
1928 #define DATA_ARENA_OFFSET_MASK	GENMASK(31, 16)
1929 
1930 bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
1931 {
1932 	u32 reg = FIELD_GET(FIXUP_REG_MASK, x->fixup);
1933 	u32 insn_len = FIELD_GET(FIXUP_INSN_LEN_MASK, x->fixup);
1934 	bool is_arena = !!(x->fixup & FIXUP_ARENA_ACCESS);
1935 	bool is_write = !!(x->fixup & FIXUP_ARENA_WRITE);
1936 	unsigned long addr;
1937 	s16 off;
1938 	u32 arena_reg;
1939 
1940 	if (is_arena) {
1941 		arena_reg = FIELD_GET(FIXUP_ARENA_REG_MASK, x->fixup);
1942 		off = FIELD_GET(DATA_ARENA_OFFSET_MASK, x->data);
1943 		addr = *(unsigned long *)((void *)regs + arena_reg) + off;
1944 		bpf_prog_report_arena_violation(is_write, addr, regs->ip);
1945 	}
1946 
1947 	/* jump over the faulting access, or the sequence it is part of, and clear dest register */
1948 	if (reg != DONT_CLEAR)
1949 		*(unsigned long *)((void *)regs + reg) = 0;
1950 	regs->ip += insn_len;
1951 
1952 	return true;
1953 }
1954 
1955 /*
1956  * Record an arena access that may fault. @fault_ip is the address of the
1957  * faulting insn in the RO image, @resume_off how far past it execution has to
1958  * resume: for a multi-insn lowering that is the end of the whole sequence, not
1959  * the end of the one insn.
1960  */
1961 static int emit_arena_exentry(struct bpf_prog *bpf_prog, u8 *image, u8 *rw_image,
1962 			      int *excnt, u8 *fault_ip, u32 resume_off,
1963 			      u32 fixup_reg, u32 arena_reg, bool is_write, s16 off)
1964 {
1965 	struct exception_table_entry *ex;
1966 	s64 delta;
1967 
1968 	if (!bpf_prog->aux->extable)
1969 		return 0;
1970 
1971 	if (*excnt >= bpf_prog->aux->num_exentries) {
1972 		pr_err("arena extable bug\n");
1973 		return -EFAULT;
1974 	}
1975 	ex = &bpf_prog->aux->extable[(*excnt)++];
1976 
1977 	delta = fault_ip - (u8 *)&ex->insn;
1978 	/* switch ex to rw buffer for writes */
1979 	ex = (void *)rw_image + ((void *)ex - (void *)image);
1980 
1981 	ex->insn = delta;
1982 	ex->data = EX_TYPE_BPF | FIELD_PREP(DATA_ARENA_OFFSET_MASK, off);
1983 	ex->fixup = FIELD_PREP(FIXUP_INSN_LEN_MASK, resume_off) |
1984 		    FIELD_PREP(FIXUP_ARENA_REG_MASK, arena_reg) |
1985 		    FIELD_PREP(FIXUP_REG_MASK, fixup_reg) |
1986 		    FIXUP_ARENA_ACCESS;
1987 	if (is_write)
1988 		ex->fixup |= FIXUP_ARENA_WRITE;
1989 
1990 	return 0;
1991 }
1992 
1993 static void detect_reg_usage(struct bpf_insn *insn, int insn_cnt,
1994 			     bool *regs_used)
1995 {
1996 	int i;
1997 
1998 	for (i = 1; i <= insn_cnt; i++, insn++) {
1999 		if (insn->dst_reg == BPF_REG_6 || insn->src_reg == BPF_REG_6)
2000 			regs_used[0] = true;
2001 		if (insn->dst_reg == BPF_REG_7 || insn->src_reg == BPF_REG_7)
2002 			regs_used[1] = true;
2003 		if (insn->dst_reg == BPF_REG_8 || insn->src_reg == BPF_REG_8)
2004 			regs_used[2] = true;
2005 		if (insn->dst_reg == BPF_REG_9 || insn->src_reg == BPF_REG_9)
2006 			regs_used[3] = true;
2007 	}
2008 }
2009 
2010 /* emit the 3-byte VEX prefix
2011  *
2012  * r: same as rex.r, extra bit for ModRM reg field
2013  * x: same as rex.x, extra bit for SIB index field
2014  * b: same as rex.b, extra bit for ModRM r/m, or SIB base
2015  * m: opcode map select, encoding escape bytes e.g. 0x0f38
2016  * w: same as rex.w (32 bit or 64 bit) or opcode specific
2017  * src_reg2: additional source reg (encoded as BPF reg)
2018  * l: vector length (128 bit or 256 bit) or reserved
2019  * pp: opcode prefix (none, 0x66, 0xf2 or 0xf3)
2020  */
2021 static void emit_3vex(u8 **pprog, bool r, bool x, bool b, u8 m,
2022 		      bool w, u8 src_reg2, bool l, u8 pp)
2023 {
2024 	u8 *prog = *pprog;
2025 	const u8 b0 = 0xc4; /* first byte of 3-byte VEX prefix */
2026 	u8 b1, b2;
2027 	u8 vvvv = reg2hex[src_reg2];
2028 
2029 	/* reg2hex gives only the lower 3 bit of vvvv */
2030 	if (is_ereg(src_reg2))
2031 		vvvv |= 1 << 3;
2032 
2033 	/*
2034 	 * 2nd byte of 3-byte VEX prefix
2035 	 * ~ means bit inverted encoding
2036 	 *
2037 	 *    7                           0
2038 	 *  +---+---+---+---+---+---+---+---+
2039 	 *  |~R |~X |~B |         m         |
2040 	 *  +---+---+---+---+---+---+---+---+
2041 	 */
2042 	b1 = (!r << 7) | (!x << 6) | (!b << 5) | (m & 0x1f);
2043 	/*
2044 	 * 3rd byte of 3-byte VEX prefix
2045 	 *
2046 	 *    7                           0
2047 	 *  +---+---+---+---+---+---+---+---+
2048 	 *  | W |     ~vvvv     | L |   pp  |
2049 	 *  +---+---+---+---+---+---+---+---+
2050 	 */
2051 	b2 = (w << 7) | ((~vvvv & 0xf) << 3) | (l << 2) | (pp & 3);
2052 
2053 	EMIT3(b0, b1, b2);
2054 	*pprog = prog;
2055 }
2056 
2057 /* emit BMI2 shift instruction */
2058 static void emit_shiftx(u8 **pprog, u32 dst_reg, u8 src_reg, bool is64, u8 op)
2059 {
2060 	u8 *prog = *pprog;
2061 	bool r = is_ereg(dst_reg);
2062 	u8 m = 2; /* escape code 0f38 */
2063 
2064 	emit_3vex(&prog, r, false, r, m, is64, src_reg, false, op);
2065 	EMIT2(0xf7, add_2reg(0xC0, dst_reg, dst_reg));
2066 	*pprog = prog;
2067 }
2068 
2069 struct bpf_div_magic {
2070 	u64 m;		/* multiplier, sign extended for signed division */
2071 	int s;		/* shift of the high half of the product */
2072 	bool add;	/* multiplier has 65 bits, use the add sequence */
2073 };
2074 
2075 /*
2076  * Multiplier and shift for an unsigned division by the constant d, with
2077  * 2 <= d < 2^64 and a dividend below 2^(64 - lz): n / d == (mulhu(n, m)
2078  * >> s), or with the add sequence when m needs 65 bits, (((n - t) >> 1)
2079  * + t) >> (s - 1) with t = mulhu(n, m). Hacker's Delight, 2nd ed., figure
2080  * 10-2.
2081  */
2082 static void bpf_magic_udiv(u64 d, int lz, struct bpf_div_magic *mag)
2083 {
2084 	u64 mask = ~0ULL >> (lz & 63);
2085 	u64 nc, delta, q1, r1, q2, r2;
2086 	int p;
2087 
2088 	mag->add = false;
2089 	/* Largest value with nc mod d == d - 1 */
2090 	nc = mask - (mask % d + 1) % d;
2091 	p = 63;
2092 	q1 = (1ULL << 63) / nc;			/* 2^p / nc */
2093 	r1 = (1ULL << 63) - q1 * nc;		/* 2^p mod nc */
2094 	q2 = (~0ULL >> 1) / d;			/* (2^p - 1) / d */
2095 	r2 = (~0ULL >> 1) - q2 * d;		/* (2^p - 1) mod d */
2096 	do {
2097 		p++;
2098 		if (r1 >= nc - r1) {
2099 			q1 = 2 * q1 + 1;
2100 			r1 = 2 * r1 - nc;
2101 		} else {
2102 			q1 = 2 * q1;
2103 			r1 = 2 * r1;
2104 		}
2105 		if (r2 + 1 >= d - r2) {
2106 			if (q2 >= (~0ULL >> 1))
2107 				mag->add = true;
2108 			q2 = 2 * q2 + 1;
2109 			r2 = 2 * r2 + 1 - d;
2110 		} else {
2111 			if (q2 >= (1ULL << 63))
2112 				mag->add = true;
2113 			q2 = 2 * q2;
2114 			r2 = 2 * r2 + 1;
2115 		}
2116 		delta = d - 1 - r2;
2117 	} while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
2118 
2119 	mag->m = q2 + 1;
2120 	mag->s = p - 64;
2121 }
2122 
2123 /*
2124  * Multiplier and shift for a signed division by the constant d, with
2125  * 2 <= |d| < 2^63: q = mulhs(n, m), q += n if d > 0 and m < 0, q -= n
2126  * if d < 0 and m > 0, q >>= s (arithmetic), n / d == q + (q >>> 63).
2127  * Hacker's Delight, 2nd ed., figure 10-1.
2128  */
2129 static void bpf_magic_sdiv(s64 d, struct bpf_div_magic *mag)
2130 {
2131 	u64 ad = d < 0 ? -(u64)d : (u64)d;
2132 	u64 t, anc, delta, q1, r1, q2, r2;
2133 	int p;
2134 
2135 	t = (1ULL << 63) + (d < 0);
2136 	anc = t - 1 - t % ad;			/* |nc| */
2137 	p = 63;
2138 	q1 = (1ULL << 63) / anc;		/* 2^p / |nc| */
2139 	r1 = (1ULL << 63) - q1 * anc;		/* 2^p mod |nc| */
2140 	q2 = (1ULL << 63) / ad;			/* 2^p / |d| */
2141 	r2 = (1ULL << 63) - q2 * ad;		/* 2^p mod |d| */
2142 	do {
2143 		p++;
2144 		q1 = 2 * q1;
2145 		r1 = 2 * r1;
2146 		if (r1 >= anc) {
2147 			q1++;
2148 			r1 -= anc;
2149 		}
2150 		q2 = 2 * q2;
2151 		r2 = 2 * r2;
2152 		if (r2 >= ad) {
2153 			q2++;
2154 			r2 -= ad;
2155 		}
2156 		delta = ad - r2;
2157 	} while (q1 < delta || (q1 == delta && r1 == 0));
2158 
2159 	mag->m = q2 + 1;
2160 	if (d < 0)
2161 		mag->m = -mag->m;
2162 	mag->s = p - 64;
2163 	mag->add = false;
2164 }
2165 
2166 /*
2167  * Divide dst_reg by the constant in insn->imm of a 64-bit division through
2168  * a multiplication with the magic number from bpf_magic_udiv() or
2169  * bpf_magic_sdiv(). The dividend goes through rax and the multiplier
2170  * through r11, the caller saves rax and rdx unless they are dst_reg, and
2171  * r10 is scratch. Returns false for the divisors left to div/idiv.
2172  */
2173 static bool emit_div_const(u8 **pprog, const struct bpf_insn *insn, u32 dst_reg)
2174 {
2175 	bool is_mod = BPF_OP(insn->code) == BPF_MOD;
2176 	bool is_signed = insn->off == 1;
2177 	u32 n_reg = dst_reg, q_reg;
2178 	s32 imm32 = insn->imm;
2179 	struct bpf_div_magic mag;
2180 	u8 *prog = *pprog;
2181 	int corr = 0, pre = 0, s;
2182 
2183 	if (is_signed) {
2184 		/* |d| >= 2, the verifier already rewrote d == -1 */
2185 		if (imm32 >= -1 && imm32 <= 1)
2186 			return false;
2187 		bpf_magic_sdiv(imm32, &mag);
2188 		/* q += n for d > 0 and m < 0, q -= n for d < 0 and m > 0 */
2189 		if (imm32 > 0 && (s64)mag.m < 0)
2190 			corr = 1;
2191 		else if (imm32 < 0 && (s64)mag.m > 0)
2192 			corr = -1;
2193 	} else {
2194 		/* d >= 2, a negative imm32 is a divisor above 2^63 */
2195 		if (imm32 < 2)
2196 			return false;
2197 		bpf_magic_udiv(imm32, 0, &mag);
2198 		/*
2199 		 * Shift the dividend by the trailing zeros of an even divisor
2200 		 * first, the magic number of the odd part then fits without
2201 		 * the add sequence.
2202 		 */
2203 		if (mag.add && !(imm32 & 1)) {
2204 			pre = __ffs(imm32) & 31;
2205 			bpf_magic_udiv(imm32 >> pre, pre, &mag);
2206 			if (mag.add)
2207 				return false;
2208 		}
2209 	}
2210 	s = mag.s;
2211 	/*
2212 	 * The shift is at most 63, or 64 with the add sequence which shifts
2213 	 * by s - 1 and needs s >= 1. Never hit for d >= 2, kept as a guard
2214 	 * against an unencodable count.
2215 	 */
2216 	if (s > 64 - !mag.add || (mag.add && !s))
2217 		return false;
2218 
2219 	/* Keep the dividend when the multiplication clobbers it */
2220 	if ((is_mod || mag.add || corr) &&
2221 	    (dst_reg == BPF_REG_0 || dst_reg == BPF_REG_3)) {
2222 		emit_mov_reg(&prog, true, BPF_REG_AX, dst_reg);
2223 		n_reg = BPF_REG_AX;
2224 	}
2225 
2226 	/* mov rax, dst_reg; shr rax, pre; mov r11, m; mul r11 or imul r11 */
2227 	if (dst_reg != BPF_REG_0)
2228 		emit_mov_reg(&prog, true, BPF_REG_0, dst_reg);
2229 	if (pre)
2230 		emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, pre, true);
2231 	emit_mov_imm64(&prog, AUX_REG, mag.m >> 32, (u32)mag.m);
2232 	EMIT3(0x49, 0xF7, is_signed ? 0xEB : 0xE3);
2233 	if (is_signed) {
2234 		/* add rdx, n_reg or sub rdx, n_reg */
2235 		if (corr)
2236 			emit_alu_reg(&prog, corr > 0 ? BPF_ADD : BPF_SUB,
2237 				     BPF_REG_3, n_reg, true);
2238 		/* sar rdx, s */
2239 		if (s)
2240 			emit_shift_imm(&prog, BPF_ARSH, BPF_REG_3, s, true);
2241 		/* mov rax, rdx; shr rax, 63; add rdx, rax */
2242 		emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_3);
2243 		emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, 63, true);
2244 		emit_alu_reg(&prog, BPF_ADD, BPF_REG_3, BPF_REG_0, true);
2245 		q_reg = BPF_REG_3;
2246 	} else if (!mag.add) {
2247 		/* shr rdx, s */
2248 		if (s)
2249 			emit_shift_imm(&prog, BPF_RSH, BPF_REG_3, s, true);
2250 		q_reg = BPF_REG_3;
2251 	} else {
2252 		/* mov rax, n_reg; sub rax, rdx; shr rax, 1 */
2253 		emit_mov_reg(&prog, true, BPF_REG_0, n_reg);
2254 		emit_alu_reg(&prog, BPF_SUB, BPF_REG_0, BPF_REG_3, true);
2255 		emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, 1, true);
2256 		/* add rax, rdx; shr rax, s - 1 */
2257 		emit_alu_reg(&prog, BPF_ADD, BPF_REG_0, BPF_REG_3, true);
2258 		if (s > 1)
2259 			emit_shift_imm(&prog, BPF_RSH, BPF_REG_0, s - 1, true);
2260 		q_reg = BPF_REG_0;
2261 	}
2262 
2263 	if (is_mod) {
2264 		/* imul q_reg, q_reg, imm32 */
2265 		maybe_emit_mod(&prog, q_reg, q_reg, true);
2266 		if (is_imm8(imm32))
2267 			EMIT3(0x6B, add_2reg(0xC0, q_reg, q_reg), imm32);
2268 		else
2269 			EMIT2_off32(0x69, add_2reg(0xC0, q_reg, q_reg), imm32);
2270 		/* sub n_reg, q_reg */
2271 		emit_alu_reg(&prog, BPF_SUB, n_reg, q_reg, true);
2272 		q_reg = n_reg;
2273 	}
2274 	if (q_reg != dst_reg)
2275 		emit_mov_reg(&prog, true, dst_reg, q_reg);
2276 
2277 	*pprog = prog;
2278 	return true;
2279 }
2280 
2281 static void emit_priv_frame_ptr(u8 **pprog, void __percpu *priv_frame_ptr)
2282 {
2283 	u8 *prog = *pprog;
2284 
2285 	/* movabs r9, priv_frame_ptr */
2286 	emit_mov_imm64(&prog, X86_REG_R9, (__force long) priv_frame_ptr >> 32,
2287 		       (u32) (__force long) priv_frame_ptr);
2288 
2289 #ifdef CONFIG_SMP
2290 	/* add <r9>, gs:[<off>] */
2291 	EMIT2(0x65, 0x4c);
2292 	EMIT3(0x03, 0x0c, 0x25);
2293 	EMIT((u32)(unsigned long)&this_cpu_off, 4);
2294 #endif
2295 
2296 	*pprog = prog;
2297 }
2298 
2299 #define INSN_SZ_DIFF (((addrs[i] - addrs[i - 1]) - (prog - temp)))
2300 
2301 #define __LOAD_TCC_PTR(off)			\
2302 	emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, off)
2303 /* mov rax, qword ptr [rbp - rounded_stack_depth - 16] */
2304 #define LOAD_TAIL_CALL_CNT_PTR(stack)				\
2305 	__LOAD_TCC_PTR(BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack))
2306 
2307 /* Memory size/value to protect private stack overflow/underflow */
2308 #define PRIV_STACK_GUARD_SZ    8
2309 #define PRIV_STACK_GUARD_VAL   0xEB9F12345678eb9fULL
2310 
2311 static int emit_spectre_bhb_barrier(u8 **pprog, u8 *ip,
2312 				    struct bpf_prog *bpf_prog)
2313 {
2314 	u8 *prog = *pprog;
2315 	u8 *func;
2316 
2317 	if (cpu_feature_enabled(X86_FEATURE_CLEAR_BHB_LOOP)) {
2318 		/* The clearing sequence clobbers eax and ecx. */
2319 		EMIT1(0x50); /* push rax */
2320 		EMIT1(0x51); /* push rcx */
2321 		ip += 2;
2322 
2323 		func = (u8 *)clear_bhb_loop;
2324 		ip += x86_call_depth_emit_accounting(&prog, func, ip);
2325 
2326 		if (emit_call(&prog, func, ip))
2327 			return -EINVAL;
2328 		EMIT1(0x59); /* pop rcx */
2329 		EMIT1(0x58); /* pop rax */
2330 	}
2331 	/* Insert IBHF instruction */
2332 	if ((cpu_feature_enabled(X86_FEATURE_CLEAR_BHB_LOOP) &&
2333 	     cpu_feature_enabled(X86_FEATURE_HYPERVISOR)) ||
2334 	    cpu_feature_enabled(X86_FEATURE_CLEAR_BHB_HW)) {
2335 		/*
2336 		 * Add an Indirect Branch History Fence (IBHF). IBHF acts as a
2337 		 * fence preventing branch history from before the fence from
2338 		 * affecting indirect branches after the fence. This is
2339 		 * specifically used in cBPF jitted code to prevent Intra-mode
2340 		 * BHI attacks. The IBHF instruction is designed to be a NOP on
2341 		 * hardware that doesn't need or support it.  The REP and REX.W
2342 		 * prefixes are required by the microcode, and they also ensure
2343 		 * that the NOP is unlikely to be used in existing code.
2344 		 *
2345 		 * IBHF is not a valid instruction in 32-bit mode.
2346 		 */
2347 		EMIT5(0xF3, 0x48, 0x0F, 0x1E, 0xF8); /* ibhf */
2348 	}
2349 	*pprog = prog;
2350 	return 0;
2351 }
2352 
2353 static const struct bpf_jit_arg_abi x86_arg_abi = {
2354 	.nr_arg_regs		= 6,
2355 	.backfill_after_stack	= true,
2356 	.even_stack_align	= true,
2357 };
2358 
2359 static const u8 x86_arg_reg[] = {
2360 	BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5, X86_REG_R9,
2361 };
2362 
2363 static bool x86_arg_on_stack(u8 pos)
2364 {
2365 	return pos >= x86_arg_abi.nr_arg_regs;
2366 }
2367 
2368 static s32 x86_arg_stack_off(u8 pos)
2369 {
2370 	return (pos - x86_arg_abi.nr_arg_regs) * 8;
2371 }
2372 
2373 /*
2374  * Move the arguments the x86-64 ABI places somewhere other than the argument
2375  * slot the BPF calling convention gave them. @stack_base addresses the
2376  * outgoing stack argument area from RBP. Return the number of emitted bytes.
2377  */
2378 static int emit_kfunc_arg_moves(const struct btf_func_model *fm, s32 stack_base, u8 **pprog)
2379 {
2380 	struct bpf_jit_arg_move moves[BPF_JIT_MAX_ARG_MOVES];
2381 	const u8 nreg = x86_arg_abi.nr_arg_regs;
2382 	u8 *prog = *pprog, *start = prog;
2383 	u32 i, n;
2384 
2385 	n = bpf_jit_plan_arg_moves(&x86_arg_abi, fm, moves);
2386 
2387 	for (i = 0; i < n; i++) {
2388 		u8 dst = moves[i].dst, src = moves[i].src, reg;
2389 		bool dst_mem = dst != BPF_JIT_ARG_TMP && dst >= nreg;
2390 		bool src_mem = src != BPF_JIT_ARG_TMP && src >= nreg;
2391 
2392 		/*
2393 		 * Take the value into a register: the one it belongs in, the
2394 		 * scratch when it is carried past its own destination, and
2395 		 * BPF_REG_AX only to pass one stack slot to another.
2396 		 */
2397 		if (src == BPF_JIT_ARG_TMP) {
2398 			reg = AUX_REG;
2399 		} else if (src_mem) {
2400 			reg = dst == BPF_JIT_ARG_TMP ? AUX_REG :
2401 			      dst_mem ? BPF_REG_AX : x86_arg_reg[dst];
2402 			emit_ldx(&prog, BPF_DW, reg, BPF_REG_FP,
2403 				 stack_base + (src - nreg) * 8);
2404 		} else {
2405 			reg = x86_arg_reg[src];
2406 		}
2407 
2408 		/* And leave it where the argument belongs. */
2409 		if (dst == BPF_JIT_ARG_TMP)
2410 			emit_mov_reg(&prog, true, AUX_REG, reg);
2411 		else if (dst_mem)
2412 			emit_stx(&prog, BPF_DW, BPF_REG_FP, reg,
2413 				 stack_base + (dst - nreg) * 8);
2414 		else if (reg != x86_arg_reg[dst])
2415 			emit_mov_reg(&prog, true, x86_arg_reg[dst], reg);
2416 	}
2417 
2418 	*pprog = prog;
2419 	return prog - start;
2420 }
2421 
2422 /*
2423  * Rebase the __arena args of a kfunc call to arena kernel addresses,
2424  * rN = kern_vm_start + (u32)rN, with R12 holding kern_vm_start. A nullable
2425  * arg preserves NULL by skipping the add, tested on the truncated value as
2426  * arena NULL is offset 0. Return the number of emitted bytes.
2427  */
2428 static int emit_kfunc_arena_args(struct bpf_prog *bpf_prog,
2429 				 const struct btf_func_model *fm, u8 **pprog)
2430 {
2431 	u8 *prog = *pprog;
2432 	u8 *start = prog;
2433 	int i, slot;
2434 
2435 	for (i = 0, slot = 0; i < fm->nr_args; i++) {
2436 		u32 arg_regs = (fm->arg_size[i] + 7) / 8;
2437 		u8 flags = fm->arg_flags[i];
2438 		u32 reg;
2439 
2440 		if (slot + arg_regs > MAX_BPF_FUNC_REG_ARGS)
2441 			break;
2442 		reg = BPF_REG_1 + slot;
2443 		slot += arg_regs;
2444 
2445 		if (!(flags & BTF_FMODEL_ARENA_ARG))
2446 			continue;
2447 		if (WARN_ON_ONCE(!bpf_prog_uses_arena_insns(bpf_prog)))
2448 			return -EINVAL;
2449 
2450 		/* mov eN, eN: truncate and clear the upper 32 bits */
2451 		emit_mov_reg(&prog, false, reg, reg);
2452 		if (flags & BTF_FMODEL_NULLABLE_ARG) {
2453 			/* test eN, eN; jz over the 3-byte add */
2454 			maybe_emit_mod(&prog, reg, reg, false);
2455 			EMIT2(0x85, add_2reg(0xC0, reg, reg));
2456 			EMIT2(X86_JE, 3);
2457 		}
2458 		/* add rN, r12 */
2459 		maybe_emit_mod(&prog, reg, X86_REG_R12, true);
2460 		EMIT2(0x01, add_2reg(0xC0, reg, X86_REG_R12));
2461 	}
2462 
2463 	*pprog = prog;
2464 	return prog - start;
2465 }
2466 
2467 /*
2468  * A strict compare against 1 or 128 is the non-strict one against 0 or
2469  * 127, a strict one against -129 or, with a signed condition, -1 the
2470  * non-strict one against -128 or 0: the compare against 0 is a test
2471  * without immediate, 127 and -128 fit into an imm8.
2472  */
2473 static void adjust_cmp_imm(u32 *op, s32 *imm)
2474 {
2475 	if (*imm == 1 || *imm == 128) {
2476 		switch (*op) {
2477 		case BPF_JLT:
2478 			*op = BPF_JLE;
2479 			break;
2480 		case BPF_JGE:
2481 			*op = BPF_JGT;
2482 			break;
2483 		case BPF_JSLT:
2484 			*op = BPF_JSLE;
2485 			break;
2486 		case BPF_JSGE:
2487 			*op = BPF_JSGT;
2488 			break;
2489 		default:
2490 			return;
2491 		}
2492 		*imm -= 1;
2493 	} else if (*imm == -1 || *imm == -129) {
2494 		switch (*op) {
2495 		case BPF_JGT:
2496 		case BPF_JLE:
2497 			/* -1 is the largest unsigned value */
2498 			if (*imm == -1)
2499 				return;
2500 			*op = *op == BPF_JGT ? BPF_JGE : BPF_JLT;
2501 			break;
2502 		case BPF_JSGT:
2503 			*op = BPF_JSGE;
2504 			break;
2505 		case BPF_JSLE:
2506 			*op = BPF_JSLT;
2507 			break;
2508 		default:
2509 			return;
2510 		}
2511 		*imm += 1;
2512 	}
2513 }
2514 
2515 /*
2516  * There is no branch for unwind_goto, only an extable entry
2517  *   { .insn = ret_addr - 1, .fixup = target - ret_addr }
2518  * where ret_addr is the return address of the call in front of it. unwind_exit
2519  * replaces the return address of its frame with bpf_unwind_target() of it.
2520  * ret_addr - 1, because what follows the call can have an entry of its own.
2521  * No insn starts there, so a fault cannot hit the entry.
2522  */
2523 static int add_unwind_exentry(struct bpf_prog *prog, u8 *image, u8 *rw_image, int *excnt,
2524 			      int ret_addr, int target)
2525 {
2526 	struct exception_table_entry *ex;
2527 	s64 delta;
2528 
2529 	if (!prog->aux->extable)
2530 		return 0;
2531 	if (*excnt >= prog->aux->num_exentries) {
2532 		pr_err("unwind extable bug\n");
2533 		return -EFAULT;
2534 	}
2535 	ex = &prog->aux->extable[(*excnt)++];
2536 	delta = image + ret_addr - 1 - (u8 *)&ex->insn;
2537 	if (!is_simm32(delta)) {
2538 		pr_err("extable->insn doesn't fit into 32-bit\n");
2539 		return -EFAULT;
2540 	}
2541 	/* switch ex to rw buffer for writes */
2542 	ex = (void *)rw_image + ((void *)ex - (void *)image);
2543 	ex->insn = delta;
2544 	ex->fixup = target - ret_addr;
2545 	ex->data = EX_TYPE_BPF;
2546 	return 0;
2547 }
2548 
2549 static u64 bpf_unwind_target(u64 ret_addr)
2550 {
2551 	const struct exception_table_entry *e = search_bpf_extables(ret_addr - 1);
2552 
2553 	/*
2554 	 * The verifier made sure that unwind_goto follows a call in a prog. When
2555 	 * the kernel called an async callback, it's exit.
2556 	 */
2557 	return e ? ret_addr + e->fixup : ret_addr;
2558 }
2559 
2560 /* unwind_exit: fix the return address of this frame. r0 and r2 are returned. */
2561 static int emit_unwind_ret_addr(u8 **pprog, u8 *ip)
2562 {
2563 	u8 *prog = *pprog, *start = prog;
2564 
2565 	EMIT2(0x50, 0x56);			/* push rax; push rsi */
2566 	EMIT4(0x48, 0x8B, 0x7D, 0x08);		/* mov rdi, [rbp + 8] */
2567 	ip += prog - start;
2568 	ip += x86_call_depth_emit_accounting(&prog, bpf_unwind_target, ip);
2569 	if (emit_call(&prog, bpf_unwind_target, ip))
2570 		return -EINVAL;
2571 	EMIT4(0x48, 0x89, 0x45, 0x08);		/* mov [rbp + 8], rax */
2572 	EMIT2(0x5E, 0x58);			/* pop rsi; pop rax */
2573 	*pprog = prog;
2574 	return 0;
2575 }
2576 
2577 static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *addrs, u8 *image,
2578 		  u8 *rw_image, int oldproglen, struct jit_context *ctx, bool jmp_padding)
2579 {
2580 	bool tail_call_reachable = bpf_prog->aux->tail_call_reachable;
2581 	struct bpf_insn *insn = bpf_prog->insnsi;
2582 	bool callee_regs_used[4] = {};
2583 	int insn_cnt = bpf_prog->len;
2584 	bool seen_exit = false;
2585 	u8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY];
2586 	void __percpu *priv_frame_ptr = NULL;
2587 	u16 out_stack_arg_cnt, outgoing_rsp;
2588 	u64 arena_vm_start = 0, user_vm_start = 0;
2589 	void __percpu *priv_stack_ptr;
2590 	int i, excnt = 0;
2591 	int ilen, proglen = 0;
2592 	u8 *ip, *prog = temp;
2593 	u32 stack_depth;
2594 	int callee_saved_size;
2595 	s32 outgoing_arg_base;
2596 	int err;
2597 
2598 	stack_depth = bpf_prog->aux->stack_depth;
2599 	out_stack_arg_cnt = bpf_out_stack_arg_cnt(env, bpf_prog);
2600 	priv_stack_ptr = bpf_prog->aux->priv_stack_ptr;
2601 	if (priv_stack_ptr) {
2602 		priv_frame_ptr = priv_stack_ptr + PRIV_STACK_GUARD_SZ + round_up(stack_depth, 8);
2603 		stack_depth = 0;
2604 	}
2605 
2606 	/*
2607 	 * Follow x86-64 calling convention for both BPF-to-BPF and
2608 	 * kfunc calls:
2609 	 *   - Arg 6 is passed in R9 register
2610 	 *   - Args 7+ are passed on the stack at [rsp]
2611 	 *
2612 	 * Incoming arg 6 is read from R9 (BPF r11+8 → MOV from R9).
2613 	 * Incoming args 7+ are read from [rbp + 16], [rbp + 24], ...
2614 	 * (BPF r11+16, r11+24, ... map directly with no offset change).
2615 	 *
2616 	 * tail_call_reachable is rejected by the verifier and priv_stack
2617 	 * is disabled by the JIT when stack args exist, so R9 is always
2618 	 * available.
2619 	 *
2620 	 * Stack layout (high to low):
2621 	 *   [rbp + 16 + ...]    incoming stack args 7+ (from caller)
2622 	 *   [rbp + 8]           return address
2623 	 *   [rbp]               saved rbp
2624 	 *   [rbp - prog_stack]  program stack
2625 	 *   [below]             callee-saved regs
2626 	 *   [below]             outgoing args 7+ (= rsp)
2627 	 */
2628 	if (bpf_prog_uses_arena_insns(bpf_prog)) {
2629 		arena_vm_start = bpf_arena_get_kern_vm_start(bpf_prog->aux->arena);
2630 		user_vm_start = bpf_arena_get_user_vm_start(bpf_prog->aux->arena);
2631 	}
2632 
2633 	detect_reg_usage(insn, insn_cnt, callee_regs_used);
2634 
2635 	emit_prologue(&prog, image, stack_depth,
2636 		      bpf_prog_was_classic(bpf_prog), tail_call_reachable,
2637 		      bpf_is_subprog(bpf_prog), bpf_prog->aux->exception_cb);
2638 
2639 	bpf_prog->aux->ksym.fp_start = prog - temp;
2640 
2641 	/* Exception callback will clobber callee regs for its own use, and
2642 	 * restore the original callee regs from main prog's stack frame.
2643 	 */
2644 	if (bpf_prog->aux->exception_boundary) {
2645 		/* We also need to save r12, which is not mapped to any BPF
2646 		 * register, as we throw after entry into the kernel, which may
2647 		 * overwrite r12.
2648 		 */
2649 		push_r12(&prog);
2650 		push_callee_regs(&prog, all_callee_regs_used);
2651 	} else {
2652 		if (arena_vm_start)
2653 			push_r12(&prog);
2654 		push_callee_regs(&prog, callee_regs_used);
2655 	}
2656 
2657 	/* Compute callee-saved register area size. */
2658 	callee_saved_size = 0;
2659 	if (bpf_prog->aux->exception_boundary || arena_vm_start)
2660 		callee_saved_size += 8; /* r12 */
2661 	if (bpf_prog->aux->exception_boundary) {
2662 		callee_saved_size += 4 * 8; /* rbx, r13, r14, r15 */
2663 	} else {
2664 		int j;
2665 
2666 		for (j = 0; j < 4; j++)
2667 			if (callee_regs_used[j])
2668 				callee_saved_size += 8;
2669 	}
2670 	/*
2671 	 * Base offset from rbp for translating BPF outgoing args 7+
2672 	 * to native offsets. BPF uses negative offsets from r11
2673 	 * (r11-8 for arg6, r11-16 for arg7, ...) while x86 uses
2674 	 * positive offsets from rsp ([rsp+0] for arg7, [rsp+8] for
2675 	 * arg8, ...). Arg 6 goes to R9 directly.
2676 	 *
2677 	 * The translation reverses direction:
2678 	 *   native_off = outgoing_arg_base - outgoing_rsp - bpf_off - 16
2679 	 *
2680 	 * Note that tail_call_reachable is guaranteed to be false when
2681 	 * stack args exist, so tcc pushes need not be accounted for.
2682 	 */
2683 	outgoing_arg_base = -(round_up(stack_depth, 8) + callee_saved_size);
2684 
2685 	/*
2686 	 * Allocate outgoing stack arg area for args 7+ only.
2687 	 * Arg 6 goes into r9 register, not on stack.
2688 	 */
2689 	outgoing_rsp = out_stack_arg_cnt > 1 ? (out_stack_arg_cnt - 1) * 8 : 0;
2690 	if (bpf_prog->aux->exception_boundary)
2691 		bpf_prog->aux->stack_arg_sp_adjust = outgoing_rsp;
2692 	emit_sub_rsp(&prog, outgoing_rsp);
2693 
2694 	if (arena_vm_start)
2695 		emit_mov_imm64(&prog, X86_REG_R12,
2696 			       arena_vm_start >> 32, (u32) arena_vm_start);
2697 
2698 	if (priv_frame_ptr)
2699 		emit_priv_frame_ptr(&prog, priv_frame_ptr);
2700 
2701 	ilen = prog - temp;
2702 	if (rw_image)
2703 		memcpy(rw_image + proglen, temp, ilen);
2704 	proglen += ilen;
2705 	addrs[0] = proglen;
2706 	prog = temp;
2707 
2708 	for (i = 1; i <= insn_cnt; i++, insn++) {
2709 		const s32 imm32 = insn->imm;
2710 		u32 dst_reg = insn->dst_reg;
2711 		u32 src_reg = insn->src_reg;
2712 		bool accesses_stack_only;
2713 		u8 b3 = 0;
2714 		u8 *start_of_ldx;
2715 		s64 jmp_offset;
2716 		s32 insn_off;
2717 		int insn_idx;
2718 		u8 jmp_cond;
2719 		u8 *func;
2720 		int nops;
2721 		u32 jmp_op = BPF_OP(insn->code);
2722 		s32 cmp_imm;
2723 
2724 		if (priv_frame_ptr) {
2725 			if (src_reg == BPF_REG_FP)
2726 				src_reg = X86_REG_R9;
2727 
2728 			if (dst_reg == BPF_REG_FP)
2729 				dst_reg = X86_REG_R9;
2730 		}
2731 
2732 		if (bpf_insn_is_indirect_target(env, bpf_prog, i - 1))
2733 			EMIT_ENDBR();
2734 
2735 		ip = image + addrs[i - 1] + (prog - temp);
2736 		insn_idx = i - 1 + bpf_prog->aux->subprog_start;
2737 		accesses_stack_only =
2738 			env ? !env->insn_aux_data[insn_idx].non_stack_access :
2739 			      false;
2740 
2741 		switch (insn->code) {
2742 			/* ALU */
2743 		case BPF_ALU | BPF_ADD | BPF_X:
2744 		case BPF_ALU | BPF_SUB | BPF_X:
2745 		case BPF_ALU | BPF_AND | BPF_X:
2746 		case BPF_ALU | BPF_OR | BPF_X:
2747 		case BPF_ALU | BPF_XOR | BPF_X:
2748 		case BPF_ALU64 | BPF_ADD | BPF_X:
2749 		case BPF_ALU64 | BPF_SUB | BPF_X:
2750 		case BPF_ALU64 | BPF_AND | BPF_X:
2751 		case BPF_ALU64 | BPF_OR | BPF_X:
2752 		case BPF_ALU64 | BPF_XOR | BPF_X:
2753 			emit_alu_reg(&prog, BPF_OP(insn->code), dst_reg, src_reg,
2754 				     BPF_CLASS(insn->code) == BPF_ALU64);
2755 			break;
2756 
2757 		case BPF_ALU64 | BPF_MOV | BPF_X:
2758 			if (insn_is_cast_user(insn)) {
2759 				/* mov dst_reg32, src_reg32 to zero extend the low half */
2760 				emit_mov_reg(&prog, false, dst_reg, src_reg);
2761 				/* mov r11, the high half of user_vm_start; or r11, dst_reg */
2762 				emit_mov_imm64(&prog, AUX_REG, user_vm_start >> 32, 0);
2763 				emit_alu_reg(&prog, BPF_OR, AUX_REG, dst_reg, true);
2764 				/* test dst_reg32, dst_reg32; a NULL pointer stays NULL */
2765 				maybe_emit_mod(&prog, dst_reg, dst_reg, false);
2766 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
2767 				/* cmovne dst_reg, r11 */
2768 				/* WARNING: Intel swapped src/dst register encoding in CMOVcc !!! */
2769 				maybe_emit_mod(&prog, AUX_REG, dst_reg, true);
2770 				EMIT3(0x0F, 0x45, add_2reg(0xC0, AUX_REG, dst_reg));
2771 				break;
2772 			} else if (insn_is_mov_percpu_addr(insn)) {
2773 				/* mov <dst>, <src> (if necessary) */
2774 				EMIT_mov(dst_reg, src_reg);
2775 #ifdef CONFIG_SMP
2776 				/* add <dst>, gs:[<off>] */
2777 				EMIT2(0x65, add_2mod(0x48, 0, dst_reg));
2778 				EMIT3(0x03, add_2reg(0x04, 0, dst_reg), 0x25);
2779 				EMIT((u32)(unsigned long)&this_cpu_off, 4);
2780 #endif
2781 				break;
2782 			}
2783 			fallthrough;
2784 		case BPF_ALU | BPF_MOV | BPF_X:
2785 			if (insn->off == 0)
2786 				emit_mov_reg(&prog,
2787 					     BPF_CLASS(insn->code) == BPF_ALU64,
2788 					     dst_reg, src_reg);
2789 			else
2790 				emit_movsx_reg(&prog, insn->off,
2791 					       BPF_CLASS(insn->code) == BPF_ALU64,
2792 					       dst_reg, src_reg);
2793 			break;
2794 
2795 			/* neg dst */
2796 		case BPF_ALU | BPF_NEG:
2797 		case BPF_ALU64 | BPF_NEG:
2798 			emit_neg(&prog, dst_reg, BPF_CLASS(insn->code) == BPF_ALU64);
2799 			break;
2800 
2801 		case BPF_ALU | BPF_ADD | BPF_K:
2802 		case BPF_ALU | BPF_SUB | BPF_K:
2803 		case BPF_ALU | BPF_AND | BPF_K:
2804 		case BPF_ALU | BPF_OR | BPF_K:
2805 		case BPF_ALU | BPF_XOR | BPF_K:
2806 		case BPF_ALU64 | BPF_ADD | BPF_K:
2807 		case BPF_ALU64 | BPF_SUB | BPF_K:
2808 		case BPF_ALU64 | BPF_AND | BPF_K:
2809 		case BPF_ALU64 | BPF_OR | BPF_K:
2810 		case BPF_ALU64 | BPF_XOR | BPF_K:
2811 			if (BPF_OP(insn->code) == BPF_AND &&
2812 			    (imm32 == 0xff || imm32 == 0xffff)) {
2813 				/* movzx dst_reg, dst_reg8/16 */
2814 				emit_movzx_reg(&prog, imm32 == 0xff ? 8 : 16,
2815 					       dst_reg, dst_reg);
2816 				break;
2817 			}
2818 			if (BPF_OP(insn->code) == BPF_XOR && imm32 == -1) {
2819 				/* not dst_reg */
2820 				maybe_emit_1mod(&prog, dst_reg,
2821 						BPF_CLASS(insn->code) == BPF_ALU64);
2822 				EMIT2(0xF7, add_1reg(0xD0, dst_reg));
2823 				break;
2824 			}
2825 
2826 			emit_alu_imm(&prog, BPF_OP(insn->code), dst_reg, imm32,
2827 				     BPF_CLASS(insn->code) == BPF_ALU64);
2828 			break;
2829 
2830 		case BPF_ALU64 | BPF_MOV | BPF_K:
2831 		case BPF_ALU | BPF_MOV | BPF_K:
2832 			emit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64,
2833 				       dst_reg, imm32);
2834 			break;
2835 
2836 		case BPF_LD | BPF_IMM | BPF_DW:
2837 			emit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm);
2838 			insn++;
2839 			i++;
2840 			break;
2841 
2842 			/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */
2843 		case BPF_ALU | BPF_MOD | BPF_X:
2844 		case BPF_ALU | BPF_DIV | BPF_X:
2845 		case BPF_ALU | BPF_MOD | BPF_K:
2846 		case BPF_ALU | BPF_DIV | BPF_K:
2847 		case BPF_ALU64 | BPF_MOD | BPF_X:
2848 		case BPF_ALU64 | BPF_DIV | BPF_X:
2849 		case BPF_ALU64 | BPF_MOD | BPF_K:
2850 		case BPF_ALU64 | BPF_DIV | BPF_K: {
2851 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
2852 
2853 			if (dst_reg != BPF_REG_0)
2854 				EMIT1(0x50); /* push rax */
2855 			if (dst_reg != BPF_REG_3)
2856 				EMIT1(0x52); /* push rdx */
2857 
2858 			/* LLVM strength-reduces the 32-bit ones itself */
2859 			if (is64 && BPF_SRC(insn->code) == BPF_K &&
2860 			    emit_div_const(&prog, insn, dst_reg))
2861 				goto div_done;
2862 
2863 			if (BPF_SRC(insn->code) == BPF_X) {
2864 				if (src_reg == BPF_REG_0 ||
2865 				    src_reg == BPF_REG_3) {
2866 					/* mov r11, src_reg */
2867 					EMIT_mov(AUX_REG, src_reg);
2868 					src_reg = AUX_REG;
2869 				}
2870 			} else {
2871 				/* mov r11, imm32 */
2872 				EMIT3_off32(0x49, 0xC7, 0xC3, imm32);
2873 				src_reg = AUX_REG;
2874 			}
2875 
2876 			if (dst_reg != BPF_REG_0)
2877 				/* mov rax, dst_reg */
2878 				emit_mov_reg(&prog, is64, BPF_REG_0, dst_reg);
2879 
2880 			if (insn->off == 0) {
2881 				/*
2882 				 * xor edx, edx
2883 				 * equivalent to 'xor rdx, rdx', but one byte less
2884 				 */
2885 				emit_mov_imm32(&prog, false, BPF_REG_3, 0);
2886 
2887 				/* div src_reg */
2888 				maybe_emit_1mod(&prog, src_reg, is64);
2889 				EMIT2(0xF7, add_1reg(0xF0, src_reg));
2890 			} else {
2891 				if (BPF_CLASS(insn->code) == BPF_ALU)
2892 					EMIT1(0x99); /* cdq */
2893 				else
2894 					EMIT2(0x48, 0x99); /* cqo */
2895 
2896 				/* idiv src_reg */
2897 				maybe_emit_1mod(&prog, src_reg, is64);
2898 				EMIT2(0xF7, add_1reg(0xF8, src_reg));
2899 			}
2900 
2901 			if (BPF_OP(insn->code) == BPF_MOD &&
2902 			    dst_reg != BPF_REG_3)
2903 				/* mov dst_reg, rdx */
2904 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_3);
2905 			else if (BPF_OP(insn->code) == BPF_DIV &&
2906 				 dst_reg != BPF_REG_0)
2907 				/* mov dst_reg, rax */
2908 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_0);
2909 div_done:
2910 			if (dst_reg != BPF_REG_3)
2911 				EMIT1(0x5A); /* pop rdx */
2912 			if (dst_reg != BPF_REG_0)
2913 				EMIT1(0x58); /* pop rax */
2914 			break;
2915 		}
2916 
2917 		case BPF_ALU | BPF_MUL | BPF_K:
2918 		case BPF_ALU64 | BPF_MUL | BPF_K:
2919 			/*
2920 			 * lea for 3, 5 and 9, which LLVM leaves as a
2921 			 * multiplication, but not for r13, which needs a
2922 			 * displacement as base and makes the lea a slow three
2923 			 * operand form on Intel.
2924 			 */
2925 			if ((imm32 == 3 || imm32 == 5 || imm32 == 9) &&
2926 			    !base_needs_disp(dst_reg)) {
2927 				/* lea dst_reg, [dst_reg + dst_reg * (imm32 - 1)] */
2928 				if (BPF_CLASS(insn->code) == BPF_ALU64)
2929 					EMIT1(add_3mod(0x48, dst_reg, dst_reg, dst_reg));
2930 				else if (is_ereg(dst_reg))
2931 					EMIT1(add_3mod(0x40, dst_reg, dst_reg, dst_reg));
2932 				EMIT1(0x8D);
2933 				emit_insn_suffix_SIB(&prog, dst_reg, dst_reg, dst_reg, 0,
2934 						     ilog2(imm32 - 1));
2935 				break;
2936 			}
2937 
2938 			maybe_emit_mod(&prog, dst_reg, dst_reg,
2939 				       BPF_CLASS(insn->code) == BPF_ALU64);
2940 
2941 			if (is_imm8(imm32))
2942 				/* imul dst_reg, dst_reg, imm8 */
2943 				EMIT3(0x6B, add_2reg(0xC0, dst_reg, dst_reg),
2944 				      imm32);
2945 			else
2946 				/* imul dst_reg, dst_reg, imm32 */
2947 				EMIT2_off32(0x69,
2948 					    add_2reg(0xC0, dst_reg, dst_reg),
2949 					    imm32);
2950 			break;
2951 
2952 		case BPF_ALU | BPF_MUL | BPF_X:
2953 		case BPF_ALU64 | BPF_MUL | BPF_X:
2954 			maybe_emit_mod(&prog, src_reg, dst_reg,
2955 				       BPF_CLASS(insn->code) == BPF_ALU64);
2956 
2957 			/* imul dst_reg, src_reg */
2958 			EMIT3(0x0F, 0xAF, add_2reg(0xC0, src_reg, dst_reg));
2959 			break;
2960 
2961 			/* Shifts */
2962 		case BPF_ALU | BPF_LSH | BPF_K:
2963 		case BPF_ALU | BPF_RSH | BPF_K:
2964 		case BPF_ALU | BPF_ARSH | BPF_K:
2965 		case BPF_ALU64 | BPF_LSH | BPF_K:
2966 		case BPF_ALU64 | BPF_RSH | BPF_K:
2967 		case BPF_ALU64 | BPF_ARSH | BPF_K:
2968 			emit_shift_imm(&prog, BPF_OP(insn->code), dst_reg,
2969 				       imm32, BPF_CLASS(insn->code) == BPF_ALU64);
2970 			break;
2971 
2972 		case BPF_ALU | BPF_LSH | BPF_X:
2973 		case BPF_ALU | BPF_RSH | BPF_X:
2974 		case BPF_ALU | BPF_ARSH | BPF_X:
2975 		case BPF_ALU64 | BPF_LSH | BPF_X:
2976 		case BPF_ALU64 | BPF_RSH | BPF_X:
2977 		case BPF_ALU64 | BPF_ARSH | BPF_X:
2978 			/*
2979 			 * BMI2 shifts take the count from any register and,
2980 			 * unlike the cl forms, are a single uop on Intel, so
2981 			 * prefer them also when the count already is in rcx.
2982 			 */
2983 			if (boot_cpu_has(X86_FEATURE_BMI2)) {
2984 				/* shrx/sarx/shlx dst_reg, dst_reg, src_reg */
2985 				bool w = (BPF_CLASS(insn->code) == BPF_ALU64);
2986 				u8 op;
2987 
2988 				switch (BPF_OP(insn->code)) {
2989 				case BPF_LSH:
2990 					op = 1; /* prefix 0x66 */
2991 					break;
2992 				case BPF_RSH:
2993 					op = 3; /* prefix 0xf2 */
2994 					break;
2995 				case BPF_ARSH:
2996 					op = 2; /* prefix 0xf3 */
2997 					break;
2998 				}
2999 
3000 				emit_shiftx(&prog, dst_reg, src_reg, w, op);
3001 
3002 				break;
3003 			}
3004 
3005 			if (src_reg != BPF_REG_4) { /* common case */
3006 				/* Check for bad case when dst_reg == rcx */
3007 				if (dst_reg == BPF_REG_4) {
3008 					/* mov r11, dst_reg */
3009 					EMIT_mov(AUX_REG, dst_reg);
3010 					dst_reg = AUX_REG;
3011 				} else {
3012 					EMIT1(0x51); /* push rcx */
3013 				}
3014 				/* mov rcx, src_reg */
3015 				EMIT_mov(BPF_REG_4, src_reg);
3016 			}
3017 
3018 			/* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */
3019 			maybe_emit_1mod(&prog, dst_reg,
3020 					BPF_CLASS(insn->code) == BPF_ALU64);
3021 
3022 			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
3023 			EMIT2(0xD3, add_1reg(b3, dst_reg));
3024 
3025 			if (src_reg != BPF_REG_4) {
3026 				if (insn->dst_reg == BPF_REG_4)
3027 					/* mov dst_reg, r11 */
3028 					EMIT_mov(insn->dst_reg, AUX_REG);
3029 				else
3030 					EMIT1(0x59); /* pop rcx */
3031 			}
3032 
3033 			break;
3034 
3035 		case BPF_ALU | BPF_END | BPF_FROM_BE:
3036 		case BPF_ALU64 | BPF_END | BPF_FROM_LE:
3037 			switch (imm32) {
3038 			case 16:
3039 				/* Emit 'bswap eax' to swap lower 4 bytes */
3040 				if (is_ereg(dst_reg))
3041 					EMIT1(0x41);
3042 				EMIT2(0x0F, add_1reg(0xC8, dst_reg));
3043 
3044 				/*
3045 				 * Emit 'shr eax, 16' to move the swapped lower
3046 				 * 2 bytes back down and zero extend
3047 				 */
3048 				emit_shift_imm(&prog, BPF_RSH, dst_reg, 16, false);
3049 				break;
3050 			case 32:
3051 				/* Emit 'bswap eax' to swap lower 4 bytes */
3052 				if (is_ereg(dst_reg))
3053 					EMIT2(0x41, 0x0F);
3054 				else
3055 					EMIT1(0x0F);
3056 				EMIT1(add_1reg(0xC8, dst_reg));
3057 				break;
3058 			case 64:
3059 				/* Emit 'bswap rax' to swap 8 bytes */
3060 				EMIT3(add_1mod(0x48, dst_reg), 0x0F,
3061 				      add_1reg(0xC8, dst_reg));
3062 				break;
3063 			}
3064 			break;
3065 
3066 		case BPF_ALU | BPF_END | BPF_FROM_LE:
3067 			switch (imm32) {
3068 			case 16:
3069 				/*
3070 				 * Emit 'movzwl eax, ax' to zero extend 16-bit
3071 				 * into 64 bit
3072 				 */
3073 				emit_movzx_reg(&prog, 16, dst_reg, dst_reg);
3074 				break;
3075 			case 32:
3076 				/* Emit 'mov eax, eax' to clear upper 32-bits */
3077 				if (is_ereg(dst_reg))
3078 					EMIT1(0x45);
3079 				EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg));
3080 				break;
3081 			case 64:
3082 				/* nop */
3083 				break;
3084 			}
3085 			break;
3086 
3087 			/* speculation barrier */
3088 		case BPF_ST | BPF_NOSPEC:
3089 			EMIT_LFENCE();
3090 			break;
3091 
3092 		case BPF_ST | BPF_MEM | BPF_B:
3093 		case BPF_ST | BPF_MEM | BPF_H:
3094 		case BPF_ST | BPF_MEM | BPF_W:
3095 		case BPF_ST | BPF_MEM | BPF_DW:
3096 			if (dst_reg == BPF_REG_PARAMS && insn->off == -8) {
3097 				/* Arg 6: store immediate in r9 register */
3098 				emit_mov_imm64(&prog, X86_REG_R9, imm32 >> 31,
3099 					       imm32);
3100 				break;
3101 			}
3102 			insn_off = insn->off;
3103 			if (dst_reg == BPF_REG_PARAMS) {
3104 				/*
3105 				 * Args 7+: reverse BPF negative offsets to
3106 				 * x86 positive rsp offsets.
3107 				 * BPF off=-16 → [rsp+0], off=-24 → [rsp+8], ...
3108 				 */
3109 				insn_off = outgoing_arg_base - outgoing_rsp -
3110 					   insn_off - 16;
3111 				dst_reg = BPF_REG_FP;
3112 			}
3113 			if (!accesses_stack_only) {
3114 				err = emit_kasan_check(env, &prog, dst_reg,
3115 						       insn_off,
3116 						       BPF_SIZE(insn->code), ip,
3117 						       true);
3118 				if (err)
3119 					return err;
3120 			}
3121 
3122 			emit_st(&prog, insn, dst_reg, insn_off);
3123 			break;
3124 
3125 			/* STX: *(u8*)(dst_reg + off) = src_reg */
3126 		case BPF_STX | BPF_MEM | BPF_B:
3127 		case BPF_STX | BPF_MEM | BPF_H:
3128 		case BPF_STX | BPF_MEM | BPF_W:
3129 		case BPF_STX | BPF_MEM | BPF_DW:
3130 			if (dst_reg == BPF_REG_PARAMS && insn->off == -8) {
3131 				/* Arg 6: store register value in r9 */
3132 				EMIT_mov(X86_REG_R9, src_reg);
3133 				break;
3134 			}
3135 			insn_off = insn->off;
3136 			if (dst_reg == BPF_REG_PARAMS) {
3137 				insn_off = outgoing_arg_base - outgoing_rsp - insn_off - 16;
3138 				dst_reg = BPF_REG_FP;
3139 			}
3140 			if (!accesses_stack_only) {
3141 				err = emit_kasan_check(env, &prog, dst_reg,
3142 						       insn_off,
3143 						       BPF_SIZE(insn->code), ip,
3144 						       true);
3145 				if (err)
3146 					return err;
3147 			}
3148 			emit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
3149 			break;
3150 
3151 		case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
3152 		case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
3153 		case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
3154 		case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
3155 			start_of_ldx = prog;
3156 			emit_st_r12(&prog, BPF_SIZE(insn->code), dst_reg, insn->off, insn->imm);
3157 			goto populate_extable;
3158 
3159 			/* LDX: dst_reg = *(u8*)(src_reg + r12 + off) */
3160 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_B:
3161 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
3162 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
3163 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
3164 		case BPF_LDX | BPF_PROBE_MEM32SX | BPF_B:
3165 		case BPF_LDX | BPF_PROBE_MEM32SX | BPF_H:
3166 		case BPF_LDX | BPF_PROBE_MEM32SX | BPF_W:
3167 		case BPF_STX | BPF_PROBE_MEM32 | BPF_B:
3168 		case BPF_STX | BPF_PROBE_MEM32 | BPF_H:
3169 		case BPF_STX | BPF_PROBE_MEM32 | BPF_W:
3170 		case BPF_STX | BPF_PROBE_MEM32 | BPF_DW:
3171 			start_of_ldx = prog;
3172 			if (BPF_CLASS(insn->code) == BPF_LDX) {
3173 				if (BPF_MODE(insn->code) == BPF_PROBE_MEM32SX)
3174 					emit_ldsx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
3175 				else
3176 					emit_ldx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
3177 			} else {
3178 				emit_stx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
3179 			}
3180 populate_extable:
3181 			{
3182 				u32 arena_reg, fixup_reg;
3183 				bool is_write;
3184 
3185 				/*
3186 				 * src_reg/dst_reg holds the address in the arena region with upper
3187 				 * 32-bits being zero because of a preceding addr_space_cast(r<n>,
3188 				 * 0x0, 0x1) instruction. This address is adjusted with the addition
3189 				 * of arena_vm_start (see the implementation of BPF_PROBE_MEM32 and
3190 				 * BPF_PROBE_ATOMIC) before being used for the memory access. Pass
3191 				 * the reg holding the unmodified 32-bit address to
3192 				 * ex_handler_bpf().
3193 				 *
3194 				 * A load-acquire is of BPF_STX class, but reads from src_reg
3195 				 * into dst_reg like a BPF_LDX does, hence it must not be
3196 				 * treated as a store here.
3197 				 */
3198 				if (BPF_CLASS(insn->code) == BPF_LDX ||
3199 				    bpf_atomic_is_load_acq(insn)) {
3200 					arena_reg = reg2pt_regs[src_reg];
3201 					fixup_reg = reg2pt_regs[dst_reg];
3202 					is_write = false;
3203 				} else {
3204 					/*
3205 					 * A store has no destination register to clear,
3206 					 * except for a read-modify-write with BPF_FETCH,
3207 					 * which also reads the old value into src_reg, or
3208 					 * into r0 for a BPF_CMPXCHG. Either way the access
3209 					 * is still reported as a write.
3210 					 */
3211 					int load_reg = bpf_atomic_load_reg(insn);
3212 
3213 					arena_reg = reg2pt_regs[dst_reg];
3214 					fixup_reg = load_reg < 0 ? DONT_CLEAR :
3215 						    reg2pt_regs[load_reg];
3216 					is_write = true;
3217 				}
3218 
3219 				err = emit_arena_exentry(bpf_prog, image, rw_image, &excnt,
3220 							 image + proglen + (start_of_ldx - temp),
3221 							 prog - start_of_ldx, fixup_reg,
3222 							 arena_reg, is_write, insn->off);
3223 				if (err)
3224 					return err;
3225 			}
3226 			break;
3227 
3228 			/* LDX: dst_reg = *(u8*)(src_reg + off) */
3229 		case BPF_LDX | BPF_MEM | BPF_B:
3230 		case BPF_LDX | BPF_PROBE_MEM | BPF_B:
3231 		case BPF_LDX | BPF_MEM | BPF_H:
3232 		case BPF_LDX | BPF_PROBE_MEM | BPF_H:
3233 		case BPF_LDX | BPF_MEM | BPF_W:
3234 		case BPF_LDX | BPF_PROBE_MEM | BPF_W:
3235 		case BPF_LDX | BPF_MEM | BPF_DW:
3236 		case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
3237 			/* LDXS: dst_reg = *(s8*)(src_reg + off) */
3238 		case BPF_LDX | BPF_MEMSX | BPF_B:
3239 		case BPF_LDX | BPF_MEMSX | BPF_H:
3240 		case BPF_LDX | BPF_MEMSX | BPF_W:
3241 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
3242 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
3243 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
3244 			insn_off = insn->off;
3245 			if (src_reg == BPF_REG_PARAMS) {
3246 				if (insn_off == 8) {
3247 					/* Incoming arg 6: read from r9 */
3248 					EMIT_mov(dst_reg, X86_REG_R9);
3249 					break;
3250 				}
3251 				src_reg = BPF_REG_FP;
3252 				/*
3253 				 * Incoming args 7+: native_off == bpf_off
3254 				 * (r11+16 → [rbp+16], r11+24 → [rbp+24], ...)
3255 				 * No offset adjustment needed.
3256 				 */
3257 			}
3258 
3259 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
3260 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
3261 				/* Conservatively check that src_reg + insn->off is a kernel address:
3262 				 *   src_reg + insn->off > TASK_SIZE_MAX + PAGE_SIZE
3263 				 *   and
3264 				 *   src_reg + insn->off < VSYSCALL_ADDR
3265 				 *
3266 				 * The check is done on src_reg + insn->off - VSYSCALL_ADDR
3267 				 * against the next power of two above the limit. Addresses
3268 				 * between the limit and that power of two are non-canonical
3269 				 * and would fault anyway, so they get zeroed a bit earlier.
3270 				 */
3271 
3272 				u64 limit = TASK_SIZE_MAX + PAGE_SIZE - VSYSCALL_ADDR;
3273 				u8 *end_of_jmp;
3274 
3275 				/*
3276 				 * lea r11, [src_reg + insn->off - VSYSCALL_ADDR]
3277 				 *
3278 				 * VSYSCALL_ADDR is a small negative number, so the
3279 				 * whole offset fits into the 32-bit displacement.
3280 				 */
3281 				BUILD_BUG_ON((long)(s32)VSYSCALL_ADDR != (long)VSYSCALL_ADDR);
3282 				EMIT2(add_2mod(0x48, src_reg, AUX_REG), 0x8D);
3283 				emit_insn_suffix(&prog, src_reg, AUX_REG,
3284 						 insn->off - (s32)VSYSCALL_ADDR);
3285 
3286 				/* shr r11, fls64(limit) */
3287 				emit_shift_imm(&prog, BPF_RSH, AUX_REG, fls64(limit), true);
3288 
3289 				/* if not zero, goto load */
3290 				EMIT2(X86_JNE, 0);
3291 				end_of_jmp = prog;
3292 
3293 				/* xor dst_reg, dst_reg */
3294 				emit_mov_imm32(&prog, false, dst_reg, 0);
3295 				/* jmp byte_after_ldx */
3296 				EMIT2(0xEB, 0);
3297 
3298 				/* populate jmp_offset for JNE above to jump to start_of_ldx */
3299 				start_of_ldx = prog;
3300 				end_of_jmp[-1] = start_of_ldx - end_of_jmp;
3301 			} else if (!accesses_stack_only) {
3302 				err = emit_kasan_check(env, &prog, src_reg,
3303 						       insn_off,
3304 						       BPF_SIZE(insn->code), ip,
3305 						       false);
3306 				if (err)
3307 					return err;
3308 			}
3309 			if (BPF_MODE(insn->code) == BPF_PROBE_MEMSX ||
3310 			    BPF_MODE(insn->code) == BPF_MEMSX)
3311 				emit_ldsx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
3312 			else
3313 				emit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
3314 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
3315 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
3316 				struct exception_table_entry *ex;
3317 				u8 *_insn = image + proglen + (start_of_ldx - temp);
3318 				s64 delta;
3319 
3320 				/* populate jmp_offset for JMP above */
3321 				start_of_ldx[-1] = prog - start_of_ldx;
3322 
3323 				if (!bpf_prog->aux->extable)
3324 					break;
3325 
3326 				if (excnt >= bpf_prog->aux->num_exentries) {
3327 					pr_err("ex gen bug\n");
3328 					return -EFAULT;
3329 				}
3330 				ex = &bpf_prog->aux->extable[excnt++];
3331 
3332 				delta = _insn - (u8 *)&ex->insn;
3333 				if (!is_simm32(delta)) {
3334 					pr_err("extable->insn doesn't fit into 32-bit\n");
3335 					return -EFAULT;
3336 				}
3337 				/* switch ex to rw buffer for writes */
3338 				ex = (void *)rw_image + ((void *)ex - (void *)image);
3339 
3340 				ex->insn = delta;
3341 
3342 				ex->data = EX_TYPE_BPF;
3343 
3344 				if (dst_reg > BPF_REG_9) {
3345 					pr_err("verifier error\n");
3346 					return -EFAULT;
3347 				}
3348 				/*
3349 				 * Compute size of x86 insn and its target dest x86 register.
3350 				 * ex_handler_bpf() will use lower 8 bits to adjust
3351 				 * pt_regs->ip to jump over this x86 instruction
3352 				 * and upper bits to figure out which pt_regs to zero out.
3353 				 * End result: x86 insn "mov rbx, qword ptr [rax+0x14]"
3354 				 * of 4 bytes will be ignored and rbx will be zero inited.
3355 				 */
3356 				ex->fixup = FIELD_PREP(FIXUP_INSN_LEN_MASK, prog - start_of_ldx) |
3357 					    FIELD_PREP(FIXUP_REG_MASK, reg2pt_regs[dst_reg]);
3358 			}
3359 			break;
3360 
3361 		case BPF_STX | BPF_ATOMIC | BPF_B:
3362 		case BPF_STX | BPF_ATOMIC | BPF_H:
3363 			if (!bpf_atomic_is_load_store(insn)) {
3364 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
3365 				return -EFAULT;
3366 			}
3367 			fallthrough;
3368 		case BPF_STX | BPF_ATOMIC | BPF_W:
3369 		case BPF_STX | BPF_ATOMIC | BPF_DW: {
3370 			u32 real_src_reg = src_reg;
3371 			u32 real_dst_reg = dst_reg;
3372 			bool is_atomic_fetch = is_atomic_fetch_op(insn);
3373 			u8 *old_prog;
3374 
3375 			if (is_atomic_fetch) {
3376 				/* Will need RAX as a CMPXCHG operand so save R0 */
3377 				old_prog = prog;
3378 				emit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0);
3379 				if (src_reg == BPF_REG_0)
3380 					real_src_reg = BPF_REG_AX;
3381 				if (dst_reg == BPF_REG_0)
3382 					real_dst_reg = BPF_REG_AX;
3383 				ip += (prog - old_prog);
3384 			}
3385 			if (!bpf_atomic_is_load_store(insn)) {
3386 				if (!accesses_stack_only) {
3387 					err = emit_kasan_check(
3388 						env, &prog, real_dst_reg,
3389 						insn->off, BPF_SIZE(insn->code),
3390 						ip, true);
3391 					if (err)
3392 						return err;
3393 				}
3394 			}
3395 			if (is_atomic_fetch) {
3396 				err = emit_atomic_fetch_rmw(&prog, insn, real_dst_reg,
3397 							    real_src_reg, -1, false,
3398 							    NULL, NULL);
3399 				if (err)
3400 					return err;
3401 				break;
3402 			}
3403 
3404 			if (bpf_atomic_is_load_store(insn))
3405 				err = emit_atomic_ld_st(env, &prog, insn, ip,
3406 							dst_reg, src_reg,
3407 							accesses_stack_only);
3408 			else
3409 				err = emit_atomic_rmw(&prog, insn->imm, dst_reg, src_reg,
3410 						      insn->off, BPF_SIZE(insn->code));
3411 			if (err)
3412 				return err;
3413 			break;
3414 		}
3415 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_B:
3416 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_H:
3417 			if (!bpf_atomic_is_load_store(insn)) {
3418 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
3419 				return -EFAULT;
3420 			}
3421 			fallthrough;
3422 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_W:
3423 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
3424 			if (is_atomic_fetch_op(insn)) {
3425 				u32 real_src_reg = src_reg, real_dst_reg = dst_reg;
3426 				/*
3427 				 * An access through a number has its address in
3428 				 * BPF_REG_AX (see arena_scalar_access()), so R0 is
3429 				 * saved on the stack instead, as div and mod do.
3430 				 */
3431 				bool r0_on_stack = dst_reg == BPF_REG_AX;
3432 				u8 *fault[2], *resume;
3433 				int j;
3434 
3435 				/* Will need RAX as a CMPXCHG operand so save R0 */
3436 				if (r0_on_stack) {
3437 					EMIT1(0x50); /* push rax */
3438 				} else {
3439 					emit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0);
3440 					if (src_reg == BPF_REG_0)
3441 						real_src_reg = BPF_REG_AX;
3442 					if (dst_reg == BPF_REG_0)
3443 						real_dst_reg = BPF_REG_AX;
3444 				}
3445 
3446 				err = emit_atomic_fetch_rmw(&prog, insn, real_dst_reg,
3447 							    real_src_reg, X86_REG_R12,
3448 							    r0_on_stack, fault, &resume);
3449 				if (err)
3450 					return err;
3451 
3452 				/*
3453 				 * The page may be unmapped between the load and the
3454 				 * CMPXCHG, so both need an entry. Both report a write,
3455 				 * since the BPF insn is a read-modify-write.
3456 				 */
3457 				for (j = 0; j < 2; j++) {
3458 					err = emit_arena_exentry(bpf_prog, image, rw_image,
3459 								 &excnt,
3460 								 image + proglen +
3461 									 (fault[j] - temp),
3462 								 resume - fault[j],
3463 								 reg2pt_regs[real_src_reg],
3464 								 reg2pt_regs[real_dst_reg],
3465 								 true, insn->off);
3466 					if (err)
3467 						return err;
3468 				}
3469 				break;
3470 			}
3471 			start_of_ldx = prog;
3472 
3473 			if (bpf_atomic_is_load_store(insn))
3474 				err = emit_atomic_ld_st_index(&prog, insn->imm,
3475 							      BPF_SIZE(insn->code), dst_reg,
3476 							      src_reg, X86_REG_R12, insn->off);
3477 			else
3478 				err = emit_atomic_rmw_index(&prog, insn->imm, BPF_SIZE(insn->code),
3479 							    dst_reg, src_reg, X86_REG_R12,
3480 							    insn->off);
3481 			if (err)
3482 				return err;
3483 			goto populate_extable;
3484 
3485 			/* call */
3486 		case BPF_JMP | BPF_CALL: {
3487 			const struct btf_func_model *fm = NULL;
3488 
3489 			func = (u8 *) __bpf_call_base + imm32;
3490 			if (src_reg == BPF_PSEUDO_CALL && tail_call_reachable) {
3491 				u8 *tcc_load = prog;
3492 
3493 				LOAD_TAIL_CALL_CNT_PTR(stack_depth);
3494 				ip += prog - tcc_load;
3495 			}
3496 			if (!imm32)
3497 				return -EINVAL;
3498 			if (src_reg == BPF_PSEUDO_KFUNC_CALL) {
3499 				fm = bpf_jit_find_kfunc_model(bpf_prog, insn);
3500 				if (!fm)
3501 					return -EINVAL;
3502 				err = emit_kfunc_arena_args(bpf_prog, fm, &prog);
3503 				if (err < 0)
3504 					return err;
3505 				ip += err;
3506 				ip += emit_kfunc_arg_moves(fm, outgoing_arg_base -
3507 							   outgoing_rsp, &prog);
3508 			}
3509 			if (func == (u8 *)arch_bpf_timed_may_goto) {
3510 				u32 fp = priv_frame_ptr ? X86_REG_R9 : BPF_REG_FP;
3511 
3512 				/*
3513 				 * AX has the offset of count and timestamp
3514 				 * in the stack. Turn it into a pointer.
3515 				 * add r10, rbp or add r10, r9
3516 				 */
3517 				maybe_emit_mod(&prog, BPF_REG_AX, fp, true);
3518 				EMIT2(0x01, add_2reg(0xC0, BPF_REG_AX, fp));
3519 				ip += 3;
3520 			}
3521 			if (priv_frame_ptr) {
3522 				push_r9(&prog);
3523 				ip += 2;
3524 			}
3525 			ip += x86_call_depth_emit_accounting(&prog, func, ip);
3526 			if (emit_call(&prog, func, ip))
3527 				return -EINVAL;
3528 			if (priv_frame_ptr)
3529 				pop_r9(&prog);
3530 			/*
3531 			 * A kfunc returning more than 8 bytes hands the second
3532 			 * half back in RDX (the native ABI's second return reg),
3533 			 * but BPF expects it in R0:R2. BPF R0 is RAX (no move
3534 			 * needed), while BPF R2 is RSI, so copy RDX into RSI.
3535 			 */
3536 			if (fm && fm->ret_size > 8)
3537 				emit_mov_reg(&prog, true, BPF_REG_2, BPF_REG_3);
3538 			break;
3539 		}
3540 
3541 			/* callx: call of a bpf subprog whose address is in dst_reg */
3542 		case BPF_JMP | BPF_CALL | BPF_X:
3543 			/*
3544 			 * The verifier makes sure that callees of callx are
3545 			 * not tail call reachable, hence unlike a direct call
3546 			 * of a subprog there is no need to pass
3547 			 * tail_call_cnt_ptr in rax.
3548 			 */
3549 			if (priv_frame_ptr) {
3550 				push_r9(&prog);
3551 				ip += 2;
3552 			}
3553 			if (emit_indirect_call(&prog, insn->dst_reg, ip))
3554 				return -EINVAL;
3555 			if (priv_frame_ptr)
3556 				pop_r9(&prog);
3557 			break;
3558 
3559 			/* unwind_goto. The verifier expanded may_goto. */
3560 		case BPF_JMP | BPF_JCOND:
3561 			if (!priv_frame_ptr) {
3562 				err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
3563 							 addrs[i - 1], addrs[i + insn->off]);
3564 				if (err)
3565 					return err;
3566 				break;
3567 			}
3568 			/*
3569 			 * 'pop r9' after the call has to be done on the way to
3570 			 * the pad too:
3571 			 *   call foo
3572 			 *   pop r9      <- exit returns here
3573 			 *   jmp 1f
3574 			 *   pop r9      <- unwind_exit returns here
3575 			 *   jmp pad
3576 			 * 1:
3577 			 */
3578 			err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
3579 						 addrs[i - 1] - 2, addrs[i - 1] + 2);
3580 			if (err)
3581 				return err;
3582 			EMIT2(0xEB, 7);
3583 			pop_r9(&prog);
3584 			EMIT1_off32(0xE9, addrs[i + insn->off] - (addrs[i - 1] + 9));
3585 			break;
3586 
3587 		case BPF_JMP | BPF_TAIL_CALL:
3588 			if (imm32)
3589 				emit_bpf_tail_call_direct(bpf_prog,
3590 							  &bpf_prog->aux->poke_tab[imm32 - 1],
3591 							  &prog,
3592 							  ip,
3593 							  callee_regs_used,
3594 							  stack_depth,
3595 							  ctx);
3596 			else
3597 				emit_bpf_tail_call_indirect(bpf_prog,
3598 							    &prog,
3599 							    callee_regs_used,
3600 							    stack_depth,
3601 							    ip,
3602 							    ctx);
3603 			break;
3604 
3605 			/* cond jump */
3606 		case BPF_JMP | BPF_JEQ | BPF_X:
3607 		case BPF_JMP | BPF_JNE | BPF_X:
3608 		case BPF_JMP | BPF_JGT | BPF_X:
3609 		case BPF_JMP | BPF_JLT | BPF_X:
3610 		case BPF_JMP | BPF_JGE | BPF_X:
3611 		case BPF_JMP | BPF_JLE | BPF_X:
3612 		case BPF_JMP | BPF_JSGT | BPF_X:
3613 		case BPF_JMP | BPF_JSLT | BPF_X:
3614 		case BPF_JMP | BPF_JSGE | BPF_X:
3615 		case BPF_JMP | BPF_JSLE | BPF_X:
3616 		case BPF_JMP32 | BPF_JEQ | BPF_X:
3617 		case BPF_JMP32 | BPF_JNE | BPF_X:
3618 		case BPF_JMP32 | BPF_JGT | BPF_X:
3619 		case BPF_JMP32 | BPF_JLT | BPF_X:
3620 		case BPF_JMP32 | BPF_JGE | BPF_X:
3621 		case BPF_JMP32 | BPF_JLE | BPF_X:
3622 		case BPF_JMP32 | BPF_JSGT | BPF_X:
3623 		case BPF_JMP32 | BPF_JSLT | BPF_X:
3624 		case BPF_JMP32 | BPF_JSGE | BPF_X:
3625 		case BPF_JMP32 | BPF_JSLE | BPF_X:
3626 			/* cmp dst_reg, src_reg */
3627 			maybe_emit_mod(&prog, dst_reg, src_reg,
3628 				       BPF_CLASS(insn->code) == BPF_JMP);
3629 			EMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg));
3630 			goto emit_cond_jmp;
3631 
3632 		case BPF_JMP | BPF_JSET | BPF_X:
3633 		case BPF_JMP32 | BPF_JSET | BPF_X:
3634 			/* test dst_reg, src_reg */
3635 			maybe_emit_mod(&prog, dst_reg, src_reg,
3636 				       BPF_CLASS(insn->code) == BPF_JMP);
3637 			EMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg));
3638 			goto emit_cond_jmp;
3639 
3640 		case BPF_JMP | BPF_JSET | BPF_K:
3641 		case BPF_JMP32 | BPF_JSET | BPF_K:
3642 			if ((u32)imm32 <= U8_MAX) {
3643 				/*
3644 				 * test dst_reg8, imm8: with the upper bits of the
3645 				 * mask clear the result only depends on the low byte.
3646 				 */
3647 				if (is_ereg_8l(dst_reg))
3648 					EMIT1(add_1mod(0x40, dst_reg));
3649 				if (is_axreg(dst_reg))
3650 					EMIT2(0xA8, imm32);
3651 				else
3652 					EMIT3(0xF6, add_1reg(0xC0, dst_reg), imm32);
3653 				goto emit_cond_jmp;
3654 			}
3655 			/* test dst_reg, imm32 */
3656 			maybe_emit_1mod(&prog, dst_reg,
3657 					BPF_CLASS(insn->code) == BPF_JMP);
3658 			if (is_axreg(dst_reg))
3659 				EMIT1_off32(0xA9, imm32);
3660 			else
3661 				EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);
3662 			goto emit_cond_jmp;
3663 
3664 		case BPF_JMP | BPF_JEQ | BPF_K:
3665 		case BPF_JMP | BPF_JNE | BPF_K:
3666 		case BPF_JMP | BPF_JGT | BPF_K:
3667 		case BPF_JMP | BPF_JLT | BPF_K:
3668 		case BPF_JMP | BPF_JGE | BPF_K:
3669 		case BPF_JMP | BPF_JLE | BPF_K:
3670 		case BPF_JMP | BPF_JSGT | BPF_K:
3671 		case BPF_JMP | BPF_JSLT | BPF_K:
3672 		case BPF_JMP | BPF_JSGE | BPF_K:
3673 		case BPF_JMP | BPF_JSLE | BPF_K:
3674 		case BPF_JMP32 | BPF_JEQ | BPF_K:
3675 		case BPF_JMP32 | BPF_JNE | BPF_K:
3676 		case BPF_JMP32 | BPF_JGT | BPF_K:
3677 		case BPF_JMP32 | BPF_JLT | BPF_K:
3678 		case BPF_JMP32 | BPF_JGE | BPF_K:
3679 		case BPF_JMP32 | BPF_JLE | BPF_K:
3680 		case BPF_JMP32 | BPF_JSGT | BPF_K:
3681 		case BPF_JMP32 | BPF_JSLT | BPF_K:
3682 		case BPF_JMP32 | BPF_JSGE | BPF_K:
3683 		case BPF_JMP32 | BPF_JSLE | BPF_K:
3684 			cmp_imm = imm32;
3685 			adjust_cmp_imm(&jmp_op, &cmp_imm);
3686 
3687 			/* test dst_reg, dst_reg to save one extra byte */
3688 			if (cmp_imm == 0) {
3689 				maybe_emit_mod(&prog, dst_reg, dst_reg,
3690 					       BPF_CLASS(insn->code) == BPF_JMP);
3691 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
3692 				goto emit_cond_jmp;
3693 			}
3694 
3695 			/* cmp dst_reg, imm8/32 */
3696 			maybe_emit_1mod(&prog, dst_reg,
3697 					BPF_CLASS(insn->code) == BPF_JMP);
3698 
3699 			if (is_imm8(cmp_imm))
3700 				EMIT3(0x83, add_1reg(0xF8, dst_reg), cmp_imm);
3701 			else if (is_axreg(dst_reg))
3702 				EMIT1_off32(0x3D, cmp_imm);
3703 			else
3704 				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), cmp_imm);
3705 
3706 emit_cond_jmp:		/* Convert BPF opcode to x86 */
3707 			switch (jmp_op) {
3708 			case BPF_JEQ:
3709 				jmp_cond = X86_JE;
3710 				break;
3711 			case BPF_JSET:
3712 			case BPF_JNE:
3713 				jmp_cond = X86_JNE;
3714 				break;
3715 			case BPF_JGT:
3716 				/* GT is unsigned '>', JA in x86 */
3717 				jmp_cond = X86_JA;
3718 				break;
3719 			case BPF_JLT:
3720 				/* LT is unsigned '<', JB in x86 */
3721 				jmp_cond = X86_JB;
3722 				break;
3723 			case BPF_JGE:
3724 				/* GE is unsigned '>=', JAE in x86 */
3725 				jmp_cond = X86_JAE;
3726 				break;
3727 			case BPF_JLE:
3728 				/* LE is unsigned '<=', JBE in x86 */
3729 				jmp_cond = X86_JBE;
3730 				break;
3731 			case BPF_JSGT:
3732 				/* Signed '>', GT in x86 */
3733 				jmp_cond = X86_JG;
3734 				break;
3735 			case BPF_JSLT:
3736 				/* Signed '<', LT in x86 */
3737 				jmp_cond = X86_JL;
3738 				break;
3739 			case BPF_JSGE:
3740 				/* Signed '>=', GE in x86 */
3741 				jmp_cond = X86_JGE;
3742 				break;
3743 			case BPF_JSLE:
3744 				/* Signed '<=', LE in x86 */
3745 				jmp_cond = X86_JLE;
3746 				break;
3747 			default: /* to silence GCC warning */
3748 				return -EFAULT;
3749 			}
3750 			jmp_offset = addrs[i + insn->off] - addrs[i];
3751 			if (is_imm8_jmp_offset(jmp_offset)) {
3752 				if (jmp_padding) {
3753 					/* To keep the jmp_offset valid, the extra bytes are
3754 					 * padded before the jump insn, so we subtract the
3755 					 * 2 bytes of jmp_cond insn from INSN_SZ_DIFF.
3756 					 *
3757 					 * If the previous pass already emits an imm8
3758 					 * jmp_cond, then this BPF insn won't shrink, so
3759 					 * "nops" is 0.
3760 					 *
3761 					 * On the other hand, if the previous pass emits an
3762 					 * imm32 jmp_cond, the extra 4 bytes(*) is padded to
3763 					 * keep the image from shrinking further.
3764 					 *
3765 					 * (*) imm32 jmp_cond is 6 bytes, and imm8 jmp_cond
3766 					 *     is 2 bytes, so the size difference is 4 bytes.
3767 					 */
3768 					nops = INSN_SZ_DIFF - 2;
3769 					if (nops != 0 && nops != 4) {
3770 						pr_err("unexpected jmp_cond padding: %d bytes\n",
3771 						       nops);
3772 						return -EFAULT;
3773 					}
3774 					emit_nops(&prog, nops);
3775 				}
3776 				EMIT2(jmp_cond, jmp_offset);
3777 			} else if (is_simm32(jmp_offset)) {
3778 				EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset);
3779 			} else {
3780 				pr_err("cond_jmp gen bug %llx\n", jmp_offset);
3781 				return -EFAULT;
3782 			}
3783 
3784 			break;
3785 
3786 		case BPF_JMP | BPF_JA | BPF_X:
3787 			emit_indirect_jump(&prog, insn->dst_reg, ip);
3788 			break;
3789 		case BPF_JMP | BPF_JA:
3790 		case BPF_JMP32 | BPF_JA:
3791 			if (BPF_CLASS(insn->code) == BPF_JMP) {
3792 				if (insn->off == -1)
3793 					/* -1 jmp instructions will always jump
3794 					 * backwards two bytes. Explicitly handling
3795 					 * this case avoids wasting too many passes
3796 					 * when there are long sequences of replaced
3797 					 * dead code.
3798 					 */
3799 					jmp_offset = -2;
3800 				else
3801 					jmp_offset = addrs[i + insn->off] - addrs[i];
3802 			} else {
3803 				if (insn->imm == -1)
3804 					jmp_offset = -2;
3805 				else
3806 					jmp_offset = addrs[i + insn->imm] - addrs[i];
3807 			}
3808 
3809 			if (!jmp_offset) {
3810 				/*
3811 				 * If jmp_padding is enabled, the extra nops will
3812 				 * be inserted. Otherwise, optimize out nop jumps.
3813 				 */
3814 				if (jmp_padding) {
3815 					/* There are 3 possible conditions.
3816 					 * (1) This BPF_JA is already optimized out in
3817 					 *     the previous run, so there is no need
3818 					 *     to pad any extra byte (0 byte).
3819 					 * (2) The previous pass emits an imm8 jmp,
3820 					 *     so we pad 2 bytes to match the previous
3821 					 *     insn size.
3822 					 * (3) Similarly, the previous pass emits an
3823 					 *     imm32 jmp, and 5 bytes is padded.
3824 					 */
3825 					nops = INSN_SZ_DIFF;
3826 					if (nops != 0 && nops != 2 && nops != 5) {
3827 						pr_err("unexpected nop jump padding: %d bytes\n",
3828 						       nops);
3829 						return -EFAULT;
3830 					}
3831 					emit_nops(&prog, nops);
3832 				}
3833 				break;
3834 			}
3835 emit_jmp:
3836 			if (is_imm8_jmp_offset(jmp_offset)) {
3837 				if (jmp_padding) {
3838 					/* To avoid breaking jmp_offset, the extra bytes
3839 					 * are padded before the actual jmp insn, so
3840 					 * 2 bytes is subtracted from INSN_SZ_DIFF.
3841 					 *
3842 					 * If the previous pass already emits an imm8
3843 					 * jmp, there is nothing to pad (0 byte).
3844 					 *
3845 					 * If it emits an imm32 jmp (5 bytes) previously
3846 					 * and now an imm8 jmp (2 bytes), then we pad
3847 					 * (5 - 2 = 3) bytes to stop the image from
3848 					 * shrinking further.
3849 					 */
3850 					nops = INSN_SZ_DIFF - 2;
3851 					if (nops != 0 && nops != 3) {
3852 						pr_err("unexpected jump padding: %d bytes\n",
3853 						       nops);
3854 						return -EFAULT;
3855 					}
3856 					emit_nops(&prog, INSN_SZ_DIFF - 2);
3857 				}
3858 				EMIT2(0xEB, jmp_offset);
3859 			} else if (is_simm32(jmp_offset)) {
3860 				EMIT1_off32(0xE9, jmp_offset);
3861 			} else {
3862 				pr_err("jmp gen bug %llx\n", jmp_offset);
3863 				return -EFAULT;
3864 			}
3865 			break;
3866 
3867 		case BPF_JMP | BPF_EXIT:
3868 			if (src_reg == BPF_UNWIND_EXIT && bpf_prog_can_unwind(bpf_prog) &&
3869 			    emit_unwind_ret_addr(&prog, ip))
3870 				return -EINVAL;
3871 			if (seen_exit) {
3872 				jmp_offset = ctx->cleanup_addr - addrs[i];
3873 				goto emit_jmp;
3874 			}
3875 			seen_exit = true;
3876 			/* Update cleanup_addr */
3877 			ctx->cleanup_addr = proglen + (prog - temp);
3878 			if (bpf_prog_was_classic(bpf_prog) &&
3879 			    !ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN)) {
3880 				if (emit_spectre_bhb_barrier(&prog, ip, bpf_prog))
3881 					return -EINVAL;
3882 			}
3883 			/* Deallocate outgoing args 7+ area. */
3884 			emit_add_rsp(&prog, outgoing_rsp);
3885 			if (bpf_prog->aux->exception_boundary) {
3886 				pop_callee_regs(&prog, all_callee_regs_used);
3887 				pop_r12(&prog);
3888 			} else {
3889 				pop_callee_regs(&prog, callee_regs_used);
3890 				if (arena_vm_start)
3891 					pop_r12(&prog);
3892 			}
3893 			EMIT1(0xC9);         /* leave */
3894 			bpf_prog->aux->ksym.fp_end = prog - temp;
3895 
3896 			emit_return(&prog, image + addrs[i - 1] + (prog - temp));
3897 			break;
3898 
3899 		default:
3900 			/*
3901 			 * By design x86-64 JIT should support all BPF instructions.
3902 			 * This error will be seen if new instruction was added
3903 			 * to the interpreter, but not to the JIT, or if there is
3904 			 * junk in bpf_prog.
3905 			 */
3906 			pr_err("bpf_jit: unknown opcode %02x\n", insn->code);
3907 			return -EINVAL;
3908 		}
3909 
3910 		ilen = prog - temp;
3911 		if (ilen > BPF_MAX_INSN_SIZE) {
3912 			pr_err("bpf_jit: fatal insn size error\n");
3913 			return -EFAULT;
3914 		}
3915 
3916 		if (image) {
3917 			/*
3918 			 * When populating the image, assert that:
3919 			 *
3920 			 *  i) We do not write beyond the allocated space, and
3921 			 * ii) addrs[i] did not change from the prior run, in order
3922 			 *     to validate assumptions made for computing branch
3923 			 *     displacements.
3924 			 */
3925 			if (unlikely(proglen + ilen > oldproglen ||
3926 				     proglen + ilen != addrs[i])) {
3927 				pr_err("bpf_jit: fatal error\n");
3928 				return -EFAULT;
3929 			}
3930 			memcpy(rw_image + proglen, temp, ilen);
3931 		}
3932 		proglen += ilen;
3933 		addrs[i] = proglen;
3934 		prog = temp;
3935 	}
3936 
3937 	if (image && excnt != bpf_prog->aux->num_exentries) {
3938 		pr_err("extable is not populated\n");
3939 		return -EFAULT;
3940 	}
3941 	return proglen;
3942 }
3943 
3944 static void clean_stack_garbage(const struct btf_func_model *m,
3945 				u8 **pprog, int nr_stack_slots,
3946 				int stack_size)
3947 {
3948 	int arg_size, off;
3949 	u8 *prog;
3950 
3951 	/* Generally speaking, the compiler will pass the arguments
3952 	 * on-stack with "push" instruction, which will take 8-byte
3953 	 * on the stack. In this case, there won't be garbage values
3954 	 * while we copy the arguments from origin stack frame to current
3955 	 * in BPF_DW.
3956 	 *
3957 	 * However, sometimes the compiler will only allocate 4-byte on
3958 	 * the stack for the arguments. For now, this case will only
3959 	 * happen if there is only one argument on-stack and its size
3960 	 * not more than 4 byte. In this case, there will be garbage
3961 	 * values on the upper 4-byte where we store the argument on
3962 	 * current stack frame.
3963 	 *
3964 	 * arguments on origin stack:
3965 	 *
3966 	 * stack_arg_1(4-byte) xxx(4-byte)
3967 	 *
3968 	 * what we copy:
3969 	 *
3970 	 * stack_arg_1(8-byte): stack_arg_1(origin) xxx
3971 	 *
3972 	 * and the xxx is the garbage values which we should clean here.
3973 	 */
3974 	if (nr_stack_slots != 1)
3975 		return;
3976 
3977 	/* the size of the last argument */
3978 	arg_size = m->arg_size[m->nr_args - 1];
3979 	if (arg_size <= 4) {
3980 		off = -(stack_size - 4);
3981 		prog = *pprog;
3982 		/* mov DWORD PTR [rbp + off], 0 */
3983 		if (!is_imm8(off))
3984 			EMIT2_off32(0xC7, 0x85, off);
3985 		else
3986 			EMIT3(0xC7, 0x45, off);
3987 		EMIT(0, 4);
3988 		*pprog = prog;
3989 	}
3990 }
3991 
3992 /* the eightbytes taken by the on-stack arguments, alignment holes included */
3993 static int get_nr_stack_slots(const u8 *pos_of_slot, int nr_slots)
3994 {
3995 	int slot;
3996 
3997 	for (slot = nr_slots - 1; slot >= 0; slot--) {
3998 		if (x86_arg_on_stack(pos_of_slot[slot]))
3999 			return x86_arg_stack_off(pos_of_slot[slot]) / 8 + 1;
4000 	}
4001 
4002 	return 0;
4003 }
4004 
4005 /*
4006  * Convert an arena kernel address into the arena pointer form on its way
4007  * into the BPF ctx, rax = (u32)(src - kern_vm_start). A nullable arg
4008  * preserves NULL, tested on the full 64-bit kernel pointer. The 32-bit
4009  * subtraction both truncates and clears the upper half, so the stored
4010  * value satisfies the JIT invariant for arena pointer registers.
4011  */
4012 static void emit_arena_arg_conv(u8 **pprog, u32 src_reg, bool nullable, u32 base_lo)
4013 {
4014 	u8 *prog = *pprog;
4015 
4016 	if (nullable) {
4017 		if (src_reg != BPF_REG_0)
4018 			emit_mov_reg(&prog, true, BPF_REG_0, src_reg);
4019 		/* test rax, rax; jz over the 5-byte sub */
4020 		EMIT3(0x48, 0x85, 0xC0);
4021 		EMIT2(X86_JE, 5);
4022 	} else if (src_reg != BPF_REG_0) {
4023 		emit_mov_reg(&prog, false, BPF_REG_0, src_reg);
4024 	}
4025 	/* sub eax, base_lo */
4026 	EMIT1_off32(0x2D, base_lo);
4027 
4028 	*pprog = prog;
4029 }
4030 
4031 static void save_args(const struct btf_func_model *m, u8 **prog,
4032 		      const u8 *pos_of_slot, int stack_size,
4033 		      bool for_call_origin, u32 flags, u64 arena_base)
4034 {
4035 	int arg_regs, first_off = 0, nr_stack_slots = 0;
4036 	bool use_jmp = bpf_trampoline_use_jmp(flags);
4037 	int stack_args_off = (use_jmp || (flags & BPF_TRAMP_F_INDIRECT)) ? 16 : 24;
4038 	int bargs_off = stack_size;
4039 	int i, j, slot, off, doff;
4040 
4041 	/* Store function arguments to stack.
4042 	 * For a function that accepts two pointers the sequence will be:
4043 	 * mov QWORD PTR [rbp-0x10],rdi
4044 	 * mov QWORD PTR [rbp-0x8],rsi
4045 	 */
4046 	for (i = 0, slot = 0; i < m->nr_args; i++) {
4047 		bool arena_arg = arena_base && (m->arg_flags[i] & BTF_FMODEL_ARENA_ARG);
4048 		bool nullable = m->arg_flags[i] & BTF_FMODEL_NULLABLE_ARG;
4049 
4050 		arg_regs = (m->arg_size[i] + 7) / 8;
4051 
4052 		/* According to the research of Yonghong, struct members
4053 		 * should be all in register or all on the stack.
4054 		 * Meanwhile, the compiler will pass the argument on regs
4055 		 * if the remaining regs can hold the argument.
4056 		 *
4057 		 * Disorder of the args can happen. For example:
4058 		 *
4059 		 * struct foo_struct {
4060 		 *     long a;
4061 		 *     int b;
4062 		 * };
4063 		 * int foo(char, char, char, char, char, struct foo_struct,
4064 		 *         char);
4065 		 *
4066 		 * the arg1-5,arg7 will be passed by regs, and arg6 will
4067 		 * by stack.
4068 		 *
4069 		 * An argument aligned to 16 bytes, an __int128 or a struct
4070 		 * holding one, also starts at an even stack slot, which can
4071 		 * leave a hole before it. bpf_jit_place_args() worked out
4072 		 * where each eightbyte is.
4073 		 */
4074 		for (j = 0; j < arg_regs; j++, slot++, bargs_off -= 8) {
4075 			u8 pos = pos_of_slot[slot];
4076 			u32 src;
4077 
4078 			if (!x86_arg_on_stack(pos)) {
4079 				/*
4080 				 * Only copy the arguments on-stack to
4081 				 * current 'stack_size' and ignore the regs,
4082 				 * used to prepare the arguments on-stack for
4083 				 * origin call.
4084 				 */
4085 				if (for_call_origin)
4086 					continue;
4087 
4088 				/* copy the arguments from regs into stack */
4089 				src = x86_arg_reg[pos];
4090 				if (arena_arg) {
4091 					emit_arena_arg_conv(prog, src, nullable, (u32)arena_base);
4092 					src = BPF_REG_0;
4093 				}
4094 				emit_stx(prog, BPF_DW, BPF_REG_FP, src, -bargs_off);
4095 				continue;
4096 			}
4097 
4098 			/* copy function arguments from origin stack frame
4099 			 * into current stack frame.
4100 			 *
4101 			 * The arguments on-stack start above the saved rbp
4102 			 * and the return addresses: two return addresses
4103 			 * (origin call and caller) when the trampoline is
4104 			 * entered through the fentry call, so rbp + 24, and
4105 			 * a single one when it is entered with a jmp or
4106 			 * called indirectly, so rbp + 16.
4107 			 *
4108 			 * The area for the origin call mirrors the incoming
4109 			 * one, hole and all; only the bpf program takes the
4110 			 * arguments packed.
4111 			 */
4112 			off = x86_arg_stack_off(pos);
4113 			doff = for_call_origin ? stack_size - off : bargs_off;
4114 			emit_ldx(prog, BPF_DW, BPF_REG_0, BPF_REG_FP,
4115 				 stack_args_off + off);
4116 			if (arena_arg)
4117 				emit_arena_arg_conv(prog, BPF_REG_0, nullable,
4118 						    (u32)arena_base);
4119 			emit_stx(prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -doff);
4120 
4121 			if (!nr_stack_slots)
4122 				first_off = doff;
4123 			nr_stack_slots++;
4124 		}
4125 	}
4126 
4127 	clean_stack_garbage(m, prog, nr_stack_slots, first_off);
4128 }
4129 
4130 static void restore_regs(u8 **prog, const u8 *pos_of_slot, int nr_slots,
4131 			 int stack_size)
4132 {
4133 	int slot;
4134 
4135 	/* Restore function arguments from stack.
4136 	 * For a function that accepts two pointers the sequence will be:
4137 	 * EMIT4(0x48, 0x8B, 0x7D, 0xF0); mov rdi,QWORD PTR [rbp-0x10]
4138 	 * EMIT4(0x48, 0x8B, 0x75, 0xF8); mov rsi,QWORD PTR [rbp-0x8]
4139 	 *
4140 	 * The logic here is similar to what we do in save_args()
4141 	 */
4142 	for (slot = 0; slot < nr_slots; slot++, stack_size -= 8) {
4143 		if (!x86_arg_on_stack(pos_of_slot[slot]))
4144 			emit_ldx(prog, BPF_DW, x86_arg_reg[pos_of_slot[slot]],
4145 				 BPF_REG_FP, -stack_size);
4146 	}
4147 }
4148 
4149 static int invoke_bpf_prog(const struct btf_func_model *m, u8 **pprog,
4150 			   struct bpf_tramp_image *im,
4151 			   struct bpf_tramp_node *node, int stack_size,
4152 			   int run_ctx_off, bool save_ret,
4153 			   void *image, void *rw_image)
4154 {
4155 	u8 *prog = *pprog;
4156 	u8 *jmp_insn, *skip;
4157 	int ctx_cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
4158 	struct bpf_prog *p = node->link->prog;
4159 	u64 cookie = node->cookie;
4160 
4161 	/* nop, patched to skip this prog when it is detached */
4162 	skip = image + (prog - (u8 *)rw_image);
4163 	emit_nops(&prog, X86_PATCH_SIZE);
4164 
4165 	/* mov rdi, cookie */
4166 	emit_mov_imm64(&prog, BPF_REG_1, (long) cookie >> 32, (u32) (long) cookie);
4167 
4168 	/* Prepare struct bpf_tramp_run_ctx.
4169 	 *
4170 	 * bpf_tramp_run_ctx is already preserved by
4171 	 * arch_prepare_bpf_trampoline().
4172 	 *
4173 	 * mov QWORD PTR [rbp - run_ctx_off + ctx_cookie_off], rdi
4174 	 */
4175 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_1, -run_ctx_off + ctx_cookie_off);
4176 
4177 	/* arg1: mov rdi, progs[i] */
4178 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
4179 	/* arg2: lea rsi, [rbp - ctx_cookie_off] */
4180 	if (!is_imm8(-run_ctx_off))
4181 		EMIT3_off32(0x48, 0x8D, 0xB5, -run_ctx_off);
4182 	else
4183 		EMIT4(0x48, 0x8D, 0x75, -run_ctx_off);
4184 
4185 	if (emit_rsb_call(&prog, bpf_trampoline_enter(p), image + (prog - (u8 *)rw_image)))
4186 		return -EINVAL;
4187 	/* remember prog start time returned by __bpf_prog_enter */
4188 	emit_mov_reg(&prog, true, BPF_REG_6, BPF_REG_0);
4189 
4190 	/* if (__bpf_prog_enter*(prog) == 0)
4191 	 *	goto skip_exec_of_prog;
4192 	 */
4193 	EMIT3(0x48, 0x85, 0xC0);  /* test rax,rax */
4194 	/* emit 2 nops that will be replaced with JE insn */
4195 	jmp_insn = prog;
4196 	emit_nops(&prog, 2);
4197 
4198 	/* arg1: lea rdi, [rbp - stack_size] */
4199 	if (!is_imm8(-stack_size))
4200 		EMIT3_off32(0x48, 0x8D, 0xBD, -stack_size);
4201 	else
4202 		EMIT4(0x48, 0x8D, 0x7D, -stack_size);
4203 	/* arg2: progs[i]->insnsi for interpreter */
4204 	if (!p->jited)
4205 		emit_mov_imm64(&prog, BPF_REG_2,
4206 			       (long) p->insnsi >> 32,
4207 			       (u32) (long) p->insnsi);
4208 	/* call JITed bpf program or interpreter */
4209 	if (emit_rsb_call(&prog, p->bpf_func, image + (prog - (u8 *)rw_image)))
4210 		return -EINVAL;
4211 
4212 	/*
4213 	 * BPF_TRAMP_MODIFY_RETURN trampolines can modify the return
4214 	 * of the previous call which is then passed on the stack to
4215 	 * the next BPF program.
4216 	 *
4217 	 * BPF_TRAMP_FENTRY trampoline may need to return the return
4218 	 * value of BPF_PROG_TYPE_STRUCT_OPS prog.
4219 	 */
4220 	if (save_ret)
4221 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
4222 
4223 	/* replace 2 nops with JE insn, since jmp target is known */
4224 	jmp_insn[0] = X86_JE;
4225 	jmp_insn[1] = prog - jmp_insn - 2;
4226 
4227 	/* arg1: mov rdi, progs[i] */
4228 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
4229 	/* arg2: mov rsi, rbx <- start time in nsec */
4230 	emit_mov_reg(&prog, true, BPF_REG_2, BPF_REG_6);
4231 	/* arg3: lea rdx, [rbp - run_ctx_off] */
4232 	if (!is_imm8(-run_ctx_off))
4233 		EMIT3_off32(0x48, 0x8D, 0x95, -run_ctx_off);
4234 	else
4235 		EMIT4(0x48, 0x8D, 0x55, -run_ctx_off);
4236 	if (emit_rsb_call(&prog, bpf_trampoline_exit(p), image + (prog - (u8 *)rw_image)))
4237 		return -EINVAL;
4238 
4239 	bpf_tramp_image_add_skip(im, p, skip, image + (prog - (u8 *)rw_image));
4240 
4241 	*pprog = prog;
4242 	return 0;
4243 }
4244 
4245 static void emit_align(u8 **pprog, u32 align)
4246 {
4247 	u8 *target, *prog = *pprog;
4248 
4249 	target = PTR_ALIGN(prog, align);
4250 	if (target != prog)
4251 		emit_nops(&prog, target - prog);
4252 
4253 	*pprog = prog;
4254 }
4255 
4256 static int emit_cond_near_jump(u8 **pprog, void *func, void *ip, u8 jmp_cond)
4257 {
4258 	u8 *prog = *pprog;
4259 	s64 offset;
4260 
4261 	offset = func - (ip + 2 + 4);
4262 	if (!is_simm32(offset)) {
4263 		pr_err("Target %p is out of range\n", func);
4264 		return -EINVAL;
4265 	}
4266 	EMIT2_off32(0x0F, jmp_cond + 0x10, offset);
4267 	*pprog = prog;
4268 	return 0;
4269 }
4270 
4271 static int invoke_bpf(const struct btf_func_model *m, u8 **pprog,
4272 		      struct bpf_tramp_image *im,
4273 		      struct bpf_tramp_nodes *tl, int stack_size,
4274 		      int run_ctx_off, int func_meta_off, bool save_ret,
4275 		      void *image, void *rw_image, u64 func_meta,
4276 		      int cookie_off)
4277 {
4278 	int i, cur_cookie = (cookie_off - stack_size) / 8;
4279 	u8 *prog = *pprog;
4280 
4281 	for (i = 0; i < tl->nr_nodes; i++) {
4282 		if (tl->nodes[i]->link->prog->call_session_cookie) {
4283 			emit_store_stack_imm64(&prog, BPF_REG_0, -func_meta_off,
4284 				func_meta | (cur_cookie << BPF_TRAMP_COOKIE_INDEX_SHIFT));
4285 			cur_cookie--;
4286 		}
4287 		if (invoke_bpf_prog(m, &prog, im, tl->nodes[i], stack_size,
4288 				    run_ctx_off, save_ret, image, rw_image))
4289 			return -EINVAL;
4290 	}
4291 	*pprog = prog;
4292 	return 0;
4293 }
4294 
4295 static int invoke_bpf_mod_ret(const struct btf_func_model *m, u8 **pprog,
4296 			      struct bpf_tramp_image *im,
4297 			      struct bpf_tramp_nodes *tl, int stack_size,
4298 			      int run_ctx_off, u8 **branches,
4299 			      void *image, void *rw_image)
4300 {
4301 	u8 *prog = *pprog;
4302 	int i;
4303 
4304 	/* The first fmod_ret program will receive a garbage return value.
4305 	 * Set this to 0 to avoid confusing the program.
4306 	 */
4307 	emit_mov_imm32(&prog, false, BPF_REG_0, 0);
4308 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
4309 	for (i = 0; i < tl->nr_nodes; i++) {
4310 		if (invoke_bpf_prog(m, &prog, im, tl->nodes[i], stack_size, run_ctx_off, true,
4311 				    image, rw_image))
4312 			return -EINVAL;
4313 
4314 		/* mod_ret prog stored return value into [rbp - 8]. Emit:
4315 		 * if (*(u64 *)(rbp - 8) !=  0)
4316 		 *	goto do_fexit;
4317 		 */
4318 		/* cmp QWORD PTR [rbp - 0x8], 0x0 */
4319 		EMIT4(0x48, 0x83, 0x7d, 0xf8); EMIT1(0x00);
4320 
4321 		/* Save the location of the branch and Generate 6 nops
4322 		 * (4 bytes for an offset and 2 bytes for the jump) These nops
4323 		 * are replaced with a conditional jump once do_fexit (i.e. the
4324 		 * start of the fexit invocation) is finalized.
4325 		 */
4326 		branches[i] = prog;
4327 		emit_nops(&prog, 4 + 2);
4328 	}
4329 
4330 	*pprog = prog;
4331 	return 0;
4332 }
4333 
4334 /* mov rax, qword ptr [rbp - off] */
4335 #define LOAD_TRAMP_TAIL_CALL_CNT_PTR(off)	\
4336 	__LOAD_TCC_PTR(-(off))
4337 
4338 /* Example:
4339  * __be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev);
4340  * its 'struct btf_func_model' will be nr_args=2
4341  * The assembly code when eth_type_trans is executing after trampoline:
4342  *
4343  * push rbp
4344  * mov rbp, rsp
4345  * sub rsp, 16                     // space for skb and dev
4346  * push rbx                        // temp regs to pass start time
4347  * mov qword ptr [rbp - 16], rdi   // save skb pointer to stack
4348  * mov qword ptr [rbp - 8], rsi    // save dev pointer to stack
4349  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
4350  * mov rbx, rax                    // remember start time in bpf stats are enabled
4351  * lea rdi, [rbp - 16]             // R1==ctx of bpf prog
4352  * call addr_of_jited_FENTRY_prog
4353  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
4354  * mov rsi, rbx                    // prog start time
4355  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
4356  * mov rdi, qword ptr [rbp - 16]   // restore skb pointer from stack
4357  * mov rsi, qword ptr [rbp - 8]    // restore dev pointer from stack
4358  * pop rbx
4359  * leave
4360  * ret
4361  *
4362  * eth_type_trans has 5 byte nop at the beginning. These 5 bytes will be
4363  * replaced with 'call generated_bpf_trampoline'. When it returns
4364  * eth_type_trans will continue executing with original skb and dev pointers.
4365  *
4366  * The assembly code when eth_type_trans is called from trampoline:
4367  *
4368  * push rbp
4369  * mov rbp, rsp
4370  * sub rsp, 24                     // space for skb, dev, return value
4371  * push rbx                        // temp regs to pass start time
4372  * mov qword ptr [rbp - 24], rdi   // save skb pointer to stack
4373  * mov qword ptr [rbp - 16], rsi   // save dev pointer to stack
4374  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
4375  * mov rbx, rax                    // remember start time if bpf stats are enabled
4376  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
4377  * call addr_of_jited_FENTRY_prog  // bpf prog can access skb and dev
4378  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
4379  * mov rsi, rbx                    // prog start time
4380  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
4381  * mov rdi, qword ptr [rbp - 24]   // restore skb pointer from stack
4382  * mov rsi, qword ptr [rbp - 16]   // restore dev pointer from stack
4383  * call eth_type_trans+5           // execute body of eth_type_trans
4384  * mov qword ptr [rbp - 8], rax    // save return value
4385  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
4386  * mov rbx, rax                    // remember start time in bpf stats are enabled
4387  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
4388  * call addr_of_jited_FEXIT_prog   // bpf prog can access skb, dev, return value
4389  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
4390  * mov rsi, rbx                    // prog start time
4391  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
4392  * mov rax, qword ptr [rbp - 8]    // restore eth_type_trans's return value
4393  * pop rbx
4394  * leave
4395  * add rsp, 8                      // skip eth_type_trans's frame
4396  * ret                             // return to its caller
4397  */
4398 static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_image,
4399 					 void *rw_image_end, void *image,
4400 					 const struct btf_func_model *m, u32 flags,
4401 					 struct bpf_tramp_nodes *tnodes,
4402 					 void *func_addr)
4403 {
4404 	int i, ret, nr_regs, stack_size = 0;
4405 	u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS];
4406 	int regs_off, func_meta_off, ip_off, run_ctx_off, arg_stack_off, rbx_off;
4407 	int tcc_off = 0;
4408 	struct bpf_tramp_nodes *fentry = &tnodes[BPF_TRAMP_FENTRY];
4409 	struct bpf_tramp_nodes *fexit = &tnodes[BPF_TRAMP_FEXIT];
4410 	struct bpf_tramp_nodes *fmod_ret = &tnodes[BPF_TRAMP_MODIFY_RETURN];
4411 	void *orig_call = func_addr;
4412 	int cookie_off, cookie_cnt;
4413 	u8 **branches = NULL;
4414 	u64 arena_base;
4415 	u64 func_meta;
4416 	u8 *prog;
4417 	bool save_ret;
4418 
4419 	/*
4420 	 * F_INDIRECT is only compatible with F_RET_FENTRY_RET, it is
4421 	 * explicitly incompatible with F_CALL_ORIG | F_SKIP_FRAME | F_IP_ARG
4422 	 * because @func_addr.
4423 	 */
4424 	WARN_ON_ONCE((flags & BPF_TRAMP_F_INDIRECT) &&
4425 		     (flags & ~(BPF_TRAMP_F_INDIRECT | BPF_TRAMP_F_RET_FENTRY_RET)));
4426 
4427 	arena_base = bpf_tramp_arena_base(m, tnodes, flags);
4428 
4429 	/*
4430 	 * x86-64 supports up to MAX_BPF_FUNC_ARGS argument slots, six in
4431 	 * registers and the rest on the stack, where bpf_jit_place_args()
4432 	 * puts them.
4433 	 */
4434 	nr_regs = bpf_jit_place_args(&x86_arg_abi, m, pos_of_slot);
4435 	if (nr_regs > MAX_BPF_FUNC_ARGS)
4436 		return -ENOTSUPP;
4437 
4438 	/* Generated trampoline stack layout:
4439 	 *
4440 	 * RBP + 8         [ return address  ]
4441 	 * RBP + 0         [ RBP             ]
4442 	 *
4443 	 * RBP - 8         [ return value    ]  BPF_TRAMP_F_CALL_ORIG or
4444 	 *                                      BPF_TRAMP_F_RET_FENTRY_RET flags
4445 	 *
4446 	 *                 [ arg slotN       ]  always, packed, whether
4447 	 *                 [ ...             ]  in a register or on the
4448 	 * RBP - regs_off  [ arg slot1       ]  stack; program's ctx pointer
4449 	 *
4450 	 * RBP - func_meta_off [ slot count, etc ]  always
4451 	 *
4452 	 * RBP - ip_off    [ traced function ]  BPF_TRAMP_F_IP_ARG flag
4453 	 *
4454 	 * RBP - rbx_off   [ rbx value       ]  always
4455 	 *
4456 	 * RBP - run_ctx_off [ bpf_tramp_run_ctx ]
4457 	 *
4458 	 * RBP - tcc_off   [ tail_call_cnt_ptr ]  BPF_TRAMP_F_TAIL_CALL_CTX
4459 	 *
4460 	 *                     [ stack slotN ]  BPF_TRAMP_F_CALL_ORIG,
4461 	 *                     [ ...         ]  the incoming stack
4462 	 *                     [ stack slot2 ]  arguments, alignment
4463 	 * RBP - arg_stack_off [ stack slot1 ]  holes included
4464 	 */
4465 
4466 	/* room for return value of orig_call or fentry prog */
4467 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
4468 	if (save_ret)
4469 		stack_size += 8;
4470 
4471 	stack_size += nr_regs * 8;
4472 	regs_off = stack_size;
4473 
4474 	/* function matedata, such as the argument slot count */
4475 	stack_size += 8;
4476 	func_meta_off = stack_size;
4477 
4478 	if (flags & BPF_TRAMP_F_IP_ARG)
4479 		stack_size += 8; /* room for IP address argument */
4480 
4481 	ip_off = stack_size;
4482 
4483 	cookie_cnt = bpf_fsession_cookie_cnt(tnodes);
4484 	/* room for session cookies */
4485 	stack_size += cookie_cnt * 8;
4486 	cookie_off = stack_size;
4487 
4488 	stack_size += 8;
4489 	rbx_off = stack_size;
4490 
4491 	stack_size += (sizeof(struct bpf_tramp_run_ctx) + 7) & ~0x7;
4492 	run_ctx_off = stack_size;
4493 
4494 	if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
4495 		stack_size += 8;
4496 		tcc_off = stack_size;
4497 	}
4498 
4499 	if (nr_regs > 6 && (flags & BPF_TRAMP_F_CALL_ORIG)) {
4500 		/* the space that used to pass arguments on-stack */
4501 		stack_size += get_nr_stack_slots(pos_of_slot, nr_regs) * 8;
4502 		/* make sure the stack pointer is 16-byte aligned if we
4503 		 * need pass arguments on stack, which means
4504 		 *  [stack_size + 8(rbp) + 8(rip) + 8(origin rip)]
4505 		 * should be 16-byte aligned. Following code depend on
4506 		 * that stack_size is already 8-byte aligned.
4507 		 */
4508 		if (bpf_trampoline_use_jmp(flags)) {
4509 			/* no rip in the "jmp" case */
4510 			stack_size += (stack_size % 16) ? 8 : 0;
4511 		} else {
4512 			stack_size += (stack_size % 16) ? 0 : 8;
4513 		}
4514 	}
4515 
4516 	arg_stack_off = stack_size;
4517 
4518 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
4519 		/* skip patched call instruction and point orig_call to actual
4520 		 * body of the kernel function.
4521 		 */
4522 		if (is_endbr(orig_call))
4523 			orig_call += ENDBR_INSN_SIZE;
4524 		orig_call += X86_PATCH_SIZE;
4525 	}
4526 
4527 	prog = rw_image;
4528 
4529 	if (flags & BPF_TRAMP_F_INDIRECT) {
4530 		/*
4531 		 * Indirect call for bpf_struct_ops
4532 		 */
4533 		emit_cfi(&prog, image,
4534 			 cfi_get_func_hash(func_addr),
4535 			 cfi_get_func_arity(func_addr));
4536 	} else {
4537 		/*
4538 		 * Direct-call fentry stub, as such it needs accounting for the
4539 		 * __fentry__ call.
4540 		 */
4541 		x86_call_depth_emit_accounting(&prog, NULL, image);
4542 	}
4543 	EMIT1(0x55);		 /* push rbp */
4544 	EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
4545 	if (im)
4546 		im->ksym.fp_start = prog - (u8 *)rw_image;
4547 
4548 	/* sub rsp, stack_size */
4549 	emit_sub_rsp(&prog, stack_size);
4550 	if (flags & BPF_TRAMP_F_TAIL_CALL_CTX)
4551 		/* mov QWORD PTR [rbp - tcc_off], rax */
4552 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -tcc_off);
4553 	/* mov QWORD PTR [rbp - rbx_off], rbx */
4554 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_6, -rbx_off);
4555 
4556 	func_meta = nr_regs;
4557 	/* Store number of argument slots of the traced function */
4558 	emit_store_stack_imm64(&prog, BPF_REG_0, -func_meta_off, func_meta);
4559 
4560 	if (flags & BPF_TRAMP_F_IP_ARG) {
4561 		/* Store IP address of the traced function */
4562 		emit_store_stack_imm64(&prog, BPF_REG_0, -ip_off, (long)func_addr);
4563 	}
4564 
4565 	save_args(m, &prog, pos_of_slot, regs_off, false, flags, arena_base);
4566 
4567 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
4568 		/* arg1: mov rdi, im */
4569 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
4570 		if (emit_rsb_call(&prog, __bpf_tramp_enter,
4571 				  image + (prog - (u8 *)rw_image))) {
4572 			ret = -EINVAL;
4573 			goto cleanup;
4574 		}
4575 	}
4576 
4577 	if (bpf_fsession_cnt(tnodes)) {
4578 		/* clear all the session cookies' value */
4579 		for (int i = 0; i < cookie_cnt; i++)
4580 			emit_store_stack_imm64(&prog, BPF_REG_0, -cookie_off + 8 * i, 0);
4581 		/* clear the return value to make sure fentry always get 0 */
4582 		emit_store_stack_imm64(&prog, BPF_REG_0, -8, 0);
4583 	}
4584 
4585 	if (fentry->nr_nodes) {
4586 		if (invoke_bpf(m, &prog, im, fentry, regs_off, run_ctx_off, func_meta_off,
4587 			       flags & BPF_TRAMP_F_RET_FENTRY_RET, image, rw_image,
4588 			       func_meta, cookie_off))
4589 			return -EINVAL;
4590 	}
4591 
4592 	if (fmod_ret->nr_nodes) {
4593 		branches = kcalloc(fmod_ret->nr_nodes, sizeof(u8 *),
4594 				   GFP_KERNEL);
4595 		if (!branches)
4596 			return -ENOMEM;
4597 
4598 		if (invoke_bpf_mod_ret(m, &prog, im, fmod_ret, regs_off,
4599 				       run_ctx_off, branches, image, rw_image)) {
4600 			ret = -EINVAL;
4601 			goto cleanup;
4602 		}
4603 	}
4604 
4605 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
4606 		restore_regs(&prog, pos_of_slot, nr_regs, regs_off);
4607 		save_args(m, &prog, pos_of_slot, arg_stack_off, true, flags, 0);
4608 
4609 		if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
4610 			/* Before calling the original function, load the
4611 			 * tail_call_cnt_ptr from stack to rax.
4612 			 */
4613 			LOAD_TRAMP_TAIL_CALL_CNT_PTR(tcc_off);
4614 		}
4615 
4616 		if (flags & BPF_TRAMP_F_ORIG_STACK) {
4617 			emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, 8);
4618 			EMIT2(0xff, 0xd3); /* call *rbx */
4619 		} else {
4620 			/* call original function */
4621 			if (emit_rsb_call(&prog, orig_call, image + (prog - (u8 *)rw_image))) {
4622 				ret = -EINVAL;
4623 				goto cleanup;
4624 			}
4625 		}
4626 		/* remember return value in a stack for bpf prog to access */
4627 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
4628 	}
4629 
4630 	if (fmod_ret->nr_nodes) {
4631 		/* From Intel 64 and IA-32 Architectures Optimization
4632 		 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
4633 		 * Coding Rule 11: All branch targets should be 16-byte
4634 		 * aligned.
4635 		 */
4636 		emit_align(&prog, 16);
4637 		/* Update the branches saved in invoke_bpf_mod_ret with the
4638 		 * aligned address of do_fexit.
4639 		 */
4640 		for (i = 0; i < fmod_ret->nr_nodes; i++) {
4641 			emit_cond_near_jump(&branches[i], image + (prog - (u8 *)rw_image),
4642 					    image + (branches[i] - (u8 *)rw_image), X86_JNE);
4643 		}
4644 	}
4645 
4646 	/* set the "is_return" flag for fsession */
4647 	func_meta |= (1ULL << BPF_TRAMP_IS_RETURN_SHIFT);
4648 	if (bpf_fsession_cnt(tnodes))
4649 		emit_store_stack_imm64(&prog, BPF_REG_0, -func_meta_off, func_meta);
4650 
4651 	if (fexit->nr_nodes) {
4652 		if (invoke_bpf(m, &prog, im, fexit, regs_off, run_ctx_off, func_meta_off,
4653 			       false, image, rw_image, func_meta, cookie_off)) {
4654 			ret = -EINVAL;
4655 			goto cleanup;
4656 		}
4657 	}
4658 
4659 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
4660 		restore_regs(&prog, pos_of_slot, nr_regs, regs_off);
4661 
4662 	/* This needs to be done regardless. If there were fmod_ret programs,
4663 	 * the return value is only updated on the stack and still needs to be
4664 	 * restored to R0.
4665 	 */
4666 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
4667 		/* arg1: mov rdi, im */
4668 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
4669 		if (emit_rsb_call(&prog, __bpf_tramp_exit, image + (prog - (u8 *)rw_image))) {
4670 			ret = -EINVAL;
4671 			goto cleanup;
4672 		}
4673 	} else if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
4674 		/* Before running the original function, load the
4675 		 * tail_call_cnt_ptr from stack to rax.
4676 		 */
4677 		LOAD_TRAMP_TAIL_CALL_CNT_PTR(tcc_off);
4678 	}
4679 
4680 	/* restore return value of orig_call or fentry prog back into RAX */
4681 	if (save_ret)
4682 		emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, -8);
4683 
4684 	emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, -rbx_off);
4685 
4686 	EMIT1(0xC9); /* leave */
4687 	if (im)
4688 		im->ksym.fp_end = prog - (u8 *)rw_image;
4689 
4690 	if (flags & BPF_TRAMP_F_SKIP_FRAME) {
4691 		/* skip our return address and return to parent */
4692 		emit_add_rsp(&prog, 8); /* add rsp, 8 */
4693 	}
4694 	emit_return(&prog, image + (prog - (u8 *)rw_image));
4695 	/* Make sure the trampoline generation logic doesn't overflow */
4696 	if (WARN_ON_ONCE(prog > (u8 *)rw_image_end - BPF_INSN_SAFETY)) {
4697 		ret = -EFAULT;
4698 		goto cleanup;
4699 	}
4700 	ret = prog - (u8 *)rw_image + BPF_INSN_SAFETY;
4701 
4702 cleanup:
4703 	kfree(branches);
4704 	return ret;
4705 }
4706 
4707 void *arch_alloc_bpf_trampoline(unsigned int size)
4708 {
4709 	return bpf_prog_pack_alloc(size, jit_fill_hole, false);
4710 }
4711 
4712 void arch_free_bpf_trampoline(void *image, unsigned int size)
4713 {
4714 	bpf_prog_pack_free(image, size);
4715 }
4716 
4717 int arch_protect_bpf_trampoline(void *image, unsigned int size)
4718 {
4719 	return 0;
4720 }
4721 
4722 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
4723 				const struct btf_func_model *m, u32 flags,
4724 				struct bpf_tramp_nodes *tnodes,
4725 				void *func_addr)
4726 {
4727 	void *rw_image, *tmp;
4728 	int ret;
4729 	u32 size = image_end - image;
4730 
4731 	/* rw_image doesn't need to be in module memory range, so we can
4732 	 * use kvmalloc.
4733 	 */
4734 	rw_image = kvmalloc(size, GFP_KERNEL);
4735 	if (!rw_image)
4736 		return -ENOMEM;
4737 
4738 	ret = __arch_prepare_bpf_trampoline(im, rw_image, rw_image + size, image, m,
4739 					    flags, tnodes, func_addr);
4740 	if (ret < 0)
4741 		goto out;
4742 
4743 	tmp = bpf_arch_text_copy(image, rw_image, size);
4744 	if (IS_ERR(tmp))
4745 		ret = PTR_ERR(tmp);
4746 out:
4747 	kvfree(rw_image);
4748 	return ret;
4749 }
4750 
4751 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
4752 			     struct bpf_tramp_nodes *tnodes, void *func_addr)
4753 {
4754 	struct bpf_tramp_image im = {};
4755 
4756 	if (!trampoline_size_image)
4757 		return -ENOMEM;
4758 
4759 	return __arch_prepare_bpf_trampoline(&im, trampoline_size_image,
4760 					     trampoline_size_image + PAGE_SIZE,
4761 					     trampoline_size_image, m, flags,
4762 					     tnodes, func_addr);
4763 }
4764 
4765 static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf)
4766 {
4767 	u8 *jg_reloc, *prog = *pprog;
4768 	int pivot, err, jg_bytes = 1;
4769 	s64 jg_offset;
4770 
4771 	if (a == b) {
4772 		/* Leaf node of recursion, i.e. not a range of indices
4773 		 * anymore.
4774 		 */
4775 		EMIT1(add_1mod(0x48, BPF_REG_3));	/* cmp rdx,func */
4776 		if (!is_simm32(progs[a]))
4777 			return -1;
4778 		EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3),
4779 			    progs[a]);
4780 		err = emit_cond_near_jump(&prog,	/* je func */
4781 					  (void *)progs[a], image + (prog - buf),
4782 					  X86_JE);
4783 		if (err)
4784 			return err;
4785 
4786 		emit_indirect_jump(&prog, BPF_REG_3 /* R3 -> rdx */, image + (prog - buf));
4787 
4788 		*pprog = prog;
4789 		return 0;
4790 	}
4791 
4792 	/* Not a leaf node, so we pivot, and recursively descend into
4793 	 * the lower and upper ranges.
4794 	 */
4795 	pivot = (b - a) / 2;
4796 	EMIT1(add_1mod(0x48, BPF_REG_3));		/* cmp rdx,func */
4797 	if (!is_simm32(progs[a + pivot]))
4798 		return -1;
4799 	EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3), progs[a + pivot]);
4800 
4801 	if (pivot > 2) {				/* jg upper_part */
4802 		/* Require near jump. */
4803 		jg_bytes = 4;
4804 		EMIT2_off32(0x0F, X86_JG + 0x10, 0);
4805 	} else {
4806 		EMIT2(X86_JG, 0);
4807 	}
4808 	jg_reloc = prog;
4809 
4810 	err = emit_bpf_dispatcher(&prog, a, a + pivot,	/* emit lower_part */
4811 				  progs, image, buf);
4812 	if (err)
4813 		return err;
4814 
4815 	/* From Intel 64 and IA-32 Architectures Optimization
4816 	 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
4817 	 * Coding Rule 11: All branch targets should be 16-byte
4818 	 * aligned.
4819 	 */
4820 	emit_align(&prog, 16);
4821 	jg_offset = prog - jg_reloc;
4822 	emit_code(jg_reloc - jg_bytes, jg_offset, jg_bytes);
4823 
4824 	err = emit_bpf_dispatcher(&prog, a + pivot + 1,	/* emit upper_part */
4825 				  b, progs, image, buf);
4826 	if (err)
4827 		return err;
4828 
4829 	*pprog = prog;
4830 	return 0;
4831 }
4832 
4833 static int cmp_ips(const void *a, const void *b)
4834 {
4835 	const s64 *ipa = a;
4836 	const s64 *ipb = b;
4837 
4838 	if (*ipa > *ipb)
4839 		return 1;
4840 	if (*ipa < *ipb)
4841 		return -1;
4842 	return 0;
4843 }
4844 
4845 int arch_prepare_bpf_dispatcher(void *image, void *buf, s64 *funcs, int num_funcs)
4846 {
4847 	u8 *prog = buf;
4848 
4849 	sort(funcs, num_funcs, sizeof(funcs[0]), cmp_ips, NULL);
4850 	return emit_bpf_dispatcher(&prog, 0, num_funcs - 1, funcs, image, buf);
4851 }
4852 
4853 static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
4854 {
4855 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
4856 	u64 *stack_ptr;
4857 
4858 	for_each_possible_cpu(cpu) {
4859 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
4860 		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
4861 		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
4862 	}
4863 }
4864 
4865 static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
4866 				   struct bpf_prog *prog)
4867 {
4868 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
4869 	u64 *stack_ptr;
4870 
4871 	for_each_possible_cpu(cpu) {
4872 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
4873 		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
4874 		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL) {
4875 			pr_err("BPF private stack overflow/underflow detected for prog %sx\n",
4876 			       bpf_jit_get_prog_name(prog));
4877 			break;
4878 		}
4879 	}
4880 }
4881 
4882 struct x64_jit_data {
4883 	struct bpf_binary_header *rw_header;
4884 	struct bpf_binary_header *header;
4885 	int *addrs;
4886 	u8 *image;
4887 	int proglen;
4888 	struct jit_context ctx;
4889 };
4890 
4891 #define MAX_PASSES 20
4892 #define PADDING_PASSES (MAX_PASSES - 5)
4893 
4894 struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog)
4895 {
4896 	struct bpf_binary_header *rw_header = NULL;
4897 	struct bpf_binary_header *header = NULL;
4898 	void __percpu *priv_stack_ptr = NULL;
4899 	struct x64_jit_data *jit_data;
4900 	int priv_stack_alloc_sz;
4901 	int proglen, oldproglen = 0;
4902 	struct jit_context ctx = {};
4903 	bool extra_pass = false;
4904 	bool padding = false;
4905 	u8 *rw_image = NULL;
4906 	u8 *image = NULL;
4907 	int *addrs;
4908 	int pass;
4909 	int i;
4910 
4911 	if (!prog->jit_requested)
4912 		return prog;
4913 
4914 	jit_data = prog->aux->jit_data;
4915 	if (!jit_data) {
4916 		jit_data = kzalloc_obj(*jit_data);
4917 		if (!jit_data)
4918 			return prog;
4919 		prog->aux->jit_data = jit_data;
4920 	}
4921 	priv_stack_ptr = prog->aux->priv_stack_ptr;
4922 	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
4923 		/* Allocate actual private stack size with verifier-calculated
4924 		 * stack size plus two memory guards to protect overflow and
4925 		 * underflow.
4926 		 */
4927 		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
4928 				      2 * PRIV_STACK_GUARD_SZ;
4929 		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 8, GFP_KERNEL);
4930 		if (!priv_stack_ptr)
4931 			goto out_priv_stack;
4932 
4933 		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
4934 		prog->aux->priv_stack_ptr = priv_stack_ptr;
4935 	}
4936 	addrs = jit_data->addrs;
4937 	if (addrs) {
4938 		ctx = jit_data->ctx;
4939 		oldproglen = jit_data->proglen;
4940 		image = jit_data->image;
4941 		header = jit_data->header;
4942 		rw_header = jit_data->rw_header;
4943 		rw_image = (void *)rw_header + ((void *)image - (void *)header);
4944 		extra_pass = true;
4945 		padding = true;
4946 		goto skip_init_addrs;
4947 	}
4948 
4949 	/*
4950 	 * An arena fetching AND/OR/XOR is lowered to a CMPXCHG loop whose load
4951 	 * and CMPXCHG can both fault, one more entry than the verifier reserved.
4952 	 * The extra pass of a program with subprograms returned above, so the
4953 	 * count is adjusted once.
4954 	 */
4955 	for (i = 0; prog->aux->arena && i < prog->len; i++) {
4956 		const struct bpf_insn *insn = &prog->insnsi[i];
4957 
4958 		if (BPF_CLASS(insn->code) == BPF_STX &&
4959 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC &&
4960 		    is_atomic_fetch_op(insn))
4961 			prog->aux->num_exentries++;
4962 	}
4963 
4964 	addrs = kvmalloc_objs(*addrs, prog->len + 1);
4965 	if (!addrs)
4966 		goto out_addrs;
4967 
4968 	/*
4969 	 * Before first pass, make a rough estimation of addrs[]
4970 	 * each BPF instruction is translated to less than 64 bytes
4971 	 */
4972 	for (proglen = 0, i = 0; i <= prog->len; i++) {
4973 		proglen += 64;
4974 		addrs[i] = proglen;
4975 	}
4976 	ctx.cleanup_addr = proglen;
4977 skip_init_addrs:
4978 
4979 	/*
4980 	 * JITed image shrinks with every pass and the loop iterates
4981 	 * until the image stops shrinking. Very large BPF programs
4982 	 * may converge on the last pass. In such case do one more
4983 	 * pass to emit the final image.
4984 	 */
4985 	for (pass = 0; pass < MAX_PASSES || image; pass++) {
4986 		if (!padding && pass >= PADDING_PASSES)
4987 			padding = true;
4988 		proglen = do_jit(env, prog, addrs, image, rw_image, oldproglen,
4989 				 &ctx, padding);
4990 		if (proglen <= 0) {
4991 out_image:
4992 			image = NULL;
4993 			if (header) {
4994 				bpf_arch_text_copy(&header->size, &rw_header->size,
4995 						   sizeof(rw_header->size));
4996 				bpf_jit_binary_pack_free(header, rw_header);
4997 			}
4998 			if (extra_pass) {
4999 				prog->bpf_func = NULL;
5000 				prog->jited = 0;
5001 				prog->jited_len = 0;
5002 			}
5003 			goto out_addrs;
5004 		}
5005 		if (image) {
5006 			if (proglen != oldproglen) {
5007 				pr_err("bpf_jit: proglen=%d != oldproglen=%d\n",
5008 				       proglen, oldproglen);
5009 				goto out_image;
5010 			}
5011 			break;
5012 		}
5013 		if (proglen == oldproglen) {
5014 			/*
5015 			 * The number of entries in extable is the number of BPF_LDX
5016 			 * insns that access kernel memory via "pointer to BTF type".
5017 			 * The verifier changed their opcode from LDX|MEM|size
5018 			 * to LDX|PROBE_MEM|size to make JITing easier. Arena
5019 			 * accesses add one each, and an arena fetching AND/OR/XOR
5020 			 * one more, see the adjustment of num_exentries above.
5021 			 */
5022 			u32 align = __alignof__(struct exception_table_entry);
5023 			u32 extable_size = prog->aux->num_exentries *
5024 				sizeof(struct exception_table_entry);
5025 
5026 			/* allocate module memory for x86 insns and extable */
5027 			header = bpf_jit_binary_pack_alloc(roundup(proglen, align) + extable_size,
5028 							   &image, align, &rw_header, &rw_image,
5029 							   jit_fill_hole,
5030 							   bpf_prog_was_classic(prog));
5031 			if (!header)
5032 				goto out_addrs;
5033 			prog->aux->extable = (void *) image + roundup(proglen, align);
5034 		}
5035 		oldproglen = proglen;
5036 		cond_resched();
5037 	}
5038 
5039 	if (bpf_jit_enable > 1)
5040 		bpf_jit_dump(prog->len, proglen, pass + 1, rw_image);
5041 
5042 	if (image) {
5043 		if (!prog->is_func || extra_pass) {
5044 			/*
5045 			 * bpf_jit_binary_pack_finalize fails in two scenarios:
5046 			 *   1) header is not pointing to proper module memory;
5047 			 *   2) the arch doesn't support bpf_arch_text_copy().
5048 			 *
5049 			 * Both cases are serious bugs and justify WARN_ON.
5050 			 */
5051 			if (WARN_ON(bpf_jit_binary_pack_finalize(header, rw_header))) {
5052 				/* header has been freed */
5053 				header = NULL;
5054 				goto out_image;
5055 			}
5056 
5057 			bpf_tail_call_direct_fixup(prog);
5058 		} else {
5059 			jit_data->addrs = addrs;
5060 			jit_data->ctx = ctx;
5061 			jit_data->proglen = proglen;
5062 			jit_data->image = image;
5063 			jit_data->header = header;
5064 			jit_data->rw_header = rw_header;
5065 		}
5066 
5067 		/*
5068 		 * The bpf_prog_update_insn_ptrs function expects addrs to
5069 		 * point to the first byte of the jitted instruction (unlike
5070 		 * the bpf_prog_fill_jited_linfo below, which, for historical
5071 		 * reasons, expects to point to the next instruction)
5072 		 */
5073 		bpf_prog_update_insn_ptrs(prog, addrs, image);
5074 
5075 		/*
5076 		 * ctx.prog_offset is used when CFI preambles put code *before*
5077 		 * the function. See emit_cfi(). For FineIBT specifically this code
5078 		 * can also be executed and bpf_prog_kallsyms_add() will
5079 		 * generate an additional symbol to cover this, hence also
5080 		 * decrement proglen.
5081 		 */
5082 		prog->bpf_func = (void *)image + cfi_get_offset();
5083 		prog->jited = 1;
5084 		prog->jited_len = proglen - cfi_get_offset();
5085 	}
5086 
5087 	if (!image || !prog->is_func || extra_pass) {
5088 		if (image)
5089 			bpf_prog_fill_jited_linfo(prog, addrs + 1);
5090 out_addrs:
5091 		kvfree(addrs);
5092 		if (!image && priv_stack_ptr) {
5093 			free_percpu(priv_stack_ptr);
5094 			prog->aux->priv_stack_ptr = NULL;
5095 		}
5096 out_priv_stack:
5097 		kfree(jit_data);
5098 		prog->aux->jit_data = NULL;
5099 	}
5100 
5101 	return prog;
5102 }
5103 
5104 bool bpf_jit_supports_callx(void)
5105 {
5106 	/*
5107 	 * FineIBT poisons ENDBR at the entry of a JITed function and expects
5108 	 * indirect callers to go through the CFI preamble instead.
5109 	 * callx doesn't do that yet.
5110 	 */
5111 	return cfi_mode != CFI_FINEIBT;
5112 }
5113 
5114 bool bpf_jit_supports_kfunc_call(void)
5115 {
5116 	return true;
5117 }
5118 
5119 bool bpf_jit_supports_kfunc_ret_reg_pair(void)
5120 {
5121 	return true;
5122 }
5123 
5124 bool bpf_jit_supports_unwind(void)
5125 {
5126 	return true;
5127 }
5128 
5129 const struct bpf_jit_arg_abi *bpf_jit_arg_abi(void)
5130 {
5131 	return &x86_arg_abi;
5132 }
5133 
5134 bool bpf_jit_supports_stack_args(void)
5135 {
5136 	return true;
5137 }
5138 
5139 bool bpf_jit_supports_arena_args(void)
5140 {
5141 	return true;
5142 }
5143 
5144 void *bpf_arch_text_copy(void *dst, void *src, size_t len)
5145 {
5146 	if (text_poke_copy(dst, src, len) == NULL)
5147 		return ERR_PTR(-EINVAL);
5148 	return dst;
5149 }
5150 
5151 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
5152 bool bpf_jit_supports_subprog_tailcalls(void)
5153 {
5154 	return true;
5155 }
5156 
5157 /*
5158  * Frame sizes are 32-bit immediates in the prologue, epilogue and tail call
5159  * sequences, a tail call pops the caller's frame and lands in the target's
5160  * prologue before the target allocates its own, and private stacks are
5161  * allocated from the program's own depth, so MAX_BPF_STACK_JIT frames need
5162  * nothing special.
5163  */
5164 bool bpf_jit_supports_large_stack(void)
5165 {
5166 	return true;
5167 }
5168 
5169 bool bpf_jit_supports_percpu_insn(void)
5170 {
5171 	return true;
5172 }
5173 
5174 void bpf_jit_free(struct bpf_prog *prog)
5175 {
5176 	if (prog->jited) {
5177 		struct x64_jit_data *jit_data = prog->aux->jit_data;
5178 		struct bpf_binary_header *hdr;
5179 		void __percpu *priv_stack_ptr;
5180 		int priv_stack_alloc_sz;
5181 
5182 		/*
5183 		 * If we fail the final pass of JIT (from jit_subprogs),
5184 		 * the program may not be finalized yet. Call finalize here
5185 		 * before freeing it.
5186 		 */
5187 		if (jit_data) {
5188 			bpf_jit_binary_pack_finalize(jit_data->header,
5189 						     jit_data->rw_header);
5190 			kvfree(jit_data->addrs);
5191 			kfree(jit_data);
5192 		}
5193 		prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset();
5194 		hdr = bpf_jit_binary_pack_hdr(prog);
5195 		bpf_jit_binary_pack_free(hdr, NULL);
5196 		priv_stack_ptr = prog->aux->priv_stack_ptr;
5197 		if (priv_stack_ptr) {
5198 			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
5199 					      2 * PRIV_STACK_GUARD_SZ;
5200 			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
5201 			free_percpu(prog->aux->priv_stack_ptr);
5202 		}
5203 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
5204 	}
5205 
5206 	bpf_prog_unlock_free(prog);
5207 }
5208 
5209 bool bpf_jit_supports_exceptions(void)
5210 {
5211 	/* We unwind through both kernel frames (starting from within bpf_throw
5212 	 * call) and BPF frames. Therefore we require ORC unwinder to be enabled
5213 	 * to walk kernel frames and reach BPF frames in the stack trace.
5214 	 */
5215 	return IS_ENABLED(CONFIG_UNWINDER_ORC);
5216 }
5217 
5218 bool bpf_jit_supports_private_stack(void)
5219 {
5220 	return true;
5221 }
5222 
5223 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
5224 {
5225 #if defined(CONFIG_UNWINDER_ORC)
5226 	struct unwind_state state;
5227 	unsigned long addr;
5228 
5229 	for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
5230 	     unwind_next_frame(&state)) {
5231 		addr = unwind_get_return_address(&state);
5232 		if (!addr || !consume_fn(cookie, (u64)addr, (u64)state.sp, (u64)state.bp))
5233 			break;
5234 	}
5235 	return;
5236 #endif
5237 }
5238 
5239 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
5240 			       struct bpf_prog *new, struct bpf_prog *old)
5241 {
5242 	u8 *old_addr, *new_addr, *old_bypass_addr;
5243 	enum bpf_text_poke_type t;
5244 	int ret;
5245 
5246 	old_bypass_addr = old ? NULL : poke->bypass_addr;
5247 	old_addr = old ? (u8 *)old->bpf_func + poke->adj_off : NULL;
5248 	new_addr = new ? (u8 *)new->bpf_func + poke->adj_off : NULL;
5249 
5250 	/*
5251 	 * On program loading or teardown, the program's kallsym entry
5252 	 * might not be in place, so we use __bpf_arch_text_poke to skip
5253 	 * the kallsyms check.
5254 	 */
5255 	if (new) {
5256 		t = old_addr ? BPF_MOD_JUMP : BPF_MOD_NOP;
5257 		ret = __bpf_arch_text_poke(poke->tailcall_target,
5258 					   t, BPF_MOD_JUMP,
5259 					   old_addr, new_addr);
5260 		BUG_ON(ret < 0);
5261 		if (!old) {
5262 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
5263 						   BPF_MOD_JUMP, BPF_MOD_NOP,
5264 						   poke->bypass_addr,
5265 						   NULL);
5266 			BUG_ON(ret < 0);
5267 		}
5268 	} else {
5269 		t = old_bypass_addr ? BPF_MOD_JUMP : BPF_MOD_NOP;
5270 		ret = __bpf_arch_text_poke(poke->tailcall_bypass,
5271 					   t, BPF_MOD_JUMP, old_bypass_addr,
5272 					   poke->bypass_addr);
5273 		BUG_ON(ret < 0);
5274 		/* let other CPUs finish the execution of program
5275 		 * so that it will not possible to expose them
5276 		 * to invalid nop, stack unwind, nop state
5277 		 */
5278 		if (!ret)
5279 			synchronize_rcu();
5280 		t = old_addr ? BPF_MOD_JUMP : BPF_MOD_NOP;
5281 		ret = __bpf_arch_text_poke(poke->tailcall_target,
5282 					   t, BPF_MOD_NOP, old_addr, NULL);
5283 		BUG_ON(ret < 0);
5284 	}
5285 }
5286 
5287 bool bpf_jit_supports_arena(void)
5288 {
5289 	return true;
5290 }
5291 
5292 bool bpf_jit_supports_arena_scalar(void)
5293 {
5294 	return true;
5295 }
5296 
5297 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
5298 {
5299 	return true;
5300 }
5301 
5302 bool bpf_jit_supports_ptr_xchg(void)
5303 {
5304 	return true;
5305 }
5306 
5307 /* x86-64 JIT emits its own code to filter user addresses so return 0 here */
5308 u64 bpf_arch_uaddress_limit(void)
5309 {
5310 	return 0;
5311 }
5312 
5313 bool bpf_jit_supports_timed_may_goto(void)
5314 {
5315 	return true;
5316 }
5317 
5318 bool bpf_jit_supports_fsession(void)
5319 {
5320 	return true;
5321 }
5322