• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * bpf_jit_comp.c: BPF JIT compiler
4  *
5  * Copyright (C) 2011-2013 Eric Dumazet (eric.dumazet@gmail.com)
6  * Internal BPF Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
7  */
8 #include <linux/netdevice.h>
9 #include <linux/filter.h>
10 #include <linux/if_vlan.h>
11 #include <linux/bpf.h>
12 #include <linux/memory.h>
13 #include <linux/sort.h>
14 #include <asm/extable.h>
15 #include <asm/set_memory.h>
16 #include <asm/nospec-branch.h>
17 #include <asm/text-patching.h>
18 
emit_code(u8 * ptr,u32 bytes,unsigned int len)19 static u8 *emit_code(u8 *ptr, u32 bytes, unsigned int len)
20 {
21 	if (len == 1)
22 		*ptr = bytes;
23 	else if (len == 2)
24 		*(u16 *)ptr = bytes;
25 	else {
26 		*(u32 *)ptr = bytes;
27 		barrier();
28 	}
29 	return ptr + len;
30 }
31 
32 #define EMIT(bytes, len) \
33 	do { prog = emit_code(prog, bytes, len); cnt += len; } while (0)
34 
35 #define EMIT1(b1)		EMIT(b1, 1)
36 #define EMIT2(b1, b2)		EMIT((b1) + ((b2) << 8), 2)
37 #define EMIT3(b1, b2, b3)	EMIT((b1) + ((b2) << 8) + ((b3) << 16), 3)
38 #define EMIT4(b1, b2, b3, b4)   EMIT((b1) + ((b2) << 8) + ((b3) << 16) + ((b4) << 24), 4)
39 
40 #define EMIT1_off32(b1, off) \
41 	do { EMIT1(b1); EMIT(off, 4); } while (0)
42 #define EMIT2_off32(b1, b2, off) \
43 	do { EMIT2(b1, b2); EMIT(off, 4); } while (0)
44 #define EMIT3_off32(b1, b2, b3, off) \
45 	do { EMIT3(b1, b2, b3); EMIT(off, 4); } while (0)
46 #define EMIT4_off32(b1, b2, b3, b4, off) \
47 	do { EMIT4(b1, b2, b3, b4); EMIT(off, 4); } while (0)
48 
is_imm8(int value)49 static bool is_imm8(int value)
50 {
51 	return value <= 127 && value >= -128;
52 }
53 
is_simm32(s64 value)54 static bool is_simm32(s64 value)
55 {
56 	return value == (s64)(s32)value;
57 }
58 
is_uimm32(u64 value)59 static bool is_uimm32(u64 value)
60 {
61 	return value == (u64)(u32)value;
62 }
63 
64 /* mov dst, src */
65 #define EMIT_mov(DST, SRC)								 \
66 	do {										 \
67 		if (DST != SRC)								 \
68 			EMIT3(add_2mod(0x48, DST, SRC), 0x89, add_2reg(0xC0, DST, SRC)); \
69 	} while (0)
70 
bpf_size_to_x86_bytes(int bpf_size)71 static int bpf_size_to_x86_bytes(int bpf_size)
72 {
73 	if (bpf_size == BPF_W)
74 		return 4;
75 	else if (bpf_size == BPF_H)
76 		return 2;
77 	else if (bpf_size == BPF_B)
78 		return 1;
79 	else if (bpf_size == BPF_DW)
80 		return 4; /* imm32 */
81 	else
82 		return 0;
83 }
84 
85 /*
86  * List of x86 cond jumps opcodes (. + s8)
87  * Add 0x10 (and an extra 0x0f) to generate far jumps (. + s32)
88  */
89 #define X86_JB  0x72
90 #define X86_JAE 0x73
91 #define X86_JE  0x74
92 #define X86_JNE 0x75
93 #define X86_JBE 0x76
94 #define X86_JA  0x77
95 #define X86_JL  0x7C
96 #define X86_JGE 0x7D
97 #define X86_JLE 0x7E
98 #define X86_JG  0x7F
99 
100 /* Pick a register outside of BPF range for JIT internal work */
101 #define AUX_REG (MAX_BPF_JIT_REG + 1)
102 #define X86_REG_R9 (MAX_BPF_JIT_REG + 2)
103 
104 /*
105  * The following table maps BPF registers to x86-64 registers.
106  *
107  * x86-64 register R12 is unused, since if used as base address
108  * register in load/store instructions, it always needs an
109  * extra byte of encoding and is callee saved.
110  *
111  * x86-64 register R9 is not used by BPF programs, but can be used by BPF
112  * trampoline. x86-64 register R10 is used for blinding (if enabled).
113  */
114 static const int reg2hex[] = {
115 	[BPF_REG_0] = 0,  /* RAX */
116 	[BPF_REG_1] = 7,  /* RDI */
117 	[BPF_REG_2] = 6,  /* RSI */
118 	[BPF_REG_3] = 2,  /* RDX */
119 	[BPF_REG_4] = 1,  /* RCX */
120 	[BPF_REG_5] = 0,  /* R8  */
121 	[BPF_REG_6] = 3,  /* RBX callee saved */
122 	[BPF_REG_7] = 5,  /* R13 callee saved */
123 	[BPF_REG_8] = 6,  /* R14 callee saved */
124 	[BPF_REG_9] = 7,  /* R15 callee saved */
125 	[BPF_REG_FP] = 5, /* RBP readonly */
126 	[BPF_REG_AX] = 2, /* R10 temp register */
127 	[AUX_REG] = 3,    /* R11 temp register */
128 	[X86_REG_R9] = 1, /* R9 register, 6th function argument */
129 };
130 
131 static const int reg2pt_regs[] = {
132 	[BPF_REG_0] = offsetof(struct pt_regs, ax),
133 	[BPF_REG_1] = offsetof(struct pt_regs, di),
134 	[BPF_REG_2] = offsetof(struct pt_regs, si),
135 	[BPF_REG_3] = offsetof(struct pt_regs, dx),
136 	[BPF_REG_4] = offsetof(struct pt_regs, cx),
137 	[BPF_REG_5] = offsetof(struct pt_regs, r8),
138 	[BPF_REG_6] = offsetof(struct pt_regs, bx),
139 	[BPF_REG_7] = offsetof(struct pt_regs, r13),
140 	[BPF_REG_8] = offsetof(struct pt_regs, r14),
141 	[BPF_REG_9] = offsetof(struct pt_regs, r15),
142 };
143 
144 /*
145  * is_ereg() == true if BPF register 'reg' maps to x86-64 r8..r15
146  * which need extra byte of encoding.
147  * rax,rcx,...,rbp have simpler encoding
148  */
is_ereg(u32 reg)149 static bool is_ereg(u32 reg)
150 {
151 	return (1 << reg) & (BIT(BPF_REG_5) |
152 			     BIT(AUX_REG) |
153 			     BIT(BPF_REG_7) |
154 			     BIT(BPF_REG_8) |
155 			     BIT(BPF_REG_9) |
156 			     BIT(X86_REG_R9) |
157 			     BIT(BPF_REG_AX));
158 }
159 
160 /*
161  * is_ereg_8l() == true if BPF register 'reg' is mapped to access x86-64
162  * lower 8-bit registers dil,sil,bpl,spl,r8b..r15b, which need extra byte
163  * of encoding. al,cl,dl,bl have simpler encoding.
164  */
is_ereg_8l(u32 reg)165 static bool is_ereg_8l(u32 reg)
166 {
167 	return is_ereg(reg) ||
168 	    (1 << reg) & (BIT(BPF_REG_1) |
169 			  BIT(BPF_REG_2) |
170 			  BIT(BPF_REG_FP));
171 }
172 
is_axreg(u32 reg)173 static bool is_axreg(u32 reg)
174 {
175 	return reg == BPF_REG_0;
176 }
177 
178 /* Add modifiers if 'reg' maps to x86-64 registers R8..R15 */
add_1mod(u8 byte,u32 reg)179 static u8 add_1mod(u8 byte, u32 reg)
180 {
181 	if (is_ereg(reg))
182 		byte |= 1;
183 	return byte;
184 }
185 
add_2mod(u8 byte,u32 r1,u32 r2)186 static u8 add_2mod(u8 byte, u32 r1, u32 r2)
187 {
188 	if (is_ereg(r1))
189 		byte |= 1;
190 	if (is_ereg(r2))
191 		byte |= 4;
192 	return byte;
193 }
194 
195 /* Encode 'dst_reg' register into x86-64 opcode 'byte' */
add_1reg(u8 byte,u32 dst_reg)196 static u8 add_1reg(u8 byte, u32 dst_reg)
197 {
198 	return byte + reg2hex[dst_reg];
199 }
200 
201 /* Encode 'dst_reg' and 'src_reg' registers into x86-64 opcode 'byte' */
add_2reg(u8 byte,u32 dst_reg,u32 src_reg)202 static u8 add_2reg(u8 byte, u32 dst_reg, u32 src_reg)
203 {
204 	return byte + reg2hex[dst_reg] + (reg2hex[src_reg] << 3);
205 }
206 
jit_fill_hole(void * area,unsigned int size)207 static void jit_fill_hole(void *area, unsigned int size)
208 {
209 	/* Fill whole space with INT3 instructions */
210 	memset(area, 0xcc, size);
211 }
212 
213 struct jit_context {
214 	int cleanup_addr; /* Epilogue code offset */
215 
216 	/*
217 	 * Program specific offsets of labels in the code; these rely on the
218 	 * JIT doing at least 2 passes, recording the position on the first
219 	 * pass, only to generate the correct offset on the second pass.
220 	 */
221 	int tail_call_direct_label;
222 	int tail_call_indirect_label;
223 };
224 
225 /* Maximum number of bytes emitted while JITing one eBPF insn */
226 #define BPF_MAX_INSN_SIZE	128
227 #define BPF_INSN_SAFETY		64
228 
229 /* Number of bytes emit_patch() needs to generate instructions */
230 #define X86_PATCH_SIZE		5
231 /* Number of bytes that will be skipped on tailcall */
232 #define X86_TAIL_CALL_OFFSET	11
233 
push_callee_regs(u8 ** pprog,bool * callee_regs_used)234 static void push_callee_regs(u8 **pprog, bool *callee_regs_used)
235 {
236 	u8 *prog = *pprog;
237 	int cnt = 0;
238 
239 	if (callee_regs_used[0])
240 		EMIT1(0x53);         /* push rbx */
241 	if (callee_regs_used[1])
242 		EMIT2(0x41, 0x55);   /* push r13 */
243 	if (callee_regs_used[2])
244 		EMIT2(0x41, 0x56);   /* push r14 */
245 	if (callee_regs_used[3])
246 		EMIT2(0x41, 0x57);   /* push r15 */
247 	*pprog = prog;
248 }
249 
pop_callee_regs(u8 ** pprog,bool * callee_regs_used)250 static void pop_callee_regs(u8 **pprog, bool *callee_regs_used)
251 {
252 	u8 *prog = *pprog;
253 	int cnt = 0;
254 
255 	if (callee_regs_used[3])
256 		EMIT2(0x41, 0x5F);   /* pop r15 */
257 	if (callee_regs_used[2])
258 		EMIT2(0x41, 0x5E);   /* pop r14 */
259 	if (callee_regs_used[1])
260 		EMIT2(0x41, 0x5D);   /* pop r13 */
261 	if (callee_regs_used[0])
262 		EMIT1(0x5B);         /* pop rbx */
263 	*pprog = prog;
264 }
265 
266 /*
267  * Emit x86-64 prologue code for BPF program.
268  * bpf_tail_call helper will skip the first X86_TAIL_CALL_OFFSET bytes
269  * while jumping to another program
270  */
emit_prologue(u8 ** pprog,u32 stack_depth,bool ebpf_from_cbpf,bool tail_call_reachable,bool is_subprog)271 static void emit_prologue(u8 **pprog, u32 stack_depth, bool ebpf_from_cbpf,
272 			  bool tail_call_reachable, bool is_subprog)
273 {
274 	u8 *prog = *pprog;
275 	int cnt = X86_PATCH_SIZE;
276 
277 	/* BPF trampoline can be made to work without these nops,
278 	 * but let's waste 5 bytes for now and optimize later
279 	 */
280 	memcpy(prog, ideal_nops[NOP_ATOMIC5], cnt);
281 	prog += cnt;
282 	if (!ebpf_from_cbpf) {
283 		if (tail_call_reachable && !is_subprog)
284 			EMIT2(0x31, 0xC0); /* xor eax, eax */
285 		else
286 			EMIT2(0x66, 0x90); /* nop2 */
287 	}
288 	EMIT1(0x55);             /* push rbp */
289 	EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
290 	/* sub rsp, rounded_stack_depth */
291 	if (stack_depth)
292 		EMIT3_off32(0x48, 0x81, 0xEC, round_up(stack_depth, 8));
293 	if (tail_call_reachable)
294 		EMIT1(0x50);         /* push rax */
295 	*pprog = prog;
296 }
297 
emit_patch(u8 ** pprog,void * func,void * ip,u8 opcode)298 static int emit_patch(u8 **pprog, void *func, void *ip, u8 opcode)
299 {
300 	u8 *prog = *pprog;
301 	int cnt = 0;
302 	s64 offset;
303 
304 	offset = func - (ip + X86_PATCH_SIZE);
305 	if (!is_simm32(offset)) {
306 		pr_err("Target call %p is out of range\n", func);
307 		return -ERANGE;
308 	}
309 	EMIT1_off32(opcode, offset);
310 	*pprog = prog;
311 	return 0;
312 }
313 
emit_call(u8 ** pprog,void * func,void * ip)314 static int emit_call(u8 **pprog, void *func, void *ip)
315 {
316 	return emit_patch(pprog, func, ip, 0xE8);
317 }
318 
emit_jump(u8 ** pprog,void * func,void * ip)319 static int emit_jump(u8 **pprog, void *func, void *ip)
320 {
321 	return emit_patch(pprog, func, ip, 0xE9);
322 }
323 
__bpf_arch_text_poke(void * ip,enum bpf_text_poke_type t,void * old_addr,void * new_addr,const bool text_live)324 static int __bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
325 				void *old_addr, void *new_addr,
326 				const bool text_live)
327 {
328 	const u8 *nop_insn = ideal_nops[NOP_ATOMIC5];
329 	u8 old_insn[X86_PATCH_SIZE];
330 	u8 new_insn[X86_PATCH_SIZE];
331 	u8 *prog;
332 	int ret;
333 
334 	memcpy(old_insn, nop_insn, X86_PATCH_SIZE);
335 	if (old_addr) {
336 		prog = old_insn;
337 		ret = t == BPF_MOD_CALL ?
338 		      emit_call(&prog, old_addr, ip) :
339 		      emit_jump(&prog, old_addr, ip);
340 		if (ret)
341 			return ret;
342 	}
343 
344 	memcpy(new_insn, nop_insn, X86_PATCH_SIZE);
345 	if (new_addr) {
346 		prog = new_insn;
347 		ret = t == BPF_MOD_CALL ?
348 		      emit_call(&prog, new_addr, ip) :
349 		      emit_jump(&prog, new_addr, ip);
350 		if (ret)
351 			return ret;
352 	}
353 
354 	ret = -EBUSY;
355 	mutex_lock(&text_mutex);
356 	if (memcmp(ip, old_insn, X86_PATCH_SIZE))
357 		goto out;
358 	ret = 1;
359 	if (memcmp(ip, new_insn, X86_PATCH_SIZE)) {
360 		if (text_live)
361 			text_poke_bp(ip, new_insn, X86_PATCH_SIZE, NULL);
362 		else
363 			memcpy(ip, new_insn, X86_PATCH_SIZE);
364 		ret = 0;
365 	}
366 out:
367 	mutex_unlock(&text_mutex);
368 	return ret;
369 }
370 
bpf_arch_text_poke(void * ip,enum bpf_text_poke_type t,void * old_addr,void * new_addr)371 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
372 		       void *old_addr, void *new_addr)
373 {
374 	if (!is_kernel_text((long)ip) &&
375 	    !is_bpf_text_address((long)ip))
376 		/* BPF poking in modules is not supported */
377 		return -EINVAL;
378 
379 	return __bpf_arch_text_poke(ip, t, old_addr, new_addr, true);
380 }
381 
382 #define EMIT_LFENCE()	EMIT3(0x0F, 0xAE, 0xE8)
383 
emit_indirect_jump(u8 ** pprog,int reg,u8 * ip)384 static void emit_indirect_jump(u8 **pprog, int reg, u8 *ip)
385 {
386 	u8 *prog = *pprog;
387 	int cnt = 0;
388 
389 #ifdef CONFIG_RETPOLINE
390 	if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
391 		EMIT_LFENCE();
392 		EMIT2(0xFF, 0xE0 + reg);
393 	} else if (cpu_feature_enabled(X86_FEATURE_RETPOLINE)) {
394 		emit_jump(&prog, &__x86_indirect_thunk_array[reg], ip);
395 	} else
396 #endif
397 	EMIT2(0xFF, 0xE0 + reg);
398 
399 	*pprog = prog;
400 }
401 
emit_return(u8 ** pprog,u8 * ip)402 static void emit_return(u8 **pprog, u8 *ip)
403 {
404 	u8 *prog = *pprog;
405 	int cnt = 0;
406 
407 	if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) {
408 		emit_jump(&prog, x86_return_thunk, ip);
409 	} else {
410 		EMIT1(0xC3);		/* ret */
411 		if (IS_ENABLED(CONFIG_SLS))
412 			EMIT1(0xCC);	/* int3 */
413 	}
414 
415 	*pprog = prog;
416 }
417 
418 /*
419  * Generate the following code:
420  *
421  * ... bpf_tail_call(void *ctx, struct bpf_array *array, u64 index) ...
422  *   if (index >= array->map.max_entries)
423  *     goto out;
424  *   if (++tail_call_cnt > MAX_TAIL_CALL_CNT)
425  *     goto out;
426  *   prog = array->ptrs[index];
427  *   if (prog == NULL)
428  *     goto out;
429  *   goto *(prog->bpf_func + prologue_size);
430  * out:
431  */
emit_bpf_tail_call_indirect(u8 ** pprog,bool * callee_regs_used,u32 stack_depth,u8 * ip,struct jit_context * ctx)432 static void emit_bpf_tail_call_indirect(u8 **pprog, bool *callee_regs_used,
433 					u32 stack_depth, u8 *ip,
434 					struct jit_context *ctx)
435 {
436 	int tcc_off = -4 - round_up(stack_depth, 8);
437 	u8 *prog = *pprog, *start = *pprog;
438 	int cnt = 0, offset;
439 
440 	/*
441 	 * rdi - pointer to ctx
442 	 * rsi - pointer to bpf_array
443 	 * rdx - index in bpf_array
444 	 */
445 
446 	/*
447 	 * if (index >= array->map.max_entries)
448 	 *	goto out;
449 	 */
450 	EMIT2(0x89, 0xD2);                        /* mov edx, edx */
451 	EMIT3(0x39, 0x56,                         /* cmp dword ptr [rsi + 16], edx */
452 	      offsetof(struct bpf_array, map.max_entries));
453 
454 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
455 	EMIT2(X86_JBE, offset);                   /* jbe out */
456 
457 	/*
458 	 * if (tail_call_cnt > MAX_TAIL_CALL_CNT)
459 	 *	goto out;
460 	 */
461 	EMIT2_off32(0x8B, 0x85, tcc_off);         /* mov eax, dword ptr [rbp - tcc_off] */
462 	EMIT3(0x83, 0xF8, MAX_TAIL_CALL_CNT);     /* cmp eax, MAX_TAIL_CALL_CNT */
463 
464 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
465 	EMIT2(X86_JA, offset);                    /* ja out */
466 	EMIT3(0x83, 0xC0, 0x01);                  /* add eax, 1 */
467 	EMIT2_off32(0x89, 0x85, tcc_off);         /* mov dword ptr [rbp - tcc_off], eax */
468 
469 	/* prog = array->ptrs[index]; */
470 	EMIT4_off32(0x48, 0x8B, 0x8C, 0xD6,       /* mov rcx, [rsi + rdx * 8 + offsetof(...)] */
471 		    offsetof(struct bpf_array, ptrs));
472 
473 	/*
474 	 * if (prog == NULL)
475 	 *	goto out;
476 	 */
477 	EMIT3(0x48, 0x85, 0xC9);                  /* test rcx,rcx */
478 
479 	offset = ctx->tail_call_indirect_label - (prog + 2 - start);
480 	EMIT2(X86_JE, offset);                    /* je out */
481 
482 	pop_callee_regs(&prog, callee_regs_used);
483 
484 	EMIT1(0x58);                              /* pop rax */
485 	if (stack_depth)
486 		EMIT3_off32(0x48, 0x81, 0xC4,     /* add rsp, sd */
487 			    round_up(stack_depth, 8));
488 
489 	/* goto *(prog->bpf_func + X86_TAIL_CALL_OFFSET); */
490 	EMIT4(0x48, 0x8B, 0x49,                   /* mov rcx, qword ptr [rcx + 32] */
491 	      offsetof(struct bpf_prog, bpf_func));
492 	EMIT4(0x48, 0x83, 0xC1,                   /* add rcx, X86_TAIL_CALL_OFFSET */
493 	      X86_TAIL_CALL_OFFSET);
494 	/*
495 	 * Now we're ready to jump into next BPF program
496 	 * rdi == ctx (1st arg)
497 	 * rcx == prog->bpf_func + X86_TAIL_CALL_OFFSET
498 	 */
499 	emit_indirect_jump(&prog, 1 /* rcx */, ip + (prog - start));
500 
501 	/* out: */
502 	ctx->tail_call_indirect_label = prog - start;
503 	*pprog = prog;
504 }
505 
emit_bpf_tail_call_direct(struct bpf_jit_poke_descriptor * poke,u8 ** pprog,u8 * ip,bool * callee_regs_used,u32 stack_depth,struct jit_context * ctx)506 static void emit_bpf_tail_call_direct(struct bpf_jit_poke_descriptor *poke,
507 				      u8 **pprog, u8 *ip,
508 				      bool *callee_regs_used, u32 stack_depth,
509 				      struct jit_context *ctx)
510 {
511 	int tcc_off = -4 - round_up(stack_depth, 8);
512 	u8 *prog = *pprog, *start = *pprog;
513 	int cnt = 0, offset;
514 
515 	/*
516 	 * if (tail_call_cnt > MAX_TAIL_CALL_CNT)
517 	 *	goto out;
518 	 */
519 	EMIT2_off32(0x8B, 0x85, tcc_off);             /* mov eax, dword ptr [rbp - tcc_off] */
520 	EMIT3(0x83, 0xF8, MAX_TAIL_CALL_CNT);         /* cmp eax, MAX_TAIL_CALL_CNT */
521 
522 	offset = ctx->tail_call_direct_label - (prog + 2 - start);
523 	EMIT2(X86_JA, offset);                        /* ja out */
524 	EMIT3(0x83, 0xC0, 0x01);                      /* add eax, 1 */
525 	EMIT2_off32(0x89, 0x85, tcc_off);             /* mov dword ptr [rbp - tcc_off], eax */
526 
527 	poke->tailcall_bypass = ip + (prog - start);
528 	poke->adj_off = X86_TAIL_CALL_OFFSET;
529 	poke->tailcall_target = ip + ctx->tail_call_direct_label - X86_PATCH_SIZE;
530 	poke->bypass_addr = (u8 *)poke->tailcall_target + X86_PATCH_SIZE;
531 
532 	emit_jump(&prog, (u8 *)poke->tailcall_target + X86_PATCH_SIZE,
533 		  poke->tailcall_bypass);
534 
535 	pop_callee_regs(&prog, callee_regs_used);
536 	EMIT1(0x58);                                  /* pop rax */
537 	if (stack_depth)
538 		EMIT3_off32(0x48, 0x81, 0xC4, round_up(stack_depth, 8));
539 
540 	memcpy(prog, ideal_nops[NOP_ATOMIC5], X86_PATCH_SIZE);
541 	prog += X86_PATCH_SIZE;
542 
543 	/* out: */
544 	ctx->tail_call_direct_label = prog - start;
545 
546 	*pprog = prog;
547 }
548 
bpf_tail_call_direct_fixup(struct bpf_prog * prog)549 static void bpf_tail_call_direct_fixup(struct bpf_prog *prog)
550 {
551 	struct bpf_jit_poke_descriptor *poke;
552 	struct bpf_array *array;
553 	struct bpf_prog *target;
554 	int i, ret;
555 
556 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
557 		poke = &prog->aux->poke_tab[i];
558 		WARN_ON_ONCE(READ_ONCE(poke->tailcall_target_stable));
559 
560 		if (poke->reason != BPF_POKE_REASON_TAIL_CALL)
561 			continue;
562 
563 		array = container_of(poke->tail_call.map, struct bpf_array, map);
564 		mutex_lock(&array->aux->poke_mutex);
565 		target = array->ptrs[poke->tail_call.key];
566 		if (target) {
567 			/* Plain memcpy is used when image is not live yet
568 			 * and still not locked as read-only. Once poke
569 			 * location is active (poke->tailcall_target_stable),
570 			 * any parallel bpf_arch_text_poke() might occur
571 			 * still on the read-write image until we finally
572 			 * locked it as read-only. Both modifications on
573 			 * the given image are under text_mutex to avoid
574 			 * interference.
575 			 */
576 			ret = __bpf_arch_text_poke(poke->tailcall_target,
577 						   BPF_MOD_JUMP, NULL,
578 						   (u8 *)target->bpf_func +
579 						   poke->adj_off, false);
580 			BUG_ON(ret < 0);
581 			ret = __bpf_arch_text_poke(poke->tailcall_bypass,
582 						   BPF_MOD_JUMP,
583 						   (u8 *)poke->tailcall_target +
584 						   X86_PATCH_SIZE, NULL, false);
585 			BUG_ON(ret < 0);
586 		}
587 		WRITE_ONCE(poke->tailcall_target_stable, true);
588 		mutex_unlock(&array->aux->poke_mutex);
589 	}
590 }
591 
emit_mov_imm32(u8 ** pprog,bool sign_propagate,u32 dst_reg,const u32 imm32)592 static void emit_mov_imm32(u8 **pprog, bool sign_propagate,
593 			   u32 dst_reg, const u32 imm32)
594 {
595 	u8 *prog = *pprog;
596 	u8 b1, b2, b3;
597 	int cnt = 0;
598 
599 	/*
600 	 * Optimization: if imm32 is positive, use 'mov %eax, imm32'
601 	 * (which zero-extends imm32) to save 2 bytes.
602 	 */
603 	if (sign_propagate && (s32)imm32 < 0) {
604 		/* 'mov %rax, imm32' sign extends imm32 */
605 		b1 = add_1mod(0x48, dst_reg);
606 		b2 = 0xC7;
607 		b3 = 0xC0;
608 		EMIT3_off32(b1, b2, add_1reg(b3, dst_reg), imm32);
609 		goto done;
610 	}
611 
612 	/*
613 	 * Optimization: if imm32 is zero, use 'xor %eax, %eax'
614 	 * to save 3 bytes.
615 	 */
616 	if (imm32 == 0) {
617 		if (is_ereg(dst_reg))
618 			EMIT1(add_2mod(0x40, dst_reg, dst_reg));
619 		b2 = 0x31; /* xor */
620 		b3 = 0xC0;
621 		EMIT2(b2, add_2reg(b3, dst_reg, dst_reg));
622 		goto done;
623 	}
624 
625 	/* mov %eax, imm32 */
626 	if (is_ereg(dst_reg))
627 		EMIT1(add_1mod(0x40, dst_reg));
628 	EMIT1_off32(add_1reg(0xB8, dst_reg), imm32);
629 done:
630 	*pprog = prog;
631 }
632 
emit_mov_imm64(u8 ** pprog,u32 dst_reg,const u32 imm32_hi,const u32 imm32_lo)633 static void emit_mov_imm64(u8 **pprog, u32 dst_reg,
634 			   const u32 imm32_hi, const u32 imm32_lo)
635 {
636 	u8 *prog = *pprog;
637 	int cnt = 0;
638 
639 	if (is_uimm32(((u64)imm32_hi << 32) | (u32)imm32_lo)) {
640 		/*
641 		 * For emitting plain u32, where sign bit must not be
642 		 * propagated LLVM tends to load imm64 over mov32
643 		 * directly, so save couple of bytes by just doing
644 		 * 'mov %eax, imm32' instead.
645 		 */
646 		emit_mov_imm32(&prog, false, dst_reg, imm32_lo);
647 	} else {
648 		/* movabsq %rax, imm64 */
649 		EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg));
650 		EMIT(imm32_lo, 4);
651 		EMIT(imm32_hi, 4);
652 	}
653 
654 	*pprog = prog;
655 }
656 
emit_mov_reg(u8 ** pprog,bool is64,u32 dst_reg,u32 src_reg)657 static void emit_mov_reg(u8 **pprog, bool is64, u32 dst_reg, u32 src_reg)
658 {
659 	u8 *prog = *pprog;
660 	int cnt = 0;
661 
662 	if (is64) {
663 		/* mov dst, src */
664 		EMIT_mov(dst_reg, src_reg);
665 	} else {
666 		/* mov32 dst, src */
667 		if (is_ereg(dst_reg) || is_ereg(src_reg))
668 			EMIT1(add_2mod(0x40, dst_reg, src_reg));
669 		EMIT2(0x89, add_2reg(0xC0, dst_reg, src_reg));
670 	}
671 
672 	*pprog = prog;
673 }
674 
675 /* LDX: dst_reg = *(u8*)(src_reg + off) */
emit_ldx(u8 ** pprog,u32 size,u32 dst_reg,u32 src_reg,int off)676 static void emit_ldx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
677 {
678 	u8 *prog = *pprog;
679 	int cnt = 0;
680 
681 	switch (size) {
682 	case BPF_B:
683 		/* Emit 'movzx rax, byte ptr [rax + off]' */
684 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB6);
685 		break;
686 	case BPF_H:
687 		/* Emit 'movzx rax, word ptr [rax + off]' */
688 		EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB7);
689 		break;
690 	case BPF_W:
691 		/* Emit 'mov eax, dword ptr [rax+0x14]' */
692 		if (is_ereg(dst_reg) || is_ereg(src_reg))
693 			EMIT2(add_2mod(0x40, src_reg, dst_reg), 0x8B);
694 		else
695 			EMIT1(0x8B);
696 		break;
697 	case BPF_DW:
698 		/* Emit 'mov rax, qword ptr [rax+0x14]' */
699 		EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x8B);
700 		break;
701 	}
702 	/*
703 	 * If insn->off == 0 we can save one extra byte, but
704 	 * special case of x86 R13 which always needs an offset
705 	 * is not worth the hassle
706 	 */
707 	if (is_imm8(off))
708 		EMIT2(add_2reg(0x40, src_reg, dst_reg), off);
709 	else
710 		EMIT1_off32(add_2reg(0x80, src_reg, dst_reg), off);
711 	*pprog = prog;
712 }
713 
714 /* STX: *(u8*)(dst_reg + off) = src_reg */
emit_stx(u8 ** pprog,u32 size,u32 dst_reg,u32 src_reg,int off)715 static void emit_stx(u8 **pprog, u32 size, u32 dst_reg, u32 src_reg, int off)
716 {
717 	u8 *prog = *pprog;
718 	int cnt = 0;
719 
720 	switch (size) {
721 	case BPF_B:
722 		/* Emit 'mov byte ptr [rax + off], al' */
723 		if (is_ereg(dst_reg) || is_ereg_8l(src_reg))
724 			/* Add extra byte for eregs or SIL,DIL,BPL in src_reg */
725 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x88);
726 		else
727 			EMIT1(0x88);
728 		break;
729 	case BPF_H:
730 		if (is_ereg(dst_reg) || is_ereg(src_reg))
731 			EMIT3(0x66, add_2mod(0x40, dst_reg, src_reg), 0x89);
732 		else
733 			EMIT2(0x66, 0x89);
734 		break;
735 	case BPF_W:
736 		if (is_ereg(dst_reg) || is_ereg(src_reg))
737 			EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x89);
738 		else
739 			EMIT1(0x89);
740 		break;
741 	case BPF_DW:
742 		EMIT2(add_2mod(0x48, dst_reg, src_reg), 0x89);
743 		break;
744 	}
745 	if (is_imm8(off))
746 		EMIT2(add_2reg(0x40, dst_reg, src_reg), off);
747 	else
748 		EMIT1_off32(add_2reg(0x80, dst_reg, src_reg), off);
749 	*pprog = prog;
750 }
751 
ex_handler_bpf(const struct exception_table_entry * x,struct pt_regs * regs,int trapnr,unsigned long error_code,unsigned long fault_addr)752 static bool ex_handler_bpf(const struct exception_table_entry *x,
753 			   struct pt_regs *regs, int trapnr,
754 			   unsigned long error_code, unsigned long fault_addr)
755 {
756 	u32 reg = x->fixup >> 8;
757 
758 	/* jump over faulting load and clear dest register */
759 	*(unsigned long *)((void *)regs + reg) = 0;
760 	regs->ip += x->fixup & 0xff;
761 	return true;
762 }
763 
detect_reg_usage(struct bpf_insn * insn,int insn_cnt,bool * regs_used,bool * tail_call_seen)764 static void detect_reg_usage(struct bpf_insn *insn, int insn_cnt,
765 			     bool *regs_used, bool *tail_call_seen)
766 {
767 	int i;
768 
769 	for (i = 1; i <= insn_cnt; i++, insn++) {
770 		if (insn->code == (BPF_JMP | BPF_TAIL_CALL))
771 			*tail_call_seen = true;
772 		if (insn->dst_reg == BPF_REG_6 || insn->src_reg == BPF_REG_6)
773 			regs_used[0] = true;
774 		if (insn->dst_reg == BPF_REG_7 || insn->src_reg == BPF_REG_7)
775 			regs_used[1] = true;
776 		if (insn->dst_reg == BPF_REG_8 || insn->src_reg == BPF_REG_8)
777 			regs_used[2] = true;
778 		if (insn->dst_reg == BPF_REG_9 || insn->src_reg == BPF_REG_9)
779 			regs_used[3] = true;
780 	}
781 }
782 
do_jit(struct bpf_prog * bpf_prog,int * addrs,u8 * image,int oldproglen,struct jit_context * ctx)783 static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image,
784 		  int oldproglen, struct jit_context *ctx)
785 {
786 	bool tail_call_reachable = bpf_prog->aux->tail_call_reachable;
787 	struct bpf_insn *insn = bpf_prog->insnsi;
788 	bool callee_regs_used[4] = {};
789 	int insn_cnt = bpf_prog->len;
790 	bool tail_call_seen = false;
791 	bool seen_exit = false;
792 	u8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY];
793 	int i, cnt = 0, excnt = 0;
794 	int proglen = 0;
795 	u8 *prog = temp;
796 
797 	detect_reg_usage(insn, insn_cnt, callee_regs_used,
798 			 &tail_call_seen);
799 
800 	/* tail call's presence in current prog implies it is reachable */
801 	tail_call_reachable |= tail_call_seen;
802 
803 	emit_prologue(&prog, bpf_prog->aux->stack_depth,
804 		      bpf_prog_was_classic(bpf_prog), tail_call_reachable,
805 		      bpf_prog->aux->func_idx != 0);
806 	push_callee_regs(&prog, callee_regs_used);
807 	addrs[0] = prog - temp;
808 
809 	for (i = 1; i <= insn_cnt; i++, insn++) {
810 		const s32 imm32 = insn->imm;
811 		u32 dst_reg = insn->dst_reg;
812 		u32 src_reg = insn->src_reg;
813 		u8 b2 = 0, b3 = 0;
814 		s64 jmp_offset;
815 		u8 jmp_cond;
816 		int ilen;
817 		u8 *func;
818 
819 		switch (insn->code) {
820 			/* ALU */
821 		case BPF_ALU | BPF_ADD | BPF_X:
822 		case BPF_ALU | BPF_SUB | BPF_X:
823 		case BPF_ALU | BPF_AND | BPF_X:
824 		case BPF_ALU | BPF_OR | BPF_X:
825 		case BPF_ALU | BPF_XOR | BPF_X:
826 		case BPF_ALU64 | BPF_ADD | BPF_X:
827 		case BPF_ALU64 | BPF_SUB | BPF_X:
828 		case BPF_ALU64 | BPF_AND | BPF_X:
829 		case BPF_ALU64 | BPF_OR | BPF_X:
830 		case BPF_ALU64 | BPF_XOR | BPF_X:
831 			switch (BPF_OP(insn->code)) {
832 			case BPF_ADD: b2 = 0x01; break;
833 			case BPF_SUB: b2 = 0x29; break;
834 			case BPF_AND: b2 = 0x21; break;
835 			case BPF_OR: b2 = 0x09; break;
836 			case BPF_XOR: b2 = 0x31; break;
837 			}
838 			if (BPF_CLASS(insn->code) == BPF_ALU64)
839 				EMIT1(add_2mod(0x48, dst_reg, src_reg));
840 			else if (is_ereg(dst_reg) || is_ereg(src_reg))
841 				EMIT1(add_2mod(0x40, dst_reg, src_reg));
842 			EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg));
843 			break;
844 
845 		case BPF_ALU64 | BPF_MOV | BPF_X:
846 		case BPF_ALU | BPF_MOV | BPF_X:
847 			emit_mov_reg(&prog,
848 				     BPF_CLASS(insn->code) == BPF_ALU64,
849 				     dst_reg, src_reg);
850 			break;
851 
852 			/* neg dst */
853 		case BPF_ALU | BPF_NEG:
854 		case BPF_ALU64 | BPF_NEG:
855 			if (BPF_CLASS(insn->code) == BPF_ALU64)
856 				EMIT1(add_1mod(0x48, dst_reg));
857 			else if (is_ereg(dst_reg))
858 				EMIT1(add_1mod(0x40, dst_reg));
859 			EMIT2(0xF7, add_1reg(0xD8, dst_reg));
860 			break;
861 
862 		case BPF_ALU | BPF_ADD | BPF_K:
863 		case BPF_ALU | BPF_SUB | BPF_K:
864 		case BPF_ALU | BPF_AND | BPF_K:
865 		case BPF_ALU | BPF_OR | BPF_K:
866 		case BPF_ALU | BPF_XOR | BPF_K:
867 		case BPF_ALU64 | BPF_ADD | BPF_K:
868 		case BPF_ALU64 | BPF_SUB | BPF_K:
869 		case BPF_ALU64 | BPF_AND | BPF_K:
870 		case BPF_ALU64 | BPF_OR | BPF_K:
871 		case BPF_ALU64 | BPF_XOR | BPF_K:
872 			if (BPF_CLASS(insn->code) == BPF_ALU64)
873 				EMIT1(add_1mod(0x48, dst_reg));
874 			else if (is_ereg(dst_reg))
875 				EMIT1(add_1mod(0x40, dst_reg));
876 
877 			/*
878 			 * b3 holds 'normal' opcode, b2 short form only valid
879 			 * in case dst is eax/rax.
880 			 */
881 			switch (BPF_OP(insn->code)) {
882 			case BPF_ADD:
883 				b3 = 0xC0;
884 				b2 = 0x05;
885 				break;
886 			case BPF_SUB:
887 				b3 = 0xE8;
888 				b2 = 0x2D;
889 				break;
890 			case BPF_AND:
891 				b3 = 0xE0;
892 				b2 = 0x25;
893 				break;
894 			case BPF_OR:
895 				b3 = 0xC8;
896 				b2 = 0x0D;
897 				break;
898 			case BPF_XOR:
899 				b3 = 0xF0;
900 				b2 = 0x35;
901 				break;
902 			}
903 
904 			if (is_imm8(imm32))
905 				EMIT3(0x83, add_1reg(b3, dst_reg), imm32);
906 			else if (is_axreg(dst_reg))
907 				EMIT1_off32(b2, imm32);
908 			else
909 				EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32);
910 			break;
911 
912 		case BPF_ALU64 | BPF_MOV | BPF_K:
913 		case BPF_ALU | BPF_MOV | BPF_K:
914 			emit_mov_imm32(&prog, BPF_CLASS(insn->code) == BPF_ALU64,
915 				       dst_reg, imm32);
916 			break;
917 
918 		case BPF_LD | BPF_IMM | BPF_DW:
919 			emit_mov_imm64(&prog, dst_reg, insn[1].imm, insn[0].imm);
920 			insn++;
921 			i++;
922 			break;
923 
924 			/* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */
925 		case BPF_ALU | BPF_MOD | BPF_X:
926 		case BPF_ALU | BPF_DIV | BPF_X:
927 		case BPF_ALU | BPF_MOD | BPF_K:
928 		case BPF_ALU | BPF_DIV | BPF_K:
929 		case BPF_ALU64 | BPF_MOD | BPF_X:
930 		case BPF_ALU64 | BPF_DIV | BPF_X:
931 		case BPF_ALU64 | BPF_MOD | BPF_K:
932 		case BPF_ALU64 | BPF_DIV | BPF_K:
933 			EMIT1(0x50); /* push rax */
934 			EMIT1(0x52); /* push rdx */
935 
936 			if (BPF_SRC(insn->code) == BPF_X)
937 				/* mov r11, src_reg */
938 				EMIT_mov(AUX_REG, src_reg);
939 			else
940 				/* mov r11, imm32 */
941 				EMIT3_off32(0x49, 0xC7, 0xC3, imm32);
942 
943 			/* mov rax, dst_reg */
944 			EMIT_mov(BPF_REG_0, dst_reg);
945 
946 			/*
947 			 * xor edx, edx
948 			 * equivalent to 'xor rdx, rdx', but one byte less
949 			 */
950 			EMIT2(0x31, 0xd2);
951 
952 			if (BPF_CLASS(insn->code) == BPF_ALU64)
953 				/* div r11 */
954 				EMIT3(0x49, 0xF7, 0xF3);
955 			else
956 				/* div r11d */
957 				EMIT3(0x41, 0xF7, 0xF3);
958 
959 			if (BPF_OP(insn->code) == BPF_MOD)
960 				/* mov r11, rdx */
961 				EMIT3(0x49, 0x89, 0xD3);
962 			else
963 				/* mov r11, rax */
964 				EMIT3(0x49, 0x89, 0xC3);
965 
966 			EMIT1(0x5A); /* pop rdx */
967 			EMIT1(0x58); /* pop rax */
968 
969 			/* mov dst_reg, r11 */
970 			EMIT_mov(dst_reg, AUX_REG);
971 			break;
972 
973 		case BPF_ALU | BPF_MUL | BPF_K:
974 		case BPF_ALU | BPF_MUL | BPF_X:
975 		case BPF_ALU64 | BPF_MUL | BPF_K:
976 		case BPF_ALU64 | BPF_MUL | BPF_X:
977 		{
978 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
979 
980 			if (dst_reg != BPF_REG_0)
981 				EMIT1(0x50); /* push rax */
982 			if (dst_reg != BPF_REG_3)
983 				EMIT1(0x52); /* push rdx */
984 
985 			/* mov r11, dst_reg */
986 			EMIT_mov(AUX_REG, dst_reg);
987 
988 			if (BPF_SRC(insn->code) == BPF_X)
989 				emit_mov_reg(&prog, is64, BPF_REG_0, src_reg);
990 			else
991 				emit_mov_imm32(&prog, is64, BPF_REG_0, imm32);
992 
993 			if (is64)
994 				EMIT1(add_1mod(0x48, AUX_REG));
995 			else if (is_ereg(AUX_REG))
996 				EMIT1(add_1mod(0x40, AUX_REG));
997 			/* mul(q) r11 */
998 			EMIT2(0xF7, add_1reg(0xE0, AUX_REG));
999 
1000 			if (dst_reg != BPF_REG_3)
1001 				EMIT1(0x5A); /* pop rdx */
1002 			if (dst_reg != BPF_REG_0) {
1003 				/* mov dst_reg, rax */
1004 				EMIT_mov(dst_reg, BPF_REG_0);
1005 				EMIT1(0x58); /* pop rax */
1006 			}
1007 			break;
1008 		}
1009 			/* Shifts */
1010 		case BPF_ALU | BPF_LSH | BPF_K:
1011 		case BPF_ALU | BPF_RSH | BPF_K:
1012 		case BPF_ALU | BPF_ARSH | BPF_K:
1013 		case BPF_ALU64 | BPF_LSH | BPF_K:
1014 		case BPF_ALU64 | BPF_RSH | BPF_K:
1015 		case BPF_ALU64 | BPF_ARSH | BPF_K:
1016 			if (BPF_CLASS(insn->code) == BPF_ALU64)
1017 				EMIT1(add_1mod(0x48, dst_reg));
1018 			else if (is_ereg(dst_reg))
1019 				EMIT1(add_1mod(0x40, dst_reg));
1020 
1021 			switch (BPF_OP(insn->code)) {
1022 			case BPF_LSH: b3 = 0xE0; break;
1023 			case BPF_RSH: b3 = 0xE8; break;
1024 			case BPF_ARSH: b3 = 0xF8; break;
1025 			}
1026 
1027 			if (imm32 == 1)
1028 				EMIT2(0xD1, add_1reg(b3, dst_reg));
1029 			else
1030 				EMIT3(0xC1, add_1reg(b3, dst_reg), imm32);
1031 			break;
1032 
1033 		case BPF_ALU | BPF_LSH | BPF_X:
1034 		case BPF_ALU | BPF_RSH | BPF_X:
1035 		case BPF_ALU | BPF_ARSH | BPF_X:
1036 		case BPF_ALU64 | BPF_LSH | BPF_X:
1037 		case BPF_ALU64 | BPF_RSH | BPF_X:
1038 		case BPF_ALU64 | BPF_ARSH | BPF_X:
1039 
1040 			/* Check for bad case when dst_reg == rcx */
1041 			if (dst_reg == BPF_REG_4) {
1042 				/* mov r11, dst_reg */
1043 				EMIT_mov(AUX_REG, dst_reg);
1044 				dst_reg = AUX_REG;
1045 			}
1046 
1047 			if (src_reg != BPF_REG_4) { /* common case */
1048 				EMIT1(0x51); /* push rcx */
1049 
1050 				/* mov rcx, src_reg */
1051 				EMIT_mov(BPF_REG_4, src_reg);
1052 			}
1053 
1054 			/* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */
1055 			if (BPF_CLASS(insn->code) == BPF_ALU64)
1056 				EMIT1(add_1mod(0x48, dst_reg));
1057 			else if (is_ereg(dst_reg))
1058 				EMIT1(add_1mod(0x40, dst_reg));
1059 
1060 			switch (BPF_OP(insn->code)) {
1061 			case BPF_LSH: b3 = 0xE0; break;
1062 			case BPF_RSH: b3 = 0xE8; break;
1063 			case BPF_ARSH: b3 = 0xF8; break;
1064 			}
1065 			EMIT2(0xD3, add_1reg(b3, dst_reg));
1066 
1067 			if (src_reg != BPF_REG_4)
1068 				EMIT1(0x59); /* pop rcx */
1069 
1070 			if (insn->dst_reg == BPF_REG_4)
1071 				/* mov dst_reg, r11 */
1072 				EMIT_mov(insn->dst_reg, AUX_REG);
1073 			break;
1074 
1075 		case BPF_ALU | BPF_END | BPF_FROM_BE:
1076 			switch (imm32) {
1077 			case 16:
1078 				/* Emit 'ror %ax, 8' to swap lower 2 bytes */
1079 				EMIT1(0x66);
1080 				if (is_ereg(dst_reg))
1081 					EMIT1(0x41);
1082 				EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8);
1083 
1084 				/* Emit 'movzwl eax, ax' */
1085 				if (is_ereg(dst_reg))
1086 					EMIT3(0x45, 0x0F, 0xB7);
1087 				else
1088 					EMIT2(0x0F, 0xB7);
1089 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
1090 				break;
1091 			case 32:
1092 				/* Emit 'bswap eax' to swap lower 4 bytes */
1093 				if (is_ereg(dst_reg))
1094 					EMIT2(0x41, 0x0F);
1095 				else
1096 					EMIT1(0x0F);
1097 				EMIT1(add_1reg(0xC8, dst_reg));
1098 				break;
1099 			case 64:
1100 				/* Emit 'bswap rax' to swap 8 bytes */
1101 				EMIT3(add_1mod(0x48, dst_reg), 0x0F,
1102 				      add_1reg(0xC8, dst_reg));
1103 				break;
1104 			}
1105 			break;
1106 
1107 		case BPF_ALU | BPF_END | BPF_FROM_LE:
1108 			switch (imm32) {
1109 			case 16:
1110 				/*
1111 				 * Emit 'movzwl eax, ax' to zero extend 16-bit
1112 				 * into 64 bit
1113 				 */
1114 				if (is_ereg(dst_reg))
1115 					EMIT3(0x45, 0x0F, 0xB7);
1116 				else
1117 					EMIT2(0x0F, 0xB7);
1118 				EMIT1(add_2reg(0xC0, dst_reg, dst_reg));
1119 				break;
1120 			case 32:
1121 				/* Emit 'mov eax, eax' to clear upper 32-bits */
1122 				if (is_ereg(dst_reg))
1123 					EMIT1(0x45);
1124 				EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg));
1125 				break;
1126 			case 64:
1127 				/* nop */
1128 				break;
1129 			}
1130 			break;
1131 
1132 			/* speculation barrier */
1133 		case BPF_ST | BPF_NOSPEC:
1134 			if (boot_cpu_has(X86_FEATURE_XMM2))
1135 				EMIT_LFENCE();
1136 			break;
1137 
1138 			/* ST: *(u8*)(dst_reg + off) = imm */
1139 		case BPF_ST | BPF_MEM | BPF_B:
1140 			if (is_ereg(dst_reg))
1141 				EMIT2(0x41, 0xC6);
1142 			else
1143 				EMIT1(0xC6);
1144 			goto st;
1145 		case BPF_ST | BPF_MEM | BPF_H:
1146 			if (is_ereg(dst_reg))
1147 				EMIT3(0x66, 0x41, 0xC7);
1148 			else
1149 				EMIT2(0x66, 0xC7);
1150 			goto st;
1151 		case BPF_ST | BPF_MEM | BPF_W:
1152 			if (is_ereg(dst_reg))
1153 				EMIT2(0x41, 0xC7);
1154 			else
1155 				EMIT1(0xC7);
1156 			goto st;
1157 		case BPF_ST | BPF_MEM | BPF_DW:
1158 			EMIT2(add_1mod(0x48, dst_reg), 0xC7);
1159 
1160 st:			if (is_imm8(insn->off))
1161 				EMIT2(add_1reg(0x40, dst_reg), insn->off);
1162 			else
1163 				EMIT1_off32(add_1reg(0x80, dst_reg), insn->off);
1164 
1165 			EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code)));
1166 			break;
1167 
1168 			/* STX: *(u8*)(dst_reg + off) = src_reg */
1169 		case BPF_STX | BPF_MEM | BPF_B:
1170 		case BPF_STX | BPF_MEM | BPF_H:
1171 		case BPF_STX | BPF_MEM | BPF_W:
1172 		case BPF_STX | BPF_MEM | BPF_DW:
1173 			emit_stx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
1174 			break;
1175 
1176 			/* LDX: dst_reg = *(u8*)(src_reg + off) */
1177 		case BPF_LDX | BPF_MEM | BPF_B:
1178 		case BPF_LDX | BPF_PROBE_MEM | BPF_B:
1179 		case BPF_LDX | BPF_MEM | BPF_H:
1180 		case BPF_LDX | BPF_PROBE_MEM | BPF_H:
1181 		case BPF_LDX | BPF_MEM | BPF_W:
1182 		case BPF_LDX | BPF_PROBE_MEM | BPF_W:
1183 		case BPF_LDX | BPF_MEM | BPF_DW:
1184 		case BPF_LDX | BPF_PROBE_MEM | BPF_DW:
1185 			emit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn->off);
1186 			if (BPF_MODE(insn->code) == BPF_PROBE_MEM) {
1187 				struct exception_table_entry *ex;
1188 				u8 *_insn = image + proglen;
1189 				s64 delta;
1190 
1191 				if (!bpf_prog->aux->extable)
1192 					break;
1193 
1194 				if (excnt >= bpf_prog->aux->num_exentries) {
1195 					pr_err("ex gen bug\n");
1196 					return -EFAULT;
1197 				}
1198 				ex = &bpf_prog->aux->extable[excnt++];
1199 
1200 				delta = _insn - (u8 *)&ex->insn;
1201 				if (!is_simm32(delta)) {
1202 					pr_err("extable->insn doesn't fit into 32-bit\n");
1203 					return -EFAULT;
1204 				}
1205 				ex->insn = delta;
1206 
1207 				delta = (u8 *)ex_handler_bpf - (u8 *)&ex->handler;
1208 				if (!is_simm32(delta)) {
1209 					pr_err("extable->handler doesn't fit into 32-bit\n");
1210 					return -EFAULT;
1211 				}
1212 				ex->handler = delta;
1213 
1214 				if (dst_reg > BPF_REG_9) {
1215 					pr_err("verifier error\n");
1216 					return -EFAULT;
1217 				}
1218 				/*
1219 				 * Compute size of x86 insn and its target dest x86 register.
1220 				 * ex_handler_bpf() will use lower 8 bits to adjust
1221 				 * pt_regs->ip to jump over this x86 instruction
1222 				 * and upper bits to figure out which pt_regs to zero out.
1223 				 * End result: x86 insn "mov rbx, qword ptr [rax+0x14]"
1224 				 * of 4 bytes will be ignored and rbx will be zero inited.
1225 				 */
1226 				ex->fixup = (prog - temp) | (reg2pt_regs[dst_reg] << 8);
1227 			}
1228 			break;
1229 
1230 			/* STX XADD: lock *(u32*)(dst_reg + off) += src_reg */
1231 		case BPF_STX | BPF_XADD | BPF_W:
1232 			/* Emit 'lock add dword ptr [rax + off], eax' */
1233 			if (is_ereg(dst_reg) || is_ereg(src_reg))
1234 				EMIT3(0xF0, add_2mod(0x40, dst_reg, src_reg), 0x01);
1235 			else
1236 				EMIT2(0xF0, 0x01);
1237 			goto xadd;
1238 		case BPF_STX | BPF_XADD | BPF_DW:
1239 			EMIT3(0xF0, add_2mod(0x48, dst_reg, src_reg), 0x01);
1240 xadd:			if (is_imm8(insn->off))
1241 				EMIT2(add_2reg(0x40, dst_reg, src_reg), insn->off);
1242 			else
1243 				EMIT1_off32(add_2reg(0x80, dst_reg, src_reg),
1244 					    insn->off);
1245 			break;
1246 
1247 			/* call */
1248 		case BPF_JMP | BPF_CALL:
1249 			func = (u8 *) __bpf_call_base + imm32;
1250 			if (tail_call_reachable) {
1251 				/* mov rax, qword ptr [rbp - rounded_stack_depth - 8] */
1252 				EMIT3_off32(0x48, 0x8B, 0x85,
1253 					    -round_up(bpf_prog->aux->stack_depth, 8) - 8);
1254 				if (!imm32 || emit_call(&prog, func, image + addrs[i - 1] + 7))
1255 					return -EINVAL;
1256 			} else {
1257 				if (!imm32 || emit_call(&prog, func, image + addrs[i - 1]))
1258 					return -EINVAL;
1259 			}
1260 			break;
1261 
1262 		case BPF_JMP | BPF_TAIL_CALL:
1263 			if (imm32)
1264 				emit_bpf_tail_call_direct(&bpf_prog->aux->poke_tab[imm32 - 1],
1265 							  &prog, image + addrs[i - 1],
1266 							  callee_regs_used,
1267 							  bpf_prog->aux->stack_depth,
1268 							  ctx);
1269 			else
1270 				emit_bpf_tail_call_indirect(&prog,
1271 							    callee_regs_used,
1272 							    bpf_prog->aux->stack_depth,
1273 							    image + addrs[i - 1],
1274 							    ctx);
1275 			break;
1276 
1277 			/* cond jump */
1278 		case BPF_JMP | BPF_JEQ | BPF_X:
1279 		case BPF_JMP | BPF_JNE | BPF_X:
1280 		case BPF_JMP | BPF_JGT | BPF_X:
1281 		case BPF_JMP | BPF_JLT | BPF_X:
1282 		case BPF_JMP | BPF_JGE | BPF_X:
1283 		case BPF_JMP | BPF_JLE | BPF_X:
1284 		case BPF_JMP | BPF_JSGT | BPF_X:
1285 		case BPF_JMP | BPF_JSLT | BPF_X:
1286 		case BPF_JMP | BPF_JSGE | BPF_X:
1287 		case BPF_JMP | BPF_JSLE | BPF_X:
1288 		case BPF_JMP32 | BPF_JEQ | BPF_X:
1289 		case BPF_JMP32 | BPF_JNE | BPF_X:
1290 		case BPF_JMP32 | BPF_JGT | BPF_X:
1291 		case BPF_JMP32 | BPF_JLT | BPF_X:
1292 		case BPF_JMP32 | BPF_JGE | BPF_X:
1293 		case BPF_JMP32 | BPF_JLE | BPF_X:
1294 		case BPF_JMP32 | BPF_JSGT | BPF_X:
1295 		case BPF_JMP32 | BPF_JSLT | BPF_X:
1296 		case BPF_JMP32 | BPF_JSGE | BPF_X:
1297 		case BPF_JMP32 | BPF_JSLE | BPF_X:
1298 			/* cmp dst_reg, src_reg */
1299 			if (BPF_CLASS(insn->code) == BPF_JMP)
1300 				EMIT1(add_2mod(0x48, dst_reg, src_reg));
1301 			else if (is_ereg(dst_reg) || is_ereg(src_reg))
1302 				EMIT1(add_2mod(0x40, dst_reg, src_reg));
1303 			EMIT2(0x39, add_2reg(0xC0, dst_reg, src_reg));
1304 			goto emit_cond_jmp;
1305 
1306 		case BPF_JMP | BPF_JSET | BPF_X:
1307 		case BPF_JMP32 | BPF_JSET | BPF_X:
1308 			/* test dst_reg, src_reg */
1309 			if (BPF_CLASS(insn->code) == BPF_JMP)
1310 				EMIT1(add_2mod(0x48, dst_reg, src_reg));
1311 			else if (is_ereg(dst_reg) || is_ereg(src_reg))
1312 				EMIT1(add_2mod(0x40, dst_reg, src_reg));
1313 			EMIT2(0x85, add_2reg(0xC0, dst_reg, src_reg));
1314 			goto emit_cond_jmp;
1315 
1316 		case BPF_JMP | BPF_JSET | BPF_K:
1317 		case BPF_JMP32 | BPF_JSET | BPF_K:
1318 			/* test dst_reg, imm32 */
1319 			if (BPF_CLASS(insn->code) == BPF_JMP)
1320 				EMIT1(add_1mod(0x48, dst_reg));
1321 			else if (is_ereg(dst_reg))
1322 				EMIT1(add_1mod(0x40, dst_reg));
1323 			EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32);
1324 			goto emit_cond_jmp;
1325 
1326 		case BPF_JMP | BPF_JEQ | BPF_K:
1327 		case BPF_JMP | BPF_JNE | BPF_K:
1328 		case BPF_JMP | BPF_JGT | BPF_K:
1329 		case BPF_JMP | BPF_JLT | BPF_K:
1330 		case BPF_JMP | BPF_JGE | BPF_K:
1331 		case BPF_JMP | BPF_JLE | BPF_K:
1332 		case BPF_JMP | BPF_JSGT | BPF_K:
1333 		case BPF_JMP | BPF_JSLT | BPF_K:
1334 		case BPF_JMP | BPF_JSGE | BPF_K:
1335 		case BPF_JMP | BPF_JSLE | BPF_K:
1336 		case BPF_JMP32 | BPF_JEQ | BPF_K:
1337 		case BPF_JMP32 | BPF_JNE | BPF_K:
1338 		case BPF_JMP32 | BPF_JGT | BPF_K:
1339 		case BPF_JMP32 | BPF_JLT | BPF_K:
1340 		case BPF_JMP32 | BPF_JGE | BPF_K:
1341 		case BPF_JMP32 | BPF_JLE | BPF_K:
1342 		case BPF_JMP32 | BPF_JSGT | BPF_K:
1343 		case BPF_JMP32 | BPF_JSLT | BPF_K:
1344 		case BPF_JMP32 | BPF_JSGE | BPF_K:
1345 		case BPF_JMP32 | BPF_JSLE | BPF_K:
1346 			/* test dst_reg, dst_reg to save one extra byte */
1347 			if (imm32 == 0) {
1348 				if (BPF_CLASS(insn->code) == BPF_JMP)
1349 					EMIT1(add_2mod(0x48, dst_reg, dst_reg));
1350 				else if (is_ereg(dst_reg))
1351 					EMIT1(add_2mod(0x40, dst_reg, dst_reg));
1352 				EMIT2(0x85, add_2reg(0xC0, dst_reg, dst_reg));
1353 				goto emit_cond_jmp;
1354 			}
1355 
1356 			/* cmp dst_reg, imm8/32 */
1357 			if (BPF_CLASS(insn->code) == BPF_JMP)
1358 				EMIT1(add_1mod(0x48, dst_reg));
1359 			else if (is_ereg(dst_reg))
1360 				EMIT1(add_1mod(0x40, dst_reg));
1361 
1362 			if (is_imm8(imm32))
1363 				EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32);
1364 			else
1365 				EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32);
1366 
1367 emit_cond_jmp:		/* Convert BPF opcode to x86 */
1368 			switch (BPF_OP(insn->code)) {
1369 			case BPF_JEQ:
1370 				jmp_cond = X86_JE;
1371 				break;
1372 			case BPF_JSET:
1373 			case BPF_JNE:
1374 				jmp_cond = X86_JNE;
1375 				break;
1376 			case BPF_JGT:
1377 				/* GT is unsigned '>', JA in x86 */
1378 				jmp_cond = X86_JA;
1379 				break;
1380 			case BPF_JLT:
1381 				/* LT is unsigned '<', JB in x86 */
1382 				jmp_cond = X86_JB;
1383 				break;
1384 			case BPF_JGE:
1385 				/* GE is unsigned '>=', JAE in x86 */
1386 				jmp_cond = X86_JAE;
1387 				break;
1388 			case BPF_JLE:
1389 				/* LE is unsigned '<=', JBE in x86 */
1390 				jmp_cond = X86_JBE;
1391 				break;
1392 			case BPF_JSGT:
1393 				/* Signed '>', GT in x86 */
1394 				jmp_cond = X86_JG;
1395 				break;
1396 			case BPF_JSLT:
1397 				/* Signed '<', LT in x86 */
1398 				jmp_cond = X86_JL;
1399 				break;
1400 			case BPF_JSGE:
1401 				/* Signed '>=', GE in x86 */
1402 				jmp_cond = X86_JGE;
1403 				break;
1404 			case BPF_JSLE:
1405 				/* Signed '<=', LE in x86 */
1406 				jmp_cond = X86_JLE;
1407 				break;
1408 			default: /* to silence GCC warning */
1409 				return -EFAULT;
1410 			}
1411 			jmp_offset = addrs[i + insn->off] - addrs[i];
1412 			if (is_imm8(jmp_offset)) {
1413 				EMIT2(jmp_cond, jmp_offset);
1414 			} else if (is_simm32(jmp_offset)) {
1415 				EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset);
1416 			} else {
1417 				pr_err("cond_jmp gen bug %llx\n", jmp_offset);
1418 				return -EFAULT;
1419 			}
1420 
1421 			break;
1422 
1423 		case BPF_JMP | BPF_JA:
1424 			if (insn->off == -1)
1425 				/* -1 jmp instructions will always jump
1426 				 * backwards two bytes. Explicitly handling
1427 				 * this case avoids wasting too many passes
1428 				 * when there are long sequences of replaced
1429 				 * dead code.
1430 				 */
1431 				jmp_offset = -2;
1432 			else
1433 				jmp_offset = addrs[i + insn->off] - addrs[i];
1434 
1435 			if (!jmp_offset)
1436 				/* Optimize out nop jumps */
1437 				break;
1438 emit_jmp:
1439 			if (is_imm8(jmp_offset)) {
1440 				EMIT2(0xEB, jmp_offset);
1441 			} else if (is_simm32(jmp_offset)) {
1442 				EMIT1_off32(0xE9, jmp_offset);
1443 			} else {
1444 				pr_err("jmp gen bug %llx\n", jmp_offset);
1445 				return -EFAULT;
1446 			}
1447 			break;
1448 
1449 		case BPF_JMP | BPF_EXIT:
1450 			if (seen_exit) {
1451 				jmp_offset = ctx->cleanup_addr - addrs[i];
1452 				goto emit_jmp;
1453 			}
1454 			seen_exit = true;
1455 			/* Update cleanup_addr */
1456 			ctx->cleanup_addr = proglen;
1457 			pop_callee_regs(&prog, callee_regs_used);
1458 			EMIT1(0xC9);         /* leave */
1459 			emit_return(&prog, image + addrs[i - 1] + (prog - temp));
1460 			break;
1461 
1462 		default:
1463 			/*
1464 			 * By design x86-64 JIT should support all BPF instructions.
1465 			 * This error will be seen if new instruction was added
1466 			 * to the interpreter, but not to the JIT, or if there is
1467 			 * junk in bpf_prog.
1468 			 */
1469 			pr_err("bpf_jit: unknown opcode %02x\n", insn->code);
1470 			return -EINVAL;
1471 		}
1472 
1473 		ilen = prog - temp;
1474 		if (ilen > BPF_MAX_INSN_SIZE) {
1475 			pr_err("bpf_jit: fatal insn size error\n");
1476 			return -EFAULT;
1477 		}
1478 
1479 		if (image) {
1480 			/*
1481 			 * When populating the image, assert that:
1482 			 *
1483 			 *  i) We do not write beyond the allocated space, and
1484 			 * ii) addrs[i] did not change from the prior run, in order
1485 			 *     to validate assumptions made for computing branch
1486 			 *     displacements.
1487 			 */
1488 			if (unlikely(proglen + ilen > oldproglen ||
1489 				     proglen + ilen != addrs[i])) {
1490 				pr_err("bpf_jit: fatal error\n");
1491 				return -EFAULT;
1492 			}
1493 			memcpy(image + proglen, temp, ilen);
1494 		}
1495 		proglen += ilen;
1496 		addrs[i] = proglen;
1497 		prog = temp;
1498 	}
1499 
1500 	if (image && excnt != bpf_prog->aux->num_exentries) {
1501 		pr_err("extable is not populated\n");
1502 		return -EFAULT;
1503 	}
1504 	return proglen;
1505 }
1506 
save_regs(const struct btf_func_model * m,u8 ** prog,int nr_args,int stack_size)1507 static void save_regs(const struct btf_func_model *m, u8 **prog, int nr_args,
1508 		      int stack_size)
1509 {
1510 	int i;
1511 	/* Store function arguments to stack.
1512 	 * For a function that accepts two pointers the sequence will be:
1513 	 * mov QWORD PTR [rbp-0x10],rdi
1514 	 * mov QWORD PTR [rbp-0x8],rsi
1515 	 */
1516 	for (i = 0; i < min(nr_args, 6); i++)
1517 		emit_stx(prog, bytes_to_bpf_size(m->arg_size[i]),
1518 			 BPF_REG_FP,
1519 			 i == 5 ? X86_REG_R9 : BPF_REG_1 + i,
1520 			 -(stack_size - i * 8));
1521 }
1522 
restore_regs(const struct btf_func_model * m,u8 ** prog,int nr_args,int stack_size)1523 static void restore_regs(const struct btf_func_model *m, u8 **prog, int nr_args,
1524 			 int stack_size)
1525 {
1526 	int i;
1527 
1528 	/* Restore function arguments from stack.
1529 	 * For a function that accepts two pointers the sequence will be:
1530 	 * EMIT4(0x48, 0x8B, 0x7D, 0xF0); mov rdi,QWORD PTR [rbp-0x10]
1531 	 * EMIT4(0x48, 0x8B, 0x75, 0xF8); mov rsi,QWORD PTR [rbp-0x8]
1532 	 */
1533 	for (i = 0; i < min(nr_args, 6); i++)
1534 		emit_ldx(prog, bytes_to_bpf_size(m->arg_size[i]),
1535 			 i == 5 ? X86_REG_R9 : BPF_REG_1 + i,
1536 			 BPF_REG_FP,
1537 			 -(stack_size - i * 8));
1538 }
1539 
invoke_bpf_prog(const struct btf_func_model * m,u8 ** pprog,struct bpf_prog * p,int stack_size,bool save_ret)1540 static int invoke_bpf_prog(const struct btf_func_model *m, u8 **pprog,
1541 			   struct bpf_prog *p, int stack_size, bool save_ret)
1542 {
1543 	u8 *prog = *pprog;
1544 	int cnt = 0;
1545 
1546 	if (p->aux->sleepable) {
1547 		if (emit_call(&prog, __bpf_prog_enter_sleepable, prog))
1548 			return -EINVAL;
1549 	} else {
1550 		if (emit_call(&prog, __bpf_prog_enter, prog))
1551 			return -EINVAL;
1552 		/* remember prog start time returned by __bpf_prog_enter */
1553 		emit_mov_reg(&prog, true, BPF_REG_6, BPF_REG_0);
1554 	}
1555 
1556 	/* arg1: lea rdi, [rbp - stack_size] */
1557 	EMIT4(0x48, 0x8D, 0x7D, -stack_size);
1558 	/* arg2: progs[i]->insnsi for interpreter */
1559 	if (!p->jited)
1560 		emit_mov_imm64(&prog, BPF_REG_2,
1561 			       (long) p->insnsi >> 32,
1562 			       (u32) (long) p->insnsi);
1563 	/* call JITed bpf program or interpreter */
1564 	if (emit_call(&prog, p->bpf_func, prog))
1565 		return -EINVAL;
1566 
1567 	/*
1568 	 * BPF_TRAMP_MODIFY_RETURN trampolines can modify the return
1569 	 * of the previous call which is then passed on the stack to
1570 	 * the next BPF program.
1571 	 *
1572 	 * BPF_TRAMP_FENTRY trampoline may need to return the return
1573 	 * value of BPF_PROG_TYPE_STRUCT_OPS prog.
1574 	 */
1575 	if (save_ret)
1576 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
1577 
1578 	if (p->aux->sleepable) {
1579 		if (emit_call(&prog, __bpf_prog_exit_sleepable, prog))
1580 			return -EINVAL;
1581 	} else {
1582 		/* arg1: mov rdi, progs[i] */
1583 		emit_mov_imm64(&prog, BPF_REG_1, (long) p >> 32,
1584 			       (u32) (long) p);
1585 		/* arg2: mov rsi, rbx <- start time in nsec */
1586 		emit_mov_reg(&prog, true, BPF_REG_2, BPF_REG_6);
1587 		if (emit_call(&prog, __bpf_prog_exit, prog))
1588 			return -EINVAL;
1589 	}
1590 
1591 	*pprog = prog;
1592 	return 0;
1593 }
1594 
emit_nops(u8 ** pprog,unsigned int len)1595 static void emit_nops(u8 **pprog, unsigned int len)
1596 {
1597 	unsigned int i, noplen;
1598 	u8 *prog = *pprog;
1599 	int cnt = 0;
1600 
1601 	while (len > 0) {
1602 		noplen = len;
1603 
1604 		if (noplen > ASM_NOP_MAX)
1605 			noplen = ASM_NOP_MAX;
1606 
1607 		for (i = 0; i < noplen; i++)
1608 			EMIT1(ideal_nops[noplen][i]);
1609 		len -= noplen;
1610 	}
1611 
1612 	*pprog = prog;
1613 }
1614 
emit_align(u8 ** pprog,u32 align)1615 static void emit_align(u8 **pprog, u32 align)
1616 {
1617 	u8 *target, *prog = *pprog;
1618 
1619 	target = PTR_ALIGN(prog, align);
1620 	if (target != prog)
1621 		emit_nops(&prog, target - prog);
1622 
1623 	*pprog = prog;
1624 }
1625 
emit_cond_near_jump(u8 ** pprog,void * func,void * ip,u8 jmp_cond)1626 static int emit_cond_near_jump(u8 **pprog, void *func, void *ip, u8 jmp_cond)
1627 {
1628 	u8 *prog = *pprog;
1629 	int cnt = 0;
1630 	s64 offset;
1631 
1632 	offset = func - (ip + 2 + 4);
1633 	if (!is_simm32(offset)) {
1634 		pr_err("Target %p is out of range\n", func);
1635 		return -EINVAL;
1636 	}
1637 	EMIT2_off32(0x0F, jmp_cond + 0x10, offset);
1638 	*pprog = prog;
1639 	return 0;
1640 }
1641 
invoke_bpf(const struct btf_func_model * m,u8 ** pprog,struct bpf_tramp_progs * tp,int stack_size,bool save_ret)1642 static int invoke_bpf(const struct btf_func_model *m, u8 **pprog,
1643 		      struct bpf_tramp_progs *tp, int stack_size,
1644 		      bool save_ret)
1645 {
1646 	int i;
1647 	u8 *prog = *pprog;
1648 
1649 	for (i = 0; i < tp->nr_progs; i++) {
1650 		if (invoke_bpf_prog(m, &prog, tp->progs[i], stack_size,
1651 				    save_ret))
1652 			return -EINVAL;
1653 	}
1654 	*pprog = prog;
1655 	return 0;
1656 }
1657 
invoke_bpf_mod_ret(const struct btf_func_model * m,u8 ** pprog,struct bpf_tramp_progs * tp,int stack_size,u8 ** branches)1658 static int invoke_bpf_mod_ret(const struct btf_func_model *m, u8 **pprog,
1659 			      struct bpf_tramp_progs *tp, int stack_size,
1660 			      u8 **branches)
1661 {
1662 	u8 *prog = *pprog;
1663 	int i, cnt = 0;
1664 
1665 	/* The first fmod_ret program will receive a garbage return value.
1666 	 * Set this to 0 to avoid confusing the program.
1667 	 */
1668 	emit_mov_imm32(&prog, false, BPF_REG_0, 0);
1669 	emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
1670 	for (i = 0; i < tp->nr_progs; i++) {
1671 		if (invoke_bpf_prog(m, &prog, tp->progs[i], stack_size, true))
1672 			return -EINVAL;
1673 
1674 		/* mod_ret prog stored return value into [rbp - 8]. Emit:
1675 		 * if (*(u64 *)(rbp - 8) !=  0)
1676 		 *	goto do_fexit;
1677 		 */
1678 		/* cmp QWORD PTR [rbp - 0x8], 0x0 */
1679 		EMIT4(0x48, 0x83, 0x7d, 0xf8); EMIT1(0x00);
1680 
1681 		/* Save the location of the branch and Generate 6 nops
1682 		 * (4 bytes for an offset and 2 bytes for the jump) These nops
1683 		 * are replaced with a conditional jump once do_fexit (i.e. the
1684 		 * start of the fexit invocation) is finalized.
1685 		 */
1686 		branches[i] = prog;
1687 		emit_nops(&prog, 4 + 2);
1688 	}
1689 
1690 	*pprog = prog;
1691 	return 0;
1692 }
1693 
is_valid_bpf_tramp_flags(unsigned int flags)1694 static bool is_valid_bpf_tramp_flags(unsigned int flags)
1695 {
1696 	if ((flags & BPF_TRAMP_F_RESTORE_REGS) &&
1697 	    (flags & BPF_TRAMP_F_SKIP_FRAME))
1698 		return false;
1699 
1700 	/*
1701 	 * BPF_TRAMP_F_RET_FENTRY_RET is only used by bpf_struct_ops,
1702 	 * and it must be used alone.
1703 	 */
1704 	if ((flags & BPF_TRAMP_F_RET_FENTRY_RET) &&
1705 	    (flags & ~BPF_TRAMP_F_RET_FENTRY_RET))
1706 		return false;
1707 
1708 	return true;
1709 }
1710 
1711 /* Example:
1712  * __be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev);
1713  * its 'struct btf_func_model' will be nr_args=2
1714  * The assembly code when eth_type_trans is executing after trampoline:
1715  *
1716  * push rbp
1717  * mov rbp, rsp
1718  * sub rsp, 16                     // space for skb and dev
1719  * push rbx                        // temp regs to pass start time
1720  * mov qword ptr [rbp - 16], rdi   // save skb pointer to stack
1721  * mov qword ptr [rbp - 8], rsi    // save dev pointer to stack
1722  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
1723  * mov rbx, rax                    // remember start time in bpf stats are enabled
1724  * lea rdi, [rbp - 16]             // R1==ctx of bpf prog
1725  * call addr_of_jited_FENTRY_prog
1726  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
1727  * mov rsi, rbx                    // prog start time
1728  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
1729  * mov rdi, qword ptr [rbp - 16]   // restore skb pointer from stack
1730  * mov rsi, qword ptr [rbp - 8]    // restore dev pointer from stack
1731  * pop rbx
1732  * leave
1733  * ret
1734  *
1735  * eth_type_trans has 5 byte nop at the beginning. These 5 bytes will be
1736  * replaced with 'call generated_bpf_trampoline'. When it returns
1737  * eth_type_trans will continue executing with original skb and dev pointers.
1738  *
1739  * The assembly code when eth_type_trans is called from trampoline:
1740  *
1741  * push rbp
1742  * mov rbp, rsp
1743  * sub rsp, 24                     // space for skb, dev, return value
1744  * push rbx                        // temp regs to pass start time
1745  * mov qword ptr [rbp - 24], rdi   // save skb pointer to stack
1746  * mov qword ptr [rbp - 16], rsi   // save dev pointer to stack
1747  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
1748  * mov rbx, rax                    // remember start time if bpf stats are enabled
1749  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
1750  * call addr_of_jited_FENTRY_prog  // bpf prog can access skb and dev
1751  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
1752  * mov rsi, rbx                    // prog start time
1753  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
1754  * mov rdi, qword ptr [rbp - 24]   // restore skb pointer from stack
1755  * mov rsi, qword ptr [rbp - 16]   // restore dev pointer from stack
1756  * call eth_type_trans+5           // execute body of eth_type_trans
1757  * mov qword ptr [rbp - 8], rax    // save return value
1758  * call __bpf_prog_enter           // rcu_read_lock and preempt_disable
1759  * mov rbx, rax                    // remember start time in bpf stats are enabled
1760  * lea rdi, [rbp - 24]             // R1==ctx of bpf prog
1761  * call addr_of_jited_FEXIT_prog   // bpf prog can access skb, dev, return value
1762  * movabsq rdi, 64bit_addr_of_struct_bpf_prog  // unused if bpf stats are off
1763  * mov rsi, rbx                    // prog start time
1764  * call __bpf_prog_exit            // rcu_read_unlock, preempt_enable and stats math
1765  * mov rax, qword ptr [rbp - 8]    // restore eth_type_trans's return value
1766  * pop rbx
1767  * leave
1768  * add rsp, 8                      // skip eth_type_trans's frame
1769  * ret                             // return to its caller
1770  */
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_progs * tprogs,void * orig_call)1771 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
1772 				const struct btf_func_model *m, u32 flags,
1773 				struct bpf_tramp_progs *tprogs,
1774 				void *orig_call)
1775 {
1776 	int ret, i, cnt = 0, nr_args = m->nr_args;
1777 	int stack_size = nr_args * 8;
1778 	struct bpf_tramp_progs *fentry = &tprogs[BPF_TRAMP_FENTRY];
1779 	struct bpf_tramp_progs *fexit = &tprogs[BPF_TRAMP_FEXIT];
1780 	struct bpf_tramp_progs *fmod_ret = &tprogs[BPF_TRAMP_MODIFY_RETURN];
1781 	u8 **branches = NULL;
1782 	u8 *prog;
1783 	bool save_ret;
1784 
1785 	/* x86-64 supports up to 6 arguments. 7+ can be added in the future */
1786 	if (nr_args > 6)
1787 		return -ENOTSUPP;
1788 
1789 	if (!is_valid_bpf_tramp_flags(flags))
1790 		return -EINVAL;
1791 
1792 	/* room for return value of orig_call or fentry prog */
1793 	save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET);
1794 	if (save_ret)
1795 		stack_size += 8;
1796 
1797 	if (flags & BPF_TRAMP_F_SKIP_FRAME)
1798 		/* skip patched call instruction and point orig_call to actual
1799 		 * body of the kernel function.
1800 		 */
1801 		orig_call += X86_PATCH_SIZE;
1802 
1803 	prog = image;
1804 
1805 	EMIT1(0x55);		 /* push rbp */
1806 	EMIT3(0x48, 0x89, 0xE5); /* mov rbp, rsp */
1807 	EMIT4(0x48, 0x83, 0xEC, stack_size); /* sub rsp, stack_size */
1808 	EMIT1(0x53);		 /* push rbx */
1809 
1810 	save_regs(m, &prog, nr_args, stack_size);
1811 
1812 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
1813 		/* arg1: mov rdi, im */
1814 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
1815 		if (emit_call(&prog, __bpf_tramp_enter, prog)) {
1816 			ret = -EINVAL;
1817 			goto cleanup;
1818 		}
1819 	}
1820 
1821 	if (fentry->nr_progs)
1822 		if (invoke_bpf(m, &prog, fentry, stack_size,
1823 			       flags & BPF_TRAMP_F_RET_FENTRY_RET))
1824 			return -EINVAL;
1825 
1826 	if (fmod_ret->nr_progs) {
1827 		branches = kcalloc(fmod_ret->nr_progs, sizeof(u8 *),
1828 				   GFP_KERNEL);
1829 		if (!branches)
1830 			return -ENOMEM;
1831 
1832 		if (invoke_bpf_mod_ret(m, &prog, fmod_ret, stack_size,
1833 				       branches)) {
1834 			ret = -EINVAL;
1835 			goto cleanup;
1836 		}
1837 	}
1838 
1839 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
1840 		restore_regs(m, &prog, nr_args, stack_size);
1841 
1842 		/* call original function */
1843 		if (emit_call(&prog, orig_call, prog)) {
1844 			ret = -EINVAL;
1845 			goto cleanup;
1846 		}
1847 		/* remember return value in a stack for bpf prog to access */
1848 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
1849 		im->ip_after_call = prog;
1850 		memcpy(prog, ideal_nops[NOP_ATOMIC5], X86_PATCH_SIZE);
1851 		prog += X86_PATCH_SIZE;
1852 	}
1853 
1854 	if (fmod_ret->nr_progs) {
1855 		/* From Intel 64 and IA-32 Architectures Optimization
1856 		 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
1857 		 * Coding Rule 11: All branch targets should be 16-byte
1858 		 * aligned.
1859 		 */
1860 		emit_align(&prog, 16);
1861 		/* Update the branches saved in invoke_bpf_mod_ret with the
1862 		 * aligned address of do_fexit.
1863 		 */
1864 		for (i = 0; i < fmod_ret->nr_progs; i++)
1865 			emit_cond_near_jump(&branches[i], prog, branches[i],
1866 					    X86_JNE);
1867 	}
1868 
1869 	if (fexit->nr_progs)
1870 		if (invoke_bpf(m, &prog, fexit, stack_size, false)) {
1871 			ret = -EINVAL;
1872 			goto cleanup;
1873 		}
1874 
1875 	if (flags & BPF_TRAMP_F_RESTORE_REGS)
1876 		restore_regs(m, &prog, nr_args, stack_size);
1877 
1878 	/* This needs to be done regardless. If there were fmod_ret programs,
1879 	 * the return value is only updated on the stack and still needs to be
1880 	 * restored to R0.
1881 	 */
1882 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
1883 		im->ip_epilogue = prog;
1884 		/* arg1: mov rdi, im */
1885 		emit_mov_imm64(&prog, BPF_REG_1, (long) im >> 32, (u32) (long) im);
1886 		if (emit_call(&prog, __bpf_tramp_exit, prog)) {
1887 			ret = -EINVAL;
1888 			goto cleanup;
1889 		}
1890 	}
1891 	/* restore return value of orig_call or fentry prog back into RAX */
1892 	if (save_ret)
1893 		emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, -8);
1894 
1895 	EMIT1(0x5B); /* pop rbx */
1896 	EMIT1(0xC9); /* leave */
1897 	if (flags & BPF_TRAMP_F_SKIP_FRAME)
1898 		/* skip our return address and return to parent */
1899 		EMIT4(0x48, 0x83, 0xC4, 8); /* add rsp, 8 */
1900 	emit_return(&prog, prog);
1901 	/* Make sure the trampoline generation logic doesn't overflow */
1902 	if (WARN_ON_ONCE(prog > (u8 *)image_end - BPF_INSN_SAFETY)) {
1903 		ret = -EFAULT;
1904 		goto cleanup;
1905 	}
1906 	ret = prog - (u8 *)image;
1907 
1908 cleanup:
1909 	kfree(branches);
1910 	return ret;
1911 }
1912 
emit_bpf_dispatcher(u8 ** pprog,int a,int b,s64 * progs)1913 static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs)
1914 {
1915 	u8 *jg_reloc, *prog = *pprog;
1916 	int pivot, err, jg_bytes = 1, cnt = 0;
1917 	s64 jg_offset;
1918 
1919 	if (a == b) {
1920 		/* Leaf node of recursion, i.e. not a range of indices
1921 		 * anymore.
1922 		 */
1923 		EMIT1(add_1mod(0x48, BPF_REG_3));	/* cmp rdx,func */
1924 		if (!is_simm32(progs[a]))
1925 			return -1;
1926 		EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3),
1927 			    progs[a]);
1928 		err = emit_cond_near_jump(&prog,	/* je func */
1929 					  (void *)progs[a], prog,
1930 					  X86_JE);
1931 		if (err)
1932 			return err;
1933 
1934 		emit_indirect_jump(&prog, 2 /* rdx */, prog);
1935 
1936 		*pprog = prog;
1937 		return 0;
1938 	}
1939 
1940 	/* Not a leaf node, so we pivot, and recursively descend into
1941 	 * the lower and upper ranges.
1942 	 */
1943 	pivot = (b - a) / 2;
1944 	EMIT1(add_1mod(0x48, BPF_REG_3));		/* cmp rdx,func */
1945 	if (!is_simm32(progs[a + pivot]))
1946 		return -1;
1947 	EMIT2_off32(0x81, add_1reg(0xF8, BPF_REG_3), progs[a + pivot]);
1948 
1949 	if (pivot > 2) {				/* jg upper_part */
1950 		/* Require near jump. */
1951 		jg_bytes = 4;
1952 		EMIT2_off32(0x0F, X86_JG + 0x10, 0);
1953 	} else {
1954 		EMIT2(X86_JG, 0);
1955 	}
1956 	jg_reloc = prog;
1957 
1958 	err = emit_bpf_dispatcher(&prog, a, a + pivot,	/* emit lower_part */
1959 				  progs);
1960 	if (err)
1961 		return err;
1962 
1963 	/* From Intel 64 and IA-32 Architectures Optimization
1964 	 * Reference Manual, 3.4.1.4 Code Alignment, Assembly/Compiler
1965 	 * Coding Rule 11: All branch targets should be 16-byte
1966 	 * aligned.
1967 	 */
1968 	emit_align(&prog, 16);
1969 	jg_offset = prog - jg_reloc;
1970 	emit_code(jg_reloc - jg_bytes, jg_offset, jg_bytes);
1971 
1972 	err = emit_bpf_dispatcher(&prog, a + pivot + 1,	/* emit upper_part */
1973 				  b, progs);
1974 	if (err)
1975 		return err;
1976 
1977 	*pprog = prog;
1978 	return 0;
1979 }
1980 
cmp_ips(const void * a,const void * b)1981 static int cmp_ips(const void *a, const void *b)
1982 {
1983 	const s64 *ipa = a;
1984 	const s64 *ipb = b;
1985 
1986 	if (*ipa > *ipb)
1987 		return 1;
1988 	if (*ipa < *ipb)
1989 		return -1;
1990 	return 0;
1991 }
1992 
arch_prepare_bpf_dispatcher(void * image,s64 * funcs,int num_funcs)1993 int arch_prepare_bpf_dispatcher(void *image, s64 *funcs, int num_funcs)
1994 {
1995 	u8 *prog = image;
1996 
1997 	sort(funcs, num_funcs, sizeof(funcs[0]), cmp_ips, NULL);
1998 	return emit_bpf_dispatcher(&prog, 0, num_funcs - 1, funcs);
1999 }
2000 
2001 struct x64_jit_data {
2002 	struct bpf_binary_header *header;
2003 	int *addrs;
2004 	u8 *image;
2005 	int proglen;
2006 	struct jit_context ctx;
2007 };
2008 
bpf_int_jit_compile(struct bpf_prog * prog)2009 struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *prog)
2010 {
2011 	struct bpf_binary_header *header = NULL;
2012 	struct bpf_prog *tmp, *orig_prog = prog;
2013 	struct x64_jit_data *jit_data;
2014 	int proglen, oldproglen = 0;
2015 	struct jit_context ctx = {};
2016 	bool tmp_blinded = false;
2017 	bool extra_pass = false;
2018 	u8 *image = NULL;
2019 	int *addrs;
2020 	int pass;
2021 	int i;
2022 
2023 	if (!prog->jit_requested)
2024 		return orig_prog;
2025 
2026 	tmp = bpf_jit_blind_constants(prog);
2027 	/*
2028 	 * If blinding was requested and we failed during blinding,
2029 	 * we must fall back to the interpreter.
2030 	 */
2031 	if (IS_ERR(tmp))
2032 		return orig_prog;
2033 	if (tmp != prog) {
2034 		tmp_blinded = true;
2035 		prog = tmp;
2036 	}
2037 
2038 	jit_data = prog->aux->jit_data;
2039 	if (!jit_data) {
2040 		jit_data = kzalloc(sizeof(*jit_data), GFP_KERNEL);
2041 		if (!jit_data) {
2042 			prog = orig_prog;
2043 			goto out;
2044 		}
2045 		prog->aux->jit_data = jit_data;
2046 	}
2047 	addrs = jit_data->addrs;
2048 	if (addrs) {
2049 		ctx = jit_data->ctx;
2050 		oldproglen = jit_data->proglen;
2051 		image = jit_data->image;
2052 		header = jit_data->header;
2053 		extra_pass = true;
2054 		goto skip_init_addrs;
2055 	}
2056 	addrs = kvmalloc_array(prog->len + 1, sizeof(*addrs), GFP_KERNEL);
2057 	if (!addrs) {
2058 		prog = orig_prog;
2059 		goto out_addrs;
2060 	}
2061 
2062 	/*
2063 	 * Before first pass, make a rough estimation of addrs[]
2064 	 * each BPF instruction is translated to less than 64 bytes
2065 	 */
2066 	for (proglen = 0, i = 0; i <= prog->len; i++) {
2067 		proglen += 64;
2068 		addrs[i] = proglen;
2069 	}
2070 	ctx.cleanup_addr = proglen;
2071 skip_init_addrs:
2072 
2073 	/*
2074 	 * JITed image shrinks with every pass and the loop iterates
2075 	 * until the image stops shrinking. Very large BPF programs
2076 	 * may converge on the last pass. In such case do one more
2077 	 * pass to emit the final image.
2078 	 */
2079 	for (pass = 0; pass < 20 || image; pass++) {
2080 		proglen = do_jit(prog, addrs, image, oldproglen, &ctx);
2081 		if (proglen <= 0) {
2082 out_image:
2083 			image = NULL;
2084 			if (header)
2085 				bpf_jit_binary_free(header);
2086 			prog = orig_prog;
2087 			goto out_addrs;
2088 		}
2089 		if (image) {
2090 			if (proglen != oldproglen) {
2091 				pr_err("bpf_jit: proglen=%d != oldproglen=%d\n",
2092 				       proglen, oldproglen);
2093 				goto out_image;
2094 			}
2095 			break;
2096 		}
2097 		if (proglen == oldproglen) {
2098 			/*
2099 			 * The number of entries in extable is the number of BPF_LDX
2100 			 * insns that access kernel memory via "pointer to BTF type".
2101 			 * The verifier changed their opcode from LDX|MEM|size
2102 			 * to LDX|PROBE_MEM|size to make JITing easier.
2103 			 */
2104 			u32 align = __alignof__(struct exception_table_entry);
2105 			u32 extable_size = prog->aux->num_exentries *
2106 				sizeof(struct exception_table_entry);
2107 
2108 			/* allocate module memory for x86 insns and extable */
2109 			header = bpf_jit_binary_alloc(roundup(proglen, align) + extable_size,
2110 						      &image, align, jit_fill_hole);
2111 			if (!header) {
2112 				prog = orig_prog;
2113 				goto out_addrs;
2114 			}
2115 			prog->aux->extable = (void *) image + roundup(proglen, align);
2116 		}
2117 		oldproglen = proglen;
2118 		cond_resched();
2119 	}
2120 
2121 	if (bpf_jit_enable > 1)
2122 		bpf_jit_dump(prog->len, proglen, pass + 1, image);
2123 
2124 	if (image) {
2125 		if (!prog->is_func || extra_pass) {
2126 			bpf_tail_call_direct_fixup(prog);
2127 			bpf_jit_binary_lock_ro(header);
2128 		} else {
2129 			jit_data->addrs = addrs;
2130 			jit_data->ctx = ctx;
2131 			jit_data->proglen = proglen;
2132 			jit_data->image = image;
2133 			jit_data->header = header;
2134 		}
2135 		prog->bpf_func = (void *)image;
2136 		prog->jited = 1;
2137 		prog->jited_len = proglen;
2138 	} else {
2139 		prog = orig_prog;
2140 	}
2141 
2142 	if (!image || !prog->is_func || extra_pass) {
2143 		if (image)
2144 			bpf_prog_fill_jited_linfo(prog, addrs + 1);
2145 out_addrs:
2146 		kvfree(addrs);
2147 		kfree(jit_data);
2148 		prog->aux->jit_data = NULL;
2149 	}
2150 out:
2151 	if (tmp_blinded)
2152 		bpf_jit_prog_release_other(prog, prog == orig_prog ?
2153 					   tmp : orig_prog);
2154 	return prog;
2155 }
2156