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