summaryrefslogtreecommitdiff
path: root/3rdparty/plibsys/src/puthread-posix.c
blob: 90e14d57bd8831037b1c8f6fdc7298cb3898dda2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
/*
 * The MIT License
 *
 * Copyright (C) 2010-2019 Alexander Saprykin <saprykin.spb@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "pmem.h"
#include "patomic.h"
#include "puthread.h"
#include "puthread-private.h"

#ifdef P_OS_SCO
#  include "pmutex.h"
#endif

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <time.h>

/* On some OS like OpenBSD it must follow <pthread.h> */
#ifdef PLIBSYS_NEED_PTHREAD_NP_H
#  include <pthread_np.h>
#endif

#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
#  ifndef P_OS_VMS
#    include <sched.h>
#  endif
#endif

#ifdef PLIBSYS_HAS_PTHREAD_PRCTL
#  include <sys/prctl.h>
#  include <linux/prctl.h>
#endif

#ifdef P_OS_QNX6
#  include <sys/neutrino.h>
#endif

#ifdef P_OS_HAIKU
#  include <kernel/OS.h>
#endif

/* Some systems without native pthreads may lack some of the constants,
 * leave them zero as we are not going to use them anyway */

#ifndef PTHREAD_CREATE_JOINABLE
#  define PTHREAD_CREATE_JOINABLE	0
#endif

#ifndef PTHREAD_CREATE_DETACHED
#  define PTHREAD_CREATE_DETACHED	0
#endif

#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
#  ifndef PTHREAD_INHERIT_SCHED
#    define PTHREAD_INHERIT_SCHED	0
#  endif

#  ifndef PTHREAD_EXPLICIT_SCHED
#    define PTHREAD_EXPLICIT_SCHED	0
#  endif

/* Old Linux kernels may lack a definition */
#  if defined (P_OS_LINUX) && !defined (SCHED_IDLE)
#    define SCHED_IDLE 5
#  endif
#endif

/* Max length of a thead name */
#if defined(P_OS_LINUX)
#  define PUTHREAD_MAX_NAME		16
#elif defined(P_OS_NETBSD)
#  define PUTHREAD_MAX_NAME		PTHREAD_MAX_NAMELEN_NP
#elif defined(P_OS_DRAGONFLY)
#  define PUTHREAD_MAX_NAME		16
#elif defined(P_OS_SOLARIS)
#  define PUTHREAD_MAX_NAME		32
#elif defined(P_OS_TRU64)
#  define PUTHREAD_MAX_NAME		32
#elif defined(P_OS_VMS)
#  define PUTHREAD_MAX_NAME		32
#elif defined(P_OS_QNX6)
#  define PUTHREAD_MAX_NAME		_NTO_THREAD_NAME_MAX
#elif defined(P_OS_HAIKU)
#  define PUTHREAD_MAX_NAME		32
#endif

typedef pthread_t puthread_hdl;

struct PUThread_ {
	PUThreadBase	base;
	puthread_hdl	hdl;
};

struct PUThreadKey_ {
	pthread_key_t	*key;
	PDestroyFunc	free_func;
};

#ifdef P_OS_SCO
static PMutex *pp_uthread_tls_mutex = NULL;
#endif

#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
static pboolean pp_uthread_get_unix_priority (PUThreadPriority prio, int *sched_policy, int *sched_priority);
#endif

static pthread_key_t * pp_uthread_get_tls_key (PUThreadKey *key);

#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
static pboolean
pp_uthread_get_unix_priority (PUThreadPriority prio, int *sched_policy, int *sched_priority)
{
	pint	lowBound, upperBound;
	pint	prio_min, prio_max;
	pint	native_prio;

#ifdef SCHED_IDLE
	if (prio == P_UTHREAD_PRIORITY_IDLE) {
		*sched_policy = SCHED_IDLE;
		*sched_priority = 0;
		return TRUE;
	}

	lowBound = (pint) P_UTHREAD_PRIORITY_LOWEST;
#else
	lowBound = (pint) P_UTHREAD_PRIORITY_IDLE;
#endif
	upperBound = (pint) P_UTHREAD_PRIORITY_TIMECRITICAL;

	prio_min = sched_get_priority_min (*sched_policy);
	prio_max = sched_get_priority_max (*sched_policy);

	if (P_UNLIKELY (prio_min == -1 || prio_max == -1))
		return FALSE;

	native_prio = ((pint) prio - lowBound) * (prio_max - prio_min) / upperBound + prio_min;

	if (P_UNLIKELY (native_prio > prio_max))
		native_prio = prio_max;

	if (P_UNLIKELY (native_prio < prio_min))
		native_prio = prio_min;

	*sched_priority = native_prio;

	return TRUE;
}
#endif

