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