[mono-threads] Fix win32 to posix priority conversion
[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 static int
44 win32_priority_to_posix_priority (MonoThreadPriority priority, int policy)
45 {
46         g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
47         g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
48         g_assert (MONO_THREAD_PRIORITY_LOWEST < MONO_THREAD_PRIORITY_HIGHEST);
49
50 /* Necessary to get valid priority range */
51 #ifdef _POSIX_PRIORITY_SCHEDULING
52         int max, min;
53
54         min = sched_get_priority_min (policy);
55         max = sched_get_priority_max (policy);
56
57         if (max > 0 && min >= 0 && max > min) {
58                 double srange, drange, sposition, dposition;
59                 srange = MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST;
60                 drange = max - min;
61                 sposition = priority - MONO_THREAD_PRIORITY_LOWEST;
62                 dposition = (sposition / srange) * drange;
63                 return (int)(dposition + min);
64         }
65 #endif
66
67         switch (policy) {
68         case SCHED_FIFO:
69         case SCHED_RR:
70                 return 50;
71 #ifdef SCHED_BATCH
72         case SCHED_BATCH:
73 #endif
74         case SCHED_OTHER:
75                 return 0;
76         default:
77                 return -1;
78         }
79 }
80
81 void
82 mono_threads_platform_register (MonoThreadInfo *info)
83 {
84         gpointer thread_handle;
85
86         info->owned_mutexes = g_ptr_array_new ();
87         info->priority = MONO_THREAD_PRIORITY_NORMAL;
88
89         thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, NULL);
90         if (thread_handle == INVALID_HANDLE_VALUE)
91                 g_error ("%s: failed to create handle", __func__);
92
93         /* We need to keep the handle alive, as long as the corresponding managed
94          * thread object is alive. The handle is going to be unref when calling
95          * the finalizer on the MonoThreadInternal object */
96         mono_w32handle_ref (thread_handle);
97
98         g_assert (!info->handle);
99         info->handle = thread_handle;
100 }
101
102 int
103 mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
104 {
105         pthread_attr_t attr;
106         pthread_t thread;
107         gint res;
108
109         res = pthread_attr_init (&attr);
110         g_assert (!res);
111
112 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
113         if (stack_size == 0) {
114 #if HAVE_VALGRIND_MEMCHECK_H
115                 if (RUNNING_ON_VALGRIND)
116                         stack_size = 1 << 20;
117                 else
118                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
119 #else
120                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
121 #endif
122         }
123
124 #ifdef PTHREAD_STACK_MIN
125         if (stack_size < PTHREAD_STACK_MIN)
126                 stack_size = PTHREAD_STACK_MIN;
127 #endif
128
129         res = pthread_attr_setstacksize (&attr, stack_size);
130         g_assert (!res);
131 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
132
133         /* Actually start the thread */
134         res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
135         if (res)
136                 return -1;
137
138         if (out_tid)
139                 *out_tid = thread;
140
141         return 0;
142 }
143
144 gboolean
145 mono_threads_platform_yield (void)
146 {
147         return sched_yield () == 0;
148 }
149
150 void
151 mono_threads_platform_exit (int exit_code)
152 {
153 #if defined(__native_client__)
154         nacl_shutdown_gc_thread();
155 #endif
156
157         mono_thread_info_detach ();
158
159         pthread_exit (NULL);
160 }
161
162 void
163 mono_threads_platform_unregister (MonoThreadInfo *info)
164 {
165         mono_threads_platform_set_exited (info);
166 }
167
168 int
169 mono_threads_get_max_stack_size (void)
170 {
171         struct rlimit lim;
172
173         /* If getrlimit fails, we don't enforce any limits. */
174         if (getrlimit (RLIMIT_STACK, &lim))
175                 return INT_MAX;
176         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
177         if (lim.rlim_max > (rlim_t)INT_MAX)
178                 return INT_MAX;
179         return (int)lim.rlim_max;
180 }
181
182 HANDLE
183 mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
184 {
185         mono_w32handle_ref (handle);
186
187         return handle;
188 }
189
190 void
191 mono_threads_platform_close_thread_handle (HANDLE handle)
192 {
193         mono_w32handle_unref (handle);
194 }
195
196 int
197 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
198 {
199         THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
200 #ifdef USE_TKILL_ON_ANDROID
201         int result, old_errno = errno;
202         result = tkill (info->native_handle, signum);
203         if (result < 0) {
204                 result = errno;
205                 errno = old_errno;
206         }
207         return result;
208 #elif defined(__native_client__)
209         /* Workaround pthread_kill abort() in NaCl glibc. */
210         return 0;
211 #elif !defined(HAVE_PTHREAD_KILL)
212         g_error ("pthread_kill() is not supported by this platform");
213 #else
214         return pthread_kill (mono_thread_info_get_tid (info), signum);
215 #endif
216 }
217
218 MonoNativeThreadId
219 mono_native_thread_id_get (void)
220 {
221         return pthread_self ();
222 }
223
224 gboolean
225 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
226 {
227         return pthread_equal (id1, id2);
228 }
229
230 /*
231  * mono_native_thread_create:
232  *
233  *   Low level thread creation function without any GC wrappers.
234  */
235 gboolean
236 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
237 {
238         return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
239 }
240
241 void
242 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
243 {
244 #ifdef __MACH__
245         /*
246          * We can't set the thread name for other threads, but we can at least make
247          * it work for threads that try to change their own name.
248          */
249         if (tid != mono_native_thread_id_get ())
250                 return;
251
252         if (!name) {
253                 pthread_setname_np ("");
254         } else {
255                 char n [63];
256
257                 strncpy (n, name, 63);
258                 n [62] = '\0';
259                 pthread_setname_np (n);
260         }
261 #elif defined (__NetBSD__)
262         if (!name) {
263                 pthread_setname_np (tid, "%s", (void*)"");
264         } else {
265                 char n [PTHREAD_MAX_NAMELEN_NP];
266
267                 strncpy (n, name, PTHREAD_MAX_NAMELEN_NP);
268                 n [PTHREAD_MAX_NAMELEN_NP - 1] = '\0';
269                 pthread_setname_np (tid, "%s", (void*)n);
270         }
271 #elif defined (HAVE_PTHREAD_SETNAME_NP)
272         if (!name) {
273                 pthread_setname_np (tid, "");
274         } else {
275                 char n [16];
276
277                 strncpy (n, name, 16);
278                 n [15] = '\0';
279                 pthread_setname_np (tid, n);
280         }
281 #endif
282 }
283
284 void
285 mono_threads_platform_set_exited (MonoThreadInfo *info)
286 {
287         gpointer mutex_handle;
288         int i, thr_ret;
289         pid_t pid;
290         pthread_t tid;
291
292         g_assert (info->handle);
293
294         if (mono_w32handle_issignalled (info->handle))
295                 g_error ("%s: handle %p thread %p has already exited, it's handle is signalled", __func__, info->handle, mono_thread_info_get_tid (info));
296         if (mono_w32handle_get_type (info->handle) == MONO_W32HANDLE_UNUSED)
297                 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));
298
299         pid = wapi_getpid ();
300         tid = pthread_self ();
301
302         for (i = 0; i < info->owned_mutexes->len; i++) {
303                 mutex_handle = g_ptr_array_index (info->owned_mutexes, i);
304                 wapi_mutex_abandon (mutex_handle, pid, tid);
305                 mono_thread_info_disown_mutex (info, mutex_handle);
306         }
307
308         g_ptr_array_free (info->owned_mutexes, TRUE);
309
310         thr_ret = mono_w32handle_lock_handle (info->handle);
311         g_assert (thr_ret == 0);
312
313         mono_w32handle_set_signal_state (info->handle, TRUE, TRUE);
314
315         thr_ret = mono_w32handle_unlock_handle (info->handle);
316         g_assert (thr_ret == 0);
317
318         /* The thread is no longer active, so unref it */
319         mono_w32handle_unref (info->handle);
320
321         info->handle = NULL;
322 }
323
324 void
325 mono_threads_platform_describe (MonoThreadInfo *info, GString *text)
326 {
327         int i;
328
329         g_string_append_printf (text, "thread handle %p state : ", info->handle);
330
331         mono_thread_info_describe_interrupt_token (info, text);
332
333         g_string_append_printf (text, ", owns (");
334         for (i = 0; i < info->owned_mutexes->len; i++)
335                 g_string_append_printf (text, i > 0 ? ", %p" : "%p", g_ptr_array_index (info->owned_mutexes, i));
336         g_string_append_printf (text, ")");
337 }
338
339 void
340 mono_threads_platform_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
341 {
342         mono_w32handle_ref (mutex_handle);
343
344         g_ptr_array_add (info->owned_mutexes, mutex_handle);
345 }
346
347 void
348 mono_threads_platform_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
349 {
350         mono_w32handle_unref (mutex_handle);
351
352         g_ptr_array_remove (info->owned_mutexes, mutex_handle);
353 }
354
355 MonoThreadPriority
356 mono_threads_platform_get_priority (MonoThreadInfo *info)
357 {
358         return info->priority;
359 }
360
361 gboolean
362 mono_threads_platform_set_priority (MonoThreadInfo *info, MonoThreadPriority priority)
363 {
364         int policy, posix_priority;
365         struct sched_param param;
366         pthread_t tid;
367
368         tid = mono_thread_info_get_tid (info);
369
370         switch (pthread_getschedparam (tid, &policy, &param)) {
371         case 0:
372                 break;
373         case ESRCH:
374                 g_warning ("pthread_getschedparam: error looking up thread id %x", (gsize)tid);
375                 return FALSE;
376         default:
377                 return FALSE;
378         }
379
380         posix_priority =  win32_priority_to_posix_priority (priority, policy);
381         if (posix_priority < 0)
382                 return FALSE;
383
384         param.sched_priority = posix_priority;
385         switch (pthread_setschedparam (tid, policy, &param)) {
386         case 0:
387                 break;
388         case ESRCH:
389                 g_warning ("%s: pthread_setschedprio: error looking up thread id %x", __func__, (gsize)tid);
390                 return FALSE;
391         case ENOTSUP:
392                 g_warning ("%s: priority %d not supported", __func__, priority);
393                 return FALSE;
394         case EPERM:
395                 g_warning ("%s: permission denied", __func__);
396                 return FALSE;
397         default:
398                 return FALSE;
399         }
400
401         info->priority = priority;
402         return TRUE;
403
404 }
405
406 static const gchar* thread_typename (void)
407 {
408         return "Thread";
409 }
410
411 static gsize thread_typesize (void)
412 {
413         return 0;
414 }
415
416 static MonoW32HandleOps thread_ops = {
417         NULL,                           /* close */
418         NULL,                           /* signal */
419         NULL,                           /* own */
420         NULL,                           /* is_owned */
421         NULL,                           /* special_wait */
422         NULL,                           /* prewait */
423         NULL,                           /* details */
424         thread_typename,        /* typename */
425         thread_typesize,        /* typesize */
426 };
427
428 void
429 mono_threads_platform_init (void)
430 {
431         mono_w32handle_register_ops (MONO_W32HANDLE_THREAD, &thread_ops);
432
433         mono_w32handle_register_capabilities (MONO_W32HANDLE_THREAD, MONO_W32HANDLE_CAP_WAIT);
434 }
435
436 #endif /* defined(_POSIX_VERSION) || defined(__native_client__) */
437
438 #if defined(USE_POSIX_BACKEND)
439
440 gboolean
441 mono_threads_suspend_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
442 {
443         int sig = interrupt_kernel ? mono_threads_posix_get_abort_signal () :  mono_threads_posix_get_suspend_signal ();
444
445         if (!mono_threads_pthread_kill (info, sig)) {
446                 mono_threads_add_to_pending_operation_set (info);
447                 return TRUE;
448         }
449         return FALSE;
450 }
451
452 gboolean
453 mono_threads_suspend_check_suspend_result (MonoThreadInfo *info)
454 {
455         return info->suspend_can_continue;
456 }
457
458 /*
459 This begins async resume. This function must do the following:
460
461 - Install an async target if one was requested.
462 - Notify the target to resume.
463 */
464 gboolean
465 mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
466 {
467         mono_threads_add_to_pending_operation_set (info);
468         return mono_threads_pthread_kill (info, mono_threads_posix_get_restart_signal ()) == 0;
469 }
470
471 void
472 mono_threads_suspend_register (MonoThreadInfo *info)
473 {
474 #if defined (PLATFORM_ANDROID)
475         info->native_handle = gettid ();
476 #endif
477 }
478
479 void
480 mono_threads_suspend_free (MonoThreadInfo *info)
481 {
482 }
483
484 void
485 mono_threads_suspend_init (void)
486 {
487         mono_threads_posix_init_signals (MONO_THREADS_POSIX_INIT_SIGNALS_SUSPEND_RESTART);
488 }
489
490 #endif /* defined(USE_POSIX_BACKEND) */