xref: /linux/arch/mips/net/bpf_jit_comp.c (revision 20bed0d6ff62d985fe8222958825504b8aad4e88)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Just-In-Time compiler for eBPF bytecode on MIPS.
4  * Implementation of JIT functions common to 32-bit and 64-bit CPUs.
5  *
6  * Copyright (c) 2021 Anyfi Networks AB.
7  * Author: Johan Almbladh <johan.almbladh@gmail.com>
8  *
9  * Based on code and ideas from
10  * Copyright (c) 2017 Cavium, Inc.
11  * Copyright (c) 2017 Shubham Bansal <illusionist.neo@gmail.com>
12  * Copyright (c) 2011 Mircea Gherzan <mgherzan@gmail.com>
13  */
14 
15 /*
16  * Code overview
17  * =============
18  *
19  * - bpf_jit_comp.h
20  *   Common definitions and utilities.
21  *
22  * - bpf_jit_comp.c
23  *   Implementation of JIT top-level logic and exported JIT API functions.
24  *   Implementation of internal operations shared by 32-bit and 64-bit code.
25  *   JMP and ALU JIT control code, register control code, shared ALU and
26  *   JMP/JMP32 JIT operations.
27  *
28  * - bpf_jit_comp32.c
29  *   Implementation of functions to JIT prologue, epilogue and a single eBPF
30  *   instruction for 32-bit MIPS CPUs. The functions use shared operations
31  *   where possible, and implement the rest for 32-bit MIPS such as ALU64
32  *   operations.
33  *
34  * - bpf_jit_comp64.c
35  *   Ditto, for 64-bit MIPS CPUs.
36  *
37  * Zero and sign extension
38  * ========================
39  * 32-bit MIPS instructions on 64-bit MIPS registers use sign extension,
40  * but the eBPF instruction set mandates zero extension. We let the verifier
41  * insert explicit zero-extensions after 32-bit ALU operations, both for
42  * 32-bit and 64-bit MIPS JITs. Conditional JMP32 operations on 64-bit MIPs
43  * are JITed with sign extensions inserted when so expected.
44  *
45  * ALU operations
46  * ==============
47  * ALU operations on 32/64-bit MIPS and ALU64 operations on 64-bit MIPS are
48  * JITed in the following steps. ALU64 operations on 32-bit MIPS are more
49  * complicated and therefore only processed by special implementations in
50  * step (3).
51  *
52  * 1) valid_alu_i:
53  *    Determine if an immediate operation can be emitted as such, or if
54  *    we must fall back to the register version.
55  *
56  * 2) rewrite_alu_i:
57  *    Convert BPF operation and immediate value to a canonical form for
58  *    JITing. In some degenerate cases this form may be a no-op.
59  *
60  * 3) emit_alu_{i,i64,r,64}:
61  *    Emit instructions for an ALU or ALU64 immediate or register operation.
62  *
63  * JMP operations
64  * ==============
65  * JMP and JMP32 operations require an JIT instruction offset table for
66  * translating the jump offset. This table is computed by dry-running the
67  * JIT without actually emitting anything. However, the computed PC-relative
68  * offset may overflow the 18-bit offset field width of the native MIPS
69  * branch instruction. In such cases, the long jump is converted into the
70  * following sequence.
71  *
72  *    <branch> !<cond> +2    Inverted PC-relative branch
73  *    nop                    Delay slot
74  *    j <offset>             Unconditional absolute long jump
75  *    nop                    Delay slot
76  *
77  * Since this converted sequence alters the offset table, all offsets must
78  * be re-calculated. This may in turn trigger new branch conversions, so
79  * the process is repeated until no further changes are made. Normally it
80  * completes in 1-2 iterations. If JIT_MAX_ITERATIONS should reached, we
81  * fall back to converting every remaining jump operation. The branch
82  * conversion is independent of how the JMP or JMP32 condition is JITed.
83  *
84  * JMP32 and JMP operations are JITed as follows.
85  *
86  * 1) setup_jmp_{i,r}:
87  *    Convert jump conditional and offset into a form that can be JITed.
88  *    This form may be a no-op, a canonical form, or an inverted PC-relative
89  *    jump if branch conversion is necessary.
90  *
91  * 2) valid_jmp_i:
92  *    Determine if an immediate operations can be emitted as such, or if
93  *    we must fall back to the register version. Applies to JMP32 for 32-bit
94  *    MIPS, and both JMP and JMP32 for 64-bit MIPS.
95  *
96  * 3) emit_jmp_{i,i64,r,r64}:
97  *    Emit instructions for an JMP or JMP32 immediate or register operation.
98  *
99  * 4) finish_jmp_{i,r}:
100  *    Emit any instructions needed to finish the jump. This includes a nop
101  *    for the delay slot if a branch was emitted, and a long absolute jump
102  *    if the branch was converted.
103  */
104 
105 #include <linux/limits.h>
106 #include <linux/bitops.h>
107 #include <linux/errno.h>
108 #include <linux/filter.h>
109 #include <linux/bpf.h>
110 #include <linux/slab.h>
111 #include <asm/bitops.h>
112 #include <asm/cacheflush.h>
113 #include <asm/cpu-features.h>
114 #include <asm/isa-rev.h>
115 #include <asm/uasm.h>
116 
117 #include "bpf_jit_comp.h"
118 
119 /* Convenience macros for descriptor access */
120 #define CONVERTED(desc)	((desc) & JIT_DESC_CONVERT)
121 #define INDEX(desc)	((desc) & ~JIT_DESC_CONVERT)
122 
123 /*
124  * Push registers on the stack, starting at a given depth from the stack
125  * pointer and increasing. The next depth to be written is returned.
126  */
127 int push_regs(struct jit_context *ctx, u32 mask, u32 excl, int depth)
128 {
129 	int reg;
130 
131 	for (reg = 0; reg < BITS_PER_BYTE * sizeof(mask); reg++)
132 		if (mask & BIT(reg)) {
133 			if ((excl & BIT(reg)) == 0) {
134 				if (sizeof(long) == 4)
135 					emit(ctx, sw, reg, depth, MIPS_R_SP);
136 				else /* sizeof(long) == 8 */
137 					emit(ctx, sd, reg, depth, MIPS_R_SP);
138 			}
139 			depth += sizeof(long);
140 		}
141 
142 	ctx->stack_used = max((int)ctx->stack_used, depth);
143 	return depth;
144 }
145 
146 /*
147  * Pop registers from the stack, starting at a given depth from the stack
148  * pointer and increasing. The next depth to be read is returned.
149  */
150 int pop_regs(struct jit_context *ctx, u32 mask, u32 excl, int depth)
151 {
152 	int reg;
153 
154 	for (reg = 0; reg < BITS_PER_BYTE * sizeof(mask); reg++)
155 		if (mask & BIT(reg)) {
156 			if ((excl & BIT(reg)) == 0) {
157 				if (sizeof(long) == 4)
158 					emit(ctx, lw, reg, depth, MIPS_R_SP);
159 				else /* sizeof(long) == 8 */
160 					emit(ctx, ld, reg, depth, MIPS_R_SP);
161 			}
162 			depth += sizeof(long);
163 		}
164 
165 	return depth;
166 }
167 
168 /* Compute the 28-bit jump target address from a BPF program location */
169 int get_target(struct jit_context *ctx, u32 loc)
170 {
171 	u32 index = INDEX(ctx->descriptors[loc]);
172 	unsigned long pc = (unsigned long)&ctx->target[ctx->jit_index];
173 	unsigned long addr = (unsigned long)&ctx->target[index];
174 
175 	if (!ctx->target)
176 		return 0;
177 
178 	if ((addr ^ pc) & ~MIPS_JMP_MASK)
179 		return -1;
180 
181 	return addr & MIPS_JMP_MASK;
182 }
183 
184 /* Compute the PC-relative offset to relative BPF program offset */
185 int get_offset(const struct jit_context *ctx, int off)
186 {
187 	return (INDEX(ctx->descriptors[ctx->bpf_index + off]) -
188 		ctx->jit_index - 1) * sizeof(u32);
189 }
190 
191 /* dst = imm (register width) */
192 void emit_mov_i(struct jit_context *ctx, u8 dst, s32 imm)
193 {
194 	if (imm >= -0x8000 && imm <= 0x7fff) {
195 		emit(ctx, addiu, dst, MIPS_R_ZERO, imm);
196 	} else {
197 		emit(ctx, lui, dst, (s16)((u32)imm >> 16));
198 		emit(ctx, ori, dst, dst, (u16)(imm & 0xffff));
199 	}
200 	clobber_reg(ctx, dst);
201 }
202 
203 /* dst = src (register width) */
204 void emit_mov_r(struct jit_context *ctx, u8 dst, u8 src)
205 {
206 	emit(ctx, ori, dst, src, 0);
207 	clobber_reg(ctx, dst);
208 }
209 
210 /* Validate ALU immediate range */
211 bool valid_alu_i(u8 op, s32 imm, s16 off)
212 {
213 	switch (BPF_OP(op)) {
214 	case BPF_NEG:
215 	case BPF_LSH:
216 	case BPF_RSH:
217 	case BPF_ARSH:
218 		/* All legal eBPF values are valid */
219 		return true;
220 	case BPF_ADD:
221 		if (IS_ENABLED(CONFIG_CPU_DADDI_WORKAROUNDS))
222 			return false;
223 		/* imm must be 16 bits */
224 		return imm >= -0x8000 && imm <= 0x7fff;
225 	case BPF_SUB:
226 		if (IS_ENABLED(CONFIG_CPU_DADDI_WORKAROUNDS))
227 			return false;
228 		/* -imm must be 16 bits */
229 		return imm >= -0x7fff && imm <= 0x8000;
230 	case BPF_AND:
231 	case BPF_OR:
232 	case BPF_XOR:
233 		/* imm must be 16 bits unsigned */
234 		return imm >= 0 && imm <= 0xffff;
235 	case BPF_MUL:
236 		/* imm must be zero or a positive power of two */
237 		return imm == 0 || (imm > 0 && is_power_of_2(imm));
238 	case BPF_DIV:
239 	case BPF_MOD:
240 		/* Do not use unsigned shift/mask rewrites for signed div/mod. */
241 		if (off == 1)
242 			return false;
243 		/* imm must be an 17-bit power of two */
244 		return (u32)imm <= 0x10000 && is_power_of_2((u32)imm);
245 	}
246 	return false;
247 }
248 
249 /* Rewrite ALU immediate operation */
250 bool rewrite_alu_i(u8 op, s32 imm, u8 *alu, s32 *val)
251 {
252 	bool act = true;
253 
254 	switch (BPF_OP(op)) {
255 	case BPF_LSH:
256 	case BPF_RSH:
257 	case BPF_ARSH:
258 	case BPF_ADD:
259 	case BPF_SUB:
260 	case BPF_OR:
261 	case BPF_XOR:
262 		/* imm == 0 is a no-op */
263 		act = imm != 0;
264 		break;
265 	case BPF_MUL:
266 		if (imm == 1) {
267 			/* dst * 1 is a no-op */
268 			act = false;
269 		} else if (imm == 0) {
270 			/* dst * 0 is dst & 0 */
271 			op = BPF_AND;
272 		} else {
273 			/* dst * (1 << n) is dst << n */
274 			op = BPF_LSH;
275 			imm = ilog2(abs(imm));
276 		}
277 		break;
278 	case BPF_DIV:
279 		if (imm == 1) {
280 			/* dst / 1 is a no-op */
281 			act = false;
282 		} else {
283 			/* dst / (1 << n) is dst >> n */
284 			op = BPF_RSH;
285 			imm = ilog2(imm);
286 		}
287 		break;
288 	case BPF_MOD:
289 		/* dst % (1 << n) is dst & ((1 << n) - 1) */
290 		op = BPF_AND;
291 		imm--;
292 		break;
293 	}
294 
295 	*alu = op;
296 	*val = imm;
297 	return act;
298 }
299 
300 /* ALU immediate operation (32-bit) */
301 void emit_alu_i(struct jit_context *ctx, u8 dst, s32 imm, u8 op)
302 {
303 	switch (BPF_OP(op)) {
304 	/* dst = -dst */
305 	case BPF_NEG:
306 		emit(ctx, subu, dst, MIPS_R_ZERO, dst);
307 		break;
308 	/* dst = dst & imm */
309 	case BPF_AND:
310 		emit(ctx, andi, dst, dst, (u16)imm);
311 		break;
312 	/* dst = dst | imm */
313 	case BPF_OR:
314 		emit(ctx, ori, dst, dst, (u16)imm);
315 		break;
316 	/* dst = dst ^ imm */
317 	case BPF_XOR:
318 		emit(ctx, xori, dst, dst, (u16)imm);
319 		break;
320 	/* dst = dst << imm */
321 	case BPF_LSH:
322 		emit(ctx, sll, dst, dst, imm);
323 		break;
324 	/* dst = dst >> imm */
325 	case BPF_RSH:
326 		emit(ctx, srl, dst, dst, imm);
327 		break;
328 	/* dst = dst >> imm (arithmetic) */
329 	case BPF_ARSH:
330 		emit(ctx, sra, dst, dst, imm);
331 		break;
332 	/* dst = dst + imm */
333 	case BPF_ADD:
334 		emit(ctx, addiu, dst, dst, imm);
335 		break;
336 	/* dst = dst - imm */
337 	case BPF_SUB:
338 		emit(ctx, addiu, dst, dst, -imm);
339 		break;
340 	}
341 	clobber_reg(ctx, dst);
342 }
343 
344 /* ALU division operation (32-bit) */
345 static void emit_div(struct jit_context *ctx, u8 dst, u8 src, s16 off)
346 {
347 	if (cpu_has_mips32r6) {
348 		if (off == 1)
349 			emit(ctx, div_r6, dst, dst, src);
350 		else
351 			emit(ctx, divu_r6, dst, dst, src);
352 	} else {
353 		if (off == 1)
354 			emit(ctx, div, dst, src);
355 		else
356 			emit(ctx, divu, dst, src);
357 		emit(ctx, mflo, dst);
358 	}
359 }
360 
361 /* ALU modulo operation (32-bit) */
362 static void emit_mod(struct jit_context *ctx, u8 dst, u8 src, s16 off)
363 {
364 	if (cpu_has_mips32r6) {
365 		if (off == 1)
366 			emit(ctx, mod, dst, dst, src);
367 		else
368 			emit(ctx, modu, dst, dst, src);
369 	} else {
370 		if (off == 1)
371 			emit(ctx, div, dst, src);
372 		else
373 			emit(ctx, divu, dst, src);
374 		emit(ctx, mfhi, dst);
375 	}
376 }
377 
378 /* ALU register operation (32-bit) */
379 void emit_alu_r(struct jit_context *ctx, u8 dst, u8 src, u8 op, s16 off)
380 {
381 	switch (BPF_OP(op)) {
382 	/* dst = dst & src */
383 	case BPF_AND:
384 		emit(ctx, and, dst, dst, src);
385 		break;
386 	/* dst = dst | src */
387 	case BPF_OR:
388 		emit(ctx, or, dst, dst, src);
389 		break;
390 	/* dst = dst ^ src */
391 	case BPF_XOR:
392 		emit(ctx, xor, dst, dst, src);
393 		break;
394 	/* dst = dst << src */
395 	case BPF_LSH:
396 		emit(ctx, sllv, dst, dst, src);
397 		break;
398 	/* dst = dst >> src */
399 	case BPF_RSH:
400 		emit(ctx, srlv, dst, dst, src);
401 		break;
402 	/* dst = dst >> src (arithmetic) */
403 	case BPF_ARSH:
404 		emit(ctx, srav, dst, dst, src);
405 		break;
406 	/* dst = dst + src */
407 	case BPF_ADD:
408 		emit(ctx, addu, dst, dst, src);
409 		break;
410 	/* dst = dst - src */
411 	case BPF_SUB:
412 		emit(ctx, subu, dst, dst, src);
413 		break;
414 	/* dst = dst * src */
415 	case BPF_MUL:
416 		if (cpu_has_mips32r1 || cpu_has_mips32r6) {
417 			emit(ctx, mul, dst, dst, src);
418 		} else {
419 			emit(ctx, multu, dst, src);
420 			emit(ctx, mflo, dst);
421 		}
422 		break;
423 	/* dst = dst / src */
424 	case BPF_DIV:
425 		emit_div(ctx, dst, src, off);
426 		break;
427 	/* dst = dst % src */
428 	case BPF_MOD:
429 		emit_mod(ctx, dst, src, off);
430 		break;
431 	}
432 	clobber_reg(ctx, dst);
433 }
434 
435 /* Atomic read-modify-write (32-bit) */
436 void emit_atomic_r(struct jit_context *ctx, u8 dst, u8 src, s16 off, u8 code)
437 {
438 	LLSC_sync(ctx);
439 	emit(ctx, ll, MIPS_R_T9, off, dst);
440 	switch (code) {
441 	case BPF_ADD:
442 	case BPF_ADD | BPF_FETCH:
443 		emit(ctx, addu, MIPS_R_T8, MIPS_R_T9, src);
444 		break;
445 	case BPF_AND:
446 	case BPF_AND | BPF_FETCH:
447 		emit(ctx, and, MIPS_R_T8, MIPS_R_T9, src);
448 		break;
449 	case BPF_OR:
450 	case BPF_OR | BPF_FETCH:
451 		emit(ctx, or, MIPS_R_T8, MIPS_R_T9, src);
452 		break;
453 	case BPF_XOR:
454 	case BPF_XOR | BPF_FETCH:
455 		emit(ctx, xor, MIPS_R_T8, MIPS_R_T9, src);
456 		break;
457 	case BPF_XCHG:
458 		emit(ctx, move, MIPS_R_T8, src);
459 		break;
460 	}
461 	emit(ctx, sc, MIPS_R_T8, off, dst);
462 	emit(ctx, LLSC_beqz, MIPS_R_T8, -16 - LLSC_offset);
463 	emit(ctx, nop); /* Delay slot */
464 
465 	if (code & BPF_FETCH) {
466 		emit(ctx, move, src, MIPS_R_T9);
467 		clobber_reg(ctx, src);
468 	}
469 }
470 
471 /* Atomic compare-and-exchange (32-bit) */
472 void emit_cmpxchg_r(struct jit_context *ctx, u8 dst, u8 src, u8 res, s16 off)
473 {
474 	LLSC_sync(ctx);
475 	emit(ctx, ll, MIPS_R_T9, off, dst);
476 	emit(ctx, bne, MIPS_R_T9, res, 12);
477 	emit(ctx, move, MIPS_R_T8, src);     /* Delay slot */
478 	emit(ctx, sc, MIPS_R_T8, off, dst);
479 	emit(ctx, LLSC_beqz, MIPS_R_T8, -20 - LLSC_offset);
480 	emit(ctx, move, res, MIPS_R_T9);     /* Delay slot */
481 	clobber_reg(ctx, res);
482 }
483 
484 /* Swap bytes and truncate a register word or half word */
485 void emit_bswap_r(struct jit_context *ctx, u8 dst, u32 width)
486 {
487 	u8 tmp = MIPS_R_T8;
488 	u8 msk = MIPS_R_T9;
489 
490 	switch (width) {
491 	/* Swap bytes in a word */
492 	case 32:
493 		if (cpu_has_mips32r2 || cpu_has_mips32r6) {
494 			emit(ctx, wsbh, dst, dst);
495 			emit(ctx, rotr, dst, dst, 16);
496 		} else {
497 			emit(ctx, sll, tmp, dst, 16);    /* tmp  = dst << 16 */
498 			emit(ctx, srl, dst, dst, 16);    /* dst = dst >> 16  */
499 			emit(ctx, or, dst, dst, tmp);    /* dst = dst | tmp  */
500 
501 			emit(ctx, lui, msk, 0xff);       /* msk = 0x00ff0000 */
502 			emit(ctx, ori, msk, msk, 0xff);  /* msk = msk | 0xff */
503 
504 			emit(ctx, and, tmp, dst, msk);   /* tmp = dst & msk  */
505 			emit(ctx, sll, tmp, tmp, 8);     /* tmp = tmp << 8   */
506 			emit(ctx, srl, dst, dst, 8);     /* dst = dst >> 8   */
507 			emit(ctx, and, dst, dst, msk);   /* dst = dst & msk  */
508 			emit(ctx, or, dst, dst, tmp);    /* reg = dst | tmp  */
509 		}
510 		break;
511 	/* Swap bytes in a half word */
512 	case 16:
513 		if (cpu_has_mips32r2 || cpu_has_mips32r6) {
514 			emit(ctx, wsbh, dst, dst);
515 			emit(ctx, andi, dst, dst, 0xffff);
516 		} else {
517 			emit(ctx, andi, tmp, dst, 0xff00); /* t = d & 0xff00 */
518 			emit(ctx, srl, tmp, tmp, 8);       /* t = t >> 8     */
519 			emit(ctx, andi, dst, dst, 0x00ff); /* d = d & 0x00ff */
520 			emit(ctx, sll, dst, dst, 8);       /* d = d << 8     */
521 			emit(ctx, or,  dst, dst, tmp);     /* d = d | t      */
522 		}
523 		break;
524 	}
525 	clobber_reg(ctx, dst);
526 }
527 
528 /* Validate jump immediate range */
529 bool valid_jmp_i(u8 op, s32 imm)
530 {
531 	switch (op) {
532 	case JIT_JNOP:
533 		/* Immediate value not used */
534 		return true;
535 	case BPF_JEQ:
536 	case BPF_JNE:
537 		/* No immediate operation */
538 		return false;
539 	case BPF_JSET:
540 	case JIT_JNSET:
541 		/* imm must be 16 bits unsigned */
542 		return imm >= 0 && imm <= 0xffff;
543 	case BPF_JGE:
544 	case BPF_JLT:
545 	case BPF_JSGE:
546 	case BPF_JSLT:
547 		/* imm must be 16 bits */
548 		return imm >= -0x8000 && imm <= 0x7fff;
549 	case BPF_JGT:
550 	case BPF_JLE:
551 	case BPF_JSGT:
552 	case BPF_JSLE:
553 		/* imm + 1 must be 16 bits */
554 		return imm >= -0x8001 && imm <= 0x7ffe;
555 	}
556 	return false;
557 }
558 
559 /* Invert a conditional jump operation */
560 static u8 invert_jmp(u8 op)
561 {
562 	switch (op) {
563 	case BPF_JA: return JIT_JNOP;
564 	case BPF_JEQ: return BPF_JNE;
565 	case BPF_JNE: return BPF_JEQ;
566 	case BPF_JSET: return JIT_JNSET;
567 	case BPF_JGT: return BPF_JLE;
568 	case BPF_JGE: return BPF_JLT;
569 	case BPF_JLT: return BPF_JGE;
570 	case BPF_JLE: return BPF_JGT;
571 	case BPF_JSGT: return BPF_JSLE;
572 	case BPF_JSGE: return BPF_JSLT;
573 	case BPF_JSLT: return BPF_JSGE;
574 	case BPF_JSLE: return BPF_JSGT;
575 	}
576 	return 0;
577 }
578 
579 /* Prepare a PC-relative jump operation */
580 static void setup_jmp(struct jit_context *ctx, u8 bpf_op,
581 		      s16 bpf_off, u8 *jit_op, s32 *jit_off)
582 {
583 	u32 *descp = &ctx->descriptors[ctx->bpf_index];
584 	int op = bpf_op;
585 	int offset = 0;
586 
587 	/* Do not compute offsets on the first pass */
588 	if (INDEX(*descp) == 0)
589 		goto done;
590 
591 	/* Skip jumps never taken */
592 	if (bpf_op == JIT_JNOP)
593 		goto done;
594 
595 	/* Convert jumps always taken */
596 	if (bpf_op == BPF_JA)
597 		*descp |= JIT_DESC_CONVERT;
598 
599 	/*
600 	 * Current ctx->jit_index points to the start of the branch preamble.
601 	 * Since the preamble differs among different branch conditionals,
602 	 * the current index cannot be used to compute the branch offset.
603 	 * Instead, we use the offset table value for the next instruction,
604 	 * which gives the index immediately after the branch delay slot.
605 	 */
606 	if (!CONVERTED(*descp)) {
607 		int target = ctx->bpf_index + bpf_off + 1;
608 		int origin = ctx->bpf_index + 1;
609 
610 		offset = (INDEX(ctx->descriptors[target]) -
611 			  INDEX(ctx->descriptors[origin]) + 1) * sizeof(u32);
612 	}
613 
614 	/*
615 	 * The PC-relative branch offset field on MIPS is 18 bits signed,
616 	 * so if the computed offset is larger than this we generate a an
617 	 * absolute jump that we skip with an inverted conditional branch.
618 	 */
619 	if (CONVERTED(*descp) || offset < -0x20000 || offset > 0x1ffff) {
620 		offset = 3 * sizeof(u32);
621 		op = invert_jmp(bpf_op);
622 		ctx->changes += !CONVERTED(*descp);
623 		*descp |= JIT_DESC_CONVERT;
624 	}
625 
626 done:
627 	*jit_off = offset;
628 	*jit_op = op;
629 }
630 
631 /* Prepare a PC-relative jump operation with immediate conditional */
632 void setup_jmp_i(struct jit_context *ctx, s32 imm, u8 width,
633 		 u8 bpf_op, s16 bpf_off, u8 *jit_op, s32 *jit_off)
634 {
635 	bool always = false;
636 	bool never = false;
637 
638 	switch (bpf_op) {
639 	case BPF_JEQ:
640 	case BPF_JNE:
641 		break;
642 	case BPF_JSET:
643 	case BPF_JLT:
644 		never = imm == 0;
645 		break;
646 	case BPF_JGE:
647 		always = imm == 0;
648 		break;
649 	case BPF_JGT:
650 		never = (u32)imm == U32_MAX;
651 		break;
652 	case BPF_JLE:
653 		always = (u32)imm == U32_MAX;
654 		break;
655 	case BPF_JSGT:
656 		never = imm == S32_MAX && width == 32;
657 		break;
658 	case BPF_JSGE:
659 		always = imm == S32_MIN && width == 32;
660 		break;
661 	case BPF_JSLT:
662 		never = imm == S32_MIN && width == 32;
663 		break;
664 	case BPF_JSLE:
665 		always = imm == S32_MAX && width == 32;
666 		break;
667 	}
668 
669 	if (never)
670 		bpf_op = JIT_JNOP;
671 	if (always)
672 		bpf_op = BPF_JA;
673 	setup_jmp(ctx, bpf_op, bpf_off, jit_op, jit_off);
674 }
675 
676 /* Prepare a PC-relative jump operation with register conditional */
677 void setup_jmp_r(struct jit_context *ctx, bool same_reg,
678 		 u8 bpf_op, s16 bpf_off, u8 *jit_op, s32 *jit_off)
679 {
680 	switch (bpf_op) {
681 	case BPF_JSET:
682 		break;
683 	case BPF_JEQ:
684 	case BPF_JGE:
685 	case BPF_JLE:
686 	case BPF_JSGE:
687 	case BPF_JSLE:
688 		if (same_reg)
689 			bpf_op = BPF_JA;
690 		break;
691 	case BPF_JNE:
692 	case BPF_JLT:
693 	case BPF_JGT:
694 	case BPF_JSGT:
695 	case BPF_JSLT:
696 		if (same_reg)
697 			bpf_op = JIT_JNOP;
698 		break;
699 	}
700 	setup_jmp(ctx, bpf_op, bpf_off, jit_op, jit_off);
701 }
702 
703 /* Finish a PC-relative jump operation */
704 int finish_jmp(struct jit_context *ctx, u8 jit_op, s16 bpf_off)
705 {
706 	/* Emit conditional branch delay slot */
707 	if (jit_op != JIT_JNOP)
708 		emit(ctx, nop);
709 	/*
710 	 * Emit an absolute long jump with delay slot,
711 	 * if the PC-relative branch was converted.
712 	 */
713 	if (CONVERTED(ctx->descriptors[ctx->bpf_index])) {
714 		int target = get_target(ctx, ctx->bpf_index + bpf_off + 1);
715 
716 		if (target < 0)
717 			return -1;
718 		emit(ctx, j, target);
719 		emit(ctx, nop);
720 	}
721 	return 0;
722 }
723 
724 /* Jump immediate (32-bit) */
725 void emit_jmp_i(struct jit_context *ctx, u8 dst, s32 imm, s32 off, u8 op)
726 {
727 	switch (op) {
728 	/* No-op, used internally for branch optimization */
729 	case JIT_JNOP:
730 		break;
731 	/* PC += off if dst & imm */
732 	case BPF_JSET:
733 		emit(ctx, andi, MIPS_R_T9, dst, (u16)imm);
734 		emit(ctx, bnez, MIPS_R_T9, off);
735 		break;
736 	/* PC += off if (dst & imm) == 0 (not in BPF, used for long jumps) */
737 	case JIT_JNSET:
738 		emit(ctx, andi, MIPS_R_T9, dst, (u16)imm);
739 		emit(ctx, beqz, MIPS_R_T9, off);
740 		break;
741 	/* PC += off if dst > imm */
742 	case BPF_JGT:
743 		emit(ctx, sltiu, MIPS_R_T9, dst, imm + 1);
744 		emit(ctx, beqz, MIPS_R_T9, off);
745 		break;
746 	/* PC += off if dst >= imm */
747 	case BPF_JGE:
748 		emit(ctx, sltiu, MIPS_R_T9, dst, imm);
749 		emit(ctx, beqz, MIPS_R_T9, off);
750 		break;
751 	/* PC += off if dst < imm */
752 	case BPF_JLT:
753 		emit(ctx, sltiu, MIPS_R_T9, dst, imm);
754 		emit(ctx, bnez, MIPS_R_T9, off);
755 		break;
756 	/* PC += off if dst <= imm */
757 	case BPF_JLE:
758 		emit(ctx, sltiu, MIPS_R_T9, dst, imm + 1);
759 		emit(ctx, bnez, MIPS_R_T9, off);
760 		break;
761 	/* PC += off if dst > imm (signed) */
762 	case BPF_JSGT:
763 		emit(ctx, slti, MIPS_R_T9, dst, imm + 1);
764 		emit(ctx, beqz, MIPS_R_T9, off);
765 		break;
766 	/* PC += off if dst >= imm (signed) */
767 	case BPF_JSGE:
768 		emit(ctx, slti, MIPS_R_T9, dst, imm);
769 		emit(ctx, beqz, MIPS_R_T9, off);
770 		break;
771 	/* PC += off if dst < imm (signed) */
772 	case BPF_JSLT:
773 		emit(ctx, slti, MIPS_R_T9, dst, imm);
774 		emit(ctx, bnez, MIPS_R_T9, off);
775 		break;
776 	/* PC += off if dst <= imm (signed) */
777 	case BPF_JSLE:
778 		emit(ctx, slti, MIPS_R_T9, dst, imm + 1);
779 		emit(ctx, bnez, MIPS_R_T9, off);
780 		break;
781 	}
782 }
783 
784 /* Jump register (32-bit) */
785 void emit_jmp_r(struct jit_context *ctx, u8 dst, u8 src, s32 off, u8 op)
786 {
787 	switch (op) {
788 	/* No-op, used internally for branch optimization */
789 	case JIT_JNOP:
790 		break;
791 	/* PC += off if dst == src */
792 	case BPF_JEQ:
793 		emit(ctx, beq, dst, src, off);
794 		break;
795 	/* PC += off if dst != src */
796 	case BPF_JNE:
797 		emit(ctx, bne, dst, src, off);
798 		break;
799 	/* PC += off if dst & src */
800 	case BPF_JSET:
801 		emit(ctx, and, MIPS_R_T9, dst, src);
802 		emit(ctx, bnez, MIPS_R_T9, off);
803 		break;
804 	/* PC += off if (dst & imm) == 0 (not in BPF, used for long jumps) */
805 	case JIT_JNSET:
806 		emit(ctx, and, MIPS_R_T9, dst, src);
807 		emit(ctx, beqz, MIPS_R_T9, off);
808 		break;
809 	/* PC += off if dst > src */
810 	case BPF_JGT:
811 		emit(ctx, sltu, MIPS_R_T9, src, dst);
812 		emit(ctx, bnez, MIPS_R_T9, off);
813 		break;
814 	/* PC += off if dst >= src */
815 	case BPF_JGE:
816 		emit(ctx, sltu, MIPS_R_T9, dst, src);
817 		emit(ctx, beqz, MIPS_R_T9, off);
818 		break;
819 	/* PC += off if dst < src */
820 	case BPF_JLT:
821 		emit(ctx, sltu, MIPS_R_T9, dst, src);
822 		emit(ctx, bnez, MIPS_R_T9, off);
823 		break;
824 	/* PC += off if dst <= src */
825 	case BPF_JLE:
826 		emit(ctx, sltu, MIPS_R_T9, src, dst);
827 		emit(ctx, beqz, MIPS_R_T9, off);
828 		break;
829 	/* PC += off if dst > src (signed) */
830 	case BPF_JSGT:
831 		emit(ctx, slt, MIPS_R_T9, src, dst);
832 		emit(ctx, bnez, MIPS_R_T9, off);
833 		break;
834 	/* PC += off if dst >= src (signed) */
835 	case BPF_JSGE:
836 		emit(ctx, slt, MIPS_R_T9, dst, src);
837 		emit(ctx, beqz, MIPS_R_T9, off);
838 		break;
839 	/* PC += off if dst < src (signed) */
840 	case BPF_JSLT:
841 		emit(ctx, slt, MIPS_R_T9, dst, src);
842 		emit(ctx, bnez, MIPS_R_T9, off);
843 		break;
844 	/* PC += off if dst <= src (signed) */
845 	case BPF_JSLE:
846 		emit(ctx, slt, MIPS_R_T9, src, dst);
847 		emit(ctx, beqz, MIPS_R_T9, off);
848 		break;
849 	}
850 }
851 
852 /* Jump always */
853 int emit_ja(struct jit_context *ctx, s32 off)
854 {
855 	int target = get_target(ctx, ctx->bpf_index + off + 1);
856 
857 	if (target < 0)
858 		return -1;
859 	emit(ctx, j, target);
860 	emit(ctx, nop);
861 	return 0;
862 }
863 
864 /* Jump to epilogue */
865 int emit_exit(struct jit_context *ctx)
866 {
867 	int target = get_target(ctx, ctx->program->len);
868 
869 	if (target < 0)
870 		return -1;
871 	emit(ctx, j, target);
872 	emit(ctx, nop);
873 	return 0;
874 }
875 
876 /* Build the program body from eBPF bytecode */
877 static int build_body(struct jit_context *ctx)
878 {
879 	const struct bpf_prog *prog = ctx->program;
880 	unsigned int i;
881 
882 	ctx->stack_used = 0;
883 	for (i = 0; i < prog->len; i++) {
884 		const struct bpf_insn *insn = &prog->insnsi[i];
885 		u32 *descp = &ctx->descriptors[i];
886 		int ret;
887 
888 		access_reg(ctx, insn->src_reg);
889 		access_reg(ctx, insn->dst_reg);
890 
891 		ctx->bpf_index = i;
892 		if (ctx->target == NULL) {
893 			ctx->changes += INDEX(*descp) != ctx->jit_index;
894 			*descp &= JIT_DESC_CONVERT;
895 			*descp |= ctx->jit_index;
896 		}
897 
898 		ret = build_insn(insn, ctx);
899 		if (ret < 0)
900 			return ret;
901 
902 		if (ret > 0) {
903 			i++;
904 			if (ctx->target == NULL)
905 				descp[1] = ctx->jit_index;
906 		}
907 	}
908 
909 	/* Store the end offset, where the epilogue begins */
910 	ctx->descriptors[prog->len] = ctx->jit_index;
911 	return 0;
912 }
913 
914 /* Set the branch conversion flag on all instructions */
915 static void set_convert_flag(struct jit_context *ctx, bool enable)
916 {
917 	const struct bpf_prog *prog = ctx->program;
918 	u32 flag = enable ? JIT_DESC_CONVERT : 0;
919 	unsigned int i;
920 
921 	for (i = 0; i <= prog->len; i++)
922 		ctx->descriptors[i] = INDEX(ctx->descriptors[i]) | flag;
923 }
924 
925 static void jit_fill_hole(void *area, unsigned int size)
926 {
927 	u32 *p;
928 
929 	/* We are guaranteed to have aligned memory. */
930 	for (p = area; size >= sizeof(u32); size -= sizeof(u32))
931 		uasm_i_break(&p, BRK_BUG); /* Increments p */
932 }
933 
934 bool bpf_jit_needs_zext(void)
935 {
936 	return true;
937 }
938 
939 struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog)
940 {
941 	struct bpf_binary_header *header = NULL;
942 	struct jit_context ctx;
943 	unsigned int tmp_idx;
944 	unsigned int image_size;
945 	u8 *image_ptr;
946 	int tries;
947 
948 	/*
949 	 * If BPF JIT was not enabled then we must fall back to
950 	 * the interpreter.
951 	 */
952 	if (!prog->jit_requested)
953 		return prog;
954 
955 	memset(&ctx, 0, sizeof(ctx));
956 	ctx.program = prog;
957 
958 	/*
959 	 * Not able to allocate memory for descriptors[], then
960 	 * we must fall back to the interpreter
961 	 */
962 	ctx.descriptors = kcalloc(prog->len + 1, sizeof(*ctx.descriptors),
963 				  GFP_KERNEL);
964 	if (ctx.descriptors == NULL)
965 		goto out_err;
966 
967 	/* First pass discovers used resources */
968 	if (build_body(&ctx) < 0)
969 		goto out_err;
970 	/*
971 	 * Second pass computes instruction offsets.
972 	 * If any PC-relative branches are out of range, a sequence of
973 	 * a PC-relative branch + a jump is generated, and we have to
974 	 * try again from the beginning to generate the new offsets.
975 	 * This is done until no additional conversions are necessary.
976 	 * The last two iterations are done with all branches being
977 	 * converted, to guarantee offset table convergence within a
978 	 * fixed number of iterations.
979 	 */
980 	ctx.jit_index = 0;
981 	build_prologue(&ctx);
982 	tmp_idx = ctx.jit_index;
983 
984 	tries = JIT_MAX_ITERATIONS;
985 	do {
986 		ctx.jit_index = tmp_idx;
987 		ctx.changes = 0;
988 		if (tries == 2)
989 			set_convert_flag(&ctx, true);
990 		if (build_body(&ctx) < 0)
991 			goto out_err;
992 	} while (ctx.changes > 0 && --tries > 0);
993 
994 	if (WARN_ONCE(ctx.changes > 0, "JIT offsets failed to converge"))
995 		goto out_err;
996 
997 	build_epilogue(&ctx, MIPS_R_RA);
998 
999 	/* Now we know the size of the structure to make */
1000 	image_size = sizeof(u32) * ctx.jit_index;
1001 	header = bpf_jit_binary_alloc(image_size, &image_ptr,
1002 				      sizeof(u32), jit_fill_hole);
1003 	/*
1004 	 * Not able to allocate memory for the structure then
1005 	 * we must fall back to the interpretation
1006 	 */
1007 	if (header == NULL)
1008 		goto out_err;
1009 
1010 	/* Actual pass to generate final JIT code */
1011 	ctx.target = (u32 *)image_ptr;
1012 	ctx.jit_index = 0;
1013 
1014 	/*
1015 	 * If building the JITed code fails somehow,
1016 	 * we fall back to the interpretation.
1017 	 */
1018 	build_prologue(&ctx);
1019 	if (build_body(&ctx) < 0)
1020 		goto out_err;
1021 	build_epilogue(&ctx, MIPS_R_RA);
1022 
1023 	/* Populate line info meta data */
1024 	set_convert_flag(&ctx, false);
1025 	bpf_prog_fill_jited_linfo(prog, &ctx.descriptors[1]);
1026 
1027 	/* Set as read-only exec and flush instruction cache */
1028 	if (bpf_jit_binary_lock_ro(header))
1029 		goto out_err;
1030 	flush_icache_range((unsigned long)header,
1031 			   (unsigned long)&ctx.target[ctx.jit_index]);
1032 
1033 	if (bpf_jit_enable > 1)
1034 		bpf_jit_dump(prog->len, image_size, 2, ctx.target);
1035 
1036 	prog->bpf_func = (void *)ctx.target;
1037 	prog->jited = 1;
1038 	prog->jited_len = image_size;
1039 
1040 out:
1041 	kfree(ctx.descriptors);
1042 	return prog;
1043 
1044 out_err:
1045 	if (header)
1046 		bpf_jit_binary_free(header);
1047 	goto out;
1048 }
1049