frontend: Remove duplicated code
[pcsx_rearmed.git] / deps / lightrec / lightrec.c
CommitLineData
98fa08a5 1// SPDX-License-Identifier: LGPL-2.1-or-later
d16005f8 2/*
98fa08a5 3 * Copyright (C) 2014-2021 Paul Cercueil <paul@crapouillou.net>
d16005f8
PC
4 */
5
6#include "blockcache.h"
d16005f8
PC
7#include "debug.h"
8#include "disassembler.h"
9#include "emitter.h"
10#include "interpreter.h"
98fa08a5
PC
11#include "lightrec-config.h"
12#include "lightning-wrapper.h"
d16005f8
PC
13#include "lightrec.h"
14#include "memmanager.h"
a59e5536 15#include "reaper.h"
d16005f8
PC
16#include "recompiler.h"
17#include "regcache.h"
18#include "optimizer.h"
02487de7 19#include "tlsf/tlsf.h"
d16005f8
PC
20
21#include <errno.h>
98fa08a5 22#include <inttypes.h>
d16005f8
PC
23#include <limits.h>
24#if ENABLE_THREADED_COMPILER
25#include <stdatomic.h>
26#endif
27#include <stdbool.h>
28#include <stddef.h>
29#include <string.h>
d16005f8
PC
30
31#define GENMASK(h, l) \
32 (((uintptr_t)-1 << (l)) & ((uintptr_t)-1 >> (__WORDSIZE - 1 - (h))))
33
34static struct block * lightrec_precompile_block(struct lightrec_state *state,
35 u32 pc);
98fa08a5
PC
36static bool lightrec_block_is_fully_tagged(const struct block *block);
37
38static void lightrec_mtc2(struct lightrec_state *state, u8 reg, u32 data);
39static u32 lightrec_mfc2(struct lightrec_state *state, u8 reg);
d16005f8 40
a59e5536 41static void lightrec_default_sb(struct lightrec_state *state, u32 opcode,
42 void *host, u32 addr, u8 data)
43{
44 *(u8 *)host = data;
45
46 if (!state->invalidate_from_dma_only)
47 lightrec_invalidate(state, addr, 1);
48}
49
50static void lightrec_default_sh(struct lightrec_state *state, u32 opcode,
51 void *host, u32 addr, u16 data)
52{
53 *(u16 *)host = HTOLE16(data);
54
55 if (!state->invalidate_from_dma_only)
56 lightrec_invalidate(state, addr, 2);
57}
58
59static void lightrec_default_sw(struct lightrec_state *state, u32 opcode,
60 void *host, u32 addr, u32 data)
61{
62 *(u32 *)host = HTOLE32(data);
63
64 if (!state->invalidate_from_dma_only)
65 lightrec_invalidate(state, addr, 4);
66}
67
68static u8 lightrec_default_lb(struct lightrec_state *state,
69 u32 opcode, void *host, u32 addr)
70{
71 return *(u8 *)host;
72}
73
74static u16 lightrec_default_lh(struct lightrec_state *state,
75 u32 opcode, void *host, u32 addr)
76{
77 return LE16TOH(*(u16 *)host);
78}
79
80static u32 lightrec_default_lw(struct lightrec_state *state,
81 u32 opcode, void *host, u32 addr)
82{
83 return LE32TOH(*(u32 *)host);
84}
85
86static const struct lightrec_mem_map_ops lightrec_default_ops = {
87 .sb = lightrec_default_sb,
88 .sh = lightrec_default_sh,
89 .sw = lightrec_default_sw,
90 .lb = lightrec_default_lb,
91 .lh = lightrec_default_lh,
92 .lw = lightrec_default_lw,
93};
94
98fa08a5
PC
95static void __segfault_cb(struct lightrec_state *state, u32 addr,
96 const struct block *block)
d16005f8
PC
97{
98 lightrec_set_exit_flags(state, LIGHTREC_EXIT_SEGFAULT);
99 pr_err("Segmentation fault in recompiled code: invalid "
100 "load/store at address 0x%08x\n", addr);
98fa08a5
PC
101 if (block)
102 pr_err("Was executing block PC 0x%08x\n", block->pc);
d16005f8
PC
103}
104
a59e5536 105static void lightrec_swl(struct lightrec_state *state,
106 const struct lightrec_mem_map_ops *ops,
107 u32 opcode, void *host, u32 addr, u32 data)
d16005f8 108{
a59e5536 109 unsigned int shift = addr & 0x3;
110 unsigned int mask = GENMASK(31, (shift + 1) * 8);
111 u32 old_data;
112
113 /* Align to 32 bits */
114 addr &= ~3;
115 host = (void *)((uintptr_t)host & ~3);
116
117 old_data = ops->lw(state, opcode, host, addr);
118
119 data = (data >> ((3 - shift) * 8)) | (old_data & mask);
120
121 ops->sw(state, opcode, host, addr, data);
122}
123
124static void lightrec_swr(struct lightrec_state *state,
125 const struct lightrec_mem_map_ops *ops,
126 u32 opcode, void *host, u32 addr, u32 data)
127{
128 unsigned int shift = addr & 0x3;
129 unsigned int mask = (1 << (shift * 8)) - 1;
130 u32 old_data;
131
132 /* Align to 32 bits */
133 addr &= ~3;
134 host = (void *)((uintptr_t)host & ~3);
135
136 old_data = ops->lw(state, opcode, host, addr);
137
138 data = (data << (shift * 8)) | (old_data & mask);
139
140 ops->sw(state, opcode, host, addr, data);
141}
142
143static void lightrec_swc2(struct lightrec_state *state, union code op,
144 const struct lightrec_mem_map_ops *ops,
145 void *host, u32 addr)
146{
98fa08a5 147 u32 data = lightrec_mfc2(state, op.i.rt);
a59e5536 148
149 ops->sw(state, op.opcode, host, addr, data);
150}
151
152static u32 lightrec_lwl(struct lightrec_state *state,
153 const struct lightrec_mem_map_ops *ops,
154 u32 opcode, void *host, u32 addr, u32 data)
155{
156 unsigned int shift = addr & 0x3;
157 unsigned int mask = (1 << (24 - shift * 8)) - 1;
158 u32 old_data;
159
160 /* Align to 32 bits */
161 addr &= ~3;
162 host = (void *)((uintptr_t)host & ~3);
163
164 old_data = ops->lw(state, opcode, host, addr);
165
166 return (data & mask) | (old_data << (24 - shift * 8));
167}
168
169static u32 lightrec_lwr(struct lightrec_state *state,
170 const struct lightrec_mem_map_ops *ops,
171 u32 opcode, void *host, u32 addr, u32 data)
172{
173 unsigned int shift = addr & 0x3;
174 unsigned int mask = GENMASK(31, 32 - shift * 8);
175 u32 old_data;
176
177 /* Align to 32 bits */
178 addr &= ~3;
179 host = (void *)((uintptr_t)host & ~3);
180
181 old_data = ops->lw(state, opcode, host, addr);
182
183 return (data & mask) | (old_data >> (shift * 8));
184}
185
186static void lightrec_lwc2(struct lightrec_state *state, union code op,
187 const struct lightrec_mem_map_ops *ops,
188 void *host, u32 addr)
189{
190 u32 data = ops->lw(state, op.opcode, host, addr);
191
98fa08a5 192 lightrec_mtc2(state, op.i.rt, data);
d16005f8
PC
193}
194
195static void lightrec_invalidate_map(struct lightrec_state *state,
98fa08a5 196 const struct lightrec_mem_map *map, u32 addr, u32 len)
d16005f8 197{
98fa08a5 198 if (map == &state->maps[PSX_MAP_KERNEL_USER_RAM]) {
02487de7
PC
199 memset(lut_address(state, lut_offset(addr)), 0,
200 ((len + 3) / 4) * lut_elm_size(state));
98fa08a5 201 }
d16005f8
PC
202}
203
02487de7
PC
204enum psx_map
205lightrec_get_map_idx(struct lightrec_state *state, u32 kaddr)
d16005f8 206{
98fa08a5 207 const struct lightrec_mem_map *map;
d16005f8
PC
208 unsigned int i;
209
210 for (i = 0; i < state->nb_maps; i++) {
02487de7 211 map = &state->maps[i];
d16005f8 212
02487de7
PC
213 if (kaddr >= map->pc && kaddr < map->pc + map->length)
214 return (enum psx_map) i;
d16005f8
PC
215 }
216
02487de7
PC
217 return PSX_MAP_UNKNOWN;
218}
219
220const struct lightrec_mem_map *
221lightrec_get_map(struct lightrec_state *state, void **host, u32 kaddr)
222{
223 const struct lightrec_mem_map *map;
224 enum psx_map idx;
225 u32 addr;
226
227 idx = lightrec_get_map_idx(state, kaddr);
228 if (idx == PSX_MAP_UNKNOWN)
98fa08a5
PC
229 return NULL;
230
02487de7 231 map = &state->maps[idx];
98fa08a5
PC
232 addr = kaddr - map->pc;
233
234 while (map->mirror_of)
235 map = map->mirror_of;
236
237 if (host)
238 *host = map->address + addr;
239
240 return map;
d16005f8
PC
241}
242
243u32 lightrec_rw(struct lightrec_state *state, union code op,
98fa08a5 244 u32 addr, u32 data, u16 *flags, struct block *block)
d16005f8
PC
245{
246 const struct lightrec_mem_map *map;
a59e5536 247 const struct lightrec_mem_map_ops *ops;
98fa08a5 248 u32 opcode = op.opcode;
a59e5536 249 void *host;
d16005f8
PC
250
251 addr += (s16) op.i.imm;
d16005f8 252
98fa08a5 253 map = lightrec_get_map(state, &host, kunseg(addr));
d16005f8 254 if (!map) {
98fa08a5 255 __segfault_cb(state, addr, block);
d16005f8
PC
256 return 0;
257 }
258
d16005f8 259 if (unlikely(map->ops)) {
22eee2ac
PC
260 if (flags && !LIGHTREC_FLAGS_GET_IO_MODE(*flags))
261 *flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_HW);
d16005f8 262
a59e5536 263 ops = map->ops;
264 } else {
22eee2ac
PC
265 if (flags && !LIGHTREC_FLAGS_GET_IO_MODE(*flags))
266 *flags |= LIGHTREC_IO_MODE(LIGHTREC_IO_DIRECT);
d16005f8 267
a59e5536 268 ops = &lightrec_default_ops;
269 }
d16005f8
PC
270
271 switch (op.i.op) {
272 case OP_SB:
a59e5536 273 ops->sb(state, opcode, host, addr, (u8) data);
d16005f8
PC
274 return 0;
275 case OP_SH:
a59e5536 276 ops->sh(state, opcode, host, addr, (u16) data);
d16005f8
PC
277 return 0;
278 case OP_SWL:
a59e5536 279 lightrec_swl(state, ops, opcode, host, addr, data);
d16005f8
PC
280 return 0;
281 case OP_SWR:
a59e5536 282 lightrec_swr(state, ops, opcode, host, addr, data);
d16005f8
PC
283 return 0;
284 case OP_SW:
a59e5536 285 ops->sw(state, opcode, host, addr, data);
d16005f8
PC
286 return 0;
287 case OP_SWC2:
a59e5536 288 lightrec_swc2(state, op, ops, host, addr);
d16005f8
PC
289 return 0;
290 case OP_LB:
a59e5536 291 return (s32) (s8) ops->lb(state, opcode, host, addr);
d16005f8 292 case OP_LBU:
a59e5536 293 return ops->lb(state, opcode, host, addr);
d16005f8 294 case OP_LH:
a59e5536 295 return (s32) (s16) ops->lh(state, opcode, host, addr);
d16005f8 296 case OP_LHU:
a59e5536 297 return ops->lh(state, opcode, host, addr);
d16005f8 298 case OP_LWC2:
a59e5536 299 lightrec_lwc2(state, op, ops, host, addr);
d16005f8 300 return 0;
a59e5536 301 case OP_LWL:
302 return lightrec_lwl(state, ops, opcode, host, addr, data);
303 case OP_LWR:
304 return lightrec_lwr(state, ops, opcode, host, addr, data);
d16005f8
PC
305 case OP_LW:
306 default:
a59e5536 307 return ops->lw(state, opcode, host, addr);
d16005f8
PC
308 }
309}
310
311static void lightrec_rw_helper(struct lightrec_state *state,
98fa08a5
PC
312 union code op, u16 *flags,
313 struct block *block)
d16005f8 314{
98fa08a5
PC
315 u32 ret = lightrec_rw(state, op, state->regs.gpr[op.i.rs],
316 state->regs.gpr[op.i.rt], flags, block);
d16005f8
PC
317
318 switch (op.i.op) {
319 case OP_LB:
320 case OP_LBU:
321 case OP_LH:
322 case OP_LHU:
323 case OP_LWL:
324 case OP_LWR:
325 case OP_LW:
326 if (op.i.rt)
98fa08a5 327 state->regs.gpr[op.i.rt] = ret;
d8b04acd
PC
328 fallthrough;
329 default:
d16005f8
PC
330 break;
331 }
332}
333
22eee2ac 334static void lightrec_rw_cb(struct lightrec_state *state)
d16005f8 335{
22eee2ac 336 lightrec_rw_helper(state, (union code)state->c_wrapper_arg, NULL, NULL);
d16005f8
PC
337}
338
22eee2ac 339static void lightrec_rw_generic_cb(struct lightrec_state *state)
d16005f8 340{
98fa08a5
PC
341 struct block *block;
342 struct opcode *op;
343 bool was_tagged;
22eee2ac 344 u32 arg = state->c_wrapper_arg;
98fa08a5
PC
345 u16 offset = (u16)arg;
346
347 block = lightrec_find_block_from_lut(state->block_cache,
348 arg >> 16, state->next_pc);
349 if (unlikely(!block)) {
350 pr_err("rw_generic: No block found in LUT for PC 0x%x offset 0x%x\n",
351 state->next_pc, offset);
352 return;
353 }
354
355 op = &block->opcode_list[offset];
22eee2ac 356 was_tagged = LIGHTREC_FLAGS_GET_IO_MODE(op->flags);
d16005f8 357
98fa08a5 358 lightrec_rw_helper(state, op->c, &op->flags, block);
d16005f8
PC
359
360 if (!was_tagged) {
98fa08a5
PC
361 pr_debug("Opcode of block at PC 0x%08x has been tagged - flag "
362 "for recompilation\n", block->pc);
d16005f8 363
a59e5536 364 block->flags |= BLOCK_SHOULD_RECOMPILE;
d16005f8
PC
365 }
366}
367
98fa08a5 368static u32 clamp_s32(s32 val, s32 min, s32 max)
d16005f8 369{
98fa08a5
PC
370 return val < min ? min : val > max ? max : val;
371}
d16005f8 372
98fa08a5
PC
373static u32 lightrec_mfc2(struct lightrec_state *state, u8 reg)
374{
375 s16 gteir1, gteir2, gteir3;
376
377 switch (reg) {
378 case 1:
379 case 3:
380 case 5:
381 case 8:
382 case 9:
383 case 10:
384 case 11:
385 return (s32)(s16) state->regs.cp2d[reg];
386 case 7:
387 case 16:
388 case 17:
389 case 18:
390 case 19:
391 return (u16) state->regs.cp2d[reg];
392 case 28:
393 case 29:
394 gteir1 = (s16) state->regs.cp2d[9];
395 gteir2 = (s16) state->regs.cp2d[10];
396 gteir3 = (s16) state->regs.cp2d[11];
397
398 return clamp_s32(gteir1 >> 7, 0, 0x1f) << 0 |
399 clamp_s32(gteir2 >> 7, 0, 0x1f) << 5 |
400 clamp_s32(gteir3 >> 7, 0, 0x1f) << 10;
401 case 15:
402 reg = 14;
d8b04acd
PC
403 fallthrough;
404 default:
98fa08a5
PC
405 return state->regs.cp2d[reg];
406 }
407}
d16005f8 408
98fa08a5
PC
409u32 lightrec_mfc(struct lightrec_state *state, union code op)
410{
411 if (op.i.op == OP_CP0)
412 return state->regs.cp0[op.r.rd];
413 else if (op.r.rs == OP_CP2_BASIC_MFC2)
414 return lightrec_mfc2(state, op.r.rd);
d16005f8 415 else
98fa08a5 416 return state->regs.cp2c[op.r.rd];
d16005f8
PC
417}
418
98fa08a5 419static void lightrec_mtc0(struct lightrec_state *state, u8 reg, u32 data)
d16005f8 420{
fd58fa32 421 u32 status, oldstatus, cause;
98fa08a5
PC
422
423 switch (reg) {
424 case 1:
425 case 4:
426 case 8:
427 case 14:
428 case 15:
429 /* Those registers are read-only */
430 return;
fd58fa32 431 default:
98fa08a5
PC
432 break;
433 }
d16005f8 434
98fa08a5
PC
435 if (reg == 12) {
436 status = state->regs.cp0[12];
fd58fa32 437 oldstatus = status;
d16005f8 438
98fa08a5
PC
439 if (status & ~data & BIT(16)) {
440 state->ops.enable_ram(state, true);
441 lightrec_invalidate_all(state);
442 } else if (~status & data & BIT(16)) {
443 state->ops.enable_ram(state, false);
444 }
445 }
446
fd58fa32
PC
447 if (reg == 13) {
448 state->regs.cp0[13] &= ~0x300;
449 state->regs.cp0[13] |= data & 0x300;
450 } else {
451 state->regs.cp0[reg] = data;
452 }
98fa08a5
PC
453
454 if (reg == 12 || reg == 13) {
455 cause = state->regs.cp0[13];
456 status = state->regs.cp0[12];
457
fd58fa32 458 /* Handle software interrupts */
98fa08a5
PC
459 if (!!(status & cause & 0x300) & status)
460 lightrec_set_exit_flags(state, LIGHTREC_EXIT_CHECK_INTERRUPT);
fd58fa32
PC
461
462 /* Handle hardware interrupts */
463 if (reg == 12 && !(~status & 0x401) && (~oldstatus & 0x401))
464 lightrec_set_exit_flags(state, LIGHTREC_EXIT_CHECK_INTERRUPT);
98fa08a5
PC
465 }
466}
467
468static u32 count_leading_bits(s32 data)
469{
98fa08a5
PC
470 u32 cnt = 33;
471
de742fa0
PC
472#ifdef __has_builtin
473#if __has_builtin(__builtin_clrsb)
474 return 1 + __builtin_clrsb(data);
475#endif
476#endif
477
98fa08a5
PC
478 data = (data ^ (data >> 31)) << 1;
479
480 do {
481 cnt -= 1;
482 data >>= 1;
483 } while (data);
484
485 return cnt;
98fa08a5
PC
486}
487
488static void lightrec_mtc2(struct lightrec_state *state, u8 reg, u32 data)
489{
490 switch (reg) {
491 case 15:
492 state->regs.cp2d[12] = state->regs.cp2d[13];
493 state->regs.cp2d[13] = state->regs.cp2d[14];
494 state->regs.cp2d[14] = data;
495 break;
496 case 28:
497 state->regs.cp2d[9] = (data << 7) & 0xf80;
498 state->regs.cp2d[10] = (data << 2) & 0xf80;
499 state->regs.cp2d[11] = (data >> 3) & 0xf80;
500 break;
501 case 31:
502 return;
503 case 30:
504 state->regs.cp2d[31] = count_leading_bits((s32) data);
d8b04acd
PC
505 fallthrough;
506 default:
98fa08a5
PC
507 state->regs.cp2d[reg] = data;
508 break;
509 }
510}
d16005f8 511
98fa08a5
PC
512static void lightrec_ctc2(struct lightrec_state *state, u8 reg, u32 data)
513{
514 switch (reg) {
515 case 4:
516 case 12:
517 case 20:
518 case 26:
519 case 27:
520 case 29:
521 case 30:
522 data = (s32)(s16) data;
523 break;
524 case 31:
525 data = (data & 0x7ffff000) | !!(data & 0x7f87e000) << 31;
d8b04acd
PC
526 fallthrough;
527 default:
98fa08a5
PC
528 break;
529 }
530
531 state->regs.cp2c[reg] = data;
532}
533
534void lightrec_mtc(struct lightrec_state *state, union code op, u32 data)
535{
536 if (op.i.op == OP_CP0)
537 lightrec_mtc0(state, op.r.rd, data);
538 else if (op.r.rs == OP_CP2_BASIC_CTC2)
539 lightrec_ctc2(state, op.r.rd, data);
540 else
541 lightrec_mtc2(state, op.r.rd, data);
d16005f8
PC
542}
543
22eee2ac 544static void lightrec_mtc_cb(struct lightrec_state *state)
d16005f8 545{
22eee2ac
PC
546 union code op = (union code) state->c_wrapper_arg;
547
98fa08a5 548 lightrec_mtc(state, op, state->regs.gpr[op.r.rt]);
d16005f8
PC
549}
550
98fa08a5 551void lightrec_rfe(struct lightrec_state *state)
d16005f8
PC
552{
553 u32 status;
554
555 /* Read CP0 Status register (r12) */
98fa08a5 556 status = state->regs.cp0[12];
d16005f8
PC
557
558 /* Switch the bits */
559 status = ((status & 0x3c) >> 2) | (status & ~0xf);
560
561 /* Write it back */
98fa08a5 562 lightrec_mtc0(state, 12, status);
d16005f8
PC
563}
564
98fa08a5 565void lightrec_cp(struct lightrec_state *state, union code op)
d16005f8 566{
98fa08a5
PC
567 if (op.i.op == OP_CP0) {
568 pr_err("Invalid CP opcode to coprocessor #0\n");
569 return;
570 }
d16005f8 571
98fa08a5 572 (*state->ops.cop2_op)(state, op.opcode);
d16005f8
PC
573}
574
22eee2ac
PC
575static void lightrec_cp_cb(struct lightrec_state *state)
576{
577 lightrec_cp(state, (union code) state->c_wrapper_arg);
578}
579
580static void lightrec_syscall_cb(struct lightrec_state *state)
d16005f8
PC
581{
582 lightrec_set_exit_flags(state, LIGHTREC_EXIT_SYSCALL);
583}
584
22eee2ac 585static void lightrec_break_cb(struct lightrec_state *state)
d16005f8
PC
586{
587 lightrec_set_exit_flags(state, LIGHTREC_EXIT_BREAK);
588}
589
590struct block * lightrec_get_block(struct lightrec_state *state, u32 pc)
591{
592 struct block *block = lightrec_find_block(state->block_cache, pc);
593
98fa08a5 594 if (block && lightrec_block_is_outdated(state, block)) {
d16005f8
PC
595 pr_debug("Block at PC 0x%08x is outdated!\n", block->pc);
596
597 /* Make sure the recompiler isn't processing the block we'll
598 * destroy */
599 if (ENABLE_THREADED_COMPILER)
600 lightrec_recompiler_remove(state->rec, block);
601
602 lightrec_unregister_block(state->block_cache, block);
a59e5536 603 remove_from_code_lut(state->block_cache, block);
98fa08a5 604 lightrec_free_block(state, block);
d16005f8
PC
605 block = NULL;
606 }
607
608 if (!block) {
609 block = lightrec_precompile_block(state, pc);
610 if (!block) {
611 pr_err("Unable to recompile block at PC 0x%x\n", pc);
612 lightrec_set_exit_flags(state, LIGHTREC_EXIT_SEGFAULT);
613 return NULL;
614 }
615
616 lightrec_register_block(state->block_cache, block);
617 }
618
619 return block;
620}
621
622static void * get_next_block_func(struct lightrec_state *state, u32 pc)
623{
624 struct block *block;
625 bool should_recompile;
626 void *func;
d8b04acd 627 int err;
d16005f8
PC
628
629 for (;;) {
d8b04acd 630 func = lut_read(state, lut_offset(pc));
d16005f8 631 if (func && func != state->get_next_block)
98fa08a5 632 break;
d16005f8
PC
633
634 block = lightrec_get_block(state, pc);
635
636 if (unlikely(!block))
98fa08a5
PC
637 break;
638
639 if (OPT_REPLACE_MEMSET && (block->flags & BLOCK_IS_MEMSET)) {
640 func = state->memset_func;
641 break;
642 }
d16005f8 643
a59e5536 644 should_recompile = block->flags & BLOCK_SHOULD_RECOMPILE &&
645 !(block->flags & BLOCK_IS_DEAD);
d16005f8
PC
646
647 if (unlikely(should_recompile)) {
a59e5536 648 pr_debug("Block at PC 0x%08x should recompile\n", pc);
d16005f8 649
d16005f8 650 lightrec_unregister(MEM_FOR_CODE, block->code_size);
a59e5536 651
d8b04acd 652 if (ENABLE_THREADED_COMPILER) {
a59e5536 653 lightrec_recompiler_add(state->rec, block);
d8b04acd
PC
654 } else {
655 err = lightrec_compile_block(state->cstate, block);
656 if (err) {
657 state->exit_flags = LIGHTREC_EXIT_NOMEM;
658 return NULL;
659 }
660 }
d16005f8
PC
661 }
662
663 if (ENABLE_THREADED_COMPILER && likely(!should_recompile))
98fa08a5 664 func = lightrec_recompiler_run_first_pass(state, block, &pc);
d16005f8
PC
665 else
666 func = block->function;
667
668 if (likely(func))
98fa08a5 669 break;
d16005f8 670
98fa08a5
PC
671 if (unlikely(block->flags & BLOCK_NEVER_COMPILE)) {
672 pc = lightrec_emulate_block(state, block, pc);
673
674 } else if (!ENABLE_THREADED_COMPILER) {
675 /* Block wasn't compiled yet - run the interpreter */
676 if (block->flags & BLOCK_FULLY_TAGGED)
677 pr_debug("Block fully tagged, skipping first pass\n");
678 else if (ENABLE_FIRST_PASS && likely(!should_recompile))
679 pc = lightrec_emulate_block(state, block, pc);
d16005f8 680
d16005f8 681 /* Then compile it using the profiled data */
d8b04acd
PC
682 err = lightrec_compile_block(state->cstate, block);
683 if (err) {
684 state->exit_flags = LIGHTREC_EXIT_NOMEM;
685 return NULL;
686 }
98fa08a5
PC
687 } else {
688 lightrec_recompiler_add(state->rec, block);
d16005f8
PC
689 }
690
691 if (state->exit_flags != LIGHTREC_EXIT_NORMAL ||
98fa08a5
PC
692 state->current_cycle >= state->target_cycle)
693 break;
d16005f8 694 }
d16005f8 695
98fa08a5
PC
696 state->next_pc = pc;
697 return func;
d16005f8
PC
698}
699
700static s32 c_function_wrapper(struct lightrec_state *state, s32 cycles_delta,
22eee2ac 701 void (*f)(struct lightrec_state *))
d16005f8
PC
702{
703 state->current_cycle = state->target_cycle - cycles_delta;
704
22eee2ac 705 (*f)(state);
d16005f8
PC
706
707 return state->target_cycle - state->current_cycle;
708}
709
d8b04acd
PC
710static void * lightrec_alloc_code(struct lightrec_state *state, size_t size)
711{
712 void *code;
713
714 if (ENABLE_THREADED_COMPILER)
715 lightrec_code_alloc_lock(state);
716
717 code = tlsf_malloc(state->tlsf, size);
718
719 if (ENABLE_THREADED_COMPILER)
720 lightrec_code_alloc_unlock(state);
721
722 return code;
723}
724
725static void lightrec_realloc_code(struct lightrec_state *state,
726 void *ptr, size_t size)
727{
728 /* NOTE: 'size' MUST be smaller than the size specified during
729 * the allocation. */
730
731 if (ENABLE_THREADED_COMPILER)
732 lightrec_code_alloc_lock(state);
733
734 tlsf_realloc(state->tlsf, ptr, size);
735
736 if (ENABLE_THREADED_COMPILER)
737 lightrec_code_alloc_unlock(state);
738}
739
740static void lightrec_free_code(struct lightrec_state *state, void *ptr)
741{
742 if (ENABLE_THREADED_COMPILER)
743 lightrec_code_alloc_lock(state);
744
745 tlsf_free(state->tlsf, ptr);
746
747 if (ENABLE_THREADED_COMPILER)
748 lightrec_code_alloc_unlock(state);
749}
750
02487de7 751static void * lightrec_emit_code(struct lightrec_state *state,
d8b04acd 752 const struct block *block,
02487de7
PC
753 jit_state_t *_jit, unsigned int *size)
754{
755 bool has_code_buffer = ENABLE_CODE_BUFFER && state->tlsf;
756 jit_word_t code_size, new_code_size;
757 void *code;
758
759 jit_realize();
760
761 if (!ENABLE_DISASSEMBLER)
762 jit_set_data(NULL, 0, JIT_DISABLE_DATA | JIT_DISABLE_NOTE);
763
764 if (has_code_buffer) {
765 jit_get_code(&code_size);
d8b04acd
PC
766 code = lightrec_alloc_code(state, (size_t) code_size);
767
768 if (!code) {
769 if (ENABLE_THREADED_COMPILER) {
770 /* If we're using the threaded compiler, return
771 * an allocation error here. The threaded
772 * compiler will then empty its job queue and
773 * request a code flush using the reaper. */
774 return NULL;
775 }
776
777 /* Remove outdated blocks, and try again */
778 lightrec_remove_outdated_blocks(state->block_cache, block);
779
780 pr_debug("Re-try to alloc %zu bytes...\n", code_size);
781
782 code = lightrec_alloc_code(state, code_size);
783 if (!code) {
784 pr_err("Could not alloc even after removing old blocks!\n");
785 return NULL;
786 }
787 }
02487de7
PC
788
789 jit_set_code(code, code_size);
790 }
791
792 code = jit_emit();
793
794 jit_get_code(&new_code_size);
795 lightrec_register(MEM_FOR_CODE, new_code_size);
796
797 if (has_code_buffer) {
d8b04acd 798 lightrec_realloc_code(state, code, (size_t) new_code_size);
02487de7
PC
799
800 pr_debug("Creating code block at address 0x%" PRIxPTR ", "
801 "code size: %" PRIuPTR " new: %" PRIuPTR "\n",
802 (uintptr_t) code, code_size, new_code_size);
803 }
804
805 *size = (unsigned int) new_code_size;
806
807 return code;
808}
809
98fa08a5 810static struct block * generate_wrapper(struct lightrec_state *state)
d16005f8
PC
811{
812 struct block *block;
813 jit_state_t *_jit;
814 unsigned int i;
815 int stack_ptr;
d16005f8 816 jit_node_t *to_tramp, *to_fn_epilog;
fd58fa32 817 jit_node_t *addr[C_WRAPPERS_COUNT - 1];
d16005f8
PC
818
819 block = lightrec_malloc(state, MEM_FOR_IR, sizeof(*block));
820 if (!block)
821 goto err_no_mem;
822
823 _jit = jit_new_state();
824 if (!_jit)
825 goto err_free_block;
826
827 jit_name("RW wrapper");
828 jit_note(__FILE__, __LINE__);
829
830 /* Wrapper entry point */
831 jit_prolog();
fd58fa32
PC
832 jit_tramp(256);
833
834 /* Add entry points; separate them by opcodes that increment
835 * LIGHTREC_REG_STATE (since we cannot touch other registers).
836 * The difference will then tell us which C function to call. */
837 for (i = C_WRAPPERS_COUNT - 1; i > 0; i--) {
838 jit_addi(LIGHTREC_REG_STATE, LIGHTREC_REG_STATE, __WORDSIZE / 8);
839 addr[i - 1] = jit_indirect();
840 }
841
842 jit_epilog();
843 jit_prolog();
d16005f8
PC
844
845 stack_ptr = jit_allocai(sizeof(uintptr_t) * NUM_TEMPS);
846
fd58fa32 847 /* Save all temporaries on stack */
d16005f8
PC
848 for (i = 0; i < NUM_TEMPS; i++)
849 jit_stxi(stack_ptr + i * sizeof(uintptr_t), JIT_FP, JIT_R(i));
850
851 /* Jump to the trampoline */
852 to_tramp = jit_jmpi();
853
854 /* The trampoline will jump back here */
855 to_fn_epilog = jit_label();
856
fd58fa32 857 /* Restore temporaries from stack */
d16005f8
PC
858 for (i = 0; i < NUM_TEMPS; i++)
859 jit_ldxi(JIT_R(i), JIT_FP, stack_ptr + i * sizeof(uintptr_t));
860
861 jit_ret();
862 jit_epilog();
863
864 /* Trampoline entry point.
865 * The sole purpose of the trampoline is to cheese Lightning not to
866 * save/restore the callee-saved register LIGHTREC_REG_CYCLE, since we
867 * do want to return to the caller with this register modified. */
868 jit_prolog();
869 jit_tramp(256);
870 jit_patch(to_tramp);
871
fd58fa32
PC
872 /* Retrieve the wrapper function */
873 jit_ldxi(JIT_R0, LIGHTREC_REG_STATE,
874 offsetof(struct lightrec_state, c_wrappers));
875
876 /* Restore LIGHTREC_REG_STATE to its correct value */
877 jit_movi(LIGHTREC_REG_STATE, (uintptr_t) state);
878
d16005f8
PC
879 jit_prepare();
880 jit_pushargr(LIGHTREC_REG_STATE);
881 jit_pushargr(LIGHTREC_REG_CYCLE);
d16005f8 882 jit_pushargr(JIT_R0);
98fa08a5 883 jit_finishi(c_function_wrapper);
d16005f8 884 jit_retval_i(LIGHTREC_REG_CYCLE);
d16005f8
PC
885
886 jit_patch_at(jit_jmpi(), to_fn_epilog);
887 jit_epilog();
888
d16005f8 889 block->_jit = _jit;
d16005f8
PC
890 block->opcode_list = NULL;
891 block->flags = 0;
892 block->nb_ops = 0;
893
d8b04acd 894 block->function = lightrec_emit_code(state, block, _jit,
02487de7
PC
895 &block->code_size);
896 if (!block->function)
897 goto err_free_block;
898
fd58fa32
PC
899 state->wrappers_eps[C_WRAPPERS_COUNT - 1] = block->function;
900
901 for (i = 0; i < C_WRAPPERS_COUNT - 1; i++)
902 state->wrappers_eps[i] = jit_address(addr[i]);
903
d16005f8
PC
904 if (ENABLE_DISASSEMBLER) {
905 pr_debug("Wrapper block:\n");
906 jit_disassemble();
907 }
908
909 jit_clear_state();
910 return block;
911
912err_free_block:
913 lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
914err_no_mem:
915 pr_err("Unable to compile wrapper: Out of memory\n");
916 return NULL;
917}
918
98fa08a5
PC
919static u32 lightrec_memset(struct lightrec_state *state)
920{
921 u32 kunseg_pc = kunseg(state->regs.gpr[4]);
922 void *host;
923 const struct lightrec_mem_map *map = lightrec_get_map(state, &host, kunseg_pc);
924 u32 length = state->regs.gpr[5] * 4;
925
926 if (!map) {
927 pr_err("Unable to find memory map for memset target address "
928 "0x%x\n", kunseg_pc);
929 return 0;
930 }
931
932 pr_debug("Calling host memset, PC 0x%x (host address 0x%" PRIxPTR ") for %u bytes\n",
933 kunseg_pc, (uintptr_t)host, length);
934 memset(host, 0, length);
935
936 if (!state->invalidate_from_dma_only)
937 lightrec_invalidate_map(state, map, kunseg_pc, length);
938
939 /* Rough estimation of the number of cycles consumed */
940 return 8 + 5 * (length + 3 / 4);
941}
942
d16005f8
PC
943static struct block * generate_dispatcher(struct lightrec_state *state)
944{
945 struct block *block;
946 jit_state_t *_jit;
02487de7 947 jit_node_t *to_end, *loop, *addr, *addr2, *addr3;
d16005f8 948 unsigned int i;
02487de7 949 u32 offset;
d16005f8
PC
950
951 block = lightrec_malloc(state, MEM_FOR_IR, sizeof(*block));
952 if (!block)
953 goto err_no_mem;
954
955 _jit = jit_new_state();
956 if (!_jit)
957 goto err_free_block;
958
959 jit_name("dispatcher");
960 jit_note(__FILE__, __LINE__);
961
962 jit_prolog();
963 jit_frame(256);
964
965 jit_getarg(JIT_R0, jit_arg());
d16005f8 966 jit_getarg_i(LIGHTREC_REG_CYCLE, jit_arg());
d16005f8
PC
967
968 /* Force all callee-saved registers to be pushed on the stack */
969 for (i = 0; i < NUM_REGS; i++)
970 jit_movr(JIT_V(i), JIT_V(i));
971
972 /* Pass lightrec_state structure to blocks, using the last callee-saved
973 * register that Lightning provides */
974 jit_movi(LIGHTREC_REG_STATE, (intptr_t) state);
975
976 loop = jit_label();
977
978 /* Call the block's code */
979 jit_jmpr(JIT_R0);
980
98fa08a5
PC
981 if (OPT_REPLACE_MEMSET) {
982 /* Blocks will jump here when they need to call
983 * lightrec_memset() */
984 addr3 = jit_indirect();
985
986 jit_prepare();
987 jit_pushargr(LIGHTREC_REG_STATE);
988 jit_finishi(lightrec_memset);
989
990 jit_ldxi_ui(JIT_V0, LIGHTREC_REG_STATE,
991 offsetof(struct lightrec_state, regs.gpr[31]));
992
993 jit_retval(JIT_R0);
994 jit_subr(LIGHTREC_REG_CYCLE, LIGHTREC_REG_CYCLE, JIT_R0);
995 }
996
d16005f8
PC
997 /* The block will jump here, with the number of cycles remaining in
998 * LIGHTREC_REG_CYCLE */
999 addr2 = jit_indirect();
1000
98fa08a5
PC
1001 /* Store back the next_pc to the lightrec_state structure */
1002 offset = offsetof(struct lightrec_state, next_pc);
1003 jit_stxi_i(offset, LIGHTREC_REG_STATE, JIT_V0);
1004
d16005f8
PC
1005 /* Jump to end if state->target_cycle < state->current_cycle */
1006 to_end = jit_blei(LIGHTREC_REG_CYCLE, 0);
1007
1008 /* Convert next PC to KUNSEG and avoid mirrors */
02487de7
PC
1009 jit_andi(JIT_R0, JIT_V0, 0x10000000 | (RAM_SIZE - 1));
1010 jit_rshi_u(JIT_R1, JIT_R0, 28);
1011 jit_andi(JIT_R2, JIT_V0, BIOS_SIZE - 1);
1012 jit_addi(JIT_R2, JIT_R2, RAM_SIZE);
1013 jit_movnr(JIT_R0, JIT_R2, JIT_R1);
1014
1015 /* If possible, use the code LUT */
1016 if (!lut_is_32bit(state))
98fa08a5 1017 jit_lshi(JIT_R0, JIT_R0, 1);
d16005f8 1018 jit_addr(JIT_R0, JIT_R0, LIGHTREC_REG_STATE);
02487de7
PC
1019
1020 offset = offsetof(struct lightrec_state, code_lut);
1021 if (lut_is_32bit(state))
1022 jit_ldxi_ui(JIT_R0, JIT_R0, offset);
1023 else
1024 jit_ldxi(JIT_R0, JIT_R0, offset);
d16005f8
PC
1025
1026 /* If we get non-NULL, loop */
1027 jit_patch_at(jit_bnei(JIT_R0, 0), loop);
1028
1029 /* Slow path: call C function get_next_block_func() */
d16005f8 1030
98fa08a5 1031 if (ENABLE_FIRST_PASS || OPT_DETECT_IMPOSSIBLE_BRANCHES) {
d16005f8
PC
1032 /* We may call the interpreter - update state->current_cycle */
1033 jit_ldxi_i(JIT_R2, LIGHTREC_REG_STATE,
1034 offsetof(struct lightrec_state, target_cycle));
1035 jit_subr(JIT_R1, JIT_R2, LIGHTREC_REG_CYCLE);
1036 jit_stxi_i(offsetof(struct lightrec_state, current_cycle),
1037 LIGHTREC_REG_STATE, JIT_R1);
1038 }
1039
1040 /* The code LUT will be set to this address when the block at the target
1041 * PC has been preprocessed but not yet compiled by the threaded
1042 * recompiler */
1043 addr = jit_indirect();
1044
1045 /* Get the next block */
1046 jit_prepare();
1047 jit_pushargr(LIGHTREC_REG_STATE);
1048 jit_pushargr(JIT_V0);
1049 jit_finishi(&get_next_block_func);
1050 jit_retval(JIT_R0);
1051
98fa08a5 1052 if (ENABLE_FIRST_PASS || OPT_DETECT_IMPOSSIBLE_BRANCHES) {
d16005f8
PC
1053 /* The interpreter may have updated state->current_cycle and
1054 * state->target_cycle - recalc the delta */
1055 jit_ldxi_i(JIT_R1, LIGHTREC_REG_STATE,
1056 offsetof(struct lightrec_state, current_cycle));
1057 jit_ldxi_i(JIT_R2, LIGHTREC_REG_STATE,
1058 offsetof(struct lightrec_state, target_cycle));
1059 jit_subr(LIGHTREC_REG_CYCLE, JIT_R2, JIT_R1);
1060 }
1061
1062 /* If we get non-NULL, loop */
1063 jit_patch_at(jit_bnei(JIT_R0, 0), loop);
1064
d16005f8
PC
1065 /* When exiting, the recompiled code will jump to that address */
1066 jit_note(__FILE__, __LINE__);
1067 jit_patch(to_end);
1068
d16005f8
PC
1069 jit_retr(LIGHTREC_REG_CYCLE);
1070 jit_epilog();
1071
d16005f8 1072 block->_jit = _jit;
d16005f8
PC
1073 block->opcode_list = NULL;
1074 block->flags = 0;
1075 block->nb_ops = 0;
1076
d8b04acd 1077 block->function = lightrec_emit_code(state, block, _jit,
02487de7
PC
1078 &block->code_size);
1079 if (!block->function)
1080 goto err_free_block;
d16005f8
PC
1081
1082 state->eob_wrapper_func = jit_address(addr2);
98fa08a5
PC
1083 if (OPT_REPLACE_MEMSET)
1084 state->memset_func = jit_address(addr3);
d16005f8
PC
1085 state->get_next_block = jit_address(addr);
1086
1087 if (ENABLE_DISASSEMBLER) {
1088 pr_debug("Dispatcher block:\n");
1089 jit_disassemble();
1090 }
1091
1092 /* We're done! */
1093 jit_clear_state();
1094 return block;
1095
1096err_free_block:
1097 lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
1098err_no_mem:
1099 pr_err("Unable to compile dispatcher: Out of memory\n");
1100 return NULL;
1101}
1102
1103union code lightrec_read_opcode(struct lightrec_state *state, u32 pc)
1104{
fd58fa32 1105 void *host = NULL;
d16005f8 1106
98fa08a5 1107 lightrec_get_map(state, &host, kunseg(pc));
d16005f8 1108
98fa08a5 1109 const u32 *code = (u32 *)host;
02487de7 1110 return (union code) LE32TOH(*code);
98fa08a5 1111}
d16005f8 1112
98fa08a5
PC
1113unsigned int lightrec_cycles_of_opcode(union code code)
1114{
1115 return 2;
1116}
d16005f8 1117
98fa08a5
PC
1118void lightrec_free_opcode_list(struct lightrec_state *state, struct block *block)
1119{
1120 lightrec_free(state, MEM_FOR_IR,
1121 sizeof(*block->opcode_list) * block->nb_ops,
1122 block->opcode_list);
1123}
1124
1125static unsigned int lightrec_get_mips_block_len(const u32 *src)
1126{
1127 unsigned int i;
1128 union code c;
1129
1130 for (i = 1; ; i++) {
1131 c.opcode = LE32TOH(*src++);
1132
1133 if (is_syscall(c))
1134 return i;
1135
1136 if (is_unconditional_jump(c))
1137 return i + 1;
1138 }
1139}
1140
1141static struct opcode * lightrec_disassemble(struct lightrec_state *state,
1142 const u32 *src, unsigned int *len)
1143{
1144 struct opcode *list;
1145 unsigned int i, length;
1146
1147 length = lightrec_get_mips_block_len(src);
1148
1149 list = lightrec_malloc(state, MEM_FOR_IR, sizeof(*list) * length);
1150 if (!list) {
1151 pr_err("Unable to allocate memory\n");
1152 return NULL;
1153 }
1154
1155 for (i = 0; i < length; i++) {
1156 list[i].opcode = LE32TOH(src[i]);
1157 list[i].flags = 0;
1158 }
1159
1160 *len = length * sizeof(u32);
1161
1162 return list;
d16005f8
PC
1163}
1164
1165static struct block * lightrec_precompile_block(struct lightrec_state *state,
1166 u32 pc)
1167{
1168 struct opcode *list;
1169 struct block *block;
98fa08a5
PC
1170 void *host;
1171 const struct lightrec_mem_map *map = lightrec_get_map(state, &host, kunseg(pc));
1172 const u32 *code = (u32 *) host;
d16005f8 1173 unsigned int length;
98fa08a5 1174 bool fully_tagged;
d16005f8
PC
1175
1176 if (!map)
1177 return NULL;
1178
d16005f8
PC
1179 block = lightrec_malloc(state, MEM_FOR_IR, sizeof(*block));
1180 if (!block) {
1181 pr_err("Unable to recompile block: Out of memory\n");
1182 return NULL;
1183 }
1184
1185 list = lightrec_disassemble(state, code, &length);
1186 if (!list) {
1187 lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
1188 return NULL;
1189 }
1190
1191 block->pc = pc;
d16005f8
PC
1192 block->_jit = NULL;
1193 block->function = NULL;
1194 block->opcode_list = list;
98fa08a5 1195 block->code = code;
d16005f8
PC
1196 block->next = NULL;
1197 block->flags = 0;
1198 block->code_size = 0;
d8b04acd 1199 block->precompile_date = state->current_cycle;
d16005f8
PC
1200#if ENABLE_THREADED_COMPILER
1201 block->op_list_freed = (atomic_flag)ATOMIC_FLAG_INIT;
1202#endif
1203 block->nb_ops = length / sizeof(u32);
1204
98fa08a5 1205 lightrec_optimize(state, block);
d16005f8
PC
1206
1207 length = block->nb_ops * sizeof(u32);
1208
1209 lightrec_register(MEM_FOR_MIPS_CODE, length);
1210
1211 if (ENABLE_DISASSEMBLER) {
98fa08a5
PC
1212 pr_debug("Disassembled block at PC: 0x%08x\n", block->pc);
1213 lightrec_print_disassembly(block, code);
d16005f8
PC
1214 }
1215
98fa08a5 1216 pr_debug("Block size: %hu opcodes\n", block->nb_ops);
d16005f8
PC
1217
1218 /* If the first opcode is an 'impossible' branch, never compile the
1219 * block */
98fa08a5 1220 if (should_emulate(block->opcode_list))
d16005f8
PC
1221 block->flags |= BLOCK_NEVER_COMPILE;
1222
98fa08a5
PC
1223 fully_tagged = lightrec_block_is_fully_tagged(block);
1224 if (fully_tagged)
1225 block->flags |= BLOCK_FULLY_TAGGED;
1226
1227 if (OPT_REPLACE_MEMSET && (block->flags & BLOCK_IS_MEMSET))
02487de7 1228 lut_write(state, lut_offset(pc), state->memset_func);
98fa08a5 1229
d16005f8
PC
1230 block->hash = lightrec_calculate_block_hash(block);
1231
a59e5536 1232 pr_debug("Recompile count: %u\n", state->nb_precompile++);
1233
d16005f8
PC
1234 return block;
1235}
1236
98fa08a5 1237static bool lightrec_block_is_fully_tagged(const struct block *block)
d16005f8 1238{
98fa08a5
PC
1239 const struct opcode *op;
1240 unsigned int i;
1241
1242 for (i = 0; i < block->nb_ops; i++) {
1243 op = &block->opcode_list[i];
d16005f8 1244
d16005f8
PC
1245 /* Verify that all load/stores of the opcode list
1246 * Check all loads/stores of the opcode list and mark the
1247 * block as fully compiled if they all have been tagged. */
1248 switch (op->c.i.op) {
1249 case OP_LB:
1250 case OP_LH:
1251 case OP_LWL:
1252 case OP_LW:
1253 case OP_LBU:
1254 case OP_LHU:
1255 case OP_LWR:
1256 case OP_SB:
1257 case OP_SH:
1258 case OP_SWL:
1259 case OP_SW:
1260 case OP_SWR:
1261 case OP_LWC2:
1262 case OP_SWC2:
22eee2ac 1263 if (!LIGHTREC_FLAGS_GET_IO_MODE(op->flags))
d16005f8 1264 return false;
d8b04acd
PC
1265 fallthrough;
1266 default:
d16005f8
PC
1267 continue;
1268 }
1269 }
1270
1271 return true;
1272}
1273
98fa08a5 1274static void lightrec_reap_block(struct lightrec_state *state, void *data)
a59e5536 1275{
1276 struct block *block = data;
1277
1278 pr_debug("Reap dead block at PC 0x%08x\n", block->pc);
98fa08a5
PC
1279 lightrec_unregister_block(state->block_cache, block);
1280 lightrec_free_block(state, block);
a59e5536 1281}
1282
98fa08a5 1283static void lightrec_reap_jit(struct lightrec_state *state, void *data)
a59e5536 1284{
1285 _jit_destroy_state(data);
1286}
1287
02487de7
PC
1288static void lightrec_free_function(struct lightrec_state *state, void *fn)
1289{
1290 if (ENABLE_CODE_BUFFER && state->tlsf) {
1291 pr_debug("Freeing code block at 0x%" PRIxPTR "\n", (uintptr_t) fn);
d8b04acd 1292 lightrec_free_code(state, fn);
02487de7
PC
1293 }
1294}
1295
1296static void lightrec_reap_function(struct lightrec_state *state, void *data)
1297{
1298 lightrec_free_function(state, data);
1299}
1300
98fa08a5
PC
1301int lightrec_compile_block(struct lightrec_cstate *cstate,
1302 struct block *block)
d16005f8 1303{
98fa08a5 1304 struct lightrec_state *state = cstate->state;
a59e5536 1305 struct lightrec_branch_target *target;
d16005f8 1306 bool op_list_freed = false, fully_tagged = false;
a59e5536 1307 struct block *block2;
d16005f8 1308 struct opcode *elm;
a59e5536 1309 jit_state_t *_jit, *oldjit;
d16005f8
PC
1310 jit_node_t *start_of_block;
1311 bool skip_next = false;
d8b04acd 1312 void *old_fn, *new_fn;
d16005f8 1313 unsigned int i, j;
98fa08a5 1314 u32 offset;
d16005f8
PC
1315
1316 fully_tagged = lightrec_block_is_fully_tagged(block);
1317 if (fully_tagged)
1318 block->flags |= BLOCK_FULLY_TAGGED;
1319
1320 _jit = jit_new_state();
1321 if (!_jit)
1322 return -ENOMEM;
1323
a59e5536 1324 oldjit = block->_jit;
02487de7 1325 old_fn = block->function;
d16005f8
PC
1326 block->_jit = _jit;
1327
98fa08a5
PC
1328 lightrec_regcache_reset(cstate->reg_cache);
1329 cstate->cycles = 0;
1330 cstate->nb_branches = 0;
1331 cstate->nb_local_branches = 0;
1332 cstate->nb_targets = 0;
d16005f8
PC
1333
1334 jit_prolog();
1335 jit_tramp(256);
1336
1337 start_of_block = jit_label();
1338
98fa08a5
PC
1339 for (i = 0; i < block->nb_ops; i++) {
1340 elm = &block->opcode_list[i];
d16005f8
PC
1341
1342 if (skip_next) {
1343 skip_next = false;
1344 continue;
1345 }
1346
98fa08a5 1347 cstate->cycles += lightrec_cycles_of_opcode(elm->c);
d16005f8 1348
98fa08a5 1349 if (should_emulate(elm)) {
d16005f8 1350 pr_debug("Branch at offset 0x%x will be emulated\n",
98fa08a5
PC
1351 i << 2);
1352
1353 lightrec_emit_eob(cstate, block, i, false);
d16005f8 1354 skip_next = !(elm->flags & LIGHTREC_NO_DS);
98fa08a5
PC
1355 } else {
1356 lightrec_rec_opcode(cstate, block, i);
d16005f8
PC
1357 skip_next = has_delay_slot(elm->c) &&
1358 !(elm->flags & LIGHTREC_NO_DS);
1359#if _WIN32
1360 /* FIXME: GNU Lightning on Windows seems to use our
1361 * mapped registers as temporaries. Until the actual bug
1362 * is found and fixed, unconditionally mark our
1363 * registers as live here. */
98fa08a5 1364 lightrec_regcache_mark_live(cstate->reg_cache, _jit);
d16005f8
PC
1365#endif
1366 }
1367 }
1368
98fa08a5
PC
1369 for (i = 0; i < cstate->nb_branches; i++)
1370 jit_patch(cstate->branches[i]);
d16005f8 1371
98fa08a5
PC
1372 for (i = 0; i < cstate->nb_local_branches; i++) {
1373 struct lightrec_branch *branch = &cstate->local_branches[i];
d16005f8
PC
1374
1375 pr_debug("Patch local branch to offset 0x%x\n",
1376 branch->target << 2);
1377
1378 if (branch->target == 0) {
1379 jit_patch_at(branch->branch, start_of_block);
1380 continue;
1381 }
1382
98fa08a5
PC
1383 for (j = 0; j < cstate->nb_targets; j++) {
1384 if (cstate->targets[j].offset == branch->target) {
d16005f8 1385 jit_patch_at(branch->branch,
98fa08a5 1386 cstate->targets[j].label);
d16005f8
PC
1387 break;
1388 }
1389 }
1390
98fa08a5 1391 if (j == cstate->nb_targets)
d16005f8
PC
1392 pr_err("Unable to find branch target\n");
1393 }
1394
1395 jit_ldxi(JIT_R0, LIGHTREC_REG_STATE,
1396 offsetof(struct lightrec_state, eob_wrapper_func));
1397
1398 jit_jmpr(JIT_R0);
1399
1400 jit_ret();
1401 jit_epilog();
1402
d8b04acd
PC
1403 new_fn = lightrec_emit_code(state, block, _jit, &block->code_size);
1404 if (!new_fn) {
1405 if (!ENABLE_THREADED_COMPILER)
1406 pr_err("Unable to compile block!\n");
1407 block->_jit = oldjit;
1408 _jit_destroy_state(_jit);
1409 return -ENOMEM;
02487de7
PC
1410 }
1411
d8b04acd 1412 block->function = new_fn;
a59e5536 1413 block->flags &= ~BLOCK_SHOULD_RECOMPILE;
d16005f8
PC
1414
1415 /* Add compiled function to the LUT */
02487de7 1416 lut_write(state, lut_offset(block->pc), block->function);
d16005f8 1417
98fa08a5
PC
1418 if (ENABLE_THREADED_COMPILER) {
1419 /* Since we might try to reap the same block multiple times,
1420 * we need the reaper to wait until everything has been
1421 * submitted, so that the duplicate entries can be dropped. */
1422 lightrec_reaper_pause(state->reaper);
a59e5536 1423 }
1424
1425 /* Detect old blocks that have been covered by the new one */
98fa08a5
PC
1426 for (i = 0; i < cstate->nb_targets; i++) {
1427 target = &cstate->targets[i];
a59e5536 1428
1429 if (!target->offset)
1430 continue;
1431
1432 offset = block->pc + target->offset * sizeof(u32);
1433 block2 = lightrec_find_block(state->block_cache, offset);
1434 if (block2) {
1435 /* No need to check if block2 is compilable - it must
1436 * be, otherwise block wouldn't be compilable either */
1437
98fa08a5
PC
1438 /* Set the "block dead" flag to prevent the dynarec from
1439 * recompiling this block */
a59e5536 1440 block2->flags |= BLOCK_IS_DEAD;
1441
98fa08a5
PC
1442 /* If block2 was pending for compilation, cancel it.
1443 * If it's being compiled right now, wait until it
1444 * finishes. */
1445 if (ENABLE_THREADED_COMPILER)
1446 lightrec_recompiler_remove(state->rec, block2);
fd58fa32 1447 }
98fa08a5 1448
fd58fa32
PC
1449 /* We know from now on that block2 (if present) isn't going to
1450 * be compiled. We can override the LUT entry with our new
1451 * block's entry point. */
1452 offset = lut_offset(block->pc) + target->offset;
02487de7 1453 lut_write(state, offset, jit_address(target->label));
98fa08a5 1454
fd58fa32 1455 if (block2) {
a59e5536 1456 pr_debug("Reap block 0x%08x as it's covered by block "
1457 "0x%08x\n", block2->pc, block->pc);
1458
98fa08a5 1459 /* Finally, reap the block. */
a59e5536 1460 if (ENABLE_THREADED_COMPILER) {
a59e5536 1461 lightrec_reaper_add(state->reaper,
1462 lightrec_reap_block,
1463 block2);
1464 } else {
98fa08a5
PC
1465 lightrec_unregister_block(state->block_cache, block2);
1466 lightrec_free_block(state, block2);
a59e5536 1467 }
1468 }
1469 }
1470
b19ddc79 1471 if (ENABLE_THREADED_COMPILER)
98fa08a5
PC
1472 lightrec_reaper_continue(state->reaper);
1473
d16005f8 1474 if (ENABLE_DISASSEMBLER) {
98fa08a5 1475 pr_debug("Compiling block at PC: 0x%08x\n", block->pc);
d16005f8
PC
1476 jit_disassemble();
1477 }
1478
1479 jit_clear_state();
1480
1481#if ENABLE_THREADED_COMPILER
1482 if (fully_tagged)
1483 op_list_freed = atomic_flag_test_and_set(&block->op_list_freed);
1484#endif
1485 if (fully_tagged && !op_list_freed) {
1486 pr_debug("Block PC 0x%08x is fully tagged"
1487 " - free opcode list\n", block->pc);
98fa08a5 1488 lightrec_free_opcode_list(state, block);
d16005f8
PC
1489 block->opcode_list = NULL;
1490 }
1491
a59e5536 1492 if (oldjit) {
1493 pr_debug("Block 0x%08x recompiled, reaping old jit context.\n",
1494 block->pc);
1495
02487de7 1496 if (ENABLE_THREADED_COMPILER) {
a59e5536 1497 lightrec_reaper_add(state->reaper,
1498 lightrec_reap_jit, oldjit);
02487de7
PC
1499 lightrec_reaper_add(state->reaper,
1500 lightrec_reap_function, old_fn);
1501 } else {
a59e5536 1502 _jit_destroy_state(oldjit);
02487de7
PC
1503 lightrec_free_function(state, old_fn);
1504 }
a59e5536 1505 }
1506
d16005f8
PC
1507 return 0;
1508}
1509
98fa08a5
PC
1510static void lightrec_print_info(struct lightrec_state *state)
1511{
1512 if ((state->current_cycle & ~0xfffffff) != state->old_cycle_counter) {
1513 pr_info("Lightrec RAM usage: IR %u KiB, CODE %u KiB, "
1514 "MIPS %u KiB, TOTAL %u KiB, avg. IPI %f\n",
1515 lightrec_get_mem_usage(MEM_FOR_IR) / 1024,
1516 lightrec_get_mem_usage(MEM_FOR_CODE) / 1024,
1517 lightrec_get_mem_usage(MEM_FOR_MIPS_CODE) / 1024,
1518 lightrec_get_total_mem_usage() / 1024,
1519 lightrec_get_average_ipi());
1520 state->old_cycle_counter = state->current_cycle & ~0xfffffff;
1521 }
1522}
1523
d16005f8
PC
1524u32 lightrec_execute(struct lightrec_state *state, u32 pc, u32 target_cycle)
1525{
1526 s32 (*func)(void *, s32) = (void *)state->dispatcher->function;
1527 void *block_trace;
1528 s32 cycles_delta;
1529
1530 state->exit_flags = LIGHTREC_EXIT_NORMAL;
1531
1532 /* Handle the cycle counter overflowing */
1533 if (unlikely(target_cycle < state->current_cycle))
1534 target_cycle = UINT_MAX;
1535
1536 state->target_cycle = target_cycle;
98fa08a5 1537 state->next_pc = pc;
d16005f8
PC
1538
1539 block_trace = get_next_block_func(state, pc);
1540 if (block_trace) {
1541 cycles_delta = state->target_cycle - state->current_cycle;
1542
1543 cycles_delta = (*func)(block_trace, cycles_delta);
1544
1545 state->current_cycle = state->target_cycle - cycles_delta;
1546 }
1547
a59e5536 1548 if (ENABLE_THREADED_COMPILER)
1549 lightrec_reaper_reap(state->reaper);
1550
98fa08a5
PC
1551 if (LOG_LEVEL >= INFO_L)
1552 lightrec_print_info(state);
1553
d16005f8
PC
1554 return state->next_pc;
1555}
1556
1557u32 lightrec_execute_one(struct lightrec_state *state, u32 pc)
1558{
1559 return lightrec_execute(state, pc, state->current_cycle);
1560}
1561
1562u32 lightrec_run_interpreter(struct lightrec_state *state, u32 pc)
1563{
1564 struct block *block = lightrec_get_block(state, pc);
1565 if (!block)
1566 return 0;
1567
1568 state->exit_flags = LIGHTREC_EXIT_NORMAL;
1569
98fa08a5
PC
1570 pc = lightrec_emulate_block(state, block, pc);
1571
1572 if (LOG_LEVEL >= INFO_L)
1573 lightrec_print_info(state);
1574
1575 return pc;
d16005f8
PC
1576}
1577
98fa08a5 1578void lightrec_free_block(struct lightrec_state *state, struct block *block)
d16005f8
PC
1579{
1580 lightrec_unregister(MEM_FOR_MIPS_CODE, block->nb_ops * sizeof(u32));
1581 if (block->opcode_list)
98fa08a5 1582 lightrec_free_opcode_list(state, block);
d16005f8
PC
1583 if (block->_jit)
1584 _jit_destroy_state(block->_jit);
d8b04acd
PC
1585 if (block->function) {
1586 lightrec_free_function(state, block->function);
1587 lightrec_unregister(MEM_FOR_CODE, block->code_size);
1588 }
98fa08a5
PC
1589 lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
1590}
1591
1592struct lightrec_cstate * lightrec_create_cstate(struct lightrec_state *state)
1593{
1594 struct lightrec_cstate *cstate;
1595
1596 cstate = lightrec_malloc(state, MEM_FOR_LIGHTREC, sizeof(*cstate));
1597 if (!cstate)
1598 return NULL;
1599
1600 cstate->reg_cache = lightrec_regcache_init(state);
1601 if (!cstate->reg_cache) {
1602 lightrec_free(state, MEM_FOR_LIGHTREC, sizeof(*cstate), cstate);
1603 return NULL;
1604 }
1605
1606 cstate->state = state;
1607
1608 return cstate;
1609}
1610
1611void lightrec_free_cstate(struct lightrec_cstate *cstate)
1612{
1613 lightrec_free_regcache(cstate->reg_cache);
1614 lightrec_free(cstate->state, MEM_FOR_LIGHTREC, sizeof(*cstate), cstate);
d16005f8
PC
1615}
1616
1617struct lightrec_state * lightrec_init(char *argv0,
1618 const struct lightrec_mem_map *map,
1619 size_t nb,
1620 const struct lightrec_ops *ops)
1621{
d8b04acd 1622 const struct lightrec_mem_map *codebuf_map = &map[PSX_MAP_CODE_BUFFER];
d16005f8 1623 struct lightrec_state *state;
02487de7
PC
1624 uintptr_t addr;
1625 void *tlsf = NULL;
1626 bool with_32bit_lut = false;
1627 size_t lut_size;
d16005f8
PC
1628
1629 /* Sanity-check ops */
98fa08a5 1630 if (!ops || !ops->cop2_op || !ops->enable_ram) {
d16005f8
PC
1631 pr_err("Missing callbacks in lightrec_ops structure\n");
1632 return NULL;
1633 }
1634
d8b04acd
PC
1635 if (ENABLE_CODE_BUFFER && nb > PSX_MAP_CODE_BUFFER
1636 && codebuf_map->address) {
02487de7
PC
1637 tlsf = tlsf_create_with_pool(codebuf_map->address,
1638 codebuf_map->length);
1639 if (!tlsf) {
1640 pr_err("Unable to initialize code buffer\n");
1641 return NULL;
1642 }
1643
1644 if (__WORDSIZE == 64) {
1645 addr = (uintptr_t) codebuf_map->address + codebuf_map->length - 1;
1646 with_32bit_lut = addr == (u32) addr;
1647 }
1648 }
1649
1650 if (with_32bit_lut)
1651 lut_size = CODE_LUT_SIZE * 4;
1652 else
1653 lut_size = CODE_LUT_SIZE * sizeof(void *);
1654
d16005f8
PC
1655 init_jit(argv0);
1656
02487de7 1657 state = calloc(1, sizeof(*state) + lut_size);
d16005f8
PC
1658 if (!state)
1659 goto err_finish_jit;
1660
02487de7
PC
1661 lightrec_register(MEM_FOR_LIGHTREC, sizeof(*state) + lut_size);
1662
1663 state->tlsf = tlsf;
1664 state->with_32bit_lut = with_32bit_lut;
d16005f8 1665
d16005f8
PC
1666 state->block_cache = lightrec_blockcache_init(state);
1667 if (!state->block_cache)
d8b04acd 1668 goto err_free_state;
d16005f8 1669
d16005f8
PC
1670 if (ENABLE_THREADED_COMPILER) {
1671 state->rec = lightrec_recompiler_init(state);
1672 if (!state->rec)
98fa08a5 1673 goto err_free_block_cache;
a59e5536 1674
1675 state->reaper = lightrec_reaper_init(state);
1676 if (!state->reaper)
1677 goto err_free_recompiler;
98fa08a5
PC
1678 } else {
1679 state->cstate = lightrec_create_cstate(state);
1680 if (!state->cstate)
1681 goto err_free_block_cache;
d16005f8
PC
1682 }
1683
1684 state->nb_maps = nb;
1685 state->maps = map;
1686
1687 memcpy(&state->ops, ops, sizeof(*ops));
1688
1689 state->dispatcher = generate_dispatcher(state);
1690 if (!state->dispatcher)
a59e5536 1691 goto err_free_reaper;
d16005f8 1692
98fa08a5
PC
1693 state->c_wrapper_block = generate_wrapper(state);
1694 if (!state->c_wrapper_block)
d16005f8
PC
1695 goto err_free_dispatcher;
1696
98fa08a5
PC
1697 state->c_wrappers[C_WRAPPER_RW] = lightrec_rw_cb;
1698 state->c_wrappers[C_WRAPPER_RW_GENERIC] = lightrec_rw_generic_cb;
98fa08a5 1699 state->c_wrappers[C_WRAPPER_MTC] = lightrec_mtc_cb;
22eee2ac 1700 state->c_wrappers[C_WRAPPER_CP] = lightrec_cp_cb;
98fa08a5
PC
1701 state->c_wrappers[C_WRAPPER_SYSCALL] = lightrec_syscall_cb;
1702 state->c_wrappers[C_WRAPPER_BREAK] = lightrec_break_cb;
d16005f8
PC
1703
1704 map = &state->maps[PSX_MAP_BIOS];
1705 state->offset_bios = (uintptr_t)map->address - map->pc;
1706
1707 map = &state->maps[PSX_MAP_SCRATCH_PAD];
1708 state->offset_scratch = (uintptr_t)map->address - map->pc;
1709
1710 map = &state->maps[PSX_MAP_KERNEL_USER_RAM];
1711 state->offset_ram = (uintptr_t)map->address - map->pc;
1712
1713 if (state->maps[PSX_MAP_MIRROR1].address == map->address + 0x200000 &&
1714 state->maps[PSX_MAP_MIRROR2].address == map->address + 0x400000 &&
1715 state->maps[PSX_MAP_MIRROR3].address == map->address + 0x600000)
1716 state->mirrors_mapped = true;
1717
98fa08a5
PC
1718 if (state->offset_bios == 0 &&
1719 state->offset_scratch == 0 &&
1720 state->offset_ram == 0 &&
1721 state->mirrors_mapped) {
1722 pr_info("Memory map is perfect. Emitted code will be best.\n");
1723 } else {
1724 pr_info("Memory map is sub-par. Emitted code will be slow.\n");
1725 }
1726
02487de7
PC
1727 if (state->with_32bit_lut)
1728 pr_info("Using 32-bit LUT\n");
1729
d16005f8
PC
1730 return state;
1731
d16005f8 1732err_free_dispatcher:
98fa08a5 1733 lightrec_free_block(state, state->dispatcher);
a59e5536 1734err_free_reaper:
1735 if (ENABLE_THREADED_COMPILER)
1736 lightrec_reaper_destroy(state->reaper);
d16005f8
PC
1737err_free_recompiler:
1738 if (ENABLE_THREADED_COMPILER)
1739 lightrec_free_recompiler(state->rec);
98fa08a5
PC
1740 else
1741 lightrec_free_cstate(state->cstate);
d16005f8
PC
1742err_free_block_cache:
1743 lightrec_free_block_cache(state->block_cache);
d16005f8 1744err_free_state:
d16005f8 1745 lightrec_unregister(MEM_FOR_LIGHTREC, sizeof(*state) +
02487de7 1746 lut_elm_size(state) * CODE_LUT_SIZE);
d16005f8
PC
1747 free(state);
1748err_finish_jit:
1749 finish_jit();
02487de7
PC
1750 if (ENABLE_CODE_BUFFER && tlsf)
1751 tlsf_destroy(tlsf);
d16005f8
PC
1752 return NULL;
1753}
1754
1755void lightrec_destroy(struct lightrec_state *state)
1756{
98fa08a5
PC
1757 /* Force a print info on destroy*/
1758 state->current_cycle = ~state->current_cycle;
1759 lightrec_print_info(state);
1760
a59e5536 1761 if (ENABLE_THREADED_COMPILER) {
d16005f8 1762 lightrec_free_recompiler(state->rec);
a59e5536 1763 lightrec_reaper_destroy(state->reaper);
98fa08a5
PC
1764 } else {
1765 lightrec_free_cstate(state->cstate);
a59e5536 1766 }
d16005f8 1767
d16005f8 1768 lightrec_free_block_cache(state->block_cache);
98fa08a5
PC
1769 lightrec_free_block(state, state->dispatcher);
1770 lightrec_free_block(state, state->c_wrapper_block);
d16005f8 1771 finish_jit();
02487de7
PC
1772 if (ENABLE_CODE_BUFFER && state->tlsf)
1773 tlsf_destroy(state->tlsf);
d16005f8 1774
d16005f8 1775 lightrec_unregister(MEM_FOR_LIGHTREC, sizeof(*state) +
02487de7 1776 lut_elm_size(state) * CODE_LUT_SIZE);
d16005f8
PC
1777 free(state);
1778}
1779
1780void lightrec_invalidate(struct lightrec_state *state, u32 addr, u32 len)
1781{
1782 u32 kaddr = kunseg(addr & ~0x3);
d8b04acd 1783 enum psx_map idx = lightrec_get_map_idx(state, kaddr);
d16005f8 1784
d8b04acd
PC
1785 switch (idx) {
1786 case PSX_MAP_MIRROR1:
1787 case PSX_MAP_MIRROR2:
1788 case PSX_MAP_MIRROR3:
d16005f8 1789 /* Handle mirrors */
d8b04acd
PC
1790 kaddr &= RAM_SIZE - 1;
1791 fallthrough;
1792 case PSX_MAP_KERNEL_USER_RAM:
1793 break;
1794 default:
1795 return;
d16005f8 1796 }
d8b04acd
PC
1797
1798 memset(lut_address(state, lut_offset(kaddr)), 0,
1799 ((len + 3) / 4) * lut_elm_size(state));
d16005f8
PC
1800}
1801
1802void lightrec_invalidate_all(struct lightrec_state *state)
1803{
02487de7 1804 memset(state->code_lut, 0, lut_elm_size(state) * CODE_LUT_SIZE);
d16005f8
PC
1805}
1806
1807void lightrec_set_invalidate_mode(struct lightrec_state *state, bool dma_only)
1808{
1809 if (state->invalidate_from_dma_only != dma_only)
1810 lightrec_invalidate_all(state);
1811
1812 state->invalidate_from_dma_only = dma_only;
1813}
1814
1815void lightrec_set_exit_flags(struct lightrec_state *state, u32 flags)
1816{
1817 if (flags != LIGHTREC_EXIT_NORMAL) {
1818 state->exit_flags |= flags;
1819 state->target_cycle = state->current_cycle;
1820 }
1821}
1822
1823u32 lightrec_exit_flags(struct lightrec_state *state)
1824{
1825 return state->exit_flags;
1826}
1827
d16005f8
PC
1828u32 lightrec_current_cycle_count(const struct lightrec_state *state)
1829{
1830 return state->current_cycle;
1831}
1832
1833void lightrec_reset_cycle_count(struct lightrec_state *state, u32 cycles)
1834{
1835 state->current_cycle = cycles;
1836
1837 if (state->target_cycle < cycles)
1838 state->target_cycle = cycles;
1839}
1840
1841void lightrec_set_target_cycle_count(struct lightrec_state *state, u32 cycles)
1842{
1843 if (state->exit_flags == LIGHTREC_EXIT_NORMAL) {
1844 if (cycles < state->current_cycle)
1845 cycles = state->current_cycle;
1846
1847 state->target_cycle = cycles;
1848 }
1849}
98fa08a5
PC
1850
1851struct lightrec_registers * lightrec_get_registers(struct lightrec_state *state)
1852{
1853 return &state->regs;
1854}