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