Fix dynarec crashes on 3DS
[pcsx_rearmed.git] / frontend / 3ds / 3ds_utils.h
1 #ifndef _3DS_UTILS_H
2 #define _3DS_UTILS_H
3
4 #include <stdio.h>
5 #include <stdbool.h>
6
7 #define MEMOP_PROT      6
8 #define MEMOP_MAP       4
9 #define MEMOP_UNMAP     5
10
11 #define GET_VERSION_MAJOR(version)    ((version) >>24)
12
13 void* linearMemAlign(size_t size, size_t alignment);
14 void linearFree(void* mem);
15
16 int32_t svcDuplicateHandle(uint32_t* out, uint32_t original);
17 int32_t svcCloseHandle(uint32_t handle);
18 int32_t svcControlMemory(void* addr_out, void* addr0, void* addr1, uint32_t size, uint32_t op, uint32_t perm);
19 int32_t svcControlProcessMemory(uint32_t process, void* addr0, void* addr1, uint32_t size, uint32_t op, uint32_t perm);
20
21 int32_t threadCreate(void *(*entrypoint)(void*), void* arg, size_t stack_size, int32_t prio, int32_t affinity, bool detached);
22 int32_t threadJoin(int32_t thread, int64_t timeout_ns);
23 void threadFree(int32_t thread);
24 void threadExit(int32_t rc)  __attribute__((noreturn));
25
26 int32_t svcGetSystemInfo(int64_t* out, uint32_t type, int32_t param);
27 int32_t svcBackdoor(int32_t (*callback)(void));
28
29 #define DEBUG_HOLD() do{printf("%s@%s:%d.\n",__FUNCTION__, __FILE__, __LINE__);fflush(stdout);wait_for_input();}while(0)
30
31 void wait_for_input(void);
32
33 extern __attribute__((weak)) int  __ctr_svchax;
34
35 bool has_rosalina;
36
37 static void check_rosalina() {
38   int64_t version;
39   uint32_t major;
40
41   has_rosalina = false;
42
43   if (!svcGetSystemInfo(&version, 0x10000, 0)) {
44      major = GET_VERSION_MAJOR(version);
45
46      if (major >= 8)
47        has_rosalina = true;
48   }
49 }
50
51 void ctr_clear_cache(void);
52
53 typedef int32_t (*ctr_callback_type)(void);
54
55 static inline void ctr_invalidate_ICache_kernel(void)
56 {
57    __asm__ volatile(
58       "cpsid aif\n\t"
59       "mov r0, #0\n\t"
60       "mcr p15, 0, r0, c7, c5, 0\n\t");
61 }
62
63 static inline void ctr_flush_DCache_kernel(void)
64 {
65    __asm__ volatile(
66       "cpsid aif\n\t"
67       "mov r0, #0\n\t"
68       "mcr p15, 0, r0, c7, c10, 0\n\t");
69 }
70
71 static inline void ctr_invalidate_ICache(void)
72 {
73    svcBackdoor((ctr_callback_type)ctr_invalidate_ICache_kernel);
74 }
75
76 static inline void ctr_flush_DCache(void)
77 {
78    svcBackdoor((ctr_callback_type)ctr_flush_DCache_kernel);
79 }
80
81 static inline void ctr_flush_invalidate_cache(void)
82 {
83    if (has_rosalina) {
84       ctr_clear_cache();
85    } else {
86       ctr_flush_DCache();
87       ctr_invalidate_ICache();
88    }
89 }
90
91 #endif // _3DS_UTILS_H