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