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_mfc_cb(struct lightrec_state *state, union code op)
410 {
411         u32 rt = lightrec_mfc(state, op);
412
413         if (op.r.rt)
414                 state->regs.gpr[op.r.rt] = rt;
415 }
416
417 static void lightrec_mtc0(struct lightrec_state *state, u8 reg, u32 data)
418 {
419         u32 status, cause;
420
421         switch (reg) {
422         case 1:
423         case 4:
424         case 8:
425         case 14:
426         case 15:
427                 /* Those registers are read-only */
428                 return;
429         default: /* fall-through */
430                 break;
431         }
432
433         if (reg == 12) {
434                 status = state->regs.cp0[12];
435
436                 if (status & ~data & BIT(16)) {
437                         state->ops.enable_ram(state, true);
438                         lightrec_invalidate_all(state);
439                 } else if (~status & data & BIT(16)) {
440                         state->ops.enable_ram(state, false);
441                 }
442         }
443
444         state->regs.cp0[reg] = data;
445
446         if (reg == 12 || reg == 13) {
447                 cause = state->regs.cp0[13];
448                 status = state->regs.cp0[12];
449
450                 if (!!(status & cause & 0x300) & status)
451                         lightrec_set_exit_flags(state, LIGHTREC_EXIT_CHECK_INTERRUPT);
452         }
453 }
454
455 static u32 count_leading_bits(s32 data)
456 {
457         u32 cnt = 33;
458
459 #ifdef __has_builtin
460 #if __has_builtin(__builtin_clrsb)
461         return 1 + __builtin_clrsb(data);
462 #endif
463 #endif
464
465         data = (data ^ (data >> 31)) << 1;
466
467         do {
468                 cnt -= 1;
469                 data >>= 1;
470         } while (data);
471
472         return cnt;
473 }
474
475 static void lightrec_mtc2(struct lightrec_state *state, u8 reg, u32 data)
476 {
477         switch (reg) {
478         case 15:
479                 state->regs.cp2d[12] = state->regs.cp2d[13];
480                 state->regs.cp2d[13] = state->regs.cp2d[14];
481                 state->regs.cp2d[14] = data;
482                 break;
483         case 28:
484                 state->regs.cp2d[9] = (data << 7) & 0xf80;
485                 state->regs.cp2d[10] = (data << 2) & 0xf80;
486                 state->regs.cp2d[11] = (data >> 3) & 0xf80;
487                 break;
488         case 31:
489                 return;
490         case 30:
491                 state->regs.cp2d[31] = count_leading_bits((s32) data);
492         default: /* fall-through */
493                 state->regs.cp2d[reg] = data;
494                 break;
495         }
496 }
497
498 static void lightrec_ctc2(struct lightrec_state *state, u8 reg, u32 data)
499 {
500         switch (reg) {
501         case 4:
502         case 12:
503         case 20:
504         case 26:
505         case 27:
506         case 29:
507         case 30:
508                 data = (s32)(s16) data;
509                 break;
510         case 31:
511                 data = (data & 0x7ffff000) | !!(data & 0x7f87e000) << 31;
512         default: /* fall-through */
513                 break;
514         }
515
516         state->regs.cp2c[reg] = data;
517 }
518
519 void lightrec_mtc(struct lightrec_state *state, union code op, u32 data)
520 {
521         if (op.i.op == OP_CP0)
522                 lightrec_mtc0(state, op.r.rd, data);
523         else if (op.r.rs == OP_CP2_BASIC_CTC2)
524                 lightrec_ctc2(state, op.r.rd, data);
525         else
526                 lightrec_mtc2(state, op.r.rd, data);
527 }
528
529 static void lightrec_mtc_cb(struct lightrec_state *state, union code op)
530 {
531         lightrec_mtc(state, op, state->regs.gpr[op.r.rt]);
532 }
533
534 void lightrec_rfe(struct lightrec_state *state)
535 {
536         u32 status;
537
538         /* Read CP0 Status register (r12) */
539         status = state->regs.cp0[12];
540
541         /* Switch the bits */
542         status = ((status & 0x3c) >> 2) | (status & ~0xf);
543
544         /* Write it back */
545         lightrec_mtc0(state, 12, status);
546 }
547
548 void lightrec_cp(struct lightrec_state *state, union code op)
549 {
550         if (op.i.op == OP_CP0) {
551                 pr_err("Invalid CP opcode to coprocessor #0\n");
552                 return;
553         }
554
555         (*state->ops.cop2_op)(state, op.opcode);
556 }
557
558 static void lightrec_syscall_cb(struct lightrec_state *state, union code op)
559 {
560         lightrec_set_exit_flags(state, LIGHTREC_EXIT_SYSCALL);
561 }
562
563 static void lightrec_break_cb(struct lightrec_state *state, union code op)
564 {
565         lightrec_set_exit_flags(state, LIGHTREC_EXIT_BREAK);
566 }
567
568 struct block * lightrec_get_block(struct lightrec_state *state, u32 pc)
569 {
570         struct block *block = lightrec_find_block(state->block_cache, pc);
571
572         if (block && lightrec_block_is_outdated(state, block)) {
573                 pr_debug("Block at PC 0x%08x is outdated!\n", block->pc);
574
575                 /* Make sure the recompiler isn't processing the block we'll
576                  * destroy */
577                 if (ENABLE_THREADED_COMPILER)
578                         lightrec_recompiler_remove(state->rec, block);
579
580                 lightrec_unregister_block(state->block_cache, block);
581                 remove_from_code_lut(state->block_cache, block);
582                 lightrec_free_block(state, block);
583                 block = NULL;
584         }
585
586         if (!block) {
587                 block = lightrec_precompile_block(state, pc);
588                 if (!block) {
589                         pr_err("Unable to recompile block at PC 0x%x\n", pc);
590                         lightrec_set_exit_flags(state, LIGHTREC_EXIT_SEGFAULT);
591                         return NULL;
592                 }
593
594                 lightrec_register_block(state->block_cache, block);
595         }
596
597         return block;
598 }
599
600 static void * get_next_block_func(struct lightrec_state *state, u32 pc)
601 {
602         struct block *block;
603         bool should_recompile;
604         void *func;
605
606         for (;;) {
607                 func = state->code_lut[lut_offset(pc)];
608                 if (func && func != state->get_next_block)
609                         break;
610
611                 block = lightrec_get_block(state, pc);
612
613                 if (unlikely(!block))
614                         break;
615
616                 if (OPT_REPLACE_MEMSET && (block->flags & BLOCK_IS_MEMSET)) {
617                         func = state->memset_func;
618                         break;
619                 }
620
621                 should_recompile = block->flags & BLOCK_SHOULD_RECOMPILE &&
622                         !(block->flags & BLOCK_IS_DEAD);
623
624                 if (unlikely(should_recompile)) {
625                         pr_debug("Block at PC 0x%08x should recompile\n", pc);
626
627                         lightrec_unregister(MEM_FOR_CODE, block->code_size);
628
629                         if (ENABLE_THREADED_COMPILER)
630                                 lightrec_recompiler_add(state->rec, block);
631                         else
632                                 lightrec_compile_block(state->cstate, block);
633                 }
634
635                 if (ENABLE_THREADED_COMPILER && likely(!should_recompile))
636                         func = lightrec_recompiler_run_first_pass(state, block, &pc);
637                 else
638                         func = block->function;
639
640                 if (likely(func))
641                         break;
642
643                 if (unlikely(block->flags & BLOCK_NEVER_COMPILE)) {
644                         pc = lightrec_emulate_block(state, block, pc);
645
646                 } else if (!ENABLE_THREADED_COMPILER) {
647                         /* Block wasn't compiled yet - run the interpreter */
648                         if (block->flags & BLOCK_FULLY_TAGGED)
649                                 pr_debug("Block fully tagged, skipping first pass\n");
650                         else if (ENABLE_FIRST_PASS && likely(!should_recompile))
651                                 pc = lightrec_emulate_block(state, block, pc);
652
653                         /* Then compile it using the profiled data */
654                         lightrec_compile_block(state->cstate, block);
655                 } else {
656                         lightrec_recompiler_add(state->rec, block);
657                 }
658
659                 if (state->exit_flags != LIGHTREC_EXIT_NORMAL ||
660                     state->current_cycle >= state->target_cycle)
661                         break;
662         }
663
664         state->next_pc = pc;
665         return func;
666 }
667
668 static s32 c_function_wrapper(struct lightrec_state *state, s32 cycles_delta,
669                               void (*f)(struct lightrec_state *, u32 d),
670                               u32 d)
671 {
672         state->current_cycle = state->target_cycle - cycles_delta;
673
674         (*f)(state, d);
675
676         return state->target_cycle - state->current_cycle;
677 }
678
679 static struct block * generate_wrapper(struct lightrec_state *state)
680 {
681         struct block *block;
682         jit_state_t *_jit;
683         unsigned int i;
684         int stack_ptr;
685         jit_word_t code_size;
686         jit_node_t *to_tramp, *to_fn_epilog;
687
688         block = lightrec_malloc(state, MEM_FOR_IR, sizeof(*block));
689         if (!block)
690                 goto err_no_mem;
691
692         _jit = jit_new_state();
693         if (!_jit)
694                 goto err_free_block;
695
696         jit_name("RW wrapper");
697         jit_note(__FILE__, __LINE__);
698
699         /* Wrapper entry point */
700         jit_prolog();
701
702         stack_ptr = jit_allocai(sizeof(uintptr_t) * NUM_TEMPS);
703
704         for (i = 0; i < NUM_TEMPS; i++)
705                 jit_stxi(stack_ptr + i * sizeof(uintptr_t), JIT_FP, JIT_R(i));
706
707         /* Jump to the trampoline */
708         to_tramp = jit_jmpi();
709
710         /* The trampoline will jump back here */
711         to_fn_epilog = jit_label();
712
713         for (i = 0; i < NUM_TEMPS; i++)
714                 jit_ldxi(JIT_R(i), JIT_FP, stack_ptr + i * sizeof(uintptr_t));
715
716         jit_ret();
717         jit_epilog();
718
719         /* Trampoline entry point.
720          * The sole purpose of the trampoline is to cheese Lightning not to
721          * save/restore the callee-saved register LIGHTREC_REG_CYCLE, since we
722          * do want to return to the caller with this register modified. */
723         jit_prolog();
724         jit_tramp(256);
725         jit_patch(to_tramp);
726
727         jit_prepare();
728         jit_pushargr(LIGHTREC_REG_STATE);
729         jit_pushargr(LIGHTREC_REG_CYCLE);
730         jit_pushargr(JIT_R0);
731         jit_pushargr(JIT_R1);
732         jit_finishi(c_function_wrapper);
733         jit_retval_i(LIGHTREC_REG_CYCLE);
734
735         jit_patch_at(jit_jmpi(), to_fn_epilog);
736         jit_epilog();
737
738         block->_jit = _jit;
739         block->function = jit_emit();
740         block->opcode_list = NULL;
741         block->flags = 0;
742         block->nb_ops = 0;
743
744         jit_get_code(&code_size);
745         lightrec_register(MEM_FOR_CODE, code_size);
746
747         block->code_size = code_size;
748
749         if (ENABLE_DISASSEMBLER) {
750                 pr_debug("Wrapper block:\n");
751                 jit_disassemble();
752         }
753
754         jit_clear_state();
755         return block;
756
757 err_free_block:
758         lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
759 err_no_mem:
760         pr_err("Unable to compile wrapper: Out of memory\n");
761         return NULL;
762 }
763
764 static u32 lightrec_memset(struct lightrec_state *state)
765 {
766         u32 kunseg_pc = kunseg(state->regs.gpr[4]);
767         void *host;
768         const struct lightrec_mem_map *map = lightrec_get_map(state, &host, kunseg_pc);
769         u32 length = state->regs.gpr[5] * 4;
770
771         if (!map) {
772                 pr_err("Unable to find memory map for memset target address "
773                        "0x%x\n", kunseg_pc);
774                 return 0;
775         }
776
777         pr_debug("Calling host memset, PC 0x%x (host address 0x%" PRIxPTR ") for %u bytes\n",
778                  kunseg_pc, (uintptr_t)host, length);
779         memset(host, 0, length);
780
781         if (!state->invalidate_from_dma_only)
782                 lightrec_invalidate_map(state, map, kunseg_pc, length);
783
784         /* Rough estimation of the number of cycles consumed */
785         return 8 + 5 * (length  + 3 / 4);
786 }
787
788 static struct block * generate_dispatcher(struct lightrec_state *state)
789 {
790         struct block *block;
791         jit_state_t *_jit;
792         jit_node_t *to_end, *to_c, *loop, *addr, *addr2, *addr3;
793         unsigned int i;
794         u32 offset, ram_len;
795         jit_word_t code_size;
796
797         block = lightrec_malloc(state, MEM_FOR_IR, sizeof(*block));
798         if (!block)
799                 goto err_no_mem;
800
801         _jit = jit_new_state();
802         if (!_jit)
803                 goto err_free_block;
804
805         jit_name("dispatcher");
806         jit_note(__FILE__, __LINE__);
807
808         jit_prolog();
809         jit_frame(256);
810
811         jit_getarg(JIT_R0, jit_arg());
812         jit_getarg_i(LIGHTREC_REG_CYCLE, jit_arg());
813
814         /* Force all callee-saved registers to be pushed on the stack */
815         for (i = 0; i < NUM_REGS; i++)
816                 jit_movr(JIT_V(i), JIT_V(i));
817
818         /* Pass lightrec_state structure to blocks, using the last callee-saved
819          * register that Lightning provides */
820         jit_movi(LIGHTREC_REG_STATE, (intptr_t) state);
821
822         loop = jit_label();
823
824         /* Call the block's code */
825         jit_jmpr(JIT_R0);
826
827         if (OPT_REPLACE_MEMSET) {
828                 /* Blocks will jump here when they need to call
829                  * lightrec_memset() */
830                 addr3 = jit_indirect();
831
832                 jit_prepare();
833                 jit_pushargr(LIGHTREC_REG_STATE);
834                 jit_finishi(lightrec_memset);
835
836                 jit_ldxi_ui(JIT_V0, LIGHTREC_REG_STATE,
837                             offsetof(struct lightrec_state, regs.gpr[31]));
838
839                 jit_retval(JIT_R0);
840                 jit_subr(LIGHTREC_REG_CYCLE, LIGHTREC_REG_CYCLE, JIT_R0);
841         }
842
843         /* The block will jump here, with the number of cycles remaining in
844          * LIGHTREC_REG_CYCLE */
845         addr2 = jit_indirect();
846
847         /* Store back the next_pc to the lightrec_state structure */
848         offset = offsetof(struct lightrec_state, next_pc);
849         jit_stxi_i(offset, LIGHTREC_REG_STATE, JIT_V0);
850
851         /* Jump to end if state->target_cycle < state->current_cycle */
852         to_end = jit_blei(LIGHTREC_REG_CYCLE, 0);
853
854         /* Convert next PC to KUNSEG and avoid mirrors */
855         ram_len = state->maps[PSX_MAP_KERNEL_USER_RAM].length;
856         jit_andi(JIT_R0, JIT_V0, 0x10000000 | (ram_len - 1));
857         to_c = jit_bgei(JIT_R0, ram_len);
858
859         /* Fast path: code is running from RAM, use the code LUT */
860         if (__WORDSIZE == 64)
861                 jit_lshi(JIT_R0, JIT_R0, 1);
862         jit_addr(JIT_R0, JIT_R0, LIGHTREC_REG_STATE);
863         jit_ldxi(JIT_R0, JIT_R0, offsetof(struct lightrec_state, code_lut));
864
865         /* If we get non-NULL, loop */
866         jit_patch_at(jit_bnei(JIT_R0, 0), loop);
867
868         /* Slow path: call C function get_next_block_func() */
869         jit_patch(to_c);
870
871         if (ENABLE_FIRST_PASS || OPT_DETECT_IMPOSSIBLE_BRANCHES) {
872                 /* We may call the interpreter - update state->current_cycle */
873                 jit_ldxi_i(JIT_R2, LIGHTREC_REG_STATE,
874                            offsetof(struct lightrec_state, target_cycle));
875                 jit_subr(JIT_R1, JIT_R2, LIGHTREC_REG_CYCLE);
876                 jit_stxi_i(offsetof(struct lightrec_state, current_cycle),
877                            LIGHTREC_REG_STATE, JIT_R1);
878         }
879
880         /* The code LUT will be set to this address when the block at the target
881          * PC has been preprocessed but not yet compiled by the threaded
882          * recompiler */
883         addr = jit_indirect();
884
885         /* Get the next block */
886         jit_prepare();
887         jit_pushargr(LIGHTREC_REG_STATE);
888         jit_pushargr(JIT_V0);
889         jit_finishi(&get_next_block_func);
890         jit_retval(JIT_R0);
891
892         if (ENABLE_FIRST_PASS || OPT_DETECT_IMPOSSIBLE_BRANCHES) {
893                 /* The interpreter may have updated state->current_cycle and
894                  * state->target_cycle - recalc the delta */
895                 jit_ldxi_i(JIT_R1, LIGHTREC_REG_STATE,
896                            offsetof(struct lightrec_state, current_cycle));
897                 jit_ldxi_i(JIT_R2, LIGHTREC_REG_STATE,
898                            offsetof(struct lightrec_state, target_cycle));
899                 jit_subr(LIGHTREC_REG_CYCLE, JIT_R2, JIT_R1);
900         }
901
902         /* If we get non-NULL, loop */
903         jit_patch_at(jit_bnei(JIT_R0, 0), loop);
904
905         /* When exiting, the recompiled code will jump to that address */
906         jit_note(__FILE__, __LINE__);
907         jit_patch(to_end);
908
909         jit_retr(LIGHTREC_REG_CYCLE);
910         jit_epilog();
911
912         block->_jit = _jit;
913         block->function = jit_emit();
914         block->opcode_list = NULL;
915         block->flags = 0;
916         block->nb_ops = 0;
917
918         jit_get_code(&code_size);
919         lightrec_register(MEM_FOR_CODE, code_size);
920
921         block->code_size = code_size;
922
923         state->eob_wrapper_func = jit_address(addr2);
924         if (OPT_REPLACE_MEMSET)
925                 state->memset_func = jit_address(addr3);
926         state->get_next_block = jit_address(addr);
927
928         if (ENABLE_DISASSEMBLER) {
929                 pr_debug("Dispatcher block:\n");
930                 jit_disassemble();
931         }
932
933         /* We're done! */
934         jit_clear_state();
935         return block;
936
937 err_free_block:
938         lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
939 err_no_mem:
940         pr_err("Unable to compile dispatcher: Out of memory\n");
941         return NULL;
942 }
943
944 union code lightrec_read_opcode(struct lightrec_state *state, u32 pc)
945 {
946         void *host;
947
948         lightrec_get_map(state, &host, kunseg(pc));
949
950         const u32 *code = (u32 *)host;
951         return (union code) *code;
952 }
953
954 unsigned int lightrec_cycles_of_opcode(union code code)
955 {
956         return 2;
957 }
958
959 void lightrec_free_opcode_list(struct lightrec_state *state, struct block *block)
960 {
961         lightrec_free(state, MEM_FOR_IR,
962                       sizeof(*block->opcode_list) * block->nb_ops,
963                       block->opcode_list);
964 }
965
966 static unsigned int lightrec_get_mips_block_len(const u32 *src)
967 {
968         unsigned int i;
969         union code c;
970
971         for (i = 1; ; i++) {
972                 c.opcode = LE32TOH(*src++);
973
974                 if (is_syscall(c))
975                         return i;
976
977                 if (is_unconditional_jump(c))
978                         return i + 1;
979         }
980 }
981
982 static struct opcode * lightrec_disassemble(struct lightrec_state *state,
983                                             const u32 *src, unsigned int *len)
984 {
985         struct opcode *list;
986         unsigned int i, length;
987
988         length = lightrec_get_mips_block_len(src);
989
990         list = lightrec_malloc(state, MEM_FOR_IR, sizeof(*list) * length);
991         if (!list) {
992                 pr_err("Unable to allocate memory\n");
993                 return NULL;
994         }
995
996         for (i = 0; i < length; i++) {
997                 list[i].opcode = LE32TOH(src[i]);
998                 list[i].flags = 0;
999         }
1000
1001         *len = length * sizeof(u32);
1002
1003         return list;
1004 }
1005
1006 static struct block * lightrec_precompile_block(struct lightrec_state *state,
1007                                                 u32 pc)
1008 {
1009         struct opcode *list;
1010         struct block *block;
1011         void *host;
1012         const struct lightrec_mem_map *map = lightrec_get_map(state, &host, kunseg(pc));
1013         const u32 *code = (u32 *) host;
1014         unsigned int length;
1015         bool fully_tagged;
1016
1017         if (!map)
1018                 return NULL;
1019
1020         block = lightrec_malloc(state, MEM_FOR_IR, sizeof(*block));
1021         if (!block) {
1022                 pr_err("Unable to recompile block: Out of memory\n");
1023                 return NULL;
1024         }
1025
1026         list = lightrec_disassemble(state, code, &length);
1027         if (!list) {
1028                 lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
1029                 return NULL;
1030         }
1031
1032         block->pc = pc;
1033         block->_jit = NULL;
1034         block->function = NULL;
1035         block->opcode_list = list;
1036         block->code = code;
1037         block->next = NULL;
1038         block->flags = 0;
1039         block->code_size = 0;
1040 #if ENABLE_THREADED_COMPILER
1041         block->op_list_freed = (atomic_flag)ATOMIC_FLAG_INIT;
1042 #endif
1043         block->nb_ops = length / sizeof(u32);
1044
1045         lightrec_optimize(state, block);
1046
1047         length = block->nb_ops * sizeof(u32);
1048
1049         lightrec_register(MEM_FOR_MIPS_CODE, length);
1050
1051         if (ENABLE_DISASSEMBLER) {
1052                 pr_debug("Disassembled block at PC: 0x%08x\n", block->pc);
1053                 lightrec_print_disassembly(block, code);
1054         }
1055
1056         pr_debug("Block size: %hu opcodes\n", block->nb_ops);
1057
1058         /* If the first opcode is an 'impossible' branch, never compile the
1059          * block */
1060         if (should_emulate(block->opcode_list))
1061                 block->flags |= BLOCK_NEVER_COMPILE;
1062
1063         fully_tagged = lightrec_block_is_fully_tagged(block);
1064         if (fully_tagged)
1065                 block->flags |= BLOCK_FULLY_TAGGED;
1066
1067         if (OPT_REPLACE_MEMSET && (block->flags & BLOCK_IS_MEMSET))
1068                 state->code_lut[lut_offset(pc)] = state->memset_func;
1069
1070         block->hash = lightrec_calculate_block_hash(block);
1071
1072         pr_debug("Recompile count: %u\n", state->nb_precompile++);
1073
1074         return block;
1075 }
1076
1077 static bool lightrec_block_is_fully_tagged(const struct block *block)
1078 {
1079         const struct opcode *op;
1080         unsigned int i;
1081
1082         for (i = 0; i < block->nb_ops; i++) {
1083                 op = &block->opcode_list[i];
1084
1085                 /* Verify that all load/stores of the opcode list
1086                  * Check all loads/stores of the opcode list and mark the
1087                  * block as fully compiled if they all have been tagged. */
1088                 switch (op->c.i.op) {
1089                 case OP_LB:
1090                 case OP_LH:
1091                 case OP_LWL:
1092                 case OP_LW:
1093                 case OP_LBU:
1094                 case OP_LHU:
1095                 case OP_LWR:
1096                 case OP_SB:
1097                 case OP_SH:
1098                 case OP_SWL:
1099                 case OP_SW:
1100                 case OP_SWR:
1101                 case OP_LWC2:
1102                 case OP_SWC2:
1103                         if (!(op->flags & (LIGHTREC_DIRECT_IO |
1104                                            LIGHTREC_HW_IO)))
1105                                 return false;
1106                 default: /* fall-through */
1107                         continue;
1108                 }
1109         }
1110
1111         return true;
1112 }
1113
1114 static void lightrec_reap_block(struct lightrec_state *state, void *data)
1115 {
1116         struct block *block = data;
1117
1118         pr_debug("Reap dead block at PC 0x%08x\n", block->pc);
1119         lightrec_unregister_block(state->block_cache, block);
1120         lightrec_free_block(state, block);
1121 }
1122
1123 static void lightrec_reap_jit(struct lightrec_state *state, void *data)
1124 {
1125         _jit_destroy_state(data);
1126 }
1127
1128 int lightrec_compile_block(struct lightrec_cstate *cstate,
1129                            struct block *block)
1130 {
1131         struct lightrec_state *state = cstate->state;
1132         struct lightrec_branch_target *target;
1133         bool op_list_freed = false, fully_tagged = false;
1134         struct block *block2;
1135         struct opcode *elm;
1136         jit_state_t *_jit, *oldjit;
1137         jit_node_t *start_of_block;
1138         bool skip_next = false;
1139         jit_word_t code_size;
1140         unsigned int i, j;
1141         u32 offset;
1142
1143         fully_tagged = lightrec_block_is_fully_tagged(block);
1144         if (fully_tagged)
1145                 block->flags |= BLOCK_FULLY_TAGGED;
1146
1147         _jit = jit_new_state();
1148         if (!_jit)
1149                 return -ENOMEM;
1150
1151         oldjit = block->_jit;
1152         block->_jit = _jit;
1153
1154         lightrec_regcache_reset(cstate->reg_cache);
1155         cstate->cycles = 0;
1156         cstate->nb_branches = 0;
1157         cstate->nb_local_branches = 0;
1158         cstate->nb_targets = 0;
1159
1160         jit_prolog();
1161         jit_tramp(256);
1162
1163         start_of_block = jit_label();
1164
1165         for (i = 0; i < block->nb_ops; i++) {
1166                 elm = &block->opcode_list[i];
1167
1168                 if (skip_next) {
1169                         skip_next = false;
1170                         continue;
1171                 }
1172
1173                 cstate->cycles += lightrec_cycles_of_opcode(elm->c);
1174
1175                 if (should_emulate(elm)) {
1176                         pr_debug("Branch at offset 0x%x will be emulated\n",
1177                                  i << 2);
1178
1179                         lightrec_emit_eob(cstate, block, i, false);
1180                         skip_next = !(elm->flags & LIGHTREC_NO_DS);
1181                 } else {
1182                         lightrec_rec_opcode(cstate, block, i);
1183                         skip_next = has_delay_slot(elm->c) &&
1184                                 !(elm->flags & LIGHTREC_NO_DS);
1185 #if _WIN32
1186                         /* FIXME: GNU Lightning on Windows seems to use our
1187                          * mapped registers as temporaries. Until the actual bug
1188                          * is found and fixed, unconditionally mark our
1189                          * registers as live here. */
1190                         lightrec_regcache_mark_live(cstate->reg_cache, _jit);
1191 #endif
1192                 }
1193         }
1194
1195         for (i = 0; i < cstate->nb_branches; i++)
1196                 jit_patch(cstate->branches[i]);
1197
1198         for (i = 0; i < cstate->nb_local_branches; i++) {
1199                 struct lightrec_branch *branch = &cstate->local_branches[i];
1200
1201                 pr_debug("Patch local branch to offset 0x%x\n",
1202                          branch->target << 2);
1203
1204                 if (branch->target == 0) {
1205                         jit_patch_at(branch->branch, start_of_block);
1206                         continue;
1207                 }
1208
1209                 for (j = 0; j < cstate->nb_targets; j++) {
1210                         if (cstate->targets[j].offset == branch->target) {
1211                                 jit_patch_at(branch->branch,
1212                                              cstate->targets[j].label);
1213                                 break;
1214                         }
1215                 }
1216
1217                 if (j == cstate->nb_targets)
1218                         pr_err("Unable to find branch target\n");
1219         }
1220
1221         jit_ldxi(JIT_R0, LIGHTREC_REG_STATE,
1222                  offsetof(struct lightrec_state, eob_wrapper_func));
1223
1224         jit_jmpr(JIT_R0);
1225
1226         jit_ret();
1227         jit_epilog();
1228
1229         block->function = jit_emit();
1230         block->flags &= ~BLOCK_SHOULD_RECOMPILE;
1231
1232         /* Add compiled function to the LUT */
1233         state->code_lut[lut_offset(block->pc)] = block->function;
1234
1235         if (ENABLE_THREADED_COMPILER) {
1236                 /* Since we might try to reap the same block multiple times,
1237                  * we need the reaper to wait until everything has been
1238                  * submitted, so that the duplicate entries can be dropped. */
1239                 lightrec_reaper_pause(state->reaper);
1240         }
1241
1242         /* Detect old blocks that have been covered by the new one */
1243         for (i = 0; i < cstate->nb_targets; i++) {
1244                 target = &cstate->targets[i];
1245
1246                 if (!target->offset)
1247                         continue;
1248
1249                 offset = block->pc + target->offset * sizeof(u32);
1250                 block2 = lightrec_find_block(state->block_cache, offset);
1251                 if (block2) {
1252                         /* No need to check if block2 is compilable - it must
1253                          * be, otherwise block wouldn't be compilable either */
1254
1255                         /* Set the "block dead" flag to prevent the dynarec from
1256                          * recompiling this block */
1257                         block2->flags |= BLOCK_IS_DEAD;
1258
1259                         /* If block2 was pending for compilation, cancel it.
1260                          * If it's being compiled right now, wait until it
1261                          * finishes. */
1262                         if (ENABLE_THREADED_COMPILER)
1263                                 lightrec_recompiler_remove(state->rec, block2);
1264
1265                         /* We know from now on that block2 isn't going to be
1266                          * compiled. We can override the LUT entry with our
1267                          * new block's entry point. */
1268                         offset = lut_offset(block->pc) + target->offset;
1269                         state->code_lut[offset] = jit_address(target->label);
1270
1271                         pr_debug("Reap block 0x%08x as it's covered by block "
1272                                  "0x%08x\n", block2->pc, block->pc);
1273
1274                         /* Finally, reap the block. */
1275                         if (ENABLE_THREADED_COMPILER) {
1276                                 lightrec_reaper_add(state->reaper,
1277                                                     lightrec_reap_block,
1278                                                     block2);
1279                         } else {
1280                                 lightrec_unregister_block(state->block_cache, block2);
1281                                 lightrec_free_block(state, block2);
1282                         }
1283                 }
1284         }
1285
1286         if (ENABLE_THREADED_COMPILER)
1287                 lightrec_reaper_continue(state->reaper);
1288
1289         jit_get_code(&code_size);
1290         lightrec_register(MEM_FOR_CODE, code_size);
1291
1292         block->code_size = code_size;
1293
1294         if (ENABLE_DISASSEMBLER) {
1295                 pr_debug("Compiling block at PC: 0x%08x\n", block->pc);
1296                 jit_disassemble();
1297         }
1298
1299         jit_clear_state();
1300
1301 #if ENABLE_THREADED_COMPILER
1302         if (fully_tagged)
1303                 op_list_freed = atomic_flag_test_and_set(&block->op_list_freed);
1304 #endif
1305         if (fully_tagged && !op_list_freed) {
1306                 pr_debug("Block PC 0x%08x is fully tagged"
1307                          " - free opcode list\n", block->pc);
1308                 lightrec_free_opcode_list(state, block);
1309                 block->opcode_list = NULL;
1310         }
1311
1312         if (oldjit) {
1313                 pr_debug("Block 0x%08x recompiled, reaping old jit context.\n",
1314                          block->pc);
1315
1316                 if (ENABLE_THREADED_COMPILER)
1317                         lightrec_reaper_add(state->reaper,
1318                                             lightrec_reap_jit, oldjit);
1319                 else
1320                         _jit_destroy_state(oldjit);
1321         }
1322
1323         return 0;
1324 }
1325
1326 static void lightrec_print_info(struct lightrec_state *state)
1327 {
1328         if ((state->current_cycle & ~0xfffffff) != state->old_cycle_counter) {
1329                 pr_info("Lightrec RAM usage: IR %u KiB, CODE %u KiB, "
1330                         "MIPS %u KiB, TOTAL %u KiB, avg. IPI %f\n",
1331                         lightrec_get_mem_usage(MEM_FOR_IR) / 1024,
1332                         lightrec_get_mem_usage(MEM_FOR_CODE) / 1024,
1333                         lightrec_get_mem_usage(MEM_FOR_MIPS_CODE) / 1024,
1334                         lightrec_get_total_mem_usage() / 1024,
1335                        lightrec_get_average_ipi());
1336                 state->old_cycle_counter = state->current_cycle & ~0xfffffff;
1337         }
1338 }
1339
1340 u32 lightrec_execute(struct lightrec_state *state, u32 pc, u32 target_cycle)
1341 {
1342         s32 (*func)(void *, s32) = (void *)state->dispatcher->function;
1343         void *block_trace;
1344         s32 cycles_delta;
1345
1346         state->exit_flags = LIGHTREC_EXIT_NORMAL;
1347
1348         /* Handle the cycle counter overflowing */
1349         if (unlikely(target_cycle < state->current_cycle))
1350                 target_cycle = UINT_MAX;
1351
1352         state->target_cycle = target_cycle;
1353         state->next_pc = pc;
1354
1355         block_trace = get_next_block_func(state, pc);
1356         if (block_trace) {
1357                 cycles_delta = state->target_cycle - state->current_cycle;
1358
1359                 cycles_delta = (*func)(block_trace, cycles_delta);
1360
1361                 state->current_cycle = state->target_cycle - cycles_delta;
1362         }
1363
1364         if (ENABLE_THREADED_COMPILER)
1365                 lightrec_reaper_reap(state->reaper);
1366
1367         if (LOG_LEVEL >= INFO_L)
1368                 lightrec_print_info(state);
1369
1370         return state->next_pc;
1371 }
1372
1373 u32 lightrec_execute_one(struct lightrec_state *state, u32 pc)
1374 {
1375         return lightrec_execute(state, pc, state->current_cycle);
1376 }
1377
1378 u32 lightrec_run_interpreter(struct lightrec_state *state, u32 pc)
1379 {
1380         struct block *block = lightrec_get_block(state, pc);
1381         if (!block)
1382                 return 0;
1383
1384         state->exit_flags = LIGHTREC_EXIT_NORMAL;
1385
1386         pc = lightrec_emulate_block(state, block, pc);
1387
1388         if (LOG_LEVEL >= INFO_L)
1389                 lightrec_print_info(state);
1390
1391         return pc;
1392 }
1393
1394 void lightrec_free_block(struct lightrec_state *state, struct block *block)
1395 {
1396         lightrec_unregister(MEM_FOR_MIPS_CODE, block->nb_ops * sizeof(u32));
1397         if (block->opcode_list)
1398                 lightrec_free_opcode_list(state, block);
1399         if (block->_jit)
1400                 _jit_destroy_state(block->_jit);
1401         lightrec_unregister(MEM_FOR_CODE, block->code_size);
1402         lightrec_free(state, MEM_FOR_IR, sizeof(*block), block);
1403 }
1404
1405 struct lightrec_cstate * lightrec_create_cstate(struct lightrec_state *state)
1406 {
1407         struct lightrec_cstate *cstate;
1408
1409         cstate = lightrec_malloc(state, MEM_FOR_LIGHTREC, sizeof(*cstate));
1410         if (!cstate)
1411                 return NULL;
1412
1413         cstate->reg_cache = lightrec_regcache_init(state);
1414         if (!cstate->reg_cache) {
1415                 lightrec_free(state, MEM_FOR_LIGHTREC, sizeof(*cstate), cstate);
1416                 return NULL;
1417         }
1418
1419         cstate->state = state;
1420
1421         return cstate;
1422 }
1423
1424 void lightrec_free_cstate(struct lightrec_cstate *cstate)
1425 {
1426         lightrec_free_regcache(cstate->reg_cache);
1427         lightrec_free(cstate->state, MEM_FOR_LIGHTREC, sizeof(*cstate), cstate);
1428 }
1429
1430 struct lightrec_state * lightrec_init(char *argv0,
1431                                       const struct lightrec_mem_map *map,
1432                                       size_t nb,
1433                                       const struct lightrec_ops *ops)
1434 {
1435         struct lightrec_state *state;
1436
1437         /* Sanity-check ops */
1438         if (!ops || !ops->cop2_op || !ops->enable_ram) {
1439                 pr_err("Missing callbacks in lightrec_ops structure\n");
1440                 return NULL;
1441         }
1442
1443         init_jit(argv0);
1444
1445         state = calloc(1, sizeof(*state) +
1446                        sizeof(*state->code_lut) * CODE_LUT_SIZE);
1447         if (!state)
1448                 goto err_finish_jit;
1449
1450         lightrec_register(MEM_FOR_LIGHTREC, sizeof(*state) +
1451                           sizeof(*state->code_lut) * CODE_LUT_SIZE);
1452
1453 #if ENABLE_TINYMM
1454         state->tinymm = tinymm_init(malloc, free, 4096);
1455         if (!state->tinymm)
1456                 goto err_free_state;
1457 #endif
1458
1459         state->block_cache = lightrec_blockcache_init(state);
1460         if (!state->block_cache)
1461                 goto err_free_tinymm;
1462
1463         if (ENABLE_THREADED_COMPILER) {
1464                 state->rec = lightrec_recompiler_init(state);
1465                 if (!state->rec)
1466                         goto err_free_block_cache;
1467
1468                 state->reaper = lightrec_reaper_init(state);
1469                 if (!state->reaper)
1470                         goto err_free_recompiler;
1471         } else {
1472                 state->cstate = lightrec_create_cstate(state);
1473                 if (!state->cstate)
1474                         goto err_free_block_cache;
1475         }
1476
1477         state->nb_maps = nb;
1478         state->maps = map;
1479
1480         memcpy(&state->ops, ops, sizeof(*ops));
1481
1482         state->dispatcher = generate_dispatcher(state);
1483         if (!state->dispatcher)
1484                 goto err_free_reaper;
1485
1486         state->c_wrapper_block = generate_wrapper(state);
1487         if (!state->c_wrapper_block)
1488                 goto err_free_dispatcher;
1489
1490         state->c_wrapper = state->c_wrapper_block->function;
1491
1492         state->c_wrappers[C_WRAPPER_RW] = lightrec_rw_cb;
1493         state->c_wrappers[C_WRAPPER_RW_GENERIC] = lightrec_rw_generic_cb;
1494         state->c_wrappers[C_WRAPPER_MFC] = lightrec_mfc_cb;
1495         state->c_wrappers[C_WRAPPER_MTC] = lightrec_mtc_cb;
1496         state->c_wrappers[C_WRAPPER_CP] = lightrec_cp;
1497         state->c_wrappers[C_WRAPPER_SYSCALL] = lightrec_syscall_cb;
1498         state->c_wrappers[C_WRAPPER_BREAK] = lightrec_break_cb;
1499
1500         map = &state->maps[PSX_MAP_BIOS];
1501         state->offset_bios = (uintptr_t)map->address - map->pc;
1502
1503         map = &state->maps[PSX_MAP_SCRATCH_PAD];
1504         state->offset_scratch = (uintptr_t)map->address - map->pc;
1505
1506         map = &state->maps[PSX_MAP_KERNEL_USER_RAM];
1507         state->offset_ram = (uintptr_t)map->address - map->pc;
1508
1509         if (state->maps[PSX_MAP_MIRROR1].address == map->address + 0x200000 &&
1510             state->maps[PSX_MAP_MIRROR2].address == map->address + 0x400000 &&
1511             state->maps[PSX_MAP_MIRROR3].address == map->address + 0x600000)
1512                 state->mirrors_mapped = true;
1513
1514         if (state->offset_bios == 0 &&
1515             state->offset_scratch == 0 &&
1516             state->offset_ram == 0 &&
1517             state->mirrors_mapped) {
1518                 pr_info("Memory map is perfect. Emitted code will be best.\n");
1519         } else {
1520                 pr_info("Memory map is sub-par. Emitted code will be slow.\n");
1521         }
1522
1523         return state;
1524
1525 err_free_dispatcher:
1526         lightrec_free_block(state, state->dispatcher);
1527 err_free_reaper:
1528         if (ENABLE_THREADED_COMPILER)
1529                 lightrec_reaper_destroy(state->reaper);
1530 err_free_recompiler:
1531         if (ENABLE_THREADED_COMPILER)
1532                 lightrec_free_recompiler(state->rec);
1533         else
1534                 lightrec_free_cstate(state->cstate);
1535 err_free_block_cache:
1536         lightrec_free_block_cache(state->block_cache);
1537 err_free_tinymm:
1538 #if ENABLE_TINYMM
1539         tinymm_shutdown(state->tinymm);
1540 err_free_state:
1541 #endif
1542         lightrec_unregister(MEM_FOR_LIGHTREC, sizeof(*state) +
1543                             sizeof(*state->code_lut) * CODE_LUT_SIZE);
1544         free(state);
1545 err_finish_jit:
1546         finish_jit();
1547         return NULL;
1548 }
1549
1550 void lightrec_destroy(struct lightrec_state *state)
1551 {
1552         /* Force a print info on destroy*/
1553         state->current_cycle = ~state->current_cycle;
1554         lightrec_print_info(state);
1555
1556         if (ENABLE_THREADED_COMPILER) {
1557                 lightrec_free_recompiler(state->rec);
1558                 lightrec_reaper_destroy(state->reaper);
1559         } else {
1560                 lightrec_free_cstate(state->cstate);
1561         }
1562
1563         lightrec_free_block_cache(state->block_cache);
1564         lightrec_free_block(state, state->dispatcher);
1565         lightrec_free_block(state, state->c_wrapper_block);
1566         finish_jit();
1567
1568 #if ENABLE_TINYMM
1569         tinymm_shutdown(state->tinymm);
1570 #endif
1571         lightrec_unregister(MEM_FOR_LIGHTREC, sizeof(*state) +
1572                             sizeof(*state->code_lut) * CODE_LUT_SIZE);
1573         free(state);
1574 }
1575
1576 void lightrec_invalidate(struct lightrec_state *state, u32 addr, u32 len)
1577 {
1578         u32 kaddr = kunseg(addr & ~0x3);
1579         const struct lightrec_mem_map *map = lightrec_get_map(state, NULL, kaddr);
1580
1581         if (map) {
1582                 if (map != &state->maps[PSX_MAP_KERNEL_USER_RAM])
1583                         return;
1584
1585                 /* Handle mirrors */
1586                 kaddr &= (state->maps[PSX_MAP_KERNEL_USER_RAM].length - 1);
1587
1588                 lightrec_invalidate_map(state, map, kaddr, len);
1589         }
1590 }
1591
1592 void lightrec_invalidate_all(struct lightrec_state *state)
1593 {
1594         memset(state->code_lut, 0, sizeof(*state->code_lut) * CODE_LUT_SIZE);
1595 }
1596
1597 void lightrec_set_invalidate_mode(struct lightrec_state *state, bool dma_only)
1598 {
1599         if (state->invalidate_from_dma_only != dma_only)
1600                 lightrec_invalidate_all(state);
1601
1602         state->invalidate_from_dma_only = dma_only;
1603 }
1604
1605 void lightrec_set_exit_flags(struct lightrec_state *state, u32 flags)
1606 {
1607         if (flags != LIGHTREC_EXIT_NORMAL) {
1608                 state->exit_flags |= flags;
1609                 state->target_cycle = state->current_cycle;
1610         }
1611 }
1612
1613 u32 lightrec_exit_flags(struct lightrec_state *state)
1614 {
1615         return state->exit_flags;
1616 }
1617
1618 u32 lightrec_current_cycle_count(const struct lightrec_state *state)
1619 {
1620         return state->current_cycle;
1621 }
1622
1623 void lightrec_reset_cycle_count(struct lightrec_state *state, u32 cycles)
1624 {
1625         state->current_cycle = cycles;
1626
1627         if (state->target_cycle < cycles)
1628                 state->target_cycle = cycles;
1629 }
1630
1631 void lightrec_set_target_cycle_count(struct lightrec_state *state, u32 cycles)
1632 {
1633         if (state->exit_flags == LIGHTREC_EXIT_NORMAL) {
1634                 if (cycles < state->current_cycle)
1635                         cycles = state->current_cycle;
1636
1637                 state->target_cycle = cycles;
1638         }
1639 }
1640
1641 struct lightrec_registers * lightrec_get_registers(struct lightrec_state *state)
1642 {
1643         return &state->regs;
1644 }