static pthread_key_t *
pp_uthread_get_tls_key (PUThreadKey *key)
{
	pthread_key_t *thread_key;

	thread_key = (pthread_key_t *) p_atomic_pointer_get ((ppointer) &key->key);

	if (P_LIKELY (thread_key != NULL))
		return thread_key;

#ifdef P_OS_SCO
	p_mutex_lock (pp_uthread_tls_mutex);

	thread_key = key->key;

	if (P_LIKELY (thread_key == NULL)) {
#endif
		if (P_UNLIKELY ((thread_key = p_malloc0 (sizeof (pthread_key_t))) == NULL)) {
			P_ERROR ("PUThread::pp_uthread_get_tls_key: failed to allocate memory");
#ifdef P_OS_SCO
			p_mutex_unlock (pp_uthread_tls_mutex);
#endif
			return NULL;
		}

		if (P_UNLIKELY (pthread_key_create (thread_key, key->free_func) != 0)) {
			P_ERROR ("PUThread::pp_uthread_get_tls_key: pthread_key_create() failed");
			p_free (thread_key);
#ifdef P_OS_SCO
			p_mutex_unlock (pp_uthread_tls_mutex);
#endif
			return NULL;
		}

#ifndef P_OS_SCO
		if (P_UNLIKELY (p_atomic_pointer_compare_and_exchange ((ppointer) &key->key,
								       NULL,
								       (ppointer) thread_key) == FALSE)) {
			if (P_UNLIKELY (pthread_key_delete (*thread_key) != 0)) {
				P_ERROR ("PUThread::pp_uthread_get_tls_key: pthread_key_delete() failed");
				p_free (thread_key);
				return NULL;
			}

			p_free (thread_key);

			thread_key = key->key;
		}
#else
		key->key = thread_key;
	}

	p_mutex_unlock (pp_uthread_tls_mutex);
#endif

	return thread_key;
}

void
p_uthread_init_internal (void)
{
#ifdef P_OS_SCO
	if (P_LIKELY (pp_uthread_tls_mutex == NULL))
		pp_uthread_tls_mutex = p_mutex_new ();
#endif
}

void
p_uthread_shutdown_internal (void)
{
#ifdef P_OS_SCO
	if (P_LIKELY (pp_uthread_tls_mutex != NULL)) {
		p_mutex_free (pp_uthread_tls_mutex);
		pp_uthread_tls_mutex = NULL;
	}
#endif
}

void
p_uthread_win32_thread_detach (void)
{
}

