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