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