PUThread *
p_uthread_create_internal (PUThreadFunc		func,
			   pboolean		joinable,
			   PUThreadPriority	prio,
			   psize		stack_size)
{
	PUThread		*ret;
	pthread_attr_t		attr;
	pint			create_code;
#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
	struct sched_param	sched;
	pint			native_prio;
	pint			sched_policy;
#endif

#if defined (PLIBSYS_HAS_POSIX_STACKSIZE) && defined (_SC_THREAD_STACK_MIN)
	plong			min_stack;
#endif

	if (P_UNLIKELY ((ret = p_malloc0 (sizeof (PUThread))) == NULL)) {
		P_ERROR ("PUThread::p_uthread_create_internal: failed to allocate memory");
		return NULL;
	}

	ret->base.joinable = joinable;

	if (P_UNLIKELY (pthread_attr_init (&attr) != 0)) {
		P_ERROR ("PUThread::p_uthread_create_internal: pthread_attr_init() failed");
		p_free (ret);
		return NULL;
	}

	if (P_UNLIKELY (pthread_attr_setdetachstate (&attr,
						     joinable ? PTHREAD_CREATE_JOINABLE
							      : PTHREAD_CREATE_DETACHED) != 0)) {
		P_ERROR ("PUThread::p_uthread_create_internal: pthread_attr_setdetachstate() failed");
		pthread_attr_destroy (&attr);
		p_free (ret);
		return NULL;
	}

#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
	if (prio == P_UTHREAD_PRIORITY_INHERIT) {
		if (P_UNLIKELY (pthread_attr_setinheritsched (&attr, PTHREAD_INHERIT_SCHED) != 0))
			P_WARNING ("PUThread::p_uthread_create_internal: pthread_attr_setinheritsched() failed");
	} else {
		if (P_LIKELY (pthread_attr_getschedpolicy (&attr, &sched_policy) == 0)) {
			if (P_LIKELY (pp_uthread_get_unix_priority (prio,
								     &sched_policy,
								     &native_prio) == TRUE)) {
				memset (&sched, 0, sizeof (sched));
				sched.sched_priority = native_prio;

				if (P_LIKELY (pthread_attr_setinheritsched (&attr, PTHREAD_EXPLICIT_SCHED) != 0 ||
					      pthread_attr_setschedpolicy (&attr, sched_policy) != 0 ||
					      pthread_attr_setschedparam (&attr, &sched) != 0))
					P_WARNING ("PUThread::p_uthread_create_internal: failed to set priority");
			} else
				P_WARNING ("PUThread::p_uthread_create_internal: pp_uthread_get_unix_priority() failed");
		} else
			P_WARNING ("PUThread::p_uthread_create_internal: pthread_attr_getschedpolicy() failed");
	}
#endif

#ifdef PLIBSYS_HAS_POSIX_STACKSIZE
#  ifdef _SC_THREAD_STACK_MIN
	if (stack_size > 0) {
		min_stack = (plong) sysconf (_SC_THREAD_STACK_MIN);

		if (P_LIKELY (min_stack > 0)) {
			if (P_UNLIKELY (stack_size < (psize) min_stack))
				stack_size = (psize) min_stack;
		} else
			P_WARNING ("PUThread::p_uthread_create_internal: sysconf() with _SC_THREAD_STACK_MIN failed");

		if (P_UNLIKELY (pthread_attr_setstacksize (&attr, stack_size) != 0))
			P_WARNING ("PUThread::p_uthread_create_internal: pthread_attr_setstacksize() failed");
	}
#  endif
#endif

	create_code = pthread_create (&ret->hdl, &attr, func, ret);

#ifdef EPERM
	if (create_code == EPERM) {
#  ifdef PLIBSYS_HAS_POSIX_SCHEDULING
		pthread_attr_setinheritsched (&attr, PTHREAD_INHERIT_SCHED);
#  endif
		create_code = pthread_create (&ret->hdl, &attr, func, ret);
	}
#endif

	if (P_UNLIKELY (create_code != 0)) {
		P_ERROR ("PUThread::p_uthread_create_internal: pthread_create() failed");
		pthread_attr_destroy (&attr);
		p_free (ret);
		return NULL;
	}

	ret->base.prio = prio;
	pthread_attr_destroy (&attr);

	return ret;
}

void
p_uthread_exit_internal (void)
{
	pthread_exit (P_INT_TO_POINTER (0));
}

void
p_uthread_wait_internal (PUThread *thread)
{
	if (P_UNLIKELY (pthread_join (thread->hdl, NULL) != 0))
		P_ERROR ("PUThread::p_uthread_wait_internal: pthread_join() failed");
}

void
p_uthread_set_name_internal (PUThread *thread)
{
	pchar    *thr_name = NULL;
	pint     res       = 0;
	pboolean is_alloc  = FALSE;
#ifdef PUTHREAD_MAX_NAME
	psize    namelen   = 0;
#endif

	thr_name = thread->base.name;

#ifdef PUTHREAD_MAX_NAME
	namelen  = strlen (thr_name);

	if (namelen > PUTHREAD_MAX_NAME - 1) {
		if (P_UNLIKELY ((thr_name = p_malloc0 (namelen + 1)) == NULL)) {
			P_ERROR ("PUThread::p_uthread_set_name_internal: failed to allocate memory");
			return;
		}

		memcpy (thr_name, thread->base.name, PUTHREAD_MAX_NAME - 1);

		is_alloc = TRUE;
	}
#endif

#if defined(PLIBSYS_HAS_PTHREAD_SETNAME)
#  if defined(P_OS_MAC)
	if (thread->hdl != pthread_self ())
		P_WARNING ("PUThread::p_uthread_set_name_internal: only calling thread is supported in macOS");
	else
		res = pthread_setname_np (thr_name);
#  elif defined(P_OS_NETBSD)
	res = pthread_setname_np (thread->hdl, "%s", thr_name);
#  elif defined(P_OS_TRU64) || defined(P_OS_VMS)
	res = pthread_setname_np (thread->hdl, thr_name, 0);
#  else
	res = pthread_setname_np (thread->hdl, thr_name);
#  endif
#elif defined(PLIBSYS_HAS_PTHREAD_SET_NAME)
	pthread_set_name_np (thread->hdl, thr_name);
#elif defined(PLIBSYS_HAS_PTHREAD_PRCTL)
	if (thread->hdl != pthread_self ())
		P_WARNING ("PUThread::p_uthread_set_name_internal: prctl() can be used on calling thread only");
	else
		res = prctl (PR_SET_NAME, thr_name, NULL, NULL, NULL);
#elif defined(P_OS_HAIKU)
	res = rename_thread (find_thread (NULL), thr_name);
#endif

	if (is_alloc == TRUE)
		p_free (thr_name);

	if (res != 0)
		P_WARNING ("PUThread::p_uthread_set_name_internal: failed to set thread system name");
}

