63afa32ce5a11622ee62a305576fce308c3364eb
[pcsx_rearmed.git] / frontend / 3ds / pthread.h
1 /* Copyright  (C) 2010-2020 The RetroArch team
2  *
3  * ---------------------------------------------------------------------------------------
4  * The following license statement only applies to this file (gx_pthread.h).
5  * ---------------------------------------------------------------------------------------
6  *
7  * Permission is hereby granted, free of charge,
8  * to any person obtaining a copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
11  * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
16  * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  */
22
23 #ifndef _CTR_PTHREAD_WRAP_CTR_
24 #define _CTR_PTHREAD_WRAP_CTR_
25
26 #include <3ds/thread.h>
27 #include <3ds/services/apt.h>
28 #include "3ds_utils.h"
29
30 #include <sys/time.h>
31 #include <time.h>
32 #include <errno.h>
33
34 #define STACKSIZE (4 * 1024)
35 #define FALSE 0
36
37 #ifndef PTHREAD_SCOPE_PROCESS
38 /* An earlier version of devkitARM does not define the pthread types. Can remove in r54+. */
39
40 typedef Thread     pthread_t;
41 typedef LightLock  pthread_mutex_t;
42 typedef void*      pthread_mutexattr_t;
43 typedef int        pthread_attr_t;
44 typedef LightEvent pthread_cond_t;
45 typedef int        pthread_condattr_t;
46 #endif
47
48 #ifndef USE_CTRULIB_2
49 /* Backported CondVar API from libctru 2.0, and under its license:
50    https://github.com/devkitPro/libctru
51    Slightly modified for compatibility with older libctru. */
52
53 typedef s32 CondVar;
54
55 static inline Result syncArbitrateAddress(s32* addr, ArbitrationType type, s32 value)
56 {
57    return svcArbitrateAddress(__sync_get_arbiter(), (u32)addr, type, value, 0);
58 }
59
60 static inline Result syncArbitrateAddressWithTimeout(s32* addr, ArbitrationType type, s32 value, s64 timeout_ns)
61 {
62    return svcArbitrateAddress(__sync_get_arbiter(), (u32)addr, type, value, timeout_ns);
63 }
64
65 static inline void __dmb(void)
66 {
67         __asm__ __volatile__("mcr p15, 0, %[val], c7, c10, 5" :: [val] "r" (0) : "memory");
68 }
69
70 static inline void CondVar_BeginWait(CondVar* cv, LightLock* lock)
71 {
72         s32 val;
73         do
74                 val = __ldrex(cv) - 1;
75         while (__strex(cv, val));
76         LightLock_Unlock(lock);
77 }
78
79 static inline bool CondVar_EndWait(CondVar* cv, s32 num_threads)
80 {
81         bool hasWaiters;
82         s32 val;
83
84         do {
85                 val = __ldrex(cv);
86                 hasWaiters = val < 0;
87                 if (hasWaiters)
88                 {
89                         if (num_threads < 0)
90                                 val = 0;
91                         else if (val <= -num_threads)
92                                 val += num_threads;
93                         else
94                                 val = 0;
95                 }
96         } while (__strex(cv, val));
97
98         return hasWaiters;
99 }
100
101 static inline void CondVar_Init(CondVar* cv)
102 {
103         *cv = 0;
104 }
105
106 static inline void CondVar_Wait(CondVar* cv, LightLock* lock)
107 {
108         CondVar_BeginWait(cv, lock);
109         syncArbitrateAddress(cv, ARBITRATION_WAIT_IF_LESS_THAN, 0);
110         LightLock_Lock(lock);
111 }
112
113 static inline int CondVar_WaitTimeout(CondVar* cv, LightLock* lock, s64 timeout_ns)
114 {
115         CondVar_BeginWait(cv, lock);
116
117         bool timedOut = false;
118         Result rc = syncArbitrateAddressWithTimeout(cv, ARBITRATION_WAIT_IF_LESS_THAN_TIMEOUT, 0, timeout_ns);
119         if (R_DESCRIPTION(rc) == RD_TIMEOUT)
120         {
121                 timedOut = CondVar_EndWait(cv, 1);
122                 __dmb();
123         }
124
125         LightLock_Lock(lock);
126         return timedOut;
127 }
128
129 static inline void CondVar_WakeUp(CondVar* cv, s32 num_threads)
130 {
131         __dmb();
132         if (CondVar_EndWait(cv, num_threads))
133                 syncArbitrateAddress(cv, ARBITRATION_SIGNAL, num_threads);
134         else
135                 __dmb();
136 }
137
138 static inline void CondVar_Signal(CondVar* cv)
139 {
140         CondVar_WakeUp(cv, 1);
141 }
142
143 static inline void CondVar_Broadcast(CondVar* cv)
144 {
145         CondVar_WakeUp(cv, ARBITRATION_SIGNAL_ALL);
146 }
147 /* End libctru 2.0 backport */
148 #endif
149
150 /* libctru threads return void but pthreads return void pointer */
151 static bool mutex_inited = false;
152 static LightLock safe_double_thread_launch;
153 static void *(*start_routine_jump)(void*);
154
155 static void ctr_thread_launcher(void* data)
156 {
157         void *(*start_routine_jump_safe)(void*) = start_routine_jump;
158         LightLock_Unlock(&safe_double_thread_launch);
159         start_routine_jump_safe(data);
160 }
161
162 static inline int pthread_create(pthread_t *thread,
163       const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg)
164 {
165    s32 prio = 0;
166    Thread new_ctr_thread;
167    int procnum = -2; // use default cpu
168    bool isNew3DS;
169
170    APT_CheckNew3DS(&isNew3DS);
171
172    if (isNew3DS)
173       procnum = 2;
174
175    if (!mutex_inited)
176    {
177       LightLock_Init(&safe_double_thread_launch);
178       mutex_inited = true;
179    }
180
181    /*Must wait if attempting to launch 2 threads at once to prevent corruption of function pointer*/
182    while (LightLock_TryLock(&safe_double_thread_launch) != 0);
183
184    svcGetThreadPriority(&prio, CUR_THREAD_HANDLE);
185
186    start_routine_jump = start_routine;
187    new_ctr_thread     = threadCreate(ctr_thread_launcher, arg, STACKSIZE, prio - 1, procnum, FALSE);
188
189    if (!new_ctr_thread)
190    {
191       LightLock_Unlock(&safe_double_thread_launch);
192       return EAGAIN;
193    }
194
195    *thread = (pthread_t)new_ctr_thread;
196    return 0;
197 }
198
199 static inline pthread_t pthread_self(void)
200 {
201    return (pthread_t)threadGetCurrent();
202 }
203
204 static inline int pthread_mutex_init(pthread_mutex_t *mutex,
205       const pthread_mutexattr_t *attr)
206 {
207    LightLock_Init((LightLock *)mutex);
208    return 0;
209 }
210
211 static inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
212 {
213    /*Nothing to destroy*/
214    return 0;
215 }
216
217 static inline int pthread_mutex_lock(pthread_mutex_t *mutex)
218 {
219    LightLock_Lock((LightLock *)mutex);
220    return 0;
221 }
222
223 static inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
224 {
225    LightLock_Unlock((LightLock *)mutex);
226    return 0;
227 }
228
229 static inline void pthread_exit(void *retval)
230 {
231    /*Yes the pointer to int cast is not ideal*/
232    /*threadExit((int)retval);*/
233    (void)retval;
234
235    threadExit(0);
236 }
237
238 static inline int pthread_detach(pthread_t thread)
239 {
240    threadDetach((Thread)thread);
241    return 0;
242 }
243
244 static inline int pthread_join(pthread_t thread, void **retval)
245 {
246    /*retval is ignored*/
247    if(threadJoin((Thread)thread, INT64_MAX))
248       return -1;
249
250    threadFree((Thread)thread);
251
252    return 0;
253 }
254
255 static inline int pthread_mutex_trylock(pthread_mutex_t *mutex)
256 {
257    return LightLock_TryLock((LightLock *)mutex);
258 }
259
260 static inline int pthread_cond_wait(pthread_cond_t *cond,
261       pthread_mutex_t *mutex)
262 {
263    CondVar_Wait((CondVar *)cond, (LightLock *)mutex);
264    return 0;
265 }
266
267 static inline int pthread_cond_timedwait(pthread_cond_t *cond,
268       pthread_mutex_t *mutex, const struct timespec *abstime)
269 {
270    struct timespec now = {0};
271    /* Missing clock_gettime*/
272    struct timeval tm;
273    int retval = 0;
274
275    gettimeofday(&tm, NULL);
276    now.tv_sec = tm.tv_sec;
277    now.tv_nsec = tm.tv_usec * 1000;
278    s64 timeout = (abstime->tv_sec - now.tv_sec) * 1000000000 + (abstime->tv_nsec - now.tv_nsec);
279
280    if (timeout < 0)
281    {
282       retval = ETIMEDOUT;
283    }
284    else if (CondVar_WaitTimeout((CondVar *)cond, (LightLock *)mutex, timeout))
285    {
286       retval = ETIMEDOUT;
287    }
288
289    return retval;
290 }
291
292 static inline int pthread_cond_init(pthread_cond_t *cond,
293       const pthread_condattr_t *attr)
294 {
295    CondVar_Init((CondVar *)cond);
296    return 0;
297 }
298
299 static inline int pthread_cond_signal(pthread_cond_t *cond)
300 {
301    CondVar_Signal((CondVar *)cond);
302    return 0;
303 }
304
305 static inline int pthread_cond_broadcast(pthread_cond_t *cond)
306 {
307    CondVar_Broadcast((CondVar *)cond);
308    return 0;
309 }
310
311 static inline int pthread_cond_destroy(pthread_cond_t *cond)
312 {
313    /*Nothing to destroy*/
314    return 0;
315 }
316
317 static inline int pthread_equal(pthread_t t1, pthread_t t2)
318 {
319         if (threadGetHandle((Thread)t1) == threadGetHandle((Thread)t2))
320                 return 1;
321         return 0;
322 }
323
324 #endif