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