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