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