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