[w32mutex] Move own/disown code to w32mutex-unix.c (#3599)
[mono.git] / mono / utils / mono-threads-posix.c
1 /*
2  * mono-threads-posix.c: Low-level threading, posix version
3  *
4  * Author:
5  *      Rodrigo Kumpera (kumpera@gmail.com)
6  *
7  * (C) 2011 Novell, Inc
8  */
9
10 #include <config.h>
11
12 /* For pthread_main_np, pthread_get_stackaddr_np and pthread_get_stacksize_np */
13 #if defined (__MACH__)
14 #define _DARWIN_C_SOURCE 1
15 #endif
16
17 #include <mono/utils/mono-threads.h>
18 #include <mono/utils/mono-threads-posix-signals.h>
19 #include <mono/utils/mono-coop-semaphore.h>
20 #include <mono/metadata/gc-internals.h>
21 #include <mono/utils/w32handle.h>
22
23 #include <errno.h>
24
25 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
26 #define USE_TKILL_ON_ANDROID 1
27 #endif
28
29 #ifdef USE_TKILL_ON_ANDROID
30 extern int tkill (pid_t tid, int signal);
31 #endif
32
33 #if defined(_POSIX_VERSION) || defined(__native_client__)
34
35 #include <pthread.h>
36
37 #include <sys/resource.h>
38
39 #if defined(__native_client__)
40 void nacl_shutdown_gc_thread(void);
41 #endif
42
43 void
44 mono_threads_platform_register (MonoThreadInfo *info)
45 {
46         gpointer thread_handle;
47
48         thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, NULL);
49         if (thread_handle == INVALID_HANDLE_VALUE)
50                 g_error ("%s: failed to create handle", __func__);
51
52         g_assert (!info->handle);
53         info->handle = thread_handle;
54 }
55
56 int
57 mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
58 {
59         pthread_attr_t attr;
60         pthread_t thread;
61         int policy;
62         struct sched_param param;
63         gint res;
64
65         res = pthread_attr_init (&attr);
66         g_assert (!res);
67
68 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
69         if (stack_size == 0) {
70 #if HAVE_VALGRIND_MEMCHECK_H
71                 if (RUNNING_ON_VALGRIND)
72                         stack_size = 1 << 20;
73                 else
74                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
75 #else
76                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
77 #endif
78         }
79
80 #ifdef PTHREAD_STACK_MIN
81         if (stack_size < PTHREAD_STACK_MIN)
82                 stack_size = PTHREAD_STACK_MIN;
83 #endif
84
85         res = pthread_attr_setstacksize (&attr, stack_size);
86         g_assert (!res);
87 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
88
89         memset (&param, 0, sizeof (param));
90
91         res = pthread_attr_getschedpolicy (&attr, &policy);
92         if (res != 0)
93                 g_error ("%s: pthread_attr_getschedpolicy failed, error: \"%s\" (%d)", g_strerror (res), res);
94
95 #ifdef _POSIX_PRIORITY_SCHEDULING
96         int max, min;
97
98         /* Necessary to get valid priority range */
99
100         min = sched_get_priority_min (policy);
101         max = sched_get_priority_max (policy);
102
103         if (max > 0 && min >= 0 && max > min)
104                 param.sched_priority = (max - min) / 2 + min;
105         else
106 #endif
107         {
108                 switch (policy) {
109                 case SCHED_FIFO:
110                 case SCHED_RR:
111                         param.sched_priority = 50;
112                         break;
113 #ifdef SCHED_BATCH
114                 case SCHED_BATCH:
115 #endif
116                 case SCHED_OTHER:
117                         param.sched_priority = 0;
118                         break;
119                 default:
120                         g_error ("%s: unknown policy %d", __func__, policy);
121                 }
122         }
123
124         res = pthread_attr_setschedparam (&attr, &param);
125         if (res != 0)
126                 g_error ("%s: pthread_attr_setschedparam failed, error: \"%s\" (%d)", g_strerror (res), res);
127
128         /* Actually start the thread */
129         res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
130         if (res)
131                 return -1;
132
133         if (out_tid)
134                 *out_tid = thread;
135
136         return 0;
137 }
138
139 gboolean
140 mono_threads_platform_yield (void)
141 {
142         return sched_yield () == 0;
143 }
144
145 void
146 mono_threads_platform_exit (int exit_code)
147 {
148 #if defined(__native_client__)
149         nacl_shutdown_gc_thread();
150 #endif
151
152         mono_thread_info_detach ();
153
154         pthread_exit (NULL);
155 }
156
157 void
158 mono_threads_platform_unregister (MonoThreadInfo *info)
159 {
160         mono_threads_platform_set_exited (info);
161 }
162
163 int
164 mono_threads_get_max_stack_size (void)
165 {
166         struct rlimit lim;
167
168         /* If getrlimit fails, we don't enforce any limits. */
169         if (getrlimit (RLIMIT_STACK, &lim))
170                 return INT_MAX;
171         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
172         if (lim.rlim_max > (rlim_t)INT_MAX)
173                 return INT_MAX;
174         return (int)lim.rlim_max;
175 }
176
177 gpointer
178 mono_threads_platform_duplicate_handle (MonoThreadInfo *info)
179 {
180         g_assert (info->handle);
181         mono_w32handle_ref (info->handle);
182         return info->handle;
183 }
184
185 HANDLE
186 mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
187 {
188         mono_w32handle_ref (handle);
189
190         return handle;
191 }
192
193 void
194 mono_threads_platform_close_thread_handle (HANDLE handle)
195 {
196         mono_w32handle_unref (handle);
197 }
198
199 int
200 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
201 {
202         THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
203 #ifdef USE_TKILL_ON_ANDROID
204         int result, old_errno = errno;
205         result = tkill (info->native_handle, signum);
206         if (result < 0) {
207                 result = errno;
208                 errno = old_errno;
209         }
210         return result;
211 #elif defined(__native_client__)
212         /* Workaround pthread_kill abort() in NaCl glibc. */
213         return 0;
214 #elif !defined(HAVE_PTHREAD_KILL)
215         g_error ("pthread_kill() is not supported by this platform");
216 #else
217         return pthread_kill (mono_thread_info_get_tid (info), signum);
218 #endif
219 }
220
221 MonoNativeThreadId
222 mono_native_thread_id_get (void)
223 {
224         return pthread_self ();
225 }
226
227 gboolean
228 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
229 {
230         return pthread_equal (id1, id2);
231 }
232
233 /*
234  * mono_native_thread_create:
235  *
236  *   Low level thread creation function without any GC wrappers.
237  */
238 gboolean
239 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
240 {
241         return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
242 }
243
244 void
245 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
246 {
247 #ifdef __MACH__
248         /*
249          * We can't set the thread name for other threads, but we can at least make
250          * it work for threads that try to change their own name.
251          */
252         if (tid != mono_native_thread_id_get ())
253                 return;
254
255         if (!name) {
256                 pthread_setname_np ("");
257         } else {
258                 char n [63];
259
260                 strncpy (n, name, 63);
261                 n [62] = '\0';
262                 pthread_setname_np (n);
263         }
264 #elif defined (__NetBSD__)
265         if (!name) {
266                 pthread_setname_np (tid, "%s", (void*)"");
267         } else {
268                 char n [PTHREAD_MAX_NAMELEN_NP];
269
270                 strncpy (n, name, PTHREAD_MAX_NAMELEN_NP);
271                 n [PTHREAD_MAX_NAMELEN_NP - 1] = '\0';
272                 pthread_setname_np (tid, "%s", (void*)n);
273         }
274 #elif defined (HAVE_PTHREAD_SETNAME_NP)
275         if (!name) {
276                 pthread_setname_np (tid, "");
277         } else {
278                 char n [16];
279
280                 strncpy (n, name, 16);
281                 n [15] = '\0';
282                 pthread_setname_np (tid, n);
283         }
284 #endif
285 }
286
287 void
288 mono_threads_platform_set_exited (MonoThreadInfo *info)
289 {
290         int thr_ret;
291
292         g_assert (info->handle);
293         if (mono_w32handle_issignalled (info->handle))
294                 g_error ("%s: handle %p thread %p has already exited, it's handle is signalled", __func__, info->handle, mono_thread_info_get_tid (info));
295         if (mono_w32handle_get_type (info->handle) == MONO_W32HANDLE_UNUSED)
296                 g_error ("%s: handle %p thread %p has already exited, it's handle type is 'unused'", __func__, info->handle, mono_thread_info_get_tid (info));
297
298         thr_ret = mono_w32handle_lock_handle (info->handle);
299         g_assert (thr_ret == 0);
300
301         mono_w32handle_set_signal_state (info->handle, TRUE, TRUE);
302
303         thr_ret = mono_w32handle_unlock_handle (info->handle);
304         g_assert (thr_ret == 0);
305
306         /* The thread is no longer active, so unref it */
307         mono_w32handle_unref (info->handle);
308
309         info->handle = NULL;
310 }
311
312 static const gchar* thread_typename (void)
313 {
314         return "Thread";
315 }
316
317 static gsize thread_typesize (void)
318 {
319         return 0;
320 }
321
322 static MonoW32HandleOps thread_ops = {
323         NULL,                           /* close */
324         NULL,                           /* signal */
325         NULL,                           /* own */
326         NULL,                           /* is_owned */
327         NULL,                           /* special_wait */
328         NULL,                           /* prewait */
329         NULL,                           /* details */
330         thread_typename,        /* typename */
331         thread_typesize,        /* typesize */
332 };
333
334 void
335 mono_threads_platform_init (void)
336 {
337         mono_w32handle_register_ops (MONO_W32HANDLE_THREAD, &thread_ops);
338
339         mono_w32handle_register_capabilities (MONO_W32HANDLE_THREAD, MONO_W32HANDLE_CAP_WAIT);
340 }
341
342 #endif /* defined(_POSIX_VERSION) || defined(__native_client__) */
343
344 #if defined(USE_POSIX_BACKEND)
345
346 gboolean
347 mono_threads_suspend_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
348 {
349         int sig = interrupt_kernel ? mono_threads_posix_get_abort_signal () :  mono_threads_posix_get_suspend_signal ();
350
351         if (!mono_threads_pthread_kill (info, sig)) {
352                 mono_threads_add_to_pending_operation_set (info);
353                 return TRUE;
354         }
355         return FALSE;
356 }
357
358 gboolean
359 mono_threads_suspend_check_suspend_result (MonoThreadInfo *info)
360 {
361         return info->suspend_can_continue;
362 }
363
364 /*
365 This begins async resume. This function must do the following:
366
367 - Install an async target if one was requested.
368 - Notify the target to resume.
369 */
370 gboolean
371 mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
372 {
373         mono_threads_add_to_pending_operation_set (info);
374         return mono_threads_pthread_kill (info, mono_threads_posix_get_restart_signal ()) == 0;
375 }
376
377 void
378 mono_threads_suspend_register (MonoThreadInfo *info)
379 {
380 #if defined (PLATFORM_ANDROID)
381         info->native_handle = gettid ();
382 #endif
383 }
384
385 void
386 mono_threads_suspend_free (MonoThreadInfo *info)
387 {
388 }
389
390 void
391 mono_threads_suspend_init (void)
392 {
393         mono_threads_posix_init_signals (MONO_THREADS_POSIX_INIT_SIGNALS_SUSPEND_RESTART);
394 }
395
396 #endif /* defined(USE_POSIX_BACKEND) */