void
p_uthread_free_internal (PUThread *thread)
{
	p_free (thread);
}

P_LIB_API void
p_uthread_yield (void)
{
	sched_yield ();
}

P_LIB_API pboolean
p_uthread_set_priority (PUThread		*thread,
			PUThreadPriority	prio)
{
#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
	struct sched_param	sched;
	pint			policy;
	pint			native_prio;
#endif

	if (P_UNLIKELY (thread == NULL))
		return FALSE;

#ifdef PLIBSYS_HAS_POSIX_SCHEDULING
	if (P_UNLIKELY (pthread_getschedparam (thread->hdl, &policy, &sched) != 0)) {
		P_ERROR ("PUThread::p_uthread_set_priority: pthread_getschedparam() failed");
		return FALSE;
	}

	if (P_UNLIKELY (pp_uthread_get_unix_priority (prio, &policy, &native_prio) == FALSE)) {
		P_ERROR ("PUThread::p_uthread_set_priority: pp_uthread_get_unix_priority() failed");
		return FALSE;
	}

	memset (&sched, 0, sizeof (sched));
	sched.sched_priority = native_prio;

	if (P_UNLIKELY (pthread_setschedparam (thread->hdl, policy, &sched) != 0)) {
		P_ERROR ("PUThread::p_uthread_set_priority: pthread_setschedparam() failed");
		return FALSE;
	}
#endif

	thread->base.prio = prio;
	return TRUE;
}

P_LIB_API P_HANDLE
p_uthread_current_id (void)
{
	return (P_HANDLE) ((psize) pthread_self ());
}

P_LIB_API PUThreadKey *
p_uthread_local_new (PDestroyFunc free_func)
{
	PUThreadKey *ret;

	if (P_UNLIKELY ((ret = p_malloc0 (sizeof (PUThreadKey))) == NULL)) {
		P_ERROR ("PUThread::p_uthread_local_new: failed to allocate memory");
		return NULL;
	}

	ret->free_func = free_func;

	return ret;
}

P_LIB_API void
p_uthread_local_free (PUThreadKey *key)
{
	if (P_UNLIKELY (key == NULL))
		return;

	p_free (key);
}

P_LIB_API ppointer
p_uthread_get_local (PUThreadKey *key)
{
	pthread_key_t	*tls_key;
#ifdef P_OS_SCO
	ppointer	value;
#endif

	if (P_UNLIKELY (key == NULL))
		return NULL;

	if (P_UNLIKELY ((tls_key = pp_uthread_get_tls_key (key)) == NULL))
		return NULL;

#ifdef P_OS_SCO
	if (P_UNLIKELY (pthread_getspecific (*tls_key, &value) != 0))
		return NULL;

	return value;
#else
	return pthread_getspecific (*tls_key);
#endif
}

P_LIB_API void
p_uthread_set_local (PUThreadKey	*key,
		     ppointer		value)
{
	pthread_key_t *tls_key;

	if (P_UNLIKELY (key == NULL))
		return;

	tls_key = pp_uthread_get_tls_key (key);

	if (P_LIKELY (tls_key != NULL)) {
		if (P_UNLIKELY (pthread_setspecific (*tls_key, value) != 0))
			P_ERROR ("PUThread::p_uthread_set_local: pthread_setspecific() failed");
	}
}

P_LIB_API void
p_uthread_replace_local	(PUThreadKey	*key,
			 ppointer	value)
{
	pthread_key_t	*tls_key;
	ppointer	old_value;

	if (P_UNLIKELY (key == NULL))
		return;

	tls_key = pp_uthread_get_tls_key (key);

	if (P_UNLIKELY (tls_key == NULL))
		return;

#ifdef P_OS_SCO
	if (P_UNLIKELY (pthread_getspecific (*tls_key, &old_value) != 0))
		return;
#else
	old_value = pthread_getspecific (*tls_key);
#endif

	if (old_value != NULL && key->free_func != NULL)
		key->free_func (old_value);

	if (P_UNLIKELY (pthread_setspecific (*tls_key, value) != 0))
		P_ERROR ("PUThread::p_uthread_replace_local: pthread_setspecific() failed");
}