xref: /linux/arch/x86/net/bpf_jit_comp.c (revision 38c6104e0bc7c8af20ab4897cb0504e3339e4fe4)
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/bpf.h>
12 #include <linux/memory.h>
13 #include <linux/sort.h>
14 #include <asm/extable.h>
15 #include <asm/ftrace.h>
16 #include <asm/set_memory.h>
17 #include <asm/nospec-branch.h>
18 #include <asm/text-patching.h>
19 #include <asm/unwind.h>
20 #include <asm/cfi.h>
21 
22 static bool all_callee_regs_used[4] = {true, true, true, true};
23 
24 static u8 *emit_code(u8 *ptr, u32 bytes, unsigned int len)
25 {
26 	if (len == 1)
27 		*ptr = bytes;
28 	else if (len == 2)
29 		*(u16 *)ptr = bytes;
30 	else {
31 		*(u32 *)ptr = bytes;
32 		barrier();
33 	}
34 	return ptr + len;
35 }
36 
37 #define EMIT(bytes, len) \
38 	do { prog = emit_code(prog, bytes, len); } while (0)
39 
40 #define EMIT1(b1)		EMIT(b1, 1)
41 #define EMIT2(b1, b2)		EMIT((b1) + ((b2) << 8), 2)
42 #define EMIT3(b1, b2, b3)	EMIT((b1) + ((b2) << 8) + ((b3) << 16), 3)
43 #define EMIT4(b1, b2, b3, b4)   EMIT((b1) + ((b2) << 8) + ((b3) << 16) + ((b4) << 24), 4)
44 
45 #define EMIT1_off32(b1, off) \
46 	do { EMIT1(b1); EMIT(off, 4); } while (0)
47 #define EMIT2_off32(b1, b2, off) \
48 	do { EMIT2(b1, b2); EMIT(off, 4); } while (0)
49 #define EMIT3_off32(b1, b2, b3, off) \
50 	do { EMIT3(b1, b2, b3); EMIT(off, 4); } while (0)
51 #define EMIT4_off32(b1, b2, b3, b4, off) \
52 	do { EMIT4(b1, b2, b3, b4); EMIT(off, 4); } while (0)
53 
54 #ifdef CONFIG_X86_KERNEL_IBT
55 #define EMIT_ENDBR()		EMIT(gen_endbr(), 4)
56 #define EMIT_ENDBR_POISON()	EMIT(gen_endbr_poison(), 4)
57 #else
58 #define EMIT_ENDBR()
59 #define EMIT_ENDBR_POISON()
60 #endif
61 
62 static bool is_imm8(int value)
63 {
64 	return value <= 127 && value >= -128;
65 }
66 
67 /*
68  * Let us limit the positive offset to be <= 123.
69  * This is to ensure eventual jit convergence For the following patterns:
70  * ...
71  * pass4, final_proglen=4391:
72  *   ...
73  *   20e:    48 85 ff                test   rdi,rdi
74  *   211:    74 7d                   je     0x290
75  *   213:    48 8b 77 00             mov    rsi,QWORD PTR [rdi+0x0]
76  *   ...
77  *   289:    48 85 ff                test   rdi,rdi
78  *   28c:    74 17                   je     0x2a5
79  *   28e:    e9 7f ff ff ff          jmp    0x212
80  *   293:    bf 03 00 00 00          mov    edi,0x3
81  * Note that insn at 0x211 is 2-byte cond jump insn for offset 0x7d (-125)
82  * and insn at 0x28e is 5-byte jmp insn with offset -129.
83  *
84  * pass5, final_proglen=4392:
85  *   ...
86  *   20e:    48 85 ff                test   rdi,rdi
87  *   211:    0f 84 80 00 00 00       je     0x297
88  *   217:    48 8b 77 00             mov    rsi,QWORD PTR [rdi+0x0]
89  *   ...
90  *   28d:    48 85 ff                test   rdi,rdi
91  *   290:    74 1a                   je     0x2ac
92  *   292:    eb 84                   jmp    0x218
93  *   294:    bf 03 00 00 00          mov    edi,0x3
94  * Note that insn at 0x211 is 6-byte cond jump insn now since its offset
95  * becomes 0x80 based on previous round (0x293 - 0x213 = 0x80).
96  * At the same time, insn at 0x292 is a 2-byte insn since its offset is
97  * -124.
98  *
99  * pass6 will repeat the same code as in pass4 and this will prevent
100  * eventual convergence.
101  *
102  * To fix this issue, we need to break je (2->6 bytes) <-> jmp (5->2 bytes)
103  * cycle in the above. In the above example je offset <= 0x7c should work.
104  *
105  * For other cases, je <-> je needs offset <= 0x7b to avoid no convergence
106  * issue. For jmp <-> je and jmp <-> jmp cases, jmp offset <= 0x7c should
107  * avoid no convergence issue.
108  *
109  * Overall, let us limit the positive offset for 8bit cond/uncond jmp insn
110  * to maximum 123 (0x7b). This way, the jit pass can eventually converge.
111  */
112 static bool is_imm8_jmp_offset(int value)
113 {
114 	return value <= 123 && value >= -128;
115 }
116 
117 static bool is_simm32(s64 value)
118 {
119 	return value == (s64)(s32)value;
120 }
121 
122 static bool is_uimm32(u64 value)
123 {
124 	return value == (u64)(u32)value;
125 }
126 
127 /* mov dst, src */
128 #define EMIT_mov(DST, SRC)								 \
129 	do {										 \
130 		if (DST != SRC)								 \
131 			EMIT3(add_2mod(0x48, DST, SRC), 0x89, add_2reg(0xC0, DST, SRC)); \
132 	} while (0)
133 
134 static int bpf_size_to_x86_bytes(int bpf_size)
135 {
136 	if (bpf_size == BPF_W)
137 		return 4;
138 	else if (bpf_size == BPF_H)
139 		return 2;
140 	else if (bpf_size == BPF_B)
141 		return 1;
142 	else if (bpf_size == BPF_DW)
143 		return 4; /* imm32 */
144 	else
145 		return 0;
146 }
147 
148 /*
149  * List of x86 cond jumps opcodes (. + s8)
150  * Add 0x10 (and an extra 0x0f) to generate far jumps (. + s32)
151  */
152 #define X86_JB  0x72
153 #define X86_JAE 0x73
154 #define X86_JE  0x74
155 #define X86_JNE 0x75
156 #define X86_JBE 0x76
157 #define X86_JA  0x77
158 #define X86_JL  0x7C
159 #define X86_JGE 0x7D
160 #define X86_JLE 0x7E
161 #define X86_JG  0x7F
162 
163 /* Pick a register outside of BPF range for JIT internal work */
164 #define AUX_REG (MAX_BPF_JIT_REG + 1)
165 #define X86_REG_R9 (MAX_BPF_JIT_REG + 2)
166 #define X86_REG_R12 (MAX_BPF_JIT_REG + 3)
167 
168 /*
169  * The following table maps BPF registers to x86-64 registers.
170  *
171  * x86-64 register R12 is unused, since if used as base address
172  * register in load/store instructions, it always needs an
173  * extra byte of encoding and is callee saved.
174  *
175  * x86-64 register R9 is not used by BPF programs, but can be used by BPF
176  * trampoline. x86-64 register R10 is used for blinding (if enabled).
177  */
178 static const int reg2hex[] = {
179 	[BPF_REG_0] = 0,  /* RAX */
180 	[BPF_REG_1] = 7,  /* RDI */
181 	[BPF_REG_2] = 6,  /* RSI */
182 	[BPF_REG_3] = 2,  /* RDX */
183 	[BPF_REG_4] = 1,  /* RCX */
184 	[BPF_REG_5] = 0,  /* R8  */
185 	[BPF_REG_6] = 3,  /* RBX callee saved */
186 	[BPF_REG_7] = 5,  /* R13 callee saved */
187 	[BPF_REG_8] = 6,  /* R14 callee saved */
188 	[BPF_REG_9] = 7,  /* R15 callee saved */
189 	[BPF_REG_FP] = 5, /* RBP readonly */
190 	[BPF_REG_AX] = 2, /* R10 temp register */
191 	[AUX_REG] = 3,    /* R11 temp register */
192 	[X86_REG_R9] = 1, /* R9 register, 6th function argument */
193 	[X86_REG_R12] = 4, /* R12 callee saved */
194 };
195 
196 static const int reg2pt_regs[] = {
197 	[BPF_REG_0] = offsetof(struct pt_regs, ax),
198 	[BPF_REG_1] = offsetof(struct pt_regs, di),
199 	[BPF_REG_2] = offsetof(struct pt_regs, si),
200 	[BPF_REG_3] = offsetof(struct pt_regs, dx),
201 	[BPF_REG_4] = offsetof(struct pt_regs, cx),
202 	[BPF_REG_5] = offsetof(struct pt_regs, r8),
203 	[BPF_REG_6] = offsetof(struct pt_regs, bx),
204 	[BPF_REG_7] = offsetof(struct pt_regs, r13),
205 	[BPF_REG_8] = offsetof(struct pt_regs, r14),
206 	[BPF_REG_9] = offsetof(struct pt_regs, r15),
207 };
208 
209 /*
210  * is_ereg() == true if BPF register 'reg' maps to x86-64 r8..r15
211  * which need extra byte of encoding.
212  * rax,rcx,...,rbp have simpler encoding
213  */
214 static bool is_ereg(u32 reg)
215 {
216 	return (1 << reg) & (BIT(BPF_REG_5) |
217 			     BIT(AUX_REG) |
218 			     BIT(BPF_REG_7) |
219 			     BIT(BPF_REG_8) |
220 			     BIT(BPF_REG_9) |
221 			     BIT(X86_REG_R9) |
222 			     BIT(X86_REG_R12) |
223 			     BIT(BPF_REG_AX));
224 }
225 
226 /*
227  * is_ereg_8l() == true if BPF register 'reg' is mapped to access x86-64
228  * lower 8-bit registers dil,sil,bpl,spl,r8b..r15b, which need extra byte
229  * of encoding. al,cl,dl,bl have simpler encoding.
230  */
231 static bool is_ereg_8l(u32 reg)
232 {
233 	return is_ereg(reg) ||
234 	    (1 << reg) & (BIT(BPF_REG_1) |
235 			  BIT(BPF_REG_2) |
236 			  BIT(BPF_REG_FP));
237 }
238 
239 static bool is_axreg(u32 reg)
240 {
241 	return reg == BPF_REG_0;
242 }
243 
244 /* Add modifiers if 'reg' maps to x86-64 registers R8..R15 */
245 static u8 add_1mod(u8 byte, u32 reg)
246 {
247 	if (is_ereg(reg))
248 		byte |= 1;
249 	return byte;
250 }
251 
252 static u8 add_2mod(u8 byte, u32 r1, u32 r2)
253 {
254 	if (is_ereg(r1))
255 		byte |= 1;
256 	if (is_ereg(r2))
257 		byte |= 4;
258 	return byte;
259 }
260 
261 static u8 add_3mod(u8 byte, u32 r1, u32 r2, u32 index)
262 {
263 	if (is_ereg(r1))
264 		byte |= 1;
265 	if (is_ereg(index))
266 		byte |= 2;
267 	if (is_ereg(r2))
268 		byte |= 4;
269 	return byte;
270 }
271 
272 /* Encode 'dst_reg' register into x86-64 opcode 'byte' */
273 static u8 add_1reg(u8 byte, u32 dst_reg)
274 {
275 	return byte + reg2hex[dst_reg];
276 }
277 
278 /* Encode 'dst_reg' and 'src_reg' registers into x86-64 opcode 'byte' */
279 static u8 add_2reg(u8 byte, u32 dst_reg, u32 src_reg)
280 {
281 	return byte + reg2hex[dst_reg] + (reg2hex[src_reg] << 3);
282 }
283 
284 /* Some 1-byte opcodes for binary ALU operations */
285 static u8 simple_alu_opcodes[] = {
286 	[BPF_ADD] = 0x01,
287 	[BPF_SUB] = 0x29,
288 	[BPF_AND] = 0x21,
289 	[BPF_OR] = 0x09,
290 	[BPF_XOR] = 0x31,
291 	[BPF_LSH] = 0xE0,
292 	[BPF_RSH] = 0xE8,
293 	[BPF_ARSH] = 0xF8,
294 };
295 
296 static void jit_fill_hole(void *area, unsigned int size)
297 {
298 	/* Fill whole space with INT3 instructions */
299 	memset(area, 0xcc, size);
300 }
301 
302 int bpf_arch_text_invalidate(void *dst, size_t len)
303 {
304 	return IS_ERR_OR_NULL(text_poke_set(dst, 0xcc, len));
305 }
306 
307 struct jit_context {
308 	int cleanup_addr; /* Epilogue code offset */
309 
310 	/*
311 	 * Program specific offsets of labels in the code; these rely on the
312 	 * JIT doing at least 2 passes, recording the position on the first
313 	 * pass, only to generate the correct offset on the second pass.
314 	 */
315 	int tail_call_direct_label;
316 	int tail_call_indirect_label;
317 };
318 
319 /* Maximum number of bytes emitted while JITing one eBPF insn */
320 #define BPF_MAX_INSN_SIZE	128
321 #define BPF_INSN_SAFETY		64
322 
323 /* Number of bytes emit_patch() needs to generate instructions */
324 #define X86_PATCH_SIZE		5
325 /* Number of bytes that will be skipped on tailcall */
326 #define X86_TAIL_CALL_OFFSET	(12 + ENDBR_INSN_SIZE)
327 
328 static void push_r9(u8 **pprog)
329 {
330 	u8 *prog = *pprog;
331 
332 	EMIT2(0x41, 0x51);   /* push r9 */
333 	*pprog = prog;
334 }
335 
336 static void pop_r9(u8 **pprog)
337 {
338 	u8 *prog = *pprog;
339 
340 	EMIT2(0x41, 0x59);   /* pop r9 */
341 	*pprog = prog;
342 }
343 
344 static void push_r12(u8 **pprog)
345 {
346 	u8 *prog = *pprog;
347 
348 	EMIT2(0x41, 0x54);   /* push r12 */
349 	*pprog = prog;
350 }
351 
352 static void push_callee_regs(u8 **pprog, bool *callee_regs_used)
353 {
354 	u8 *prog = *pprog;
355 
356 	if (callee_regs_used[0])
357 		EMIT1(0x53);         /* push rbx */
358 	if (callee_regs_used[1])
359 		EMIT2(0x41, 0x55);   /* push r13 */
360 	if (callee_regs_used[2])
361 		EMIT2(0x41, 0x56);   /* push r14 */
362 	if (callee_regs_used[3])
363 		EMIT2(0x41, 0x57);   /* push r15 */
364 	*pprog = prog;
365 }
366 
367 static void pop_r12(u8 **pprog)
368 {
369 	u8 *prog = *pprog;
370 
371 	EMIT2(0x41, 0x5C);   /* pop r12 */
372 	*pprog = prog;
373 }
374 
375 static void pop_callee_regs(u8 **pprog, bool *callee_regs_used)
376 {
377 	u8 *prog = *pprog;
378 
379 	if (callee_regs_used[3])
380 		EMIT2(0x41, 0x5F);   /* pop r15 */
381 	if (callee_regs_used[2])
382 		EMIT2(0x41, 0x5E);   /* pop r14 */
383 	if (callee_regs_used[1])
384 		EMIT2(0x41, 0x5D);   /* pop r13 */
385 	if (callee_regs_used[0])
386 		EMIT1(0x5B);         /* pop rbx */
387 	*pprog = prog;
388 }
389 
390 static void emit_nops(u8 **pprog, int len)
391 {
392 	u8 *prog = *pprog;
393 	int i, noplen;
394 
395 	while (len > 0) {
396 		noplen = len;
397 
398 		if (noplen > ASM_NOP_MAX)
399 			noplen = ASM_NOP_MAX;
400 
401 		for (i = 0; i < noplen; i++)
402 			EMIT1(x86_nops[noplen][i]);
403 		len -= noplen;
404 	}
405 
406 	*pprog = prog;
407 }
408 
409 /*
410  * Emit the various CFI preambles, see asm/cfi.h and the comments about FineIBT
411  * in arch/x86/kernel/alternative.c
412  */
413 
414 static void emit_fineibt(u8 **pprog, u32 hash)
415 {
416 	u8 *prog = *pprog;
417 
418 	EMIT_ENDBR();
419 	EMIT3_off32(0x41, 0x81, 0xea, hash);		/* subl $hash, %r10d	*/
420 	EMIT2(0x74, 0x07);				/* jz.d8 +7		*/
421 	EMIT2(0x0f, 0x0b);				/* ud2			*/
422 	EMIT1(0x90);					/* nop			*/
423 	EMIT_ENDBR_POISON();
424 
425 	*pprog = prog;
426 }
427 
428 static void emit_kcfi(u8 **pprog, u32 hash)
429 {
430 	u8 *prog = *pprog;
431 
432 	EMIT1_off32(0xb8, hash);			/* movl $hash, %eax	*/
433 #ifdef CONFIG_CALL_PADDING
434 	EMIT1(0x90);
435 	EMIT1(0x90);
436 	EMIT1(0x90);
437 	EMIT1(0x90);
438 	EMIT1(0x90);
439 	EMIT1(0x90);
440 	EMIT1(0x90);
441 	EMIT1(0x90);
442 	EMIT1(0x90);
443 	EMIT1(0x90);
444 	EMIT1(0x90);
445 #endif
446 	EMIT_ENDBR();
447 
448 	*pprog = prog;
449 }
450 
451 static void emit_cfi(u8 **pprog, u32 hash)
452 {
453 	u8 *prog = *pprog;
454 
455 	switch (cfi_mode) {
456 	case CFI_FINEIBT:
457 		emit_fineibt(&prog, hash);
458 		break;
459 
460 	case CFI_KCFI:
461 		emit_kcfi(&prog, hash);
462 		break;
463 
464 	default:
465 		EMIT_ENDBR();
466 		break;
467 	}
468 
469 	*pprog = prog;
470 }
471 
472 static void emit_prologue_tail_call(u8 **pprog, bool is_subprog)
473 {
474 	u8 *prog = *pprog;
475 
476 	if (!is_subprog) {
477 		/* cmp rax, MAX_TAIL_CALL_CNT */
478 		EMIT4(0x48, 0x83, 0xF8, MAX_TAIL_CALL_CNT);
479 		EMIT2(X86_JA, 6);        /* ja 6 */
480 		/* rax is tail_call_cnt if <= MAX_TAIL_CALL_CNT.
481 		 * case1: entry of main prog.
482 		 * case2: tail callee of main prog.
483 		 */
484 		EMIT1(0x50);             /* push rax */
485 		/* Make rax as tail_call_cnt_ptr. */
486 		EMIT3(0x48, 0x89, 0xE0); /* mov rax, rsp */
487 		EMIT2(0xEB, 1);          /* jmp 1 */
488 		/* rax is tail_call_cnt_ptr if > MAX_TAIL_CALL_CNT.
489 		 * case: tail callee of subprog.
490 		 */
491 		EMIT1(0x50);             /* push rax */
492 		/* push tail_call_cnt_ptr */
493 		EMIT1(0x50);             /* push rax */
494 	} else { /* is_subprog */
495 		/* rax is tail_call_cnt_ptr. */
496 		EMIT1(0x50);             /* push rax */
497 		EMIT1(0x50);             /* push rax */
498 	}
499 
500 	*pprog = prog;
501 }
502 
503 /*
504  * Emit x86-64 prologue code for BPF program.
505  * bpf_tail_call helper will skip the first X86_TAIL_CALL_OFFSET bytes
506  * while jumping to another program
507  */
508 static void emit_prologue(u8 **pprog, u32 stack_depth, bool ebpf_from_cbpf,
509 			  bool tail_call_reachable, bool is_subprog,
510 			  bool is_exception_cb)
511 {
512 	u8 *prog = *pprog;
513 
514 	emit_cfi(&prog, is_subprog ? cfi_bpf_subprog_hash : cfi_bpf_hash);
515 	/* BPF trampoline can be made to work without these nops,
516 	 * but let's waste 5 bytes for now and optimize later
517 	 */
518 	emit_nops(&prog, X86_PATCH_SIZE);
519 	if (!ebpf_from_cbpf) {
520 		if (tail_call_reachable && !is_subprog)
521 			/* When it's the entry of the whole tailcall context,
522 			 * zeroing rax means initialising tail_call_cnt.
523 			 */
524 			EMIT3(0x48, 0x31, 0xC0); /* xor rax, rax */
525 		else
526 			/* Keep the same instruction layout. */
527 			emit_nops(&prog, 3);     /* nop3 */
528 	}
529 	/* Exception callback receives FP as third parameter */
530 	if (is_exception_cb) {
531 		EMIT3(0x48, 0x89, 0xF4); /* mov rsp, rsi */
532 		EMIT3(0x48, 0x89, 0xD5); /* mov rbp, rdx */
533 		/* The main frame must have exception_boundary as true, so we
534 		 * first restore those callee-saved regs from stack, before
535 		 * reusing the stack frame.
536 		 */
537 		pop_callee_regs(&prog, all_callee_regs_used);
538 		pop_r12(&prog);
539 		/* Reset the stack frame. */
540 		EMIT3(0x48, 0x89, 0xEC); /* mov rsp, rbp */
541 	} else {
542 		EMIT1(0x55);             /* push rbp */
543 		EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
544 	}
545 
546 	/* X86_TAIL_CALL_OFFSET is here */
547 	EMIT_ENDBR();
548 
549 	/* sub rsp, rounded_stack_depth */
550 	if (stack_depth)
551 		EMIT3_off32(0x48, 0x81, 0xEC, round_up(stack_depth, 8));
552 	if (tail_call_reachable)
553 		emit_prologue_tail_call(&prog, is_subprog);
554 	*pprog = prog;
555 }
556 
557 static int emit_patch(u8 **pprog, void *func, void *ip, u8 opcode)
558 {
559 	u8 *prog = *pprog;
560 	s64 offset;
561 
562 	offset = func - (ip + X86_PATCH_SIZE);
563 	if (!is_simm32(offset)) {
564 		pr_err("Target call %p is out of range\n", func);
565 		return -ERANGE;
566 	}
567 	EMIT1_off32(opcode, offset);
568 	*pprog = prog;
569 	return 0;
570 }
571 
572 static int emit_call(u8 **pprog, void *func, void *ip)
573 {
574 	return emit_patch(pprog, func, ip, 0xE8);
575 }
576 
577 static int emit_rsb_call(u8 **pprog, void *func, void *ip)
578 {
579 	OPTIMIZER_HIDE_VAR(func);
580 	ip += x86_call_depth_emit_accounting(pprog, func, ip);
581 	return emit_patch(pprog, func, ip, 0xE8);
582 }
583 
584 static int emit_jump(u8 **pprog, void *func, void *ip)
585 {
586 	return emit_patch(pprog, func, ip, 0xE9);
587 }
588 
589 static int __bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
590 				void *old_addr, void *new_addr)
591 {
592 	const u8 *nop_insn = x86_nops[5];
593 	u8 old_insn[X86_PATCH_SIZE];
594 	u8 new_insn[X86_PATCH_SIZE];
595 	u8 *prog;
596 	int ret;
597 
598 	memcpy(old_insn, nop_insn, X86_PATCH_SIZE);
599 	if (old_addr) {
600 		prog = old_insn;
601 		ret = t == BPF_MOD_CALL ?
602 		      emit_call(&prog, old_addr, ip) :
603 		      emit_jump(&prog, old_addr, ip);
604 		if (ret)
605 			return ret;
606 	}
607 
608 	memcpy(new_insn, nop_insn, X86_PATCH_SIZE);
609 	if (new_addr) {
610 		prog = new_insn;
611 		ret = t == BPF_MOD_CALL ?
612 		      emit_call(&prog, new_addr, ip) :
613 		      emit_jump(&prog, new_addr, ip);
614 		if (ret)
615 			return ret;
616 	}
617 
618 	ret = -EBUSY;
619 	mutex_lock(&text_mutex);
620 	if (memcmp(ip, old_insn, X86_PATCH_SIZE))
621 		goto out;
622 	ret = 1;
623 	if (memcmp(ip, new_insn, X86_PATCH_SIZE)) {
624 		text_poke_bp(ip, new_insn, X86_PATCH_SIZE, NULL);
625 		ret = 0;
626 	}
627 out:
628 	mutex_unlock(&text_mutex);
629 	return ret;
630 }
631 
632 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
633 		       void *old_addr, void *new_addr)
634 {
635 	if (!is_kernel_text((long)ip) &&
636 	    !is_bpf_text_address((long)ip))
637 		/* BPF poking in modules is not supported */
638 		return -EINVAL;
639 
640 	/*
641 	 * See emit_prologue(), for IBT builds the trampoline hook is preceded
642 	 * with an ENDBR instruction.
643 	 */
644 	if (is_endbr(*(u32 *)ip))
645 		ip += ENDBR_INSN_SIZE;
646 
647 	return __bpf_arch_text_poke(ip, t, old_addr, new_addr);
648 }
649 
650 #define EMIT_LFENCE()	EMIT3(0x0F, 0xAE, 0xE8)
651 
652 static void emit_indirect_jump(u8 **pprog, int reg, u8 *ip)
653 {
654 	u8 *prog = *pprog;
655 
656 	if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
657 		EMIT_LFENCE();
658 		EMIT2(0xFF, 0xE0 + reg);
659 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
660 		OPTIMIZER_HIDE_VAR(reg);
661 		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
662 			emit_jump(&prog, &__x86_indirect_jump_thunk_array[reg], ip);
663 		else
664 			emit_jump(&prog, &__x86_indirect_thunk_array[reg], ip);
665 	} else {
666 		EMIT2(0xFF, 0xE0 + reg);	/* jmp *%\reg */
667 		if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) || IS_ENABLED(CONFIG_MITIGATION_SLS))
668 			EMIT1(0xCC);		/* int3 */
669 	}
670 
671 	*pprog = prog;
672 }
673 
674 static void emit_return(u8 **pprog, u8 *ip)
675 {
676 	u8 *prog = *pprog;
677 
678 	if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) {
679 		emit_jump(&prog, x86_return_thunk, ip);
680 	} else {
681 		EMIT1(0xC3);		/* ret */
682 		if (IS_ENABLED(CONFIG_MITIGATION_SLS))
683 			EMIT1(0xCC);	/* int3 */
684 	}
685 
686 	*pprog = prog;
687 }
688 
689 #define BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack)	(-16 - round_up(stack, 8))
690 
691 /*
692  * Generate the following code:
693  *
694  * ... bpf_tail_call(void *ctx, struct bpf_array *array, u64 index) ...
695  *   if (index >= array->map.max_entries)
696  *     goto out;
697  *   if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
698  *     goto out;
699  *   prog = array->ptrs[index];
700  *   if (prog == NULL)
701  *     goto out;
702  *   goto *(prog->bpf_func + prologue_size);
703  * out:
704  */
705 static void emit_bpf_tail_call_indirect(struct bpf_prog *bpf_prog,
706 					u8 **pprog, bool *callee_regs_used,
707 					u32 stack_depth, u8 *ip,
708 					struct jit_context *ctx)
709 {
710 	int tcc_ptr_off = BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack_depth);
711 	u8 *prog = *pprog, *start = *pprog;
712 	int offset;
713 
714 	/*
715 	 * rdi - pointer to ctx
716 	 * rsi - pointer to bpf_array
717 	 * rdx - index in bpf_array
718 	 */
719 
720 	/*
721 	 * if (index >= array->map.max_entries)
722 	 *	goto out;
723 	 */
724 	EMIT2(0x89, 0xD2);                        /* mov edx, edx */
725 	EMIT3(0x39, 0x56,                         /* cmp dword ptr [rsi + 16], edx */
726 	      offsetof(struct bpf_array, map.max_entries));
727 
728 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
729 	EMIT2(X86_JBE, offset);                   /* jbe out */
730 
731 	/*
732 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
733 	 *	goto out;
734 	 */
735 	EMIT3_off32(0x48, 0x8B, 0x85, tcc_ptr_off); /* mov rax, qword ptr [rbp - tcc_ptr_off] */
736 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT); /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
737 
738 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
739 	EMIT2(X86_JAE, offset);                   /* jae out */
740 
741 	/* prog = array->ptrs[index]; */
742 	EMIT4_off32(0x48, 0x8B, 0x8C, 0xD6,       /* mov rcx, [rsi + rdx * 8 + offsetof(...)] */
743 		    offsetof(struct bpf_array, ptrs));
744 
745 	/*
746 	 * if (prog == NULL)
747 	 *	goto out;
748 	 */
749 	EMIT3(0x48, 0x85, 0xC9);                  /* test rcx,rcx */
750 
751 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
752 	EMIT2(X86_JE, offset);                    /* je out */
753 
754 	/* Inc tail_call_cnt if the slot is populated. */
755 	EMIT4(0x48, 0x83, 0x00, 0x01);            /* add qword ptr [rax], 1 */
756 
757 	if (bpf_prog->aux->exception_boundary) {
758 		pop_callee_regs(&prog, all_callee_regs_used);
759 		pop_r12(&prog);
760 	} else {
761 		pop_callee_regs(&prog, callee_regs_used);
762 		if (bpf_arena_get_kern_vm_start(bpf_prog->aux->arena))
763 			pop_r12(&prog);
764 	}
765 
766 	/* Pop tail_call_cnt_ptr. */
767 	EMIT1(0x58);                              /* pop rax */
768 	/* Pop tail_call_cnt, if it's main prog.
769 	 * Pop tail_call_cnt_ptr, if it's subprog.
770 	 */
771 	EMIT1(0x58);                              /* pop rax */
772 	if (stack_depth)
773 		EMIT3_off32(0x48, 0x81, 0xC4,     /* add rsp, sd */
774 			    round_up(stack_depth, 8));
775 
776 	/* goto *(prog->bpf_func + X86_TAIL_CALL_OFFSET); */
777 	EMIT4(0x48, 0x8B, 0x49,                   /* mov rcx, qword ptr [rcx + 32] */
778 	      offsetof(struct bpf_prog, bpf_func));
779 	EMIT4(0x48, 0x83, 0xC1,                   /* add rcx, X86_TAIL_CALL_OFFSET */
780 	      X86_TAIL_CALL_OFFSET);
781 	/*
782 	 * Now we're ready to jump into next BPF program
783 	 * rdi == ctx (1st arg)
784 	 * rcx == prog->bpf_func + X86_TAIL_CALL_OFFSET
785 	 */
786 	emit_indirect_jump(&prog, 1 /* rcx */, ip + (prog - start));
787 
788 	/* out: */
789 	ctx->tail_call_indirect_label = prog - start;
790 	*pprog = prog;
791 }
792 
793 static void emit_bpf_tail_call_direct(struct bpf_prog *bpf_prog,
794 				      struct bpf_jit_poke_descriptor *poke,
795 				      u8 **pprog, u8 *ip,
796 				      bool *callee_regs_used, u32 stack_depth,
797 				      struct jit_context *ctx)
798 {
799 	int tcc_ptr_off = BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack_depth);
800 	u8 *prog = *pprog, *start = *pprog;
801 	int offset;
802 
803 	/*
804 	 * if ((*tcc_ptr)++ >= MAX_TAIL_CALL_CNT)
805 	 *	goto out;
806 	 */
807 	EMIT3_off32(0x48, 0x8B, 0x85, tcc_ptr_off);   /* mov rax, qword ptr [rbp - tcc_ptr_off] */
808 	EMIT4(0x48, 0x83, 0x38, MAX_TAIL_CALL_CNT);   /* cmp qword ptr [rax], MAX_TAIL_CALL_CNT */
809 
810 	offset = ctx->tail_call_direct_label - (prog + 2 - start);
811 	EMIT2(X86_JAE, offset);                       /* jae out */
812 
813 	poke->tailcall_bypass = ip + (prog - start);
814 	poke->adj_off = X86_TAIL_CALL_OFFSET;
815 	poke->tailcall_target = ip + ctx->tail_call_direct_label - X86_PATCH_SIZE;
816 	poke->bypass_addr = (u8 *)poke->tailcall_target + X86_PATCH_SIZE;
817 
818 	emit_jump(&prog, (u8 *)poke->tailcall_target + X86_PATCH_SIZE,
819 		  poke->tailcall_bypass);
820 
821 	/* Inc tail_call_cnt if the slot is populated. */
822 	EMIT4(0x48, 0x83, 0x00, 0x01);                /* add qword ptr [rax], 1 */
823 
824 	if (bpf_prog->aux->exception_boundary) {
825 		pop_callee_regs(&prog, all_callee_regs_used);
826 		pop_r12(&prog);
827 	} else {
828 		pop_callee_regs(&prog, callee_regs_used);
829 		if (bpf_arena_get_kern_vm_start(bpf_prog->aux->arena))
830 			pop_r12(&prog);
831 	}
832 
833 	/* Pop tail_call_cnt_ptr. */
834 	EMIT1(0x58);                                  /* pop rax */
835 	/* Pop tail_call_cnt, if it's main prog.
836 	 * Pop tail_call_cnt_ptr, if it's subprog.
837 	 */
838 	EMIT1(0x58);                                  /* pop rax */
839 	if (stack_depth)
840 		EMIT3_off32(0x48, 0x81, 0xC4, round_up(stack_depth, 8));
841 
842 	emit_nops(&prog, X86_PATCH_SIZE);
843 
844 	/* out: */
845 	ctx->tail_call_direct_label = prog - start;
846 
847 	*pprog = prog;
848 }
849 
850 static void bpf_tail_call_direct_fixup(struct bpf_prog *prog)
851 {
852 	struct bpf_jit_poke_descriptor *poke;
853 	struct bpf_array *array;
854 	struct bpf_prog *target;
855 	int i, ret;
856 
857 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
858 		poke = &prog->aux->poke_tab[i];
859 		if (poke->aux && poke->aux != prog->aux)
860 			continue;
861 
862 		WARN_ON_ONCE(READ_ONCE(poke->tailcall_target_stable));
863 
864 		if (poke->reason != BPF_POKE_REASON_TAIL_CALL)
865 			continue;
866 
867 		array = container_of(poke->tail_call.map, struct bpf_array, map);
868 		mutex_lock(&array->aux->poke_mutex);
869 		target = array->ptrs[poke->tail_call.key];
870 		if (target) {
871 			ret = __bpf_arch_text_poke(poke->tailcall_target,
872 						   BPF_MOD_JUMP, NULL,
873 						   (u8 *)target->bpf_func +
874 						   poke->adj_off);
875 			BUG_ON(ret < 0);
876 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
877 						   BPF_MOD_JUMP,
878 						   (u8 *)poke->tailcall_target +
879 						   X86_PATCH_SIZE, NULL);
880 			BUG_ON(ret < 0);
881 		}
882 		WRITE_ONCE(poke->tailcall_target_stable, true);
883 		mutex_unlock(&array->aux->poke_mutex);
884 	}
885 }
886 
887 static void emit_mov_imm32(u8 **pprog, bool sign_propagate,
888 			   u32 dst_reg, const u32 imm32)
889 {
890 	u8 *prog = *pprog;
891 	u8 b1, b2, b3;
892 
893 	/*
894 	 * Optimization: if imm32 is positive, use 'mov %eax, imm32'
895 	 * (which zero-extends imm32) to save 2 bytes.
896 	 */
897 	if (sign_propagate && (s32)imm32 < 0) {
898 		/* 'mov %rax, imm32' sign extends imm32 */
899 		b1 = add_1mod(0x48, dst_reg);
900 		b2 = 0xC7;
901 		b3 = 0xC0;
902 		EMIT3_off32(b1, b2, add_1reg(b3, dst_reg), imm32);
903 		goto done;
904 	}
905 
906 	/*
907 	 * Optimization: if imm32 is zero, use 'xor %eax, %eax'
908 	 * to save 3 bytes.
909 	 */
910 	if (imm32 == 0) {
911 		if (is_ereg(dst_reg))
912 			EMIT1(add_2mod(0x40, dst_reg, dst_reg));
913 		b2 = 0x31; /* xor */
914 		b3 = 0xC0;
915 		EMIT2(b2, add_2reg(b3, dst_reg, dst_reg));
916 		goto done;
917 	}
918 
919 	/* mov %eax, imm32 */
920 	if (is_ereg(dst_reg))
921 		EMIT1(add_1mod(0x40, dst_reg));
922 	EMIT1_off32(add_1reg(0xB8, dst_reg), imm32);
923 done:
924 	*pprog = prog;
925 }
926 
927 static void emit_mov_imm64(u8 **pprog, u32 dst_reg,
928 			   const u32 imm32_hi, const u32 imm32_lo)
929 {
930 	u64 imm64 = ((u64)imm32_hi << 32) | (u32)imm32_lo;
931 	u8 *prog = *pprog;
932 
933 	if (is_uimm32(imm64)) {
934 		/*
935 		 * For emitting plain u32, where sign bit must not be
936 		 * propagated LLVM tends to load imm64 over mov32
937 		 * directly, so save couple of bytes by just doing
938 		 * 'mov %eax, imm32' instead.
939 		 */
940 		emit_mov_imm32(&prog, false, dst_reg, imm32_lo);
941 	} else if (is_simm32(imm64)) {
942 		emit_mov_imm32(&prog, true, dst_reg, imm32_lo);
943 	} else {
944 		/* movabsq rax, imm64 */
945 		EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg));
946 		EMIT(imm32_lo, 4);
947 		EMIT(imm32_hi, 4);
948 	}
949 
950 	*pprog = prog;
951 }
952 
953 static void emit_mov_reg(u8 **pprog, bool is64, u32 dst_reg, u32 src_reg)
954 {
955 	u8 *prog = *pprog;
956 
957 	if (is64) {
958 		/* mov dst, src */
959 		EMIT_mov(dst_reg, src_reg);
960 	} else {
961 		/* mov32 dst, src */
962 		if (is_ereg(dst_reg) || is_ereg(src_reg))
963 			EMIT1(add_2mod(0x40, dst_reg, src_reg));
964 		EMIT2(0x89, add_2reg(0xC0, dst_reg, src_reg));
965 	}
966 
967 	*pprog = prog;
968 }
969 
970 static void emit_movsx_reg(u8 **pprog, int num_bits, bool is64, u32 dst_reg,
971 			   u32 src_reg)
972 {
973 	u8 *prog = *pprog;
974 
975 	if (is64) {
976 		/* movs[b,w,l]q dst, src */
977 		if (num_bits == 8)
978 			EMIT4(add_2mod(0x48, src_reg, dst_reg), 0x0f, 0xbe,
979 			      add_2reg(0xC0, src_reg, dst_reg));
980 		else if (num_bits == 16)
981 			EMIT4(add_2mod(0x48, src_reg, dst_reg), 0x0f, 0xbf,
982 			      add_2reg(0xC0, src_reg, dst_reg));
983 		else if (num_bits == 32)
984 			EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x63,
985 			      add_2reg(0xC0, src_reg, dst_reg));
986 	} else {
987 		/* movs[b,w]l dst, src */
988 		if (num_bits == 8) {
989 			EMIT4(add_2mod(0x40, src_reg, dst_reg), 0x0f, 0xbe,
990 			      add_2reg(0xC0, src_reg, dst_reg));
991 		} else if (num_bits == 16) {
992 			if (is_ereg(dst_reg) || is_ereg(src_reg))
993 				EMIT1(add_2mod(0x40, src_reg, dst_reg));
994 			EMIT3(add_2mod(0x0f, src_reg, dst_reg), 0xbf,
995 			      add_2reg(0xC0, src_reg, dst_reg));
996 		}
997 	}
998 
999 	*pprog = prog;
1000 }
1001 
1002 /* Emit the suffix (ModR/M etc) for addressing *(ptr_reg + off) and val_reg */
1003 static void emit_insn_suffix(u8 **pprog, u32 ptr_reg, u32 val_reg, int off)
1004 {
1005 	u8 *prog = *pprog;
1006 
1007 	if (is_imm8(off)) {
1008 		/* 1-byte signed displacement.
1009 		 *
1010 		 * If off == 0 we could skip this and save one extra byte, but
1011 		 * special case of x86 R13 which always needs an offset is not
1012 		 * worth the hassle
1013 		 */
1014 		EMIT2(add_2reg(0x40, ptr_reg, val_reg), off);
1015 	} else {
1016 		/* 4-byte signed displacement */
1017 		EMIT1_off32(add_2reg(0x80, ptr_reg, val_reg), off);
1018 	}
1019 	*pprog = prog;
1020 }
1021 
1022 static void emit_insn_suffix_SIB(u8 **pprog, u32 ptr_reg, u32 val_reg, u32 index_reg, int off)
1023 {
1024 	u8 *prog = *pprog;
1025 
1026 	if (is_imm8(off)) {
1027 		EMIT3(add_2reg(0x44, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
1028 	} else {
1029 		EMIT2_off32(add_2reg(0x84, BPF_REG_0, val_reg), add_2reg(0, ptr_reg, index_reg) /* SIB */, off);
1030 	}
1031 	*pprog = prog;
1032 }
1033 
1034 /*
1035  * Emit a REX byte if it will be necessary to address these registers
1036  */
1037 static void maybe_emit_mod(u8 **pprog, u32 dst_reg, u32 src_reg, bool is64)
1038 {
1039 	u8 *prog = *pprog;
1040 
1041 	if (is64)
1042 		EMIT1(add_2mod(0x48, dst_reg, src_reg));
1043 	else if (is_ereg(dst_reg) || is_ereg(src_reg))
1044 		EMIT1(add_2mod(0x40, dst_reg, src_reg));
1045 	*pprog = prog;
1046 }
1047 
1048 /*
1049  * Similar version of maybe_emit_mod() for a single register
1050  */
1051 static void maybe_emit_1mod(u8 **pprog, u32 reg, bool is64)
1052 {
1053 	u8 *prog = *pprog;
1054 
1055 	if (is64)
1056 		EMIT1(add_1mod(0x48, reg));
1057 	else if (is_ereg(reg))
1058 		EMIT1(add_1mod(0x40, reg));
1059 	*pprog = prog;
1060 }
1061 
1062 /* LDX: dst_reg = *(u8*)(src_reg + off) */
1063 static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1064 {
1065 	u8 *prog = *pprog;
1066 
1067 	switch (size) {
1068 	case BPF_B:
1069 		/* Emit 'movzx rax, byte ptr [rax + off]' */
1070 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB6);
1071 		break;
1072 	case BPF_H:
1073 		/* Emit 'movzx rax, word ptr [rax + off]' */
1074 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB7);
1075 		break;
1076 	case BPF_W:
1077 		/* Emit 'mov eax, dword ptr [rax+0x14]' */
1078 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1079 			EMIT2(add_2mod(0x40, src_reg, dst_reg), 0x8B);
1080 		else
1081 			EMIT1(0x8B);
1082 		break;
1083 	case BPF_DW:
1084 		/* Emit 'mov rax, qword ptr [rax+0x14]' */
1085 		EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x8B);
1086 		break;
1087 	}
1088 	emit_insn_suffix(&prog, src_reg, dst_reg, off);
1089 	*pprog = prog;
1090 }
1091 
1092 /* LDSX: dst_reg = *(s8*)(src_reg + off) */
1093 static void emit_ldsx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1094 {
1095 	u8 *prog = *pprog;
1096 
1097 	switch (size) {
1098 	case BPF_B:
1099 		/* Emit 'movsx rax, byte ptr [rax + off]' */
1100 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xBE);
1101 		break;
1102 	case BPF_H:
1103 		/* Emit 'movsx rax, word ptr [rax + off]' */
1104 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xBF);
1105 		break;
1106 	case BPF_W:
1107 		/* Emit 'movsx rax, dword ptr [rax+0x14]' */
1108 		EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x63);
1109 		break;
1110 	}
1111 	emit_insn_suffix(&prog, src_reg, dst_reg, off);
1112 	*pprog = prog;
1113 }
1114 
1115 static void emit_ldx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 index_reg, int off)
1116 {
1117 	u8 *prog = *pprog;
1118 
1119 	switch (size) {
1120 	case BPF_B:
1121 		/* movzx rax, byte ptr [rax + r12 + off] */
1122 		EMIT3(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x0F, 0xB6);
1123 		break;
1124 	case BPF_H:
1125 		/* movzx rax, word ptr [rax + r12 + off] */
1126 		EMIT3(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x0F, 0xB7);
1127 		break;
1128 	case BPF_W:
1129 		/* mov eax, dword ptr [rax + r12 + off] */
1130 		EMIT2(add_3mod(0x40, src_reg, dst_reg, index_reg), 0x8B);
1131 		break;
1132 	case BPF_DW:
1133 		/* mov rax, qword ptr [rax + r12 + off] */
1134 		EMIT2(add_3mod(0x48, src_reg, dst_reg, index_reg), 0x8B);
1135 		break;
1136 	}
1137 	emit_insn_suffix_SIB(&prog, src_reg, dst_reg, index_reg, off);
1138 	*pprog = prog;
1139 }
1140 
1141 static void emit_ldx_r12(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1142 {
1143 	emit_ldx_index(pprog, size, dst_reg, src_reg, X86_REG_R12, off);
1144 }
1145 
1146 /* STX: *(u8*)(dst_reg + off) = src_reg */
1147 static void emit_stx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1148 {
1149 	u8 *prog = *pprog;
1150 
1151 	switch (size) {
1152 	case BPF_B:
1153 		/* Emit 'mov byte ptr [rax + off], al' */
1154 		if (is_ereg(dst_reg) || is_ereg_8l(src_reg))
1155 			/* Add extra byte for eregs or SIL,DIL,BPL in src_reg */
1156 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x88);
1157 		else
1158 			EMIT1(0x88);
1159 		break;
1160 	case BPF_H:
1161 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1162 			EMIT3(0x66, add_2mod(0x40, dst_reg, src_reg), 0x89);
1163 		else
1164 			EMIT2(0x66, 0x89);
1165 		break;
1166 	case BPF_W:
1167 		if (is_ereg(dst_reg) || is_ereg(src_reg))
1168 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x89);
1169 		else
1170 			EMIT1(0x89);
1171 		break;
1172 	case BPF_DW:
1173 		EMIT2(add_2mod(0x48, dst_reg, src_reg), 0x89);
1174 		break;
1175 	}
1176 	emit_insn_suffix(&prog, dst_reg, src_reg, off);
1177 	*pprog = prog;
1178 }
1179 
1180 /* STX: *(u8*)(dst_reg + index_reg + off) = src_reg */
1181 static void emit_stx_index(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, u32 index_reg, int off)
1182 {
1183 	u8 *prog = *pprog;
1184 
1185 	switch (size) {
1186 	case BPF_B:
1187 		/* mov byte ptr [rax + r12 + off], al */
1188 		EMIT2(add_3mod(0x40, dst_reg, src_reg, index_reg), 0x88);
1189 		break;
1190 	case BPF_H:
1191 		/* mov word ptr [rax + r12 + off], ax */
1192 		EMIT3(0x66, add_3mod(0x40, dst_reg, src_reg, index_reg), 0x89);
1193 		break;
1194 	case BPF_W:
1195 		/* mov dword ptr [rax + r12 + 1], eax */
1196 		EMIT2(add_3mod(0x40, dst_reg, src_reg, index_reg), 0x89);
1197 		break;
1198 	case BPF_DW:
1199 		/* mov qword ptr [rax + r12 + 1], rax */
1200 		EMIT2(add_3mod(0x48, dst_reg, src_reg, index_reg), 0x89);
1201 		break;
1202 	}
1203 	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off);
1204 	*pprog = prog;
1205 }
1206 
1207 static void emit_stx_r12(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
1208 {
1209 	emit_stx_index(pprog, size, dst_reg, src_reg, X86_REG_R12, off);
1210 }
1211 
1212 /* ST: *(u8*)(dst_reg + index_reg + off) = imm32 */
1213 static void emit_st_index(u8 **pprog, u32 size, u32 dst_reg, u32 index_reg, int off, int imm)
1214 {
1215 	u8 *prog = *pprog;
1216 
1217 	switch (size) {
1218 	case BPF_B:
1219 		/* mov byte ptr [rax + r12 + off], imm8 */
1220 		EMIT2(add_3mod(0x40, dst_reg, 0, index_reg), 0xC6);
1221 		break;
1222 	case BPF_H:
1223 		/* mov word ptr [rax + r12 + off], imm16 */
1224 		EMIT3(0x66, add_3mod(0x40, dst_reg, 0, index_reg), 0xC7);
1225 		break;
1226 	case BPF_W:
1227 		/* mov dword ptr [rax + r12 + 1], imm32 */
1228 		EMIT2(add_3mod(0x40, dst_reg, 0, index_reg), 0xC7);
1229 		break;
1230 	case BPF_DW:
1231 		/* mov qword ptr [rax + r12 + 1], imm32 */
1232 		EMIT2(add_3mod(0x48, dst_reg, 0, index_reg), 0xC7);
1233 		break;
1234 	}
1235 	emit_insn_suffix_SIB(&prog, dst_reg, 0, index_reg, off);
1236 	EMIT(imm, bpf_size_to_x86_bytes(size));
1237 	*pprog = prog;
1238 }
1239 
1240 static void emit_st_r12(u8 **pprog, u32 size, u32 dst_reg, int off, int imm)
1241 {
1242 	emit_st_index(pprog, size, dst_reg, X86_REG_R12, off, imm);
1243 }
1244 
1245 static int emit_atomic_rmw(u8 **pprog, u32 atomic_op,
1246 			   u32 dst_reg, u32 src_reg, s16 off, u8 bpf_size)
1247 {
1248 	u8 *prog = *pprog;
1249 
1250 	EMIT1(0xF0); /* lock prefix */
1251 
1252 	maybe_emit_mod(&prog, dst_reg, src_reg, bpf_size == BPF_DW);
1253 
1254 	/* emit opcode */
1255 	switch (atomic_op) {
1256 	case BPF_ADD:
1257 	case BPF_AND:
1258 	case BPF_OR:
1259 	case BPF_XOR:
1260 		/* lock *(u32/u64*)(dst_reg + off) <op>= src_reg */
1261 		EMIT1(simple_alu_opcodes[atomic_op]);
1262 		break;
1263 	case BPF_ADD | BPF_FETCH:
1264 		/* src_reg = atomic_fetch_add(dst_reg + off, src_reg); */
1265 		EMIT2(0x0F, 0xC1);
1266 		break;
1267 	case BPF_XCHG:
1268 		/* src_reg = atomic_xchg(dst_reg + off, src_reg); */
1269 		EMIT1(0x87);
1270 		break;
1271 	case BPF_CMPXCHG:
1272 		/* r0 = atomic_cmpxchg(dst_reg + off, r0, src_reg); */
1273 		EMIT2(0x0F, 0xB1);
1274 		break;
1275 	default:
1276 		pr_err("bpf_jit: unknown atomic opcode %02x\n", atomic_op);
1277 		return -EFAULT;
1278 	}
1279 
1280 	emit_insn_suffix(&prog, dst_reg, src_reg, off);
1281 
1282 	*pprog = prog;
1283 	return 0;
1284 }
1285 
1286 static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size,
1287 				 u32 dst_reg, u32 src_reg, u32 index_reg,
1288 				 int off)
1289 {
1290 	u8 *prog = *pprog;
1291 
1292 	EMIT1(0xF0); /* lock prefix */
1293 	switch (size) {
1294 	case BPF_W:
1295 		EMIT1(add_3mod(0x40, dst_reg, src_reg, index_reg));
1296 		break;
1297 	case BPF_DW:
1298 		EMIT1(add_3mod(0x48, dst_reg, src_reg, index_reg));
1299 		break;
1300 	default:
1301 		pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
1302 		return -EFAULT;
1303 	}
1304 
1305 	/* emit opcode */
1306 	switch (atomic_op) {
1307 	case BPF_ADD:
1308 	case BPF_AND:
1309 	case BPF_OR:
1310 	case BPF_XOR:
1311 		/* lock *(u32/u64*)(dst_reg + idx_reg + off) <op>= src_reg */
1312 		EMIT1(simple_alu_opcodes[atomic_op]);
1313 		break;
1314 	case BPF_ADD | BPF_FETCH:
1315 		/* src_reg = atomic_fetch_add(dst_reg + idx_reg + off, src_reg); */
1316 		EMIT2(0x0F, 0xC1);
1317 		break;
1318 	case BPF_XCHG:
1319 		/* src_reg = atomic_xchg(dst_reg + idx_reg + off, src_reg); */
1320 		EMIT1(0x87);
1321 		break;
1322 	case BPF_CMPXCHG:
1323 		/* r0 = atomic_cmpxchg(dst_reg + idx_reg + off, r0, src_reg); */
1324 		EMIT2(0x0F, 0xB1);
1325 		break;
1326 	default:
1327 		pr_err("bpf_jit: unknown atomic opcode %02x\n", atomic_op);
1328 		return -EFAULT;
1329 	}
1330 	emit_insn_suffix_SIB(&prog, dst_reg, src_reg, index_reg, off);
1331 	*pprog = prog;
1332 	return 0;
1333 }
1334 
1335 static int emit_atomic_ld_st(u8 **pprog, u32 atomic_op, u32 dst_reg,
1336 			     u32 src_reg, s16 off, u8 bpf_size)
1337 {
1338 	switch (atomic_op) {
1339 	case BPF_LOAD_ACQ:
1340 		/* dst_reg = smp_load_acquire(src_reg + off16) */
1341 		emit_ldx(pprog, bpf_size, dst_reg, src_reg, off);
1342 		break;
1343 	case BPF_STORE_REL:
1344 		/* smp_store_release(dst_reg + off16, src_reg) */
1345 		emit_stx(pprog, bpf_size, dst_reg, src_reg, off);
1346 		break;
1347 	default:
1348 		pr_err("bpf_jit: unknown atomic load/store opcode %02x\n",
1349 		       atomic_op);
1350 		return -EFAULT;
1351 	}
1352 
1353 	return 0;
1354 }
1355 
1356 static int emit_atomic_ld_st_index(u8 **pprog, u32 atomic_op, u32 size,
1357 				   u32 dst_reg, u32 src_reg, u32 index_reg,
1358 				   int off)
1359 {
1360 	switch (atomic_op) {
1361 	case BPF_LOAD_ACQ:
1362 		/* dst_reg = smp_load_acquire(src_reg + idx_reg + off16) */
1363 		emit_ldx_index(pprog, size, dst_reg, src_reg, index_reg, off);
1364 		break;
1365 	case BPF_STORE_REL:
1366 		/* smp_store_release(dst_reg + idx_reg + off16, src_reg) */
1367 		emit_stx_index(pprog, size, dst_reg, src_reg, index_reg, off);
1368 		break;
1369 	default:
1370 		pr_err("bpf_jit: unknown atomic load/store opcode %02x\n",
1371 		       atomic_op);
1372 		return -EFAULT;
1373 	}
1374 
1375 	return 0;
1376 }
1377 
1378 #define DONT_CLEAR 1
1379 
1380 bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
1381 {
1382 	u32 reg = x->fixup >> 8;
1383 
1384 	/* jump over faulting load and clear dest register */
1385 	if (reg != DONT_CLEAR)
1386 		*(unsigned long *)((void *)regs + reg) = 0;
1387 	regs->ip += x->fixup & 0xff;
1388 	return true;
1389 }
1390 
1391 static void detect_reg_usage(struct bpf_insn *insn, int insn_cnt,
1392 			     bool *regs_used)
1393 {
1394 	int i;
1395 
1396 	for (i = 1; i <= insn_cnt; i++, insn++) {
1397 		if (insn->dst_reg == BPF_REG_6 || insn->src_reg == BPF_REG_6)
1398 			regs_used[0] = true;
1399 		if (insn->dst_reg == BPF_REG_7 || insn->src_reg == BPF_REG_7)
1400 			regs_used[1] = true;
1401 		if (insn->dst_reg == BPF_REG_8 || insn->src_reg == BPF_REG_8)
1402 			regs_used[2] = true;
1403 		if (insn->dst_reg == BPF_REG_9 || insn->src_reg == BPF_REG_9)
1404 			regs_used[3] = true;
1405 	}
1406 }
1407 
1408 /* emit the 3-byte VEX prefix
1409  *
1410  * r: same as rex.r, extra bit for ModRM reg field
1411  * x: same as rex.x, extra bit for SIB index field
1412  * b: same as rex.b, extra bit for ModRM r/m, or SIB base
1413  * m: opcode map select, encoding escape bytes e.g. 0x0f38
1414  * w: same as rex.w (32 bit or 64 bit) or opcode specific
1415  * src_reg2: additional source reg (encoded as BPF reg)
1416  * l: vector length (128 bit or 256 bit) or reserved
1417  * pp: opcode prefix (none, 0x66, 0xf2 or 0xf3)
1418  */
1419 static void emit_3vex(u8 **pprog, bool r, bool x, bool b, u8 m,
1420 		      bool w, u8 src_reg2, bool l, u8 pp)
1421 {
1422 	u8 *prog = *pprog;
1423 	const u8 b0 = 0xc4; /* first byte of 3-byte VEX prefix */
1424 	u8 b1, b2;
1425 	u8 vvvv = reg2hex[src_reg2];
1426 
1427 	/* reg2hex gives only the lower 3 bit of vvvv */
1428 	if (is_ereg(src_reg2))
1429 		vvvv |= 1 << 3;
1430 
1431 	/*
1432 	 * 2nd byte of 3-byte VEX prefix
1433 	 * ~ means bit inverted encoding
1434 	 *
1435 	 *    7                           0
1436 	 *  +---+---+---+---+---+---+---+---+
1437 	 *  |~R |~X |~B |         m         |
1438 	 *  +---+---+---+---+---+---+---+---+
1439 	 */
1440 	b1 = (!r << 7) | (!x << 6) | (!b << 5) | (m & 0x1f);
1441 	/*
1442 	 * 3rd byte of 3-byte VEX prefix
1443 	 *
1444 	 *    7                           0
1445 	 *  +---+---+---+---+---+---+---+---+
1446 	 *  | W |     ~vvvv     | L |   pp  |
1447 	 *  +---+---+---+---+---+---+---+---+
1448 	 */
1449 	b2 = (w << 7) | ((~vvvv & 0xf) << 3) | (l << 2) | (pp & 3);
1450 
1451 	EMIT3(b0, b1, b2);
1452 	*pprog = prog;
1453 }
1454 
1455 /* emit BMI2 shift instruction */
1456 static void emit_shiftx(u8 **pprog, u32 dst_reg, u8 src_reg, bool is64, u8 op)
1457 {
1458 	u8 *prog = *pprog;
1459 	bool r = is_ereg(dst_reg);
1460 	u8 m = 2; /* escape code 0f38 */
1461 
1462 	emit_3vex(&prog, r, false, r, m, is64, src_reg, false, op);
1463 	EMIT2(0xf7, add_2reg(0xC0, dst_reg, dst_reg));
1464 	*pprog = prog;
1465 }
1466 
1467 static void emit_priv_frame_ptr(u8 **pprog, void __percpu *priv_frame_ptr)
1468 {
1469 	u8 *prog = *pprog;
1470 
1471 	/* movabs r9, priv_frame_ptr */
1472 	emit_mov_imm64(&prog, X86_REG_R9, (__force long) priv_frame_ptr >> 32,
1473 		       (u32) (__force long) priv_frame_ptr);
1474 
1475 #ifdef CONFIG_SMP
1476 	/* add <r9>, gs:[<off>] */
1477 	EMIT2(0x65, 0x4c);
1478 	EMIT3(0x03, 0x0c, 0x25);
1479 	EMIT((u32)(unsigned long)&this_cpu_off, 4);
1480 #endif
1481 
1482 	*pprog = prog;
1483 }
1484 
1485 #define INSN_SZ_DIFF (((addrs[i] - addrs[i - 1]) - (prog - temp)))
1486 
1487 #define __LOAD_TCC_PTR(off)			\
1488 	EMIT3_off32(0x48, 0x8B, 0x85, off)
1489 /* mov rax, qword ptr [rbp - rounded_stack_depth - 16] */
1490 #define LOAD_TAIL_CALL_CNT_PTR(stack)				\
1491 	__LOAD_TCC_PTR(BPF_TAIL_CALL_CNT_PTR_STACK_OFF(stack))
1492 
1493 /* Memory size/value to protect private stack overflow/underflow */
1494 #define PRIV_STACK_GUARD_SZ    8
1495 #define PRIV_STACK_GUARD_VAL   0xEB9F12345678eb9fULL
1496 
1497 static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image, u8 *rw_image,
1498 		  int oldproglen, struct jit_context *ctx, bool jmp_padding)
1499 {
1500 	bool tail_call_reachable = bpf_prog->aux->tail_call_reachable;
1501 	struct bpf_insn *insn = bpf_prog->insnsi;
1502 	bool callee_regs_used[4] = {};
1503 	int insn_cnt = bpf_prog->len;
1504 	bool seen_exit = false;
1505 	u8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY];
1506 	void __percpu *priv_frame_ptr = NULL;
1507 	u64 arena_vm_start, user_vm_start;
1508 	void __percpu *priv_stack_ptr;
1509 	int i, excnt = 0;
1510 	int ilen, proglen = 0;
1511 	u8 *prog = temp;
1512 	u32 stack_depth;
1513 	int err;
1514 
1515 	stack_depth = bpf_prog->aux->stack_depth;
1516 	priv_stack_ptr = bpf_prog->aux->priv_stack_ptr;
1517 	if (priv_stack_ptr) {
1518 		priv_frame_ptr = priv_stack_ptr + PRIV_STACK_GUARD_SZ + round_up(stack_depth, 8);
1519 		stack_depth = 0;
1520 	}
1521 
1522 	arena_vm_start = bpf_arena_get_kern_vm_start(bpf_prog->aux->arena);
1523 	user_vm_start = bpf_arena_get_user_vm_start(bpf_prog->aux->arena);
1524 
1525 	detect_reg_usage(insn, insn_cnt, callee_regs_used);
1526 
1527 	emit_prologue(&prog, stack_depth,
1528 		      bpf_prog_was_classic(bpf_prog), tail_call_reachable,
1529 		      bpf_is_subprog(bpf_prog), bpf_prog->aux->exception_cb);
1530 	/* Exception callback will clobber callee regs for its own use, and
1531 	 * restore the original callee regs from main prog's stack frame.
1532 	 */
1533 	if (bpf_prog->aux->exception_boundary) {
1534 		/* We also need to save r12, which is not mapped to any BPF
1535 		 * register, as we throw after entry into the kernel, which may
1536 		 * overwrite r12.
1537 		 */
1538 		push_r12(&prog);
1539 		push_callee_regs(&prog, all_callee_regs_used);
1540 	} else {
1541 		if (arena_vm_start)
1542 			push_r12(&prog);
1543 		push_callee_regs(&prog, callee_regs_used);
1544 	}
1545 	if (arena_vm_start)
1546 		emit_mov_imm64(&prog, X86_REG_R12,
1547 			       arena_vm_start >> 32, (u32) arena_vm_start);
1548 
1549 	if (priv_frame_ptr)
1550 		emit_priv_frame_ptr(&prog, priv_frame_ptr);
1551 
1552 	ilen = prog - temp;
1553 	if (rw_image)
1554 		memcpy(rw_image + proglen, temp, ilen);
1555 	proglen += ilen;
1556 	addrs[0] = proglen;
1557 	prog = temp;
1558 
1559 	for (i = 1; i <= insn_cnt; i++, insn++) {
1560 		const s32 imm32 = insn->imm;
1561 		u32 dst_reg = insn->dst_reg;
1562 		u32 src_reg = insn->src_reg;
1563 		u8 b2 = 0, b3 = 0;
1564 		u8 *start_of_ldx;
1565 		s64 jmp_offset;
1566 		s16 insn_off;
1567 		u8 jmp_cond;
1568 		u8 *func;
1569 		int nops;
1570 
1571 		if (priv_frame_ptr) {
1572 			if (src_reg == BPF_REG_FP)
1573 				src_reg = X86_REG_R9;
1574 
1575 			if (dst_reg == BPF_REG_FP)
1576 				dst_reg = X86_REG_R9;
1577 		}
1578 
1579 		switch (insn->code) {
1580 			/* ALU */
1581 		case BPF_ALU | BPF_ADD | BPF_X:
1582 		case BPF_ALU | BPF_SUB | BPF_X:
1583 		case BPF_ALU | BPF_AND | BPF_X:
1584 		case BPF_ALU | BPF_OR | BPF_X:
1585 		case BPF_ALU | BPF_XOR | BPF_X:
1586 		case BPF_ALU64 | BPF_ADD | BPF_X:
1587 		case BPF_ALU64 | BPF_SUB | BPF_X:
1588 		case BPF_ALU64 | BPF_AND | BPF_X:
1589 		case BPF_ALU64 | BPF_OR | BPF_X:
1590 		case BPF_ALU64 | BPF_XOR | BPF_X:
1591 			maybe_emit_mod(&prog, dst_reg, src_reg,
1592 				       BPF_CLASS(insn->code) == BPF_ALU64);
1593 			b2 = simple_alu_opcodes[BPF_OP(insn->code)];
1594 			EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg));
1595 			break;
1596 
1597 		case BPF_ALU64 | BPF_MOV | BPF_X:
1598 			if (insn_is_cast_user(insn)) {
1599 				if (dst_reg != src_reg)
1600 					/* 32-bit mov */
1601 					emit_mov_reg(&prog, false, dst_reg, src_reg);
1602 				/* shl dst_reg, 32 */
1603 				maybe_emit_1mod(&prog, dst_reg, true);
1604 				EMIT3(0xC1, add_1reg(0xE0, dst_reg), 32);
1605 
1606 				/* or dst_reg, user_vm_start */
1607 				maybe_emit_1mod(&prog, dst_reg, true);
1608 				if (is_axreg(dst_reg))
1609 					EMIT1_off32(0x0D,  user_vm_start >> 32);
1610 				else
1611 					EMIT2_off32(0x81, add_1reg(0xC8, dst_reg),  user_vm_start >> 32);
1612 
1613 				/* rol dst_reg, 32 */
1614 				maybe_emit_1mod(&prog, dst_reg, true);
1615 				EMIT3(0xC1, add_1reg(0xC0, dst_reg), 32);
1616 
1617 				/* xor r11, r11 */
1618 				EMIT3(0x4D, 0x31, 0xDB);
1619 
1620 				/* test dst_reg32, dst_reg32; check if lower 32-bit are zero */
1621 				maybe_emit_mod(&prog, dst_reg, dst_reg, false);
1622 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
1623 
1624 				/* cmove r11, dst_reg; if so, set dst_reg to zero */
1625 				/* WARNING: Intel swapped src/dst register encoding in CMOVcc !!! */
1626 				maybe_emit_mod(&prog, AUX_REG, dst_reg, true);
1627 				EMIT3(0x0F, 0x44, add_2reg(0xC0, AUX_REG, dst_reg));
1628 				break;
1629 			} else if (insn_is_mov_percpu_addr(insn)) {
1630 				/* mov <dst>, <src> (if necessary) */
1631 				EMIT_mov(dst_reg, src_reg);
1632 #ifdef CONFIG_SMP
1633 				/* add <dst>, gs:[<off>] */
1634 				EMIT2(0x65, add_1mod(0x48, dst_reg));
1635 				EMIT3(0x03, add_2reg(0x04, 0, dst_reg), 0x25);
1636 				EMIT((u32)(unsigned long)&this_cpu_off, 4);
1637 #endif
1638 				break;
1639 			}
1640 			fallthrough;
1641 		case BPF_ALU | BPF_MOV | BPF_X:
1642 			if (insn->off == 0)
1643 				emit_mov_reg(&prog,
1644 					     BPF_CLASS(insn->code) == BPF_ALU64,
1645 					     dst_reg, src_reg);
1646 			else
1647 				emit_movsx_reg(&prog, insn->off,
1648 					       BPF_CLASS(insn->code) == BPF_ALU64,
1649 					       dst_reg, src_reg);
1650 			break;
1651 
1652 			/* neg dst */
1653 		case BPF_ALU | BPF_NEG:
1654 		case BPF_ALU64 | BPF_NEG:
1655 			maybe_emit_1mod(&prog, dst_reg,
1656 					BPF_CLASS(insn->code) == BPF_ALU64);
1657 			EMIT2(0xF7, add_1reg(0xD8, dst_reg));
1658 			break;
1659 
1660 		case BPF_ALU | BPF_ADD | BPF_K:
1661 		case BPF_ALU | BPF_SUB | BPF_K:
1662 		case BPF_ALU | BPF_AND | BPF_K:
1663 		case BPF_ALU | BPF_OR | BPF_K:
1664 		case BPF_ALU | BPF_XOR | BPF_K:
1665 		case BPF_ALU64 | BPF_ADD | BPF_K:
1666 		case BPF_ALU64 | BPF_SUB | BPF_K:
1667 		case BPF_ALU64 | BPF_AND | BPF_K:
1668 		case BPF_ALU64 | BPF_OR | BPF_K:
1669 		case BPF_ALU64 | BPF_XOR | BPF_K:
1670 			maybe_emit_1mod(&prog, dst_reg,
1671 					BPF_CLASS(insn->code) == BPF_ALU64);
1672 
1673 			/*
1674 			 * b3 holds 'normal' opcode, b2 short form only valid
1675 			 * in case dst is eax/rax.
1676 			 */
1677 			switch (BPF_OP(insn->code)) {
1678 			case BPF_ADD:
1679 				b3 = 0xC0;
1680 				b2 = 0x05;
1681 				break;
1682 			case BPF_SUB:
1683 				b3 = 0xE8;
1684 				b2 = 0x2D;
1685 				break;
1686 			case BPF_AND:
1687 				b3 = 0xE0;
1688 				b2 = 0x25;
1689 				break;
1690 			case BPF_OR:
1691 				b3 = 0xC8;
1692 				b2 = 0x0D;
1693 				break;
1694 			case BPF_XOR:
1695 				b3 = 0xF0;
1696 				b2 = 0x35;
1697 				break;
1698 			}
1699 
1700 			if (is_imm8(imm32))
1701 				EMIT3(0x83, add_1reg(b3, dst_reg), imm32);
1702 			else if (is_axreg(dst_reg))
1703 				EMIT1_off32(b2, imm32);
1704 			else
1705 				EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32);
1706 			break;
1707 
1708 		case BPF_ALU64 | BPF_MOV | BPF_K:
1709 		case BPF_ALU | BPF_MOV | BPF_K:
1710 			emit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64,
1711 				       dst_reg, imm32);
1712 			break;
1713 
1714 		case BPF_LD | BPF_IMM | BPF_DW:
1715 			emit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm);
1716 			insn++;
1717 			i++;
1718 			break;
1719 
1720 			/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */
1721 		case BPF_ALU | BPF_MOD | BPF_X:
1722 		case BPF_ALU | BPF_DIV | BPF_X:
1723 		case BPF_ALU | BPF_MOD | BPF_K:
1724 		case BPF_ALU | BPF_DIV | BPF_K:
1725 		case BPF_ALU64 | BPF_MOD | BPF_X:
1726 		case BPF_ALU64 | BPF_DIV | BPF_X:
1727 		case BPF_ALU64 | BPF_MOD | BPF_K:
1728 		case BPF_ALU64 | BPF_DIV | BPF_K: {
1729 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
1730 
1731 			if (dst_reg != BPF_REG_0)
1732 				EMIT1(0x50); /* push rax */
1733 			if (dst_reg != BPF_REG_3)
1734 				EMIT1(0x52); /* push rdx */
1735 
1736 			if (BPF_SRC(insn->code) == BPF_X) {
1737 				if (src_reg == BPF_REG_0 ||
1738 				    src_reg == BPF_REG_3) {
1739 					/* mov r11, src_reg */
1740 					EMIT_mov(AUX_REG, src_reg);
1741 					src_reg = AUX_REG;
1742 				}
1743 			} else {
1744 				/* mov r11, imm32 */
1745 				EMIT3_off32(0x49, 0xC7, 0xC3, imm32);
1746 				src_reg = AUX_REG;
1747 			}
1748 
1749 			if (dst_reg != BPF_REG_0)
1750 				/* mov rax, dst_reg */
1751 				emit_mov_reg(&prog, is64, BPF_REG_0, dst_reg);
1752 
1753 			if (insn->off == 0) {
1754 				/*
1755 				 * xor edx, edx
1756 				 * equivalent to 'xor rdx, rdx', but one byte less
1757 				 */
1758 				EMIT2(0x31, 0xd2);
1759 
1760 				/* div src_reg */
1761 				maybe_emit_1mod(&prog, src_reg, is64);
1762 				EMIT2(0xF7, add_1reg(0xF0, src_reg));
1763 			} else {
1764 				if (BPF_CLASS(insn->code) == BPF_ALU)
1765 					EMIT1(0x99); /* cdq */
1766 				else
1767 					EMIT2(0x48, 0x99); /* cqo */
1768 
1769 				/* idiv src_reg */
1770 				maybe_emit_1mod(&prog, src_reg, is64);
1771 				EMIT2(0xF7, add_1reg(0xF8, src_reg));
1772 			}
1773 
1774 			if (BPF_OP(insn->code) == BPF_MOD &&
1775 			    dst_reg != BPF_REG_3)
1776 				/* mov dst_reg, rdx */
1777 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_3);
1778 			else if (BPF_OP(insn->code) == BPF_DIV &&
1779 				 dst_reg != BPF_REG_0)
1780 				/* mov dst_reg, rax */
1781 				emit_mov_reg(&prog, is64, dst_reg, BPF_REG_0);
1782 
1783 			if (dst_reg != BPF_REG_3)
1784 				EMIT1(0x5A); /* pop rdx */
1785 			if (dst_reg != BPF_REG_0)
1786 				EMIT1(0x58); /* pop rax */
1787 			break;
1788 		}
1789 
1790 		case BPF_ALU | BPF_MUL | BPF_K:
1791 		case BPF_ALU64 | BPF_MUL | BPF_K:
1792 			maybe_emit_mod(&prog, dst_reg, dst_reg,
1793 				       BPF_CLASS(insn->code) == BPF_ALU64);
1794 
1795 			if (is_imm8(imm32))
1796 				/* imul dst_reg, dst_reg, imm8 */
1797 				EMIT3(0x6B, add_2reg(0xC0, dst_reg, dst_reg),
1798 				      imm32);
1799 			else
1800 				/* imul dst_reg, dst_reg, imm32 */
1801 				EMIT2_off32(0x69,
1802 					    add_2reg(0xC0, dst_reg, dst_reg),
1803 					    imm32);
1804 			break;
1805 
1806 		case BPF_ALU | BPF_MUL | BPF_X:
1807 		case BPF_ALU64 | BPF_MUL | BPF_X:
1808 			maybe_emit_mod(&prog, src_reg, dst_reg,
1809 				       BPF_CLASS(insn->code) == BPF_ALU64);
1810 
1811 			/* imul dst_reg, src_reg */
1812 			EMIT3(0x0F, 0xAF, add_2reg(0xC0, src_reg, dst_reg));
1813 			break;
1814 
1815 			/* Shifts */
1816 		case BPF_ALU | BPF_LSH | BPF_K:
1817 		case BPF_ALU | BPF_RSH | BPF_K:
1818 		case BPF_ALU | BPF_ARSH | BPF_K:
1819 		case BPF_ALU64 | BPF_LSH | BPF_K:
1820 		case BPF_ALU64 | BPF_RSH | BPF_K:
1821 		case BPF_ALU64 | BPF_ARSH | BPF_K:
1822 			maybe_emit_1mod(&prog, dst_reg,
1823 					BPF_CLASS(insn->code) == BPF_ALU64);
1824 
1825 			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
1826 			if (imm32 == 1)
1827 				EMIT2(0xD1, add_1reg(b3, dst_reg));
1828 			else
1829 				EMIT3(0xC1, add_1reg(b3, dst_reg), imm32);
1830 			break;
1831 
1832 		case BPF_ALU | BPF_LSH | BPF_X:
1833 		case BPF_ALU | BPF_RSH | BPF_X:
1834 		case BPF_ALU | BPF_ARSH | BPF_X:
1835 		case BPF_ALU64 | BPF_LSH | BPF_X:
1836 		case BPF_ALU64 | BPF_RSH | BPF_X:
1837 		case BPF_ALU64 | BPF_ARSH | BPF_X:
1838 			/* BMI2 shifts aren't better when shift count is already in rcx */
1839 			if (boot_cpu_has(X86_FEATURE_BMI2) && src_reg != BPF_REG_4) {
1840 				/* shrx/sarx/shlx dst_reg, dst_reg, src_reg */
1841 				bool w = (BPF_CLASS(insn->code) == BPF_ALU64);
1842 				u8 op;
1843 
1844 				switch (BPF_OP(insn->code)) {
1845 				case BPF_LSH:
1846 					op = 1; /* prefix 0x66 */
1847 					break;
1848 				case BPF_RSH:
1849 					op = 3; /* prefix 0xf2 */
1850 					break;
1851 				case BPF_ARSH:
1852 					op = 2; /* prefix 0xf3 */
1853 					break;
1854 				}
1855 
1856 				emit_shiftx(&prog, dst_reg, src_reg, w, op);
1857 
1858 				break;
1859 			}
1860 
1861 			if (src_reg != BPF_REG_4) { /* common case */
1862 				/* Check for bad case when dst_reg == rcx */
1863 				if (dst_reg == BPF_REG_4) {
1864 					/* mov r11, dst_reg */
1865 					EMIT_mov(AUX_REG, dst_reg);
1866 					dst_reg = AUX_REG;
1867 				} else {
1868 					EMIT1(0x51); /* push rcx */
1869 				}
1870 				/* mov rcx, src_reg */
1871 				EMIT_mov(BPF_REG_4, src_reg);
1872 			}
1873 
1874 			/* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */
1875 			maybe_emit_1mod(&prog, dst_reg,
1876 					BPF_CLASS(insn->code) == BPF_ALU64);
1877 
1878 			b3 = simple_alu_opcodes[BPF_OP(insn->code)];
1879 			EMIT2(0xD3, add_1reg(b3, dst_reg));
1880 
1881 			if (src_reg != BPF_REG_4) {
1882 				if (insn->dst_reg == BPF_REG_4)
1883 					/* mov dst_reg, r11 */
1884 					EMIT_mov(insn->dst_reg, AUX_REG);
1885 				else
1886 					EMIT1(0x59); /* pop rcx */
1887 			}
1888 
1889 			break;
1890 
1891 		case BPF_ALU | BPF_END | BPF_FROM_BE:
1892 		case BPF_ALU64 | BPF_END | BPF_FROM_LE:
1893 			switch (imm32) {
1894 			case 16:
1895 				/* Emit 'ror %ax, 8' to swap lower 2 bytes */
1896 				EMIT1(0x66);
1897 				if (is_ereg(dst_reg))
1898 					EMIT1(0x41);
1899 				EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8);
1900 
1901 				/* Emit 'movzwl eax, ax' */
1902 				if (is_ereg(dst_reg))
1903 					EMIT3(0x45, 0x0F, 0xB7);
1904 				else
1905 					EMIT2(0x0F, 0xB7);
1906 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
1907 				break;
1908 			case 32:
1909 				/* Emit 'bswap eax' to swap lower 4 bytes */
1910 				if (is_ereg(dst_reg))
1911 					EMIT2(0x41, 0x0F);
1912 				else
1913 					EMIT1(0x0F);
1914 				EMIT1(add_1reg(0xC8, dst_reg));
1915 				break;
1916 			case 64:
1917 				/* Emit 'bswap rax' to swap 8 bytes */
1918 				EMIT3(add_1mod(0x48, dst_reg), 0x0F,
1919 				      add_1reg(0xC8, dst_reg));
1920 				break;
1921 			}
1922 			break;
1923 
1924 		case BPF_ALU | BPF_END | BPF_FROM_LE:
1925 			switch (imm32) {
1926 			case 16:
1927 				/*
1928 				 * Emit 'movzwl eax, ax' to zero extend 16-bit
1929 				 * into 64 bit
1930 				 */
1931 				if (is_ereg(dst_reg))
1932 					EMIT3(0x45, 0x0F, 0xB7);
1933 				else
1934 					EMIT2(0x0F, 0xB7);
1935 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
1936 				break;
1937 			case 32:
1938 				/* Emit 'mov eax, eax' to clear upper 32-bits */
1939 				if (is_ereg(dst_reg))
1940 					EMIT1(0x45);
1941 				EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg));
1942 				break;
1943 			case 64:
1944 				/* nop */
1945 				break;
1946 			}
1947 			break;
1948 
1949 			/* speculation barrier */
1950 		case BPF_ST | BPF_NOSPEC:
1951 			EMIT_LFENCE();
1952 			break;
1953 
1954 			/* ST: *(u8*)(dst_reg + off) = imm */
1955 		case BPF_ST | BPF_MEM | BPF_B:
1956 			if (is_ereg(dst_reg))
1957 				EMIT2(0x41, 0xC6);
1958 			else
1959 				EMIT1(0xC6);
1960 			goto st;
1961 		case BPF_ST | BPF_MEM | BPF_H:
1962 			if (is_ereg(dst_reg))
1963 				EMIT3(0x66, 0x41, 0xC7);
1964 			else
1965 				EMIT2(0x66, 0xC7);
1966 			goto st;
1967 		case BPF_ST | BPF_MEM | BPF_W:
1968 			if (is_ereg(dst_reg))
1969 				EMIT2(0x41, 0xC7);
1970 			else
1971 				EMIT1(0xC7);
1972 			goto st;
1973 		case BPF_ST | BPF_MEM | BPF_DW:
1974 			EMIT2(add_1mod(0x48, dst_reg), 0xC7);
1975 
1976 st:			if (is_imm8(insn->off))
1977 				EMIT2(add_1reg(0x40, dst_reg), insn->off);
1978 			else
1979 				EMIT1_off32(add_1reg(0x80, dst_reg), insn->off);
1980 
1981 			EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));
1982 			break;
1983 
1984 			/* STX: *(u8*)(dst_reg + off) = src_reg */
1985 		case BPF_STX | BPF_MEM | BPF_B:
1986 		case BPF_STX | BPF_MEM | BPF_H:
1987 		case BPF_STX | BPF_MEM | BPF_W:
1988 		case BPF_STX | BPF_MEM | BPF_DW:
1989 			emit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
1990 			break;
1991 
1992 		case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
1993 		case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
1994 		case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
1995 		case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
1996 			start_of_ldx = prog;
1997 			emit_st_r12(&prog, BPF_SIZE(insn->code), dst_reg, insn->off, insn->imm);
1998 			goto populate_extable;
1999 
2000 			/* LDX: dst_reg = *(u8*)(src_reg + r12 + off) */
2001 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_B:
2002 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_H:
2003 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_W:
2004 		case BPF_LDX | BPF_PROBE_MEM32 | BPF_DW:
2005 		case BPF_STX | BPF_PROBE_MEM32 | BPF_B:
2006 		case BPF_STX | BPF_PROBE_MEM32 | BPF_H:
2007 		case BPF_STX | BPF_PROBE_MEM32 | BPF_W:
2008 		case BPF_STX | BPF_PROBE_MEM32 | BPF_DW:
2009 			start_of_ldx = prog;
2010 			if (BPF_CLASS(insn->code) == BPF_LDX)
2011 				emit_ldx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2012 			else
2013 				emit_stx_r12(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
2014 populate_extable:
2015 			{
2016 				struct exception_table_entry *ex;
2017 				u8 *_insn = image + proglen + (start_of_ldx - temp);
2018 				s64 delta;
2019 
2020 				if (!bpf_prog->aux->extable)
2021 					break;
2022 
2023 				if (excnt >= bpf_prog->aux->num_exentries) {
2024 					pr_err("mem32 extable bug\n");
2025 					return -EFAULT;
2026 				}
2027 				ex = &bpf_prog->aux->extable[excnt++];
2028 
2029 				delta = _insn - (u8 *)&ex->insn;
2030 				/* switch ex to rw buffer for writes */
2031 				ex = (void *)rw_image + ((void *)ex - (void *)image);
2032 
2033 				ex->insn = delta;
2034 
2035 				ex->data = EX_TYPE_BPF;
2036 
2037 				ex->fixup = (prog - start_of_ldx) |
2038 					((BPF_CLASS(insn->code) == BPF_LDX ? reg2pt_regs[dst_reg] : DONT_CLEAR) << 8);
2039 			}
2040 			break;
2041 
2042 			/* LDX: dst_reg = *(u8*)(src_reg + off) */
2043 		case BPF_LDX | BPF_MEM | BPF_B:
2044 		case BPF_LDX | BPF_PROBE_MEM | BPF_B:
2045 		case BPF_LDX | BPF_MEM | BPF_H:
2046 		case BPF_LDX | BPF_PROBE_MEM | BPF_H:
2047 		case BPF_LDX | BPF_MEM | BPF_W:
2048 		case BPF_LDX | BPF_PROBE_MEM | BPF_W:
2049 		case BPF_LDX | BPF_MEM | BPF_DW:
2050 		case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
2051 			/* LDXS: dst_reg = *(s8*)(src_reg + off) */
2052 		case BPF_LDX | BPF_MEMSX | BPF_B:
2053 		case BPF_LDX | BPF_MEMSX | BPF_H:
2054 		case BPF_LDX | BPF_MEMSX | BPF_W:
2055 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
2056 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
2057 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
2058 			insn_off = insn->off;
2059 
2060 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
2061 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
2062 				/* Conservatively check that src_reg + insn->off is a kernel address:
2063 				 *   src_reg + insn->off > TASK_SIZE_MAX + PAGE_SIZE
2064 				 *   and
2065 				 *   src_reg + insn->off < VSYSCALL_ADDR
2066 				 */
2067 
2068 				u64 limit = TASK_SIZE_MAX + PAGE_SIZE - VSYSCALL_ADDR;
2069 				u8 *end_of_jmp;
2070 
2071 				/* movabsq r10, VSYSCALL_ADDR */
2072 				emit_mov_imm64(&prog, BPF_REG_AX, (long)VSYSCALL_ADDR >> 32,
2073 					       (u32)(long)VSYSCALL_ADDR);
2074 
2075 				/* mov src_reg, r11 */
2076 				EMIT_mov(AUX_REG, src_reg);
2077 
2078 				if (insn->off) {
2079 					/* add r11, insn->off */
2080 					maybe_emit_1mod(&prog, AUX_REG, true);
2081 					EMIT2_off32(0x81, add_1reg(0xC0, AUX_REG), insn->off);
2082 				}
2083 
2084 				/* sub r11, r10 */
2085 				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
2086 				EMIT2(0x29, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
2087 
2088 				/* movabsq r10, limit */
2089 				emit_mov_imm64(&prog, BPF_REG_AX, (long)limit >> 32,
2090 					       (u32)(long)limit);
2091 
2092 				/* cmp r10, r11 */
2093 				maybe_emit_mod(&prog, AUX_REG, BPF_REG_AX, true);
2094 				EMIT2(0x39, add_2reg(0xC0, AUX_REG, BPF_REG_AX));
2095 
2096 				/* if unsigned '>', goto load */
2097 				EMIT2(X86_JA, 0);
2098 				end_of_jmp = prog;
2099 
2100 				/* xor dst_reg, dst_reg */
2101 				emit_mov_imm32(&prog, false, dst_reg, 0);
2102 				/* jmp byte_after_ldx */
2103 				EMIT2(0xEB, 0);
2104 
2105 				/* populate jmp_offset for JAE above to jump to start_of_ldx */
2106 				start_of_ldx = prog;
2107 				end_of_jmp[-1] = start_of_ldx - end_of_jmp;
2108 			}
2109 			if (BPF_MODE(insn->code) == BPF_PROBE_MEMSX ||
2110 			    BPF_MODE(insn->code) == BPF_MEMSX)
2111 				emit_ldsx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
2112 			else
2113 				emit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
2114 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
2115 			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
2116 				struct exception_table_entry *ex;
2117 				u8 *_insn = image + proglen + (start_of_ldx - temp);
2118 				s64 delta;
2119 
2120 				/* populate jmp_offset for JMP above */
2121 				start_of_ldx[-1] = prog - start_of_ldx;
2122 
2123 				if (!bpf_prog->aux->extable)
2124 					break;
2125 
2126 				if (excnt >= bpf_prog->aux->num_exentries) {
2127 					pr_err("ex gen bug\n");
2128 					return -EFAULT;
2129 				}
2130 				ex = &bpf_prog->aux->extable[excnt++];
2131 
2132 				delta = _insn - (u8 *)&ex->insn;
2133 				if (!is_simm32(delta)) {
2134 					pr_err("extable->insn doesn't fit into 32-bit\n");
2135 					return -EFAULT;
2136 				}
2137 				/* switch ex to rw buffer for writes */
2138 				ex = (void *)rw_image + ((void *)ex - (void *)image);
2139 
2140 				ex->insn = delta;
2141 
2142 				ex->data = EX_TYPE_BPF;
2143 
2144 				if (dst_reg > BPF_REG_9) {
2145 					pr_err("verifier error\n");
2146 					return -EFAULT;
2147 				}
2148 				/*
2149 				 * Compute size of x86 insn and its target dest x86 register.
2150 				 * ex_handler_bpf() will use lower 8 bits to adjust
2151 				 * pt_regs->ip to jump over this x86 instruction
2152 				 * and upper bits to figure out which pt_regs to zero out.
2153 				 * End result: x86 insn "mov rbx, qword ptr [rax+0x14]"
2154 				 * of 4 bytes will be ignored and rbx will be zero inited.
2155 				 */
2156 				ex->fixup = (prog - start_of_ldx) | (reg2pt_regs[dst_reg] << 8);
2157 			}
2158 			break;
2159 
2160 		case BPF_STX | BPF_ATOMIC | BPF_B:
2161 		case BPF_STX | BPF_ATOMIC | BPF_H:
2162 			if (!bpf_atomic_is_load_store(insn)) {
2163 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
2164 				return -EFAULT;
2165 			}
2166 			fallthrough;
2167 		case BPF_STX | BPF_ATOMIC | BPF_W:
2168 		case BPF_STX | BPF_ATOMIC | BPF_DW:
2169 			if (insn->imm == (BPF_AND | BPF_FETCH) ||
2170 			    insn->imm == (BPF_OR | BPF_FETCH) ||
2171 			    insn->imm == (BPF_XOR | BPF_FETCH)) {
2172 				bool is64 = BPF_SIZE(insn->code) == BPF_DW;
2173 				u32 real_src_reg = src_reg;
2174 				u32 real_dst_reg = dst_reg;
2175 				u8 *branch_target;
2176 
2177 				/*
2178 				 * Can't be implemented with a single x86 insn.
2179 				 * Need to do a CMPXCHG loop.
2180 				 */
2181 
2182 				/* Will need RAX as a CMPXCHG operand so save R0 */
2183 				emit_mov_reg(&prog, true, BPF_REG_AX, BPF_REG_0);
2184 				if (src_reg == BPF_REG_0)
2185 					real_src_reg = BPF_REG_AX;
2186 				if (dst_reg == BPF_REG_0)
2187 					real_dst_reg = BPF_REG_AX;
2188 
2189 				branch_target = prog;
2190 				/* Load old value */
2191 				emit_ldx(&prog, BPF_SIZE(insn->code),
2192 					 BPF_REG_0, real_dst_reg, insn->off);
2193 				/*
2194 				 * Perform the (commutative) operation locally,
2195 				 * put the result in the AUX_REG.
2196 				 */
2197 				emit_mov_reg(&prog, is64, AUX_REG, BPF_REG_0);
2198 				maybe_emit_mod(&prog, AUX_REG, real_src_reg, is64);
2199 				EMIT2(simple_alu_opcodes[BPF_OP(insn->imm)],
2200 				      add_2reg(0xC0, AUX_REG, real_src_reg));
2201 				/* Attempt to swap in new value */
2202 				err = emit_atomic_rmw(&prog, BPF_CMPXCHG,
2203 						      real_dst_reg, AUX_REG,
2204 						      insn->off,
2205 						      BPF_SIZE(insn->code));
2206 				if (WARN_ON(err))
2207 					return err;
2208 				/*
2209 				 * ZF tells us whether we won the race. If it's
2210 				 * cleared we need to try again.
2211 				 */
2212 				EMIT2(X86_JNE, -(prog - branch_target) - 2);
2213 				/* Return the pre-modification value */
2214 				emit_mov_reg(&prog, is64, real_src_reg, BPF_REG_0);
2215 				/* Restore R0 after clobbering RAX */
2216 				emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX);
2217 				break;
2218 			}
2219 
2220 			if (bpf_atomic_is_load_store(insn))
2221 				err = emit_atomic_ld_st(&prog, insn->imm, dst_reg, src_reg,
2222 							insn->off, BPF_SIZE(insn->code));
2223 			else
2224 				err = emit_atomic_rmw(&prog, insn->imm, dst_reg, src_reg,
2225 						      insn->off, BPF_SIZE(insn->code));
2226 			if (err)
2227 				return err;
2228 			break;
2229 
2230 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_B:
2231 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_H:
2232 			if (!bpf_atomic_is_load_store(insn)) {
2233 				pr_err("bpf_jit: 1- and 2-byte RMW atomics are not supported\n");
2234 				return -EFAULT;
2235 			}
2236 			fallthrough;
2237 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_W:
2238 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
2239 			start_of_ldx = prog;
2240 
2241 			if (bpf_atomic_is_load_store(insn))
2242 				err = emit_atomic_ld_st_index(&prog, insn->imm,
2243 							      BPF_SIZE(insn->code), dst_reg,
2244 							      src_reg, X86_REG_R12, insn->off);
2245 			else
2246 				err = emit_atomic_rmw_index(&prog, insn->imm, BPF_SIZE(insn->code),
2247 							    dst_reg, src_reg, X86_REG_R12,
2248 							    insn->off);
2249 			if (err)
2250 				return err;
2251 			goto populate_extable;
2252 
2253 			/* call */
2254 		case BPF_JMP | BPF_CALL: {
2255 			u8 *ip = image + addrs[i - 1];
2256 
2257 			func = (u8 *) __bpf_call_base + imm32;
2258 			if (src_reg == BPF_PSEUDO_CALL && tail_call_reachable) {
2259 				LOAD_TAIL_CALL_CNT_PTR(stack_depth);
2260 				ip += 7;
2261 			}
2262 			if (!imm32)
2263 				return -EINVAL;
2264 			if (priv_frame_ptr) {
2265 				push_r9(&prog);
2266 				ip += 2;
2267 			}
2268 			ip += x86_call_depth_emit_accounting(&prog, func, ip);
2269 			if (emit_call(&prog, func, ip))
2270 				return -EINVAL;
2271 			if (priv_frame_ptr)
2272 				pop_r9(&prog);
2273 			break;
2274 		}
2275 
2276 		case BPF_JMP | BPF_TAIL_CALL:
2277 			if (imm32)
2278 				emit_bpf_tail_call_direct(bpf_prog,
2279 							  &bpf_prog->aux->poke_tab[imm32 - 1],
2280 							  &prog, image + addrs[i - 1],
2281 							  callee_regs_used,
2282 							  stack_depth,
2283 							  ctx);
2284 			else
2285 				emit_bpf_tail_call_indirect(bpf_prog,
2286 							    &prog,
2287 							    callee_regs_used,
2288 							    stack_depth,
2289 							    image + addrs[i - 1],
2290 							    ctx);
2291 			break;
2292 
2293 			/* cond jump */
2294 		case BPF_JMP | BPF_JEQ | BPF_X:
2295 		case BPF_JMP | BPF_JNE | BPF_X:
2296 		case BPF_JMP | BPF_JGT | BPF_X:
2297 		case BPF_JMP | BPF_JLT | BPF_X:
2298 		case BPF_JMP | BPF_JGE | BPF_X:
2299 		case BPF_JMP | BPF_JLE | BPF_X:
2300 		case BPF_JMP | BPF_JSGT | BPF_X:
2301 		case BPF_JMP | BPF_JSLT | BPF_X:
2302 		case BPF_JMP | BPF_JSGE | BPF_X:
2303 		case BPF_JMP | BPF_JSLE | BPF_X:
2304 		case BPF_JMP32 | BPF_JEQ | BPF_X:
2305 		case BPF_JMP32 | BPF_JNE | BPF_X:
2306 		case BPF_JMP32 | BPF_JGT | BPF_X:
2307 		case BPF_JMP32 | BPF_JLT | BPF_X:
2308 		case BPF_JMP32 | BPF_JGE | BPF_X:
2309 		case BPF_JMP32 | BPF_JLE | BPF_X:
2310 		case BPF_JMP32 | BPF_JSGT | BPF_X:
2311 		case BPF_JMP32 | BPF_JSLT | BPF_X:
2312 		case BPF_JMP32 | BPF_JSGE | BPF_X:
2313 		case BPF_JMP32 | BPF_JSLE | BPF_X:
2314 			/* cmp dst_reg, src_reg */
2315 			maybe_emit_mod(&prog, dst_reg, src_reg,
2316 				       BPF_CLASS(insn->code) == BPF_JMP);
2317 			EMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg));
2318 			goto emit_cond_jmp;
2319 
2320 		case BPF_JMP | BPF_JSET | BPF_X:
2321 		case BPF_JMP32 | BPF_JSET | BPF_X:
2322 			/* test dst_reg, src_reg */
2323 			maybe_emit_mod(&prog, dst_reg, src_reg,
2324 				       BPF_CLASS(insn->code) == BPF_JMP);
2325 			EMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg));
2326 			goto emit_cond_jmp;
2327 
2328 		case BPF_JMP | BPF_JSET | BPF_K:
2329 		case BPF_JMP32 | BPF_JSET | BPF_K:
2330 			/* test dst_reg, imm32 */
2331 			maybe_emit_1mod(&prog, dst_reg,
2332 					BPF_CLASS(insn->code) == BPF_JMP);
2333 			EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);
2334 			goto emit_cond_jmp;
2335 
2336 		case BPF_JMP | BPF_JEQ | BPF_K:
2337 		case BPF_JMP | BPF_JNE | BPF_K:
2338 		case BPF_JMP | BPF_JGT | BPF_K:
2339 		case BPF_JMP | BPF_JLT | BPF_K:
2340 		case BPF_JMP | BPF_JGE | BPF_K:
2341 		case BPF_JMP | BPF_JLE | BPF_K:
2342 		case BPF_JMP | BPF_JSGT | BPF_K:
2343 		case BPF_JMP | BPF_JSLT | BPF_K:
2344 		case BPF_JMP | BPF_JSGE | BPF_K:
2345 		case BPF_JMP | BPF_JSLE | BPF_K:
2346 		case BPF_JMP32 | BPF_JEQ | BPF_K:
2347 		case BPF_JMP32 | BPF_JNE | BPF_K:
2348 		case BPF_JMP32 | BPF_JGT | BPF_K:
2349 		case BPF_JMP32 | BPF_JLT | BPF_K:
2350 		case BPF_JMP32 | BPF_JGE | BPF_K:
2351 		case BPF_JMP32 | BPF_JLE | BPF_K:
2352 		case BPF_JMP32 | BPF_JSGT | BPF_K:
2353 		case BPF_JMP32 | BPF_JSLT | BPF_K:
2354 		case BPF_JMP32 | BPF_JSGE | BPF_K:
2355 		case BPF_JMP32 | BPF_JSLE | BPF_K:
2356 			/* test dst_reg, dst_reg to save one extra byte */
2357 			if (imm32 == 0) {
2358 				maybe_emit_mod(&prog, dst_reg, dst_reg,
2359 					       BPF_CLASS(insn->code) == BPF_JMP);
2360 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
2361 				goto emit_cond_jmp;
2362 			}
2363 
2364 			/* cmp dst_reg, imm8/32 */
2365 			maybe_emit_1mod(&prog, dst_reg,
2366 					BPF_CLASS(insn->code) == BPF_JMP);
2367 
2368 			if (is_imm8(imm32))
2369 				EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);
2370 			else
2371 				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);
2372 
2373 emit_cond_jmp:		/* Convert BPF opcode to x86 */
2374 			switch (BPF_OP(insn->code)) {
2375 			case BPF_JEQ:
2376 				jmp_cond = X86_JE;
2377 				break;
2378 			case BPF_JSET:
2379 			case BPF_JNE:
2380 				jmp_cond = X86_JNE;
2381 				break;
2382 			case BPF_JGT:
2383 				/* GT is unsigned '>', JA in x86 */
2384 				jmp_cond = X86_JA;
2385 				break;
2386 			case BPF_JLT:
2387 				/* LT is unsigned '<', JB in x86 */
2388 				jmp_cond = X86_JB;
2389 				break;
2390 			case BPF_JGE:
2391 				/* GE is unsigned '>=', JAE in x86 */
2392 				jmp_cond = X86_JAE;
2393 				break;
2394 			case BPF_JLE:
2395 				/* LE is unsigned '<=', JBE in x86 */
2396 				jmp_cond = X86_JBE;
2397 				break;
2398 			case BPF_JSGT:
2399 				/* Signed '>', GT in x86 */
2400 				jmp_cond = X86_JG;
2401 				break;
2402 			case BPF_JSLT:
2403 				/* Signed '<', LT in x86 */
2404 				jmp_cond = X86_JL;
2405 				break;
2406 			case BPF_JSGE:
2407 				/* Signed '>=', GE in x86 */
2408 				jmp_cond = X86_JGE;
2409 				break;
2410 			case BPF_JSLE:
2411 				/* Signed '<=', LE in x86 */
2412 				jmp_cond = X86_JLE;
2413 				break;
2414 			default: /* to silence GCC warning */
2415 				return -EFAULT;
2416 			}
2417 			jmp_offset = addrs[i + insn->off] - addrs[i];
2418 			if (is_imm8_jmp_offset(jmp_offset)) {
2419 				if (jmp_padding) {
2420 					/* To keep the jmp_offset valid, the extra bytes are
2421 					 * padded before the jump insn, so we subtract the
2422 					 * 2 bytes of jmp_cond insn from INSN_SZ_DIFF.
2423 					 *
2424 					 * If the previous pass already emits an imm8
2425 					 * jmp_cond, then this BPF insn won't shrink, so
2426 					 * "nops" is 0.
2427 					 *
2428 					 * On the other hand, if the previous pass emits an
2429 					 * imm32 jmp_cond, the extra 4 bytes(*) is padded to
2430 					 * keep the image from shrinking further.
2431 					 *
2432 					 * (*) imm32 jmp_cond is 6 bytes, and imm8 jmp_cond
2433 					 *     is 2 bytes, so the size difference is 4 bytes.
2434 					 */
2435 					nops = INSN_SZ_DIFF - 2;
2436 					if (nops != 0 && nops != 4) {
2437 						pr_err("unexpected jmp_cond padding: %d bytes\n",
2438 						       nops);
2439 						return -EFAULT;
2440 					}
2441 					emit_nops(&prog, nops);
2442 				}
2443 				EMIT2(jmp_cond, jmp_offset);
2444 			} else if (is_simm32(jmp_offset)) {
2445 				EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset);
2446 			} else {
2447 				pr_err("cond_jmp gen bug %llx\n", jmp_offset);
2448 				return -EFAULT;
2449 			}
2450 
2451 			break;
2452 
2453 		case BPF_JMP | BPF_JA:
2454 		case BPF_JMP32 | BPF_JA:
2455 			if (BPF_CLASS(insn->code) == BPF_JMP) {
2456 				if (insn->off == -1)
2457 					/* -1 jmp instructions will always jump
2458 					 * backwards two bytes. Explicitly handling
2459 					 * this case avoids wasting too many passes
2460 					 * when there are long sequences of replaced
2461 					 * dead code.
2462 					 */
2463 					jmp_offset = -2;
2464 				else
2465 					jmp_offset = addrs[i + insn->off] - addrs[i];
2466 			} else {
2467 				if (insn->imm == -1)
2468 					jmp_offset = -2;
2469 				else
2470 					jmp_offset = addrs[i + insn->imm] - addrs[i];
2471 			}
2472 
2473 			if (!jmp_offset) {
2474 				/*
2475 				 * If jmp_padding is enabled, the extra nops will
2476 				 * be inserted. Otherwise, optimize out nop jumps.
2477 				 */
2478 				if (jmp_padding) {
2479 					/* There are 3 possible conditions.
2480 					 * (1) This BPF_JA is already optimized out in
2481 					 *     the previous run, so there is no need
2482 					 *     to pad any extra byte (0 byte).
2483 					 * (2) The previous pass emits an imm8 jmp,
2484 					 *     so we pad 2 bytes to match the previous
2485 					 *     insn size.
2486 					 * (3) Similarly, the previous pass emits an
2487 					 *     imm32 jmp, and 5 bytes is padded.
2488 					 */
2489 					nops = INSN_SZ_DIFF;
2490 					if (nops != 0 && nops != 2 && nops != 5) {
2491 						pr_err("unexpected nop jump padding: %d bytes\n",
2492 						       nops);
2493 						return -EFAULT;
2494 					}
2495 					emit_nops(&prog, nops);
2496 				}
2497 				break;
2498 			}
2499 emit_jmp:
2500 			if (is_imm8_jmp_offset(jmp_offset)) {
2501 				if (jmp_padding) {
2502 					/* To avoid breaking jmp_offset, the extra bytes
2503 					 * are padded before the actual jmp insn, so
2504 					 * 2 bytes is subtracted from INSN_SZ_DIFF.
2505 					 *
2506 					 * If the previous pass already emits an imm8
2507 					 * jmp, there is nothing to pad (0 byte).
2508 					 *
2509 					 * If it emits an imm32 jmp (5 bytes) previously
2510 					 * and now an imm8 jmp (2 bytes), then we pad
2511 					 * (5 - 2 = 3) bytes to stop the image from
2512 					 * shrinking further.
2513 					 */
2514 					nops = INSN_SZ_DIFF - 2;
2515 					if (nops != 0 && nops != 3) {
2516 						pr_err("unexpected jump padding: %d bytes\n",
2517 						       nops);
2518 						return -EFAULT;
2519 					}
2520 					emit_nops(&prog, INSN_SZ_DIFF - 2);
2521 				}
2522 				EMIT2(0xEB, jmp_offset);
2523 			} else if (is_simm32(jmp_offset)) {
2524 				EMIT1_off32(0xE9, jmp_offset);
2525 			} else {
2526 				pr_err("jmp gen bug %llx\n", jmp_offset);
2527 				return -EFAULT;
2528 			}
2529 			break;
2530 
2531 		case BPF_JMP | BPF_EXIT:
2532 			if (seen_exit) {
2533 				jmp_offset = ctx->cleanup_addr - addrs[i];
2534 				goto emit_jmp;
2535 			}
2536 			seen_exit = true;
2537 			/* Update cleanup_addr */
2538 			ctx->cleanup_addr = proglen;
2539 			if (bpf_prog->aux->exception_boundary) {
2540 				pop_callee_regs(&prog, all_callee_regs_used);
2541 				pop_r12(&prog);
2542 			} else {
2543 				pop_callee_regs(&prog, callee_regs_used);
2544 				if (arena_vm_start)
2545 					pop_r12(&prog);
2546 			}
2547 			EMIT1(0xC9);         /* leave */
2548 			emit_return(&prog, image + addrs[i - 1] + (prog - temp));
2549 			break;
2550 
2551 		default:
2552 			/*
2553 			 * By design x86-64 JIT should support all BPF instructions.
2554 			 * This error will be seen if new instruction was added
2555 			 * to the interpreter, but not to the JIT, or if there is
2556 			 * junk in bpf_prog.
2557 			 */
2558 			pr_err("bpf_jit: unknown opcode %02x\n", insn->code);
2559 			return -EINVAL;
2560 		}
2561 
2562 		ilen = prog - temp;
2563 		if (ilen > BPF_MAX_INSN_SIZE) {
2564 			pr_err("bpf_jit: fatal insn size error\n");
2565 			return -EFAULT;
2566 		}
2567 
2568 		if (image) {
2569 			/*
2570 			 * When populating the image, assert that:
2571 			 *
2572 			 *  i) We do not write beyond the allocated space, and
2573 			 * ii) addrs[i] did not change from the prior run, in order
2574 			 *     to validate assumptions made for computing branch
2575 			 *     displacements.
2576 			 */
2577 			if (unlikely(proglen + ilen > oldproglen ||
2578 				     proglen + ilen != addrs[i])) {
2579 				pr_err("bpf_jit: fatal error\n");
2580 				return -EFAULT;
2581 			}
2582 			memcpy(rw_image + proglen, temp, ilen);
2583 		}
2584 		proglen += ilen;
2585 		addrs[i] = proglen;
2586 		prog = temp;
2587 	}
2588 
2589 	if (image && excnt != bpf_prog->aux->num_exentries) {
2590 		pr_err("extable is not populated\n");
2591 		return -EFAULT;
2592 	}
2593 	return proglen;
2594 }
2595 
2596 static void clean_stack_garbage(const struct btf_func_model *m,
2597 				u8 **pprog, int nr_stack_slots,
2598 				int stack_size)
2599 {
2600 	int arg_size, off;
2601 	u8 *prog;
2602 
2603 	/* Generally speaking, the compiler will pass the arguments
2604 	 * on-stack with "push" instruction, which will take 8-byte
2605 	 * on the stack. In this case, there won't be garbage values
2606 	 * while we copy the arguments from origin stack frame to current
2607 	 * in BPF_DW.
2608 	 *
2609 	 * However, sometimes the compiler will only allocate 4-byte on
2610 	 * the stack for the arguments. For now, this case will only
2611 	 * happen if there is only one argument on-stack and its size
2612 	 * not more than 4 byte. In this case, there will be garbage
2613 	 * values on the upper 4-byte where we store the argument on
2614 	 * current stack frame.
2615 	 *
2616 	 * arguments on origin stack:
2617 	 *
2618 	 * stack_arg_1(4-byte) xxx(4-byte)
2619 	 *
2620 	 * what we copy:
2621 	 *
2622 	 * stack_arg_1(8-byte): stack_arg_1(origin) xxx
2623 	 *
2624 	 * and the xxx is the garbage values which we should clean here.
2625 	 */
2626 	if (nr_stack_slots != 1)
2627 		return;
2628 
2629 	/* the size of the last argument */
2630 	arg_size = m->arg_size[m->nr_args - 1];
2631 	if (arg_size <= 4) {
2632 		off = -(stack_size - 4);
2633 		prog = *pprog;
2634 		/* mov DWORD PTR [rbp + off], 0 */
2635 		if (!is_imm8(off))
2636 			EMIT2_off32(0xC7, 0x85, off);
2637 		else
2638 			EMIT3(0xC7, 0x45, off);
2639 		EMIT(0, 4);
2640 		*pprog = prog;
2641 	}
2642 }
2643 
2644 /* get the count of the regs that are used to pass arguments */
2645 static int get_nr_used_regs(const struct btf_func_model *m)
2646 {
2647 	int i, arg_regs, nr_used_regs = 0;
2648 
2649 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
2650 		arg_regs = (m->arg_size[i] + 7) / 8;
2651 		if (nr_used_regs + arg_regs <= 6)
2652 			nr_used_regs += arg_regs;
2653 
2654 		if (nr_used_regs >= 6)
2655 			break;
2656 	}
2657 
2658 	return nr_used_regs;
2659 }
2660 
2661 static void save_args(const struct btf_func_model *m, u8 **prog,
2662 		      int stack_size, bool for_call_origin)
2663 {
2664 	int arg_regs, first_off = 0, nr_regs = 0, nr_stack_slots = 0;
2665 	int i, j;
2666 
2667 	/* Store function arguments to stack.
2668 	 * For a function that accepts two pointers the sequence will be:
2669 	 * mov QWORD PTR [rbp-0x10],rdi
2670 	 * mov QWORD PTR [rbp-0x8],rsi
2671 	 */
2672 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
2673 		arg_regs = (m->arg_size[i] + 7) / 8;
2674 
2675 		/* According to the research of Yonghong, struct members
2676 		 * should be all in register or all on the stack.
2677 		 * Meanwhile, the compiler will pass the argument on regs
2678 		 * if the remaining regs can hold the argument.
2679 		 *
2680 		 * Disorder of the args can happen. For example:
2681 		 *
2682 		 * struct foo_struct {
2683 		 *     long a;
2684 		 *     int b;
2685 		 * };
2686 		 * int foo(char, char, char, char, char, struct foo_struct,
2687 		 *         char);
2688 		 *
2689 		 * the arg1-5,arg7 will be passed by regs, and arg6 will
2690 		 * by stack.
2691 		 */
2692 		if (nr_regs + arg_regs > 6) {
2693 			/* copy function arguments from origin stack frame
2694 			 * into current stack frame.
2695 			 *
2696 			 * The starting address of the arguments on-stack
2697 			 * is:
2698 			 *   rbp + 8(push rbp) +
2699 			 *   8(return addr of origin call) +
2700 			 *   8(return addr of the caller)
2701 			 * which means: rbp + 24
2702 			 */
2703 			for (j = 0; j < arg_regs; j++) {
2704 				emit_ldx(prog, BPF_DW, BPF_REG_0, BPF_REG_FP,
2705 					 nr_stack_slots * 8 + 0x18);
2706 				emit_stx(prog, BPF_DW, BPF_REG_FP, BPF_REG_0,
2707 					 -stack_size);
2708 
2709 				if (!nr_stack_slots)
2710 					first_off = stack_size;
2711 				stack_size -= 8;
2712 				nr_stack_slots++;
2713 			}
2714 		} else {
2715 			/* Only copy the arguments on-stack to current
2716 			 * 'stack_size' and ignore the regs, used to
2717 			 * prepare the arguments on-stack for origin call.
2718 			 */
2719 			if (for_call_origin) {
2720 				nr_regs += arg_regs;
2721 				continue;
2722 			}
2723 
2724 			/* copy the arguments from regs into stack */
2725 			for (j = 0; j < arg_regs; j++) {
2726 				emit_stx(prog, BPF_DW, BPF_REG_FP,
2727 					 nr_regs == 5 ? X86_REG_R9 : BPF_REG_1 + nr_regs,
2728 					 -stack_size);
2729 				stack_size -= 8;
2730 				nr_regs++;
2731 			}
2732 		}
2733 	}
2734 
2735 	clean_stack_garbage(m, prog, nr_stack_slots, first_off);
2736 }
2737 
2738 static void restore_regs(const struct btf_func_model *m, u8 **prog,
2739 			 int stack_size)
2740 {
2741 	int i, j, arg_regs, nr_regs = 0;
2742 
2743 	/* Restore function arguments from stack.
2744 	 * For a function that accepts two pointers the sequence will be:
2745 	 * EMIT4(0x48, 0x8B, 0x7D, 0xF0); mov rdi,QWORD PTR [rbp-0x10]
2746 	 * EMIT4(0x48, 0x8B, 0x75, 0xF8); mov rsi,QWORD PTR [rbp-0x8]
2747 	 *
2748 	 * The logic here is similar to what we do in save_args()
2749 	 */
2750 	for (i = 0; i < min_t(int, m->nr_args, MAX_BPF_FUNC_ARGS); i++) {
2751 		arg_regs = (m->arg_size[i] + 7) / 8;
2752 		if (nr_regs + arg_regs <= 6) {
2753 			for (j = 0; j < arg_regs; j++) {
2754 				emit_ldx(prog, BPF_DW,
2755 					 nr_regs == 5 ? X86_REG_R9 : BPF_REG_1 + nr_regs,
2756 					 BPF_REG_FP,
2757 					 -stack_size);
2758 				stack_size -= 8;
2759 				nr_regs++;
2760 			}
2761 		} else {
2762 			stack_size -= 8 * arg_regs;
2763 		}
2764 
2765 		if (nr_regs >= 6)
2766 			break;
2767 	}
2768 }
2769 
2770 static int invoke_bpf_prog(const struct btf_func_model *m, u8 **pprog,
2771 			   struct bpf_tramp_link *l, int stack_size,
2772 			   int run_ctx_off, bool save_ret,
2773 			   void *image, void *rw_image)
2774 {
2775 	u8 *prog = *pprog;
2776 	u8 *jmp_insn;
2777 	int ctx_cookie_off = offsetof(struct bpf_tramp_run_ctx, bpf_cookie);
2778 	struct bpf_prog *p = l->link.prog;
2779 	u64 cookie = l->cookie;
2780 
2781 	/* mov rdi, cookie */
2782 	emit_mov_imm64(&prog, BPF_REG_1, (long) cookie >> 32, (u32) (long) cookie);
2783 
2784 	/* Prepare struct bpf_tramp_run_ctx.
2785 	 *
2786 	 * bpf_tramp_run_ctx is already preserved by
2787 	 * arch_prepare_bpf_trampoline().
2788 	 *
2789 	 * mov QWORD PTR [rbp - run_ctx_off + ctx_cookie_off], rdi
2790 	 */
2791 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_1, -run_ctx_off + ctx_cookie_off);
2792 
2793 	/* arg1: mov rdi, progs[i] */
2794 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
2795 	/* arg2: lea rsi, [rbp - ctx_cookie_off] */
2796 	if (!is_imm8(-run_ctx_off))
2797 		EMIT3_off32(0x48, 0x8D, 0xB5, -run_ctx_off);
2798 	else
2799 		EMIT4(0x48, 0x8D, 0x75, -run_ctx_off);
2800 
2801 	if (emit_rsb_call(&prog, bpf_trampoline_enter(p), image + (prog - (u8 *)rw_image)))
2802 		return -EINVAL;
2803 	/* remember prog start time returned by __bpf_prog_enter */
2804 	emit_mov_reg(&prog, true, BPF_REG_6, BPF_REG_0);
2805 
2806 	/* if (__bpf_prog_enter*(prog) == 0)
2807 	 *	goto skip_exec_of_prog;
2808 	 */
2809 	EMIT3(0x48, 0x85, 0xC0);  /* test rax,rax */
2810 	/* emit 2 nops that will be replaced with JE insn */
2811 	jmp_insn = prog;
2812 	emit_nops(&prog, 2);
2813 
2814 	/* arg1: lea rdi, [rbp - stack_size] */
2815 	if (!is_imm8(-stack_size))
2816 		EMIT3_off32(0x48, 0x8D, 0xBD, -stack_size);
2817 	else
2818 		EMIT4(0x48, 0x8D, 0x7D, -stack_size);
2819 	/* arg2: progs[i]->insnsi for interpreter */
2820 	if (!p->jited)
2821 		emit_mov_imm64(&prog, BPF_REG_2,
2822 			       (long) p->insnsi >> 32,
2823 			       (u32) (long) p->insnsi);
2824 	/* call JITed bpf program or interpreter */
2825 	if (emit_rsb_call(&prog, p->bpf_func, image + (prog - (u8 *)rw_image)))
2826 		return -EINVAL;
2827 
2828 	/*
2829 	 * BPF_TRAMP_MODIFY_RETURN trampolines can modify the return
2830 	 * of the previous call which is then passed on the stack to
2831 	 * the next BPF program.
2832 	 *
2833 	 * BPF_TRAMP_FENTRY trampoline may need to return the return
2834 	 * value of BPF_PROG_TYPE_STRUCT_OPS prog.
2835 	 */
2836 	if (save_ret)
2837 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
2838 
2839 	/* replace 2 nops with JE insn, since jmp target is known */
2840 	jmp_insn[0] = X86_JE;
2841 	jmp_insn[1] = prog - jmp_insn - 2;
2842 
2843 	/* arg1: mov rdi, progs[i] */
2844 	emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32, (u32) (long) p);
2845 	/* arg2: mov rsi, rbx <- start time in nsec */
2846 	emit_mov_reg(&prog, true, BPF_REG_2, BPF_REG_6);
2847 	/* arg3: lea rdx, [rbp - run_ctx_off] */
2848 	if (!is_imm8(-run_ctx_off))
2849 		EMIT3_off32(0x48, 0x8D, 0x95, -run_ctx_off);
2850 	else
2851 		EMIT4(0x48, 0x8D, 0x55, -run_ctx_off);
2852 	if (emit_rsb_call(&prog, bpf_trampoline_exit(p), image + (prog - (u8 *)rw_image)))
2853 		return -EINVAL;
2854 
2855 	*pprog = prog;
2856 	return 0;
2857 }
2858 
2859 static void emit_align(u8 **pprog, u32 align)
2860 {
2861 	u8 *target, *prog = *pprog;
2862 
2863 	target = PTR_ALIGN(prog, align);
2864 	if (target != prog)
2865 		emit_nops(&prog, target - prog);
2866 
2867 	*pprog = prog;
2868 }
2869 
2870 static int emit_cond_near_jump(u8 **pprog, void *func, void *ip, u8 jmp_cond)
2871 {
2872 	u8 *prog = *pprog;
2873 	s64 offset;
2874 
2875 	offset = func - (ip + 2 + 4);
2876 	if (!is_simm32(offset)) {
2877 		pr_err("Target %p is out of range\n", func);
2878 		return -EINVAL;
2879 	}
2880 	EMIT2_off32(0x0F, jmp_cond + 0x10, offset);
2881 	*pprog = prog;
2882 	return 0;
2883 }
2884 
2885 static int invoke_bpf(const struct btf_func_model *m, u8 **pprog,
2886 		      struct bpf_tramp_links *tl, int stack_size,
2887 		      int run_ctx_off, bool save_ret,
2888 		      void *image, void *rw_image)
2889 {
2890 	int i;
2891 	u8 *prog = *pprog;
2892 
2893 	for (i = 0; i < tl->nr_links; i++) {
2894 		if (invoke_bpf_prog(m, &prog, tl->links[i], stack_size,
2895 				    run_ctx_off, save_ret, image, rw_image))
2896 			return -EINVAL;
2897 	}
2898 	*pprog = prog;
2899 	return 0;
2900 }
2901 
2902 static int invoke_bpf_mod_ret(const struct btf_func_model *m, u8 **pprog,
2903 			      struct bpf_tramp_links *tl, int stack_size,
2904 			      int run_ctx_off, u8 **branches,
2905 			      void *image, void *rw_image)
2906 {
2907 	u8 *prog = *pprog;
2908 	int i;
2909 
2910 	/* The first fmod_ret program will receive a garbage return value.
2911 	 * Set this to 0 to avoid confusing the program.
2912 	 */
2913 	emit_mov_imm32(&prog, false, BPF_REG_0, 0);
2914 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
2915 	for (i = 0; i < tl->nr_links; i++) {
2916 		if (invoke_bpf_prog(m, &prog, tl->links[i], stack_size, run_ctx_off, true,
2917 				    image, rw_image))
2918 			return -EINVAL;
2919 
2920 		/* mod_ret prog stored return value into [rbp - 8]. Emit:
2921 		 * if (*(u64 *)(rbp - 8) !=  0)
2922 		 *	goto do_fexit;
2923 		 */
2924 		/* cmp QWORD PTR [rbp - 0x8], 0x0 */
2925 		EMIT4(0x48, 0x83, 0x7d, 0xf8); EMIT1(0x00);
2926 
2927 		/* Save the location of the branch and Generate 6 nops
2928 		 * (4 bytes for an offset and 2 bytes for the jump) These nops
2929 		 * are replaced with a conditional jump once do_fexit (i.e. the
2930 		 * start of the fexit invocation) is finalized.
2931 		 */
2932 		branches[i] = prog;
2933 		emit_nops(&prog, 4 + 2);
2934 	}
2935 
2936 	*pprog = prog;
2937 	return 0;
2938 }
2939 
2940 /* mov rax, qword ptr [rbp - rounded_stack_depth - 8] */
2941 #define LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack)	\
2942 	__LOAD_TCC_PTR(-round_up(stack, 8) - 8)
2943 
2944 /* Example:
2945  * __be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev);
2946  * its 'struct btf_func_model' will be nr_args=2
2947  * The assembly code when eth_type_trans is executing after trampoline:
2948  *
2949  * push rbp
2950  * mov rbp, rsp
2951  * sub rsp, 16                     // space for skb and dev
2952  * push rbx                        // temp regs to pass start time
2953  * mov qword ptr [rbp - 16], rdi   // save skb pointer to stack
2954  * mov qword ptr [rbp - 8], rsi    // save dev pointer to stack
2955  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
2956  * mov rbx, rax                    // remember start time in bpf stats are enabled
2957  * lea rdi, [rbp - 16]             // R1==ctx of bpf prog
2958  * call addr_of_jited_FENTRY_prog
2959  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
2960  * mov rsi, rbx                    // prog start time
2961  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
2962  * mov rdi, qword ptr [rbp - 16]   // restore skb pointer from stack
2963  * mov rsi, qword ptr [rbp - 8]    // restore dev pointer from stack
2964  * pop rbx
2965  * leave
2966  * ret
2967  *
2968  * eth_type_trans has 5 byte nop at the beginning. These 5 bytes will be
2969  * replaced with 'call generated_bpf_trampoline'. When it returns
2970  * eth_type_trans will continue executing with original skb and dev pointers.
2971  *
2972  * The assembly code when eth_type_trans is called from trampoline:
2973  *
2974  * push rbp
2975  * mov rbp, rsp
2976  * sub rsp, 24                     // space for skb, dev, return value
2977  * push rbx                        // temp regs to pass start time
2978  * mov qword ptr [rbp - 24], rdi   // save skb pointer to stack
2979  * mov qword ptr [rbp - 16], rsi   // save dev pointer to stack
2980  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
2981  * mov rbx, rax                    // remember start time if bpf stats are enabled
2982  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
2983  * call addr_of_jited_FENTRY_prog  // bpf prog can access skb and dev
2984  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
2985  * mov rsi, rbx                    // prog start time
2986  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
2987  * mov rdi, qword ptr [rbp - 24]   // restore skb pointer from stack
2988  * mov rsi, qword ptr [rbp - 16]   // restore dev pointer from stack
2989  * call eth_type_trans+5           // execute body of eth_type_trans
2990  * mov qword ptr [rbp - 8], rax    // save return value
2991  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
2992  * mov rbx, rax                    // remember start time in bpf stats are enabled
2993  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
2994  * call addr_of_jited_FEXIT_prog   // bpf prog can access skb, dev, return value
2995  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
2996  * mov rsi, rbx                    // prog start time
2997  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
2998  * mov rax, qword ptr [rbp - 8]    // restore eth_type_trans's return value
2999  * pop rbx
3000  * leave
3001  * add rsp, 8                      // skip eth_type_trans's frame
3002  * ret                             // return to its caller
3003  */
3004 static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_image,
3005 					 void *rw_image_end, void *image,
3006 					 const struct btf_func_model *m, u32 flags,
3007 					 struct bpf_tramp_links *tlinks,
3008 					 void *func_addr)
3009 {
3010 	int i, ret, nr_regs = m->nr_args, stack_size = 0;
3011 	int regs_off, nregs_off, ip_off, run_ctx_off, arg_stack_off, rbx_off;
3012 	struct bpf_tramp_links *fentry = &tlinks[BPF_TRAMP_FENTRY];
3013 	struct bpf_tramp_links *fexit = &tlinks[BPF_TRAMP_FEXIT];
3014 	struct bpf_tramp_links *fmod_ret = &tlinks[BPF_TRAMP_MODIFY_RETURN];
3015 	void *orig_call = func_addr;
3016 	u8 **branches = NULL;
3017 	u8 *prog;
3018 	bool save_ret;
3019 
3020 	/*
3021 	 * F_INDIRECT is only compatible with F_RET_FENTRY_RET, it is
3022 	 * explicitly incompatible with F_CALL_ORIG | F_SKIP_FRAME | F_IP_ARG
3023 	 * because @func_addr.
3024 	 */
3025 	WARN_ON_ONCE((flags & BPF_TRAMP_F_INDIRECT) &&
3026 		     (flags & ~(BPF_TRAMP_F_INDIRECT | BPF_TRAMP_F_RET_FENTRY_RET)));
3027 
3028 	/* extra registers for struct arguments */
3029 	for (i = 0; i < m->nr_args; i++) {
3030 		if (m->arg_flags[i] & BTF_FMODEL_STRUCT_ARG)
3031 			nr_regs += (m->arg_size[i] + 7) / 8 - 1;
3032 	}
3033 
3034 	/* x86-64 supports up to MAX_BPF_FUNC_ARGS arguments. 1-6
3035 	 * are passed through regs, the remains are through stack.
3036 	 */
3037 	if (nr_regs > MAX_BPF_FUNC_ARGS)
3038 		return -ENOTSUPP;
3039 
3040 	/* Generated trampoline stack layout:
3041 	 *
3042 	 * RBP + 8         [ return address  ]
3043 	 * RBP + 0         [ RBP             ]
3044 	 *
3045 	 * RBP - 8         [ return value    ]  BPF_TRAMP_F_CALL_ORIG or
3046 	 *                                      BPF_TRAMP_F_RET_FENTRY_RET flags
3047 	 *
3048 	 *                 [ reg_argN        ]  always
3049 	 *                 [ ...             ]
3050 	 * RBP - regs_off  [ reg_arg1        ]  program's ctx pointer
3051 	 *
3052 	 * RBP - nregs_off [ regs count	     ]  always
3053 	 *
3054 	 * RBP - ip_off    [ traced function ]  BPF_TRAMP_F_IP_ARG flag
3055 	 *
3056 	 * RBP - rbx_off   [ rbx value       ]  always
3057 	 *
3058 	 * RBP - run_ctx_off [ bpf_tramp_run_ctx ]
3059 	 *
3060 	 *                     [ stack_argN ]  BPF_TRAMP_F_CALL_ORIG
3061 	 *                     [ ...        ]
3062 	 *                     [ stack_arg2 ]
3063 	 * RBP - arg_stack_off [ stack_arg1 ]
3064 	 * RSP                 [ tail_call_cnt_ptr ] BPF_TRAMP_F_TAIL_CALL_CTX
3065 	 */
3066 
3067 	/* room for return value of orig_call or fentry prog */
3068 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
3069 	if (save_ret)
3070 		stack_size += 8;
3071 
3072 	stack_size += nr_regs * 8;
3073 	regs_off = stack_size;
3074 
3075 	/* regs count  */
3076 	stack_size += 8;
3077 	nregs_off = stack_size;
3078 
3079 	if (flags & BPF_TRAMP_F_IP_ARG)
3080 		stack_size += 8; /* room for IP address argument */
3081 
3082 	ip_off = stack_size;
3083 
3084 	stack_size += 8;
3085 	rbx_off = stack_size;
3086 
3087 	stack_size += (sizeof(struct bpf_tramp_run_ctx) + 7) & ~0x7;
3088 	run_ctx_off = stack_size;
3089 
3090 	if (nr_regs > 6 && (flags & BPF_TRAMP_F_CALL_ORIG)) {
3091 		/* the space that used to pass arguments on-stack */
3092 		stack_size += (nr_regs - get_nr_used_regs(m)) * 8;
3093 		/* make sure the stack pointer is 16-byte aligned if we
3094 		 * need pass arguments on stack, which means
3095 		 *  [stack_size + 8(rbp) + 8(rip) + 8(origin rip)]
3096 		 * should be 16-byte aligned. Following code depend on
3097 		 * that stack_size is already 8-byte aligned.
3098 		 */
3099 		stack_size += (stack_size % 16) ? 0 : 8;
3100 	}
3101 
3102 	arg_stack_off = stack_size;
3103 
3104 	if (flags & BPF_TRAMP_F_SKIP_FRAME) {
3105 		/* skip patched call instruction and point orig_call to actual
3106 		 * body of the kernel function.
3107 		 */
3108 		if (is_endbr(*(u32 *)orig_call))
3109 			orig_call += ENDBR_INSN_SIZE;
3110 		orig_call += X86_PATCH_SIZE;
3111 	}
3112 
3113 	prog = rw_image;
3114 
3115 	if (flags & BPF_TRAMP_F_INDIRECT) {
3116 		/*
3117 		 * Indirect call for bpf_struct_ops
3118 		 */
3119 		emit_cfi(&prog, cfi_get_func_hash(func_addr));
3120 	} else {
3121 		/*
3122 		 * Direct-call fentry stub, as such it needs accounting for the
3123 		 * __fentry__ call.
3124 		 */
3125 		x86_call_depth_emit_accounting(&prog, NULL, image);
3126 	}
3127 	EMIT1(0x55);		 /* push rbp */
3128 	EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
3129 	if (!is_imm8(stack_size)) {
3130 		/* sub rsp, stack_size */
3131 		EMIT3_off32(0x48, 0x81, 0xEC, stack_size);
3132 	} else {
3133 		/* sub rsp, stack_size */
3134 		EMIT4(0x48, 0x83, 0xEC, stack_size);
3135 	}
3136 	if (flags & BPF_TRAMP_F_TAIL_CALL_CTX)
3137 		EMIT1(0x50);		/* push rax */
3138 	/* mov QWORD PTR [rbp - rbx_off], rbx */
3139 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_6, -rbx_off);
3140 
3141 	/* Store number of argument registers of the traced function:
3142 	 *   mov rax, nr_regs
3143 	 *   mov QWORD PTR [rbp - nregs_off], rax
3144 	 */
3145 	emit_mov_imm64(&prog, BPF_REG_0, 0, (u32) nr_regs);
3146 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -nregs_off);
3147 
3148 	if (flags & BPF_TRAMP_F_IP_ARG) {
3149 		/* Store IP address of the traced function:
3150 		 * movabsq rax, func_addr
3151 		 * mov QWORD PTR [rbp - ip_off], rax
3152 		 */
3153 		emit_mov_imm64(&prog, BPF_REG_0, (long) func_addr >> 32, (u32) (long) func_addr);
3154 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -ip_off);
3155 	}
3156 
3157 	save_args(m, &prog, regs_off, false);
3158 
3159 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3160 		/* arg1: mov rdi, im */
3161 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
3162 		if (emit_rsb_call(&prog, __bpf_tramp_enter,
3163 				  image + (prog - (u8 *)rw_image))) {
3164 			ret = -EINVAL;
3165 			goto cleanup;
3166 		}
3167 	}
3168 
3169 	if (fentry->nr_links) {
3170 		if (invoke_bpf(m, &prog, fentry, regs_off, run_ctx_off,
3171 			       flags & BPF_TRAMP_F_RET_FENTRY_RET, image, rw_image))
3172 			return -EINVAL;
3173 	}
3174 
3175 	if (fmod_ret->nr_links) {
3176 		branches = kcalloc(fmod_ret->nr_links, sizeof(u8 *),
3177 				   GFP_KERNEL);
3178 		if (!branches)
3179 			return -ENOMEM;
3180 
3181 		if (invoke_bpf_mod_ret(m, &prog, fmod_ret, regs_off,
3182 				       run_ctx_off, branches, image, rw_image)) {
3183 			ret = -EINVAL;
3184 			goto cleanup;
3185 		}
3186 	}
3187 
3188 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3189 		restore_regs(m, &prog, regs_off);
3190 		save_args(m, &prog, arg_stack_off, true);
3191 
3192 		if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
3193 			/* Before calling the original function, load the
3194 			 * tail_call_cnt_ptr from stack to rax.
3195 			 */
3196 			LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size);
3197 		}
3198 
3199 		if (flags & BPF_TRAMP_F_ORIG_STACK) {
3200 			emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, 8);
3201 			EMIT2(0xff, 0xd3); /* call *rbx */
3202 		} else {
3203 			/* call original function */
3204 			if (emit_rsb_call(&prog, orig_call, image + (prog - (u8 *)rw_image))) {
3205 				ret = -EINVAL;
3206 				goto cleanup;
3207 			}
3208 		}
3209 		/* remember return value in a stack for bpf prog to access */
3210 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
3211 		im->ip_after_call = image + (prog - (u8 *)rw_image);
3212 		emit_nops(&prog, X86_PATCH_SIZE);
3213 	}
3214 
3215 	if (fmod_ret->nr_links) {
3216 		/* From Intel 64 and IA-32 Architectures Optimization
3217 		 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
3218 		 * Coding Rule 11: All branch targets should be 16-byte
3219 		 * aligned.
3220 		 */
3221 		emit_align(&prog, 16);
3222 		/* Update the branches saved in invoke_bpf_mod_ret with the
3223 		 * aligned address of do_fexit.
3224 		 */
3225 		for (i = 0; i < fmod_ret->nr_links; i++) {
3226 			emit_cond_near_jump(&branches[i], image + (prog - (u8 *)rw_image),
3227 					    image + (branches[i] - (u8 *)rw_image), X86_JNE);
3228 		}
3229 	}
3230 
3231 	if (fexit->nr_links) {
3232 		if (invoke_bpf(m, &prog, fexit, regs_off, run_ctx_off,
3233 			       false, image, rw_image)) {
3234 			ret = -EINVAL;
3235 			goto cleanup;
3236 		}
3237 	}
3238 
3239 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
3240 		restore_regs(m, &prog, regs_off);
3241 
3242 	/* This needs to be done regardless. If there were fmod_ret programs,
3243 	 * the return value is only updated on the stack and still needs to be
3244 	 * restored to R0.
3245 	 */
3246 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
3247 		im->ip_epilogue = image + (prog - (u8 *)rw_image);
3248 		/* arg1: mov rdi, im */
3249 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
3250 		if (emit_rsb_call(&prog, __bpf_tramp_exit, image + (prog - (u8 *)rw_image))) {
3251 			ret = -EINVAL;
3252 			goto cleanup;
3253 		}
3254 	} else if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) {
3255 		/* Before running the original function, load the
3256 		 * tail_call_cnt_ptr from stack to rax.
3257 		 */
3258 		LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size);
3259 	}
3260 
3261 	/* restore return value of orig_call or fentry prog back into RAX */
3262 	if (save_ret)
3263 		emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, -8);
3264 
3265 	emit_ldx(&prog, BPF_DW, BPF_REG_6, BPF_REG_FP, -rbx_off);
3266 	EMIT1(0xC9); /* leave */
3267 	if (flags & BPF_TRAMP_F_SKIP_FRAME) {
3268 		/* skip our return address and return to parent */
3269 		EMIT4(0x48, 0x83, 0xC4, 8); /* add rsp, 8 */
3270 	}
3271 	emit_return(&prog, image + (prog - (u8 *)rw_image));
3272 	/* Make sure the trampoline generation logic doesn't overflow */
3273 	if (WARN_ON_ONCE(prog > (u8 *)rw_image_end - BPF_INSN_SAFETY)) {
3274 		ret = -EFAULT;
3275 		goto cleanup;
3276 	}
3277 	ret = prog - (u8 *)rw_image + BPF_INSN_SAFETY;
3278 
3279 cleanup:
3280 	kfree(branches);
3281 	return ret;
3282 }
3283 
3284 void *arch_alloc_bpf_trampoline(unsigned int size)
3285 {
3286 	return bpf_prog_pack_alloc(size, jit_fill_hole);
3287 }
3288 
3289 void arch_free_bpf_trampoline(void *image, unsigned int size)
3290 {
3291 	bpf_prog_pack_free(image, size);
3292 }
3293 
3294 int arch_protect_bpf_trampoline(void *image, unsigned int size)
3295 {
3296 	return 0;
3297 }
3298 
3299 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
3300 				const struct btf_func_model *m, u32 flags,
3301 				struct bpf_tramp_links *tlinks,
3302 				void *func_addr)
3303 {
3304 	void *rw_image, *tmp;
3305 	int ret;
3306 	u32 size = image_end - image;
3307 
3308 	/* rw_image doesn't need to be in module memory range, so we can
3309 	 * use kvmalloc.
3310 	 */
3311 	rw_image = kvmalloc(size, GFP_KERNEL);
3312 	if (!rw_image)
3313 		return -ENOMEM;
3314 
3315 	ret = __arch_prepare_bpf_trampoline(im, rw_image, rw_image + size, image, m,
3316 					    flags, tlinks, func_addr);
3317 	if (ret < 0)
3318 		goto out;
3319 
3320 	tmp = bpf_arch_text_copy(image, rw_image, size);
3321 	if (IS_ERR(tmp))
3322 		ret = PTR_ERR(tmp);
3323 out:
3324 	kvfree(rw_image);
3325 	return ret;
3326 }
3327 
3328 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
3329 			     struct bpf_tramp_links *tlinks, void *func_addr)
3330 {
3331 	struct bpf_tramp_image im;
3332 	void *image;
3333 	int ret;
3334 
3335 	/* Allocate a temporary buffer for __arch_prepare_bpf_trampoline().
3336 	 * This will NOT cause fragmentation in direct map, as we do not
3337 	 * call set_memory_*() on this buffer.
3338 	 *
3339 	 * We cannot use kvmalloc here, because we need image to be in
3340 	 * module memory range.
3341 	 */
3342 	image = bpf_jit_alloc_exec(PAGE_SIZE);
3343 	if (!image)
3344 		return -ENOMEM;
3345 
3346 	ret = __arch_prepare_bpf_trampoline(&im, image, image + PAGE_SIZE, image,
3347 					    m, flags, tlinks, func_addr);
3348 	bpf_jit_free_exec(image);
3349 	return ret;
3350 }
3351 
3352 static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image, u8 *buf)
3353 {
3354 	u8 *jg_reloc, *prog = *pprog;
3355 	int pivot, err, jg_bytes = 1;
3356 	s64 jg_offset;
3357 
3358 	if (a == b) {
3359 		/* Leaf node of recursion, i.e. not a range of indices
3360 		 * anymore.
3361 		 */
3362 		EMIT1(add_1mod(0x48, BPF_REG_3));	/* cmp rdx,func */
3363 		if (!is_simm32(progs[a]))
3364 			return -1;
3365 		EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3),
3366 			    progs[a]);
3367 		err = emit_cond_near_jump(&prog,	/* je func */
3368 					  (void *)progs[a], image + (prog - buf),
3369 					  X86_JE);
3370 		if (err)
3371 			return err;
3372 
3373 		emit_indirect_jump(&prog, 2 /* rdx */, image + (prog - buf));
3374 
3375 		*pprog = prog;
3376 		return 0;
3377 	}
3378 
3379 	/* Not a leaf node, so we pivot, and recursively descend into
3380 	 * the lower and upper ranges.
3381 	 */
3382 	pivot = (b - a) / 2;
3383 	EMIT1(add_1mod(0x48, BPF_REG_3));		/* cmp rdx,func */
3384 	if (!is_simm32(progs[a + pivot]))
3385 		return -1;
3386 	EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3), progs[a + pivot]);
3387 
3388 	if (pivot > 2) {				/* jg upper_part */
3389 		/* Require near jump. */
3390 		jg_bytes = 4;
3391 		EMIT2_off32(0x0F, X86_JG + 0x10, 0);
3392 	} else {
3393 		EMIT2(X86_JG, 0);
3394 	}
3395 	jg_reloc = prog;
3396 
3397 	err = emit_bpf_dispatcher(&prog, a, a + pivot,	/* emit lower_part */
3398 				  progs, image, buf);
3399 	if (err)
3400 		return err;
3401 
3402 	/* From Intel 64 and IA-32 Architectures Optimization
3403 	 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
3404 	 * Coding Rule 11: All branch targets should be 16-byte
3405 	 * aligned.
3406 	 */
3407 	emit_align(&prog, 16);
3408 	jg_offset = prog - jg_reloc;
3409 	emit_code(jg_reloc - jg_bytes, jg_offset, jg_bytes);
3410 
3411 	err = emit_bpf_dispatcher(&prog, a + pivot + 1,	/* emit upper_part */
3412 				  b, progs, image, buf);
3413 	if (err)
3414 		return err;
3415 
3416 	*pprog = prog;
3417 	return 0;
3418 }
3419 
3420 static int cmp_ips(const void *a, const void *b)
3421 {
3422 	const s64 *ipa = a;
3423 	const s64 *ipb = b;
3424 
3425 	if (*ipa > *ipb)
3426 		return 1;
3427 	if (*ipa < *ipb)
3428 		return -1;
3429 	return 0;
3430 }
3431 
3432 int arch_prepare_bpf_dispatcher(void *image, void *buf, s64 *funcs, int num_funcs)
3433 {
3434 	u8 *prog = buf;
3435 
3436 	sort(funcs, num_funcs, sizeof(funcs[0]), cmp_ips, NULL);
3437 	return emit_bpf_dispatcher(&prog, 0, num_funcs - 1, funcs, image, buf);
3438 }
3439 
3440 static const char *bpf_get_prog_name(struct bpf_prog *prog)
3441 {
3442 	if (prog->aux->ksym.prog)
3443 		return prog->aux->ksym.name;
3444 	return prog->aux->name;
3445 }
3446 
3447 static void priv_stack_init_guard(void __percpu *priv_stack_ptr, int alloc_size)
3448 {
3449 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
3450 	u64 *stack_ptr;
3451 
3452 	for_each_possible_cpu(cpu) {
3453 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
3454 		stack_ptr[0] = PRIV_STACK_GUARD_VAL;
3455 		stack_ptr[underflow_idx] = PRIV_STACK_GUARD_VAL;
3456 	}
3457 }
3458 
3459 static void priv_stack_check_guard(void __percpu *priv_stack_ptr, int alloc_size,
3460 				   struct bpf_prog *prog)
3461 {
3462 	int cpu, underflow_idx = (alloc_size - PRIV_STACK_GUARD_SZ) >> 3;
3463 	u64 *stack_ptr;
3464 
3465 	for_each_possible_cpu(cpu) {
3466 		stack_ptr = per_cpu_ptr(priv_stack_ptr, cpu);
3467 		if (stack_ptr[0] != PRIV_STACK_GUARD_VAL ||
3468 		    stack_ptr[underflow_idx] != PRIV_STACK_GUARD_VAL) {
3469 			pr_err("BPF private stack overflow/underflow detected for prog %sx\n",
3470 			       bpf_get_prog_name(prog));
3471 			break;
3472 		}
3473 	}
3474 }
3475 
3476 struct x64_jit_data {
3477 	struct bpf_binary_header *rw_header;
3478 	struct bpf_binary_header *header;
3479 	int *addrs;
3480 	u8 *image;
3481 	int proglen;
3482 	struct jit_context ctx;
3483 };
3484 
3485 #define MAX_PASSES 20
3486 #define PADDING_PASSES (MAX_PASSES - 5)
3487 
3488 struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
3489 {
3490 	struct bpf_binary_header *rw_header = NULL;
3491 	struct bpf_binary_header *header = NULL;
3492 	struct bpf_prog *tmp, *orig_prog = prog;
3493 	void __percpu *priv_stack_ptr = NULL;
3494 	struct x64_jit_data *jit_data;
3495 	int priv_stack_alloc_sz;
3496 	int proglen, oldproglen = 0;
3497 	struct jit_context ctx = {};
3498 	bool tmp_blinded = false;
3499 	bool extra_pass = false;
3500 	bool padding = false;
3501 	u8 *rw_image = NULL;
3502 	u8 *image = NULL;
3503 	int *addrs;
3504 	int pass;
3505 	int i;
3506 
3507 	if (!prog->jit_requested)
3508 		return orig_prog;
3509 
3510 	tmp = bpf_jit_blind_constants(prog);
3511 	/*
3512 	 * If blinding was requested and we failed during blinding,
3513 	 * we must fall back to the interpreter.
3514 	 */
3515 	if (IS_ERR(tmp))
3516 		return orig_prog;
3517 	if (tmp != prog) {
3518 		tmp_blinded = true;
3519 		prog = tmp;
3520 	}
3521 
3522 	jit_data = prog->aux->jit_data;
3523 	if (!jit_data) {
3524 		jit_data = kzalloc(sizeof(*jit_data), GFP_KERNEL);
3525 		if (!jit_data) {
3526 			prog = orig_prog;
3527 			goto out;
3528 		}
3529 		prog->aux->jit_data = jit_data;
3530 	}
3531 	priv_stack_ptr = prog->aux->priv_stack_ptr;
3532 	if (!priv_stack_ptr && prog->aux->jits_use_priv_stack) {
3533 		/* Allocate actual private stack size with verifier-calculated
3534 		 * stack size plus two memory guards to protect overflow and
3535 		 * underflow.
3536 		 */
3537 		priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
3538 				      2 * PRIV_STACK_GUARD_SZ;
3539 		priv_stack_ptr = __alloc_percpu_gfp(priv_stack_alloc_sz, 8, GFP_KERNEL);
3540 		if (!priv_stack_ptr) {
3541 			prog = orig_prog;
3542 			goto out_priv_stack;
3543 		}
3544 
3545 		priv_stack_init_guard(priv_stack_ptr, priv_stack_alloc_sz);
3546 		prog->aux->priv_stack_ptr = priv_stack_ptr;
3547 	}
3548 	addrs = jit_data->addrs;
3549 	if (addrs) {
3550 		ctx = jit_data->ctx;
3551 		oldproglen = jit_data->proglen;
3552 		image = jit_data->image;
3553 		header = jit_data->header;
3554 		rw_header = jit_data->rw_header;
3555 		rw_image = (void *)rw_header + ((void *)image - (void *)header);
3556 		extra_pass = true;
3557 		padding = true;
3558 		goto skip_init_addrs;
3559 	}
3560 	addrs = kvmalloc_array(prog->len + 1, sizeof(*addrs), GFP_KERNEL);
3561 	if (!addrs) {
3562 		prog = orig_prog;
3563 		goto out_addrs;
3564 	}
3565 
3566 	/*
3567 	 * Before first pass, make a rough estimation of addrs[]
3568 	 * each BPF instruction is translated to less than 64 bytes
3569 	 */
3570 	for (proglen = 0, i = 0; i <= prog->len; i++) {
3571 		proglen += 64;
3572 		addrs[i] = proglen;
3573 	}
3574 	ctx.cleanup_addr = proglen;
3575 skip_init_addrs:
3576 
3577 	/*
3578 	 * JITed image shrinks with every pass and the loop iterates
3579 	 * until the image stops shrinking. Very large BPF programs
3580 	 * may converge on the last pass. In such case do one more
3581 	 * pass to emit the final image.
3582 	 */
3583 	for (pass = 0; pass < MAX_PASSES || image; pass++) {
3584 		if (!padding && pass >= PADDING_PASSES)
3585 			padding = true;
3586 		proglen = do_jit(prog, addrs, image, rw_image, oldproglen, &ctx, padding);
3587 		if (proglen <= 0) {
3588 out_image:
3589 			image = NULL;
3590 			if (header) {
3591 				bpf_arch_text_copy(&header->size, &rw_header->size,
3592 						   sizeof(rw_header->size));
3593 				bpf_jit_binary_pack_free(header, rw_header);
3594 			}
3595 			/* Fall back to interpreter mode */
3596 			prog = orig_prog;
3597 			if (extra_pass) {
3598 				prog->bpf_func = NULL;
3599 				prog->jited = 0;
3600 				prog->jited_len = 0;
3601 			}
3602 			goto out_addrs;
3603 		}
3604 		if (image) {
3605 			if (proglen != oldproglen) {
3606 				pr_err("bpf_jit: proglen=%d != oldproglen=%d\n",
3607 				       proglen, oldproglen);
3608 				goto out_image;
3609 			}
3610 			break;
3611 		}
3612 		if (proglen == oldproglen) {
3613 			/*
3614 			 * The number of entries in extable is the number of BPF_LDX
3615 			 * insns that access kernel memory via "pointer to BTF type".
3616 			 * The verifier changed their opcode from LDX|MEM|size
3617 			 * to LDX|PROBE_MEM|size to make JITing easier.
3618 			 */
3619 			u32 align = __alignof__(struct exception_table_entry);
3620 			u32 extable_size = prog->aux->num_exentries *
3621 				sizeof(struct exception_table_entry);
3622 
3623 			/* allocate module memory for x86 insns and extable */
3624 			header = bpf_jit_binary_pack_alloc(roundup(proglen, align) + extable_size,
3625 							   &image, align, &rw_header, &rw_image,
3626 							   jit_fill_hole);
3627 			if (!header) {
3628 				prog = orig_prog;
3629 				goto out_addrs;
3630 			}
3631 			prog->aux->extable = (void *) image + roundup(proglen, align);
3632 		}
3633 		oldproglen = proglen;
3634 		cond_resched();
3635 	}
3636 
3637 	if (bpf_jit_enable > 1)
3638 		bpf_jit_dump(prog->len, proglen, pass + 1, rw_image);
3639 
3640 	if (image) {
3641 		if (!prog->is_func || extra_pass) {
3642 			/*
3643 			 * bpf_jit_binary_pack_finalize fails in two scenarios:
3644 			 *   1) header is not pointing to proper module memory;
3645 			 *   2) the arch doesn't support bpf_arch_text_copy().
3646 			 *
3647 			 * Both cases are serious bugs and justify WARN_ON.
3648 			 */
3649 			if (WARN_ON(bpf_jit_binary_pack_finalize(header, rw_header))) {
3650 				/* header has been freed */
3651 				header = NULL;
3652 				goto out_image;
3653 			}
3654 
3655 			bpf_tail_call_direct_fixup(prog);
3656 		} else {
3657 			jit_data->addrs = addrs;
3658 			jit_data->ctx = ctx;
3659 			jit_data->proglen = proglen;
3660 			jit_data->image = image;
3661 			jit_data->header = header;
3662 			jit_data->rw_header = rw_header;
3663 		}
3664 		/*
3665 		 * ctx.prog_offset is used when CFI preambles put code *before*
3666 		 * the function. See emit_cfi(). For FineIBT specifically this code
3667 		 * can also be executed and bpf_prog_kallsyms_add() will
3668 		 * generate an additional symbol to cover this, hence also
3669 		 * decrement proglen.
3670 		 */
3671 		prog->bpf_func = (void *)image + cfi_get_offset();
3672 		prog->jited = 1;
3673 		prog->jited_len = proglen - cfi_get_offset();
3674 	} else {
3675 		prog = orig_prog;
3676 	}
3677 
3678 	if (!image || !prog->is_func || extra_pass) {
3679 		if (image)
3680 			bpf_prog_fill_jited_linfo(prog, addrs + 1);
3681 out_addrs:
3682 		kvfree(addrs);
3683 		if (!image && priv_stack_ptr) {
3684 			free_percpu(priv_stack_ptr);
3685 			prog->aux->priv_stack_ptr = NULL;
3686 		}
3687 out_priv_stack:
3688 		kfree(jit_data);
3689 		prog->aux->jit_data = NULL;
3690 	}
3691 out:
3692 	if (tmp_blinded)
3693 		bpf_jit_prog_release_other(prog, prog == orig_prog ?
3694 					   tmp : orig_prog);
3695 	return prog;
3696 }
3697 
3698 bool bpf_jit_supports_kfunc_call(void)
3699 {
3700 	return true;
3701 }
3702 
3703 void *bpf_arch_text_copy(void *dst, void *src, size_t len)
3704 {
3705 	if (text_poke_copy(dst, src, len) == NULL)
3706 		return ERR_PTR(-EINVAL);
3707 	return dst;
3708 }
3709 
3710 /* Indicate the JIT backend supports mixing bpf2bpf and tailcalls. */
3711 bool bpf_jit_supports_subprog_tailcalls(void)
3712 {
3713 	return true;
3714 }
3715 
3716 bool bpf_jit_supports_percpu_insn(void)
3717 {
3718 	return true;
3719 }
3720 
3721 void bpf_jit_free(struct bpf_prog *prog)
3722 {
3723 	if (prog->jited) {
3724 		struct x64_jit_data *jit_data = prog->aux->jit_data;
3725 		struct bpf_binary_header *hdr;
3726 		void __percpu *priv_stack_ptr;
3727 		int priv_stack_alloc_sz;
3728 
3729 		/*
3730 		 * If we fail the final pass of JIT (from jit_subprogs),
3731 		 * the program may not be finalized yet. Call finalize here
3732 		 * before freeing it.
3733 		 */
3734 		if (jit_data) {
3735 			bpf_jit_binary_pack_finalize(jit_data->header,
3736 						     jit_data->rw_header);
3737 			kvfree(jit_data->addrs);
3738 			kfree(jit_data);
3739 		}
3740 		prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset();
3741 		hdr = bpf_jit_binary_pack_hdr(prog);
3742 		bpf_jit_binary_pack_free(hdr, NULL);
3743 		priv_stack_ptr = prog->aux->priv_stack_ptr;
3744 		if (priv_stack_ptr) {
3745 			priv_stack_alloc_sz = round_up(prog->aux->stack_depth, 8) +
3746 					      2 * PRIV_STACK_GUARD_SZ;
3747 			priv_stack_check_guard(priv_stack_ptr, priv_stack_alloc_sz, prog);
3748 			free_percpu(prog->aux->priv_stack_ptr);
3749 		}
3750 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog));
3751 	}
3752 
3753 	bpf_prog_unlock_free(prog);
3754 }
3755 
3756 bool bpf_jit_supports_exceptions(void)
3757 {
3758 	/* We unwind through both kernel frames (starting from within bpf_throw
3759 	 * call) and BPF frames. Therefore we require ORC unwinder to be enabled
3760 	 * to walk kernel frames and reach BPF frames in the stack trace.
3761 	 */
3762 	return IS_ENABLED(CONFIG_UNWINDER_ORC);
3763 }
3764 
3765 bool bpf_jit_supports_private_stack(void)
3766 {
3767 	return true;
3768 }
3769 
3770 void arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
3771 {
3772 #if defined(CONFIG_UNWINDER_ORC)
3773 	struct unwind_state state;
3774 	unsigned long addr;
3775 
3776 	for (unwind_start(&state, current, NULL, NULL); !unwind_done(&state);
3777 	     unwind_next_frame(&state)) {
3778 		addr = unwind_get_return_address(&state);
3779 		if (!addr || !consume_fn(cookie, (u64)addr, (u64)state.sp, (u64)state.bp))
3780 			break;
3781 	}
3782 	return;
3783 #endif
3784 	WARN(1, "verification of programs using bpf_throw should have failed\n");
3785 }
3786 
3787 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
3788 			       struct bpf_prog *new, struct bpf_prog *old)
3789 {
3790 	u8 *old_addr, *new_addr, *old_bypass_addr;
3791 	int ret;
3792 
3793 	old_bypass_addr = old ? NULL : poke->bypass_addr;
3794 	old_addr = old ? (u8 *)old->bpf_func + poke->adj_off : NULL;
3795 	new_addr = new ? (u8 *)new->bpf_func + poke->adj_off : NULL;
3796 
3797 	/*
3798 	 * On program loading or teardown, the program's kallsym entry
3799 	 * might not be in place, so we use __bpf_arch_text_poke to skip
3800 	 * the kallsyms check.
3801 	 */
3802 	if (new) {
3803 		ret = __bpf_arch_text_poke(poke->tailcall_target,
3804 					   BPF_MOD_JUMP,
3805 					   old_addr, new_addr);
3806 		BUG_ON(ret < 0);
3807 		if (!old) {
3808 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
3809 						   BPF_MOD_JUMP,
3810 						   poke->bypass_addr,
3811 						   NULL);
3812 			BUG_ON(ret < 0);
3813 		}
3814 	} else {
3815 		ret = __bpf_arch_text_poke(poke->tailcall_bypass,
3816 					   BPF_MOD_JUMP,
3817 					   old_bypass_addr,
3818 					   poke->bypass_addr);
3819 		BUG_ON(ret < 0);
3820 		/* let other CPUs finish the execution of program
3821 		 * so that it will not possible to expose them
3822 		 * to invalid nop, stack unwind, nop state
3823 		 */
3824 		if (!ret)
3825 			synchronize_rcu();
3826 		ret = __bpf_arch_text_poke(poke->tailcall_target,
3827 					   BPF_MOD_JUMP,
3828 					   old_addr, NULL);
3829 		BUG_ON(ret < 0);
3830 	}
3831 }
3832 
3833 bool bpf_jit_supports_arena(void)
3834 {
3835 	return true;
3836 }
3837 
3838 bool bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
3839 {
3840 	if (!in_arena)
3841 		return true;
3842 	switch (insn->code) {
3843 	case BPF_STX | BPF_ATOMIC | BPF_W:
3844 	case BPF_STX | BPF_ATOMIC | BPF_DW:
3845 		if (insn->imm == (BPF_AND | BPF_FETCH) ||
3846 		    insn->imm == (BPF_OR | BPF_FETCH) ||
3847 		    insn->imm == (BPF_XOR | BPF_FETCH))
3848 			return false;
3849 	}
3850 	return true;
3851 }
3852 
3853 bool bpf_jit_supports_ptr_xchg(void)
3854 {
3855 	return true;
3856 }
3857 
3858 /* x86-64 JIT emits its own code to filter user addresses so return 0 here */
3859 u64 bpf_arch_uaddress_limit(void)
3860 {
3861 	return 0;
3862 }
3863 
3864 bool bpf_jit_supports_timed_may_goto(void)
3865 {
3866 	return true;
3867 }
3868