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