]> git.sesse.net Git - vlc/blob - src/darwin/thread.c
D3D11: use defines for DXGI
[vlc] / src / darwin / thread.c
1 /*****************************************************************************
2  * thread.c : pthread back-end for LibVLC
3  *****************************************************************************
4  * Copyright (C) 1999-2013 VLC authors and VideoLAN
5  *
6  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
7  *          Samuel Hocevar <sam@zoy.org>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *          Clément Sténac
10  *          Rémi Denis-Courmont
11  *          Felix Paul Kühne <fkuehne # videolan.org>
12  *
13  * This program is free software; you can redistribute it and/or modify it
14  * under the terms of the GNU Lesser General Public License as published by
15  * the Free Software Foundation; either version 2.1 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_atomic.h>
34
35 #include "libvlc.h"
36 #include <signal.h>
37 #include <errno.h>
38 #include <assert.h>
39
40 #include <pthread.h>
41 #include <mach/mach_init.h> /* mach_task_self in semaphores */
42 #include <mach/mach_time.h>
43 #include <execinfo.h>
44
45 static mach_timebase_info_data_t vlc_clock_conversion_factor;
46
47 static void vlc_clock_setup_once (void)
48 {
49     if (unlikely(mach_timebase_info (&vlc_clock_conversion_factor) != 0))
50         abort ();
51 }
52
53 static pthread_once_t vlc_clock_once = PTHREAD_ONCE_INIT;
54
55 #define vlc_clock_setup() \
56     pthread_once(&vlc_clock_once, vlc_clock_setup_once)
57
58 static struct timespec mtime_to_ts (mtime_t date)
59 {
60     lldiv_t d = lldiv (date, CLOCK_FREQ);
61     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
62
63     return ts;
64 }
65
66 /* Print a backtrace to the standard error for debugging purpose. */
67 void vlc_trace (const char *fn, const char *file, unsigned line)
68 {
69      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
70      fflush (stderr); /* needed before switch to low-level I/O */
71      void *stack[20];
72      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
73      backtrace_symbols_fd (stack, len, 2);
74      fsync (2);
75 }
76
77 static inline unsigned long vlc_threadid (void)
78 {
79      union { pthread_t th; unsigned long int i; } v = { };
80      v.th = pthread_self ();
81      return v.i;
82 }
83
84 #ifndef NDEBUG
85 /* Reports a fatal error from the threading layer, for debugging purposes. */
86 static void
87 vlc_thread_fatal (const char *action, int error,
88                   const char *function, const char *file, unsigned line)
89 {
90     int canc = vlc_savecancel ();
91     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
92              action, error, vlc_threadid ());
93     vlc_trace (function, file, line);
94
95     char buf[1000];
96     const char *msg;
97
98     switch (strerror_r (error, buf, sizeof (buf)))
99     {
100         case 0:
101             msg = buf;
102             break;
103         case ERANGE: /* should never happen */
104             msg = "unknown (too big to display)";
105             break;
106         default:
107             msg = "unknown (invalid error number)";
108             break;
109     }
110     fprintf (stderr, " Error message: %s\n", msg);
111     fflush (stderr);
112
113     vlc_restorecancel (canc);
114     abort ();
115 }
116
117 # define VLC_THREAD_ASSERT( action ) \
118     if (unlikely(val)) \
119         vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
120 #else
121 # define VLC_THREAD_ASSERT( action ) ((void)val)
122 #endif
123
124 /* Initializes a fast mutex. */
125 void vlc_mutex_init( vlc_mutex_t *p_mutex )
126 {
127     pthread_mutexattr_t attr;
128
129     if (unlikely(pthread_mutexattr_init (&attr)))
130         abort();
131 #ifdef NDEBUG
132     pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_DEFAULT);
133 #else
134     pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK);
135 #endif
136     if (unlikely(pthread_mutex_init (p_mutex, &attr)))
137         abort();
138     pthread_mutexattr_destroy( &attr );
139 }
140
141 /* Initializes a recursive mutex.
142  * warning: This is strongly discouraged. Please use normal mutexes. */
143 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
144 {
145     pthread_mutexattr_t attr;
146
147     if (unlikely(pthread_mutexattr_init (&attr)))
148         abort();
149     pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
150     if (unlikely(pthread_mutex_init (p_mutex, &attr)))
151         abort();
152     pthread_mutexattr_destroy( &attr );
153 }
154
155
156 /* Destroys a mutex. The mutex must not be locked.
157  *
158  * parameter: p_mutex mutex to destroy
159  * returns: always succeeds */
160 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
161 {
162     int val = pthread_mutex_destroy( p_mutex );
163     VLC_THREAD_ASSERT ("destroying mutex");
164 }
165
166 #ifndef NDEBUG
167 # ifdef HAVE_VALGRIND_VALGRIND_H
168 #  include <valgrind/valgrind.h>
169 # else
170 #  define RUNNING_ON_VALGRIND (0)
171 # endif
172
173 /* Asserts that a mutex is locked by the calling thread. */
174 void vlc_assert_locked (vlc_mutex_t *p_mutex)
175 {
176     if (RUNNING_ON_VALGRIND > 0)
177         return;
178     assert (pthread_mutex_lock (p_mutex) == EDEADLK);
179 }
180 #endif
181
182 /* Acquires a mutex. If needed, waits for any other thread to release it.
183  * Beware of deadlocks when locking multiple mutexes at the same time,
184  * or when using mutexes from callbacks.
185  * This function is not a cancellation-point.
186  *
187  * parameter: p_mutex mutex initialized with vlc_mutex_init() or
188  *                vlc_mutex_init_recursive()
189  */
190 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
191 {
192     int val = pthread_mutex_lock( p_mutex );
193     VLC_THREAD_ASSERT ("locking mutex");
194 }
195
196 /* Acquires a mutex if and only if it is not currently held by another thread.
197  * This function never sleeps and can be used in delay-critical code paths.
198  * This function is not a cancellation-point.
199  *
200  * BEWARE: If this function fails, then the mutex is held... by another
201  * thread. The calling thread must deal with the error appropriately. That
202  * typically implies postponing the operations that would have required the
203  * mutex. If the thread cannot defer those operations, then it must use
204  * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
205  *
206  * parameter: p_mutex mutex initialized with vlc_mutex_init() or
207  *                vlc_mutex_init_recursive()
208  * returns: 0 if the mutex could be acquired, an error code otherwise. */
209 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
210 {
211     int val = pthread_mutex_trylock( p_mutex );
212
213     if (val != EBUSY)
214         VLC_THREAD_ASSERT ("locking mutex");
215     return val;
216 }
217
218 /* Release a mutex (or crashes if the mutex is not locked by the caller).
219  * parameter p_mutex mutex locked with vlc_mutex_lock(). */
220 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
221 {
222     int val = pthread_mutex_unlock( p_mutex );
223     VLC_THREAD_ASSERT ("unlocking mutex");
224 }
225
226 enum
227 {
228     VLC_CLOCK_MONOTONIC = 0,
229     VLC_CLOCK_REALTIME,
230 };
231
232 /* Initialize a condition variable. */
233 void vlc_cond_init (vlc_cond_t *p_condvar)
234 {
235     if (unlikely(pthread_cond_init (&p_condvar->cond, NULL)))
236         abort ();
237     p_condvar->clock = VLC_CLOCK_MONOTONIC;
238 }
239
240 /* Initialize a condition variable.
241  * Contrary to vlc_cond_init(), the wall clock will be used as a reference for
242  * the vlc_cond_timedwait() time-out parameter. */
243 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
244 {
245     if (unlikely(pthread_cond_init (&p_condvar->cond, NULL)))
246         abort ();
247     p_condvar->clock = VLC_CLOCK_REALTIME;
248
249 }
250
251 /* Destroys a condition variable. No threads shall be waiting or signaling the
252  * condition.
253  * parameter: p_condvar condition variable to destroy */
254 void vlc_cond_destroy (vlc_cond_t *p_condvar)
255 {
256     int val = pthread_cond_destroy (&p_condvar->cond);
257
258     /* due to a faulty pthread implementation within Darwin 11 and
259      * later condition variables cannot be destroyed without
260      * terminating the application immediately.
261      * This Darwin kernel issue is still present in version 13
262      * and might not be resolved prior to Darwin 15.
263      * radar://12496249
264      *
265      * To work-around this, we are just leaking the condition variable
266      * which is acceptable due to VLC's low number of created variables
267      * and its usually limited runtime.
268      * Ideally, we should implement a re-useable pool.
269      */
270     if (val != 0) {
271         #ifndef NDEBUG
272         printf("pthread_cond_destroy returned %i\n", val);
273         #endif
274
275         if (val == EBUSY)
276             return;
277     }
278
279     VLC_THREAD_ASSERT ("destroying condition");
280 }
281
282 /* Wake up one thread waiting on a condition variable, if any.
283  * parameter: p_condvar condition variable */
284 void vlc_cond_signal (vlc_cond_t *p_condvar)
285 {
286     int val = pthread_cond_signal (&p_condvar->cond);
287     VLC_THREAD_ASSERT ("signaling condition variable");
288 }
289
290 /* Wake up all threads (if any) waiting on a condition variable.
291  * parameter: p_cond condition variable */
292 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
293 {
294     pthread_cond_broadcast (&p_condvar->cond);
295 }
296
297 /* Wait for a condition variable. The calling thread will be suspended until
298  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
299  * condition variable, the thread is cancelled with vlc_cancel(), or the
300  * system causes a "spurious" unsolicited wake-up.
301  *
302  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
303  * a recursive mutex. Although it is possible to use the same mutex for
304  * multiple condition, it is not valid to use different mutexes for the same
305  * condition variable at the same time from different threads.
306  *
307  * In case of thread cancellation, the mutex is always locked before
308  * cancellation proceeds.
309  *
310  * The canonical way to use a condition variable to wait for event foobar is:
311  sample code:
312    vlc_mutex_lock (&lock);
313    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
314
315    while (!foobar)
316        vlc_cond_wait (&wait, &lock);
317
318    --- foobar is now true, do something about it here --
319
320    vlc_cleanup_run (); // release the mutex
321  *
322  * 1st parameter: p_condvar condition variable to wait on
323  * 2nd parameter: p_mutex mutex which is unlocked while waiting,
324  *                then locked again when waking up. */
325 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
326 {
327     int val = pthread_cond_wait (&p_condvar->cond, p_mutex);
328     VLC_THREAD_ASSERT ("waiting on condition");
329 }
330
331 /* Wait for a condition variable up to a certain date.
332  * This works like vlc_cond_wait(), except for the additional time-out.
333  *
334  * If the variable was initialized with vlc_cond_init(), the timeout has the
335  * same arbitrary origin as mdate(). If the variable was initialized with
336  * vlc_cond_init_daytime(), the timeout is expressed from the Unix epoch.
337  *
338  * 1st parameter: p_condvar condition variable to wait on
339  * 2nd parameter: p_mutex mutex which is unlocked while waiting,
340  *                then locked again when waking up.
341  * 3rd parameter: deadline <b>absolute</b> timeout
342  *
343  * returns 0 if the condition was signaled, an error code in case of timeout.
344  */
345 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
346                         mtime_t deadline)
347 {
348     int val = 0;
349
350     /*
351      * Note that both pthread_cond_timedwait_relative_np and pthread_cond_timedwait
352      * convert the given timeout to a mach absolute deadline, with system startup
353      * as the time origin. There is no way you can change this behaviour.
354      *
355      * For more details, see: https://devforums.apple.com/message/931605
356      */
357
358     if (p_condvar->clock == VLC_CLOCK_MONOTONIC) {
359
360         /* 
361          * mdate() is the monotonic clock, pthread_cond_timedwait expects
362          * origin of gettimeofday(). Use timedwait_relative_np() instead.
363          */
364         mtime_t base = mdate();
365         deadline -= base;
366         if (deadline < 0)
367             deadline = 0;
368         struct timespec ts = mtime_to_ts(deadline);
369
370         val = pthread_cond_timedwait_relative_np(&p_condvar->cond, p_mutex, &ts);
371
372     } else {
373         /* variant for vlc_cond_init_daytime */
374         assert (p_condvar->clock == VLC_CLOCK_REALTIME);
375
376         /* 
377          * FIXME: It is assumed, that in this case the system waits until the real
378          * time deadline is passed, even if the real time is adjusted in between.
379          * This is not fulfilled, as described above.
380          */
381         struct timespec ts = mtime_to_ts(deadline);
382
383         val = pthread_cond_timedwait(&p_condvar->cond, p_mutex, &ts);
384     }
385     
386     if (val != ETIMEDOUT)
387         VLC_THREAD_ASSERT ("timed-waiting on condition");
388     return val;
389 }
390
391 /* Initialize a semaphore. */
392 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
393 {
394     if (unlikely(semaphore_create(mach_task_self(), sem, SYNC_POLICY_FIFO, value) != KERN_SUCCESS))
395         abort ();
396 }
397
398 /* Destroy a semaphore. */
399 void vlc_sem_destroy (vlc_sem_t *sem)
400 {
401     int val;
402
403     if (likely(semaphore_destroy(mach_task_self(), *sem) == KERN_SUCCESS))
404         return;
405
406     val = EINVAL;
407
408     VLC_THREAD_ASSERT ("destroying semaphore");
409 }
410
411 /* Increment the value of a semaphore.
412  * returns 0 on success, EOVERFLOW in case of integer overflow */
413 int vlc_sem_post (vlc_sem_t *sem)
414 {
415     int val;
416
417     if (likely(semaphore_signal(*sem) == KERN_SUCCESS))
418         return 0;
419
420     val = EINVAL;
421
422     if (unlikely(val != EOVERFLOW))
423         VLC_THREAD_ASSERT ("unlocking semaphore");
424     return val;
425 }
426
427 /* Atomically wait for the semaphore to become non-zero (if needed),
428  * then decrements it. */
429 void vlc_sem_wait (vlc_sem_t *sem)
430 {
431     int val;
432
433     if (likely(semaphore_wait(*sem) == KERN_SUCCESS))
434         return;
435
436     val = EINVAL;
437
438     VLC_THREAD_ASSERT ("locking semaphore");
439 }
440
441 /* Initialize a read/write lock. */
442 void vlc_rwlock_init (vlc_rwlock_t *lock)
443 {
444     if (unlikely(pthread_rwlock_init (lock, NULL)))
445         abort ();
446 }
447
448 /* Destroy an initialized unused read/write lock. */
449 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
450 {
451     int val = pthread_rwlock_destroy (lock);
452     VLC_THREAD_ASSERT ("destroying R/W lock");
453 }
454
455 /* Acquire a read/write lock for reading. Recursion is allowed.
456  * Attention: This function may be a cancellation point. */
457 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
458 {
459     int val = pthread_rwlock_rdlock (lock);
460     VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
461 }
462
463 /* Acquire a read/write lock for writing. Recursion is not allowed.
464  * Attention: This function may be a cancellation point. */
465 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
466 {
467     int val = pthread_rwlock_wrlock (lock);
468     VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
469 }
470
471 /* Release a read/write lock. */
472 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
473 {
474     int val = pthread_rwlock_unlock (lock);
475     VLC_THREAD_ASSERT ("releasing R/W lock");
476 }
477
478 /* Allocates a thread-specific variable.
479  * 1st parameter: key where to store the thread-specific variable handle
480  * 2nd parameter: destr a destruction callback. It is called whenever a thread
481  * exits and the thread-specific variable has a non-NULL value.
482  * returns 0 on success, a system error code otherwise.
483  *
484  * This function can actually fail because there is a fixed limit on the number
485  * of thread-specific variable in a process on most systems.
486  */
487 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
488 {
489     return pthread_key_create (key, destr);
490 }
491
492 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
493 {
494     pthread_key_delete (*p_tls);
495 }
496
497 /* Set a thread-specific variable.
498  * 1st parameter: key thread-local variable key
499  *                (created with vlc_threadvar_create())
500  * 2nd parameter: value new value for the variable for the calling thread
501  * returns 0 on success, a system error code otherwise. */
502 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
503 {
504     return pthread_setspecific (key, value);
505 }
506
507 /* Get the value of a thread-local variable for the calling thread.
508  * This function cannot fail.
509  * returns the value associated with the given variable for the calling
510  * or NULL if there is no value. */
511 void *vlc_threadvar_get (vlc_threadvar_t key)
512 {
513     return pthread_getspecific (key);
514 }
515
516 static bool rt_priorities = false;
517 static int rt_offset;
518
519 void vlc_threads_setup (libvlc_int_t *p_libvlc)
520 {
521     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
522     static bool initialized = false;
523
524     vlc_mutex_lock (&lock);
525     /* Initializes real-time priorities before any thread is created,
526      * just once per process. */
527     if (!initialized)
528     {
529         rt_offset = var_InheritInteger (p_libvlc, "rt-offset");
530         rt_priorities = true;
531         initialized = true;
532     }
533     vlc_mutex_unlock (&lock);
534 }
535
536
537 static int vlc_clone_attr (vlc_thread_t *th, pthread_attr_t *attr,
538                            void *(*entry) (void *), void *data, int priority)
539 {
540     int ret;
541
542     /* Block the signals that signals interface plugin handles.
543      * If the LibVLC caller wants to handle some signals by itself, it should
544      * block these before whenever invoking LibVLC. And it must obviously not
545      * start the VLC signals interface plugin.
546      *
547      * LibVLC will normally ignore any interruption caused by an asynchronous
548      * signal during a system call. But there may well be some buggy cases
549      * where it fails to handle EINTR (bug reports welcome). Some underlying
550      * libraries might also not handle EINTR properly.
551      */
552     sigset_t oldset;
553     {
554         sigset_t set;
555         sigemptyset (&set);
556         sigdelset (&set, SIGHUP);
557         sigaddset (&set, SIGINT);
558         sigaddset (&set, SIGQUIT);
559         sigaddset (&set, SIGTERM);
560
561         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
562         pthread_sigmask (SIG_BLOCK, &set, &oldset);
563     }
564
565     (void) priority;
566
567     /* The thread stack size.
568      * The lower the value, the less address space per thread, the highest
569      * maximum simultaneous threads per process. Too low values will cause
570      * stack overflows and weird crashes. Set with caution. Also keep in mind
571      * that 64-bits platforms consume more stack than 32-bits one.
572      *
573      * Thanks to on-demand paging, thread stack size only affects address space
574      * consumption. In terms of memory, threads only use what they need
575      * (rounded up to the page boundary).
576      *
577      * For example, on Linux i386, the default is 2 mega-bytes, which supports
578      * about 320 threads per processes. */
579 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
580
581 #ifdef VLC_STACKSIZE
582     ret = pthread_attr_setstacksize (attr, VLC_STACKSIZE);
583     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
584 #endif
585
586     ret = pthread_create (th, attr, entry, data);
587     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
588     pthread_attr_destroy (attr);
589     return ret;
590 }
591
592 /* Create and start a new thread.
593  *
594  * The thread must be joined with vlc_join() to reclaim resources when it is 
595  * not needed anymore.
596  *
597  * 1st parameter: th [OUT] pointer to write the handle of the created thread to
598  *                 (mandatory, must be non-NULL)
599  * 2nd parameter: entry entry point for the thread
600  * 3rd parameter: data data parameter given to the entry point
601  * 4th parameter: priority thread priority value
602  * returns 0 on success, a standard error code on error. */
603 int vlc_clone (vlc_thread_t *th, void *(*entry) (void *), void *data,
604                int priority)
605 {
606     pthread_attr_t attr;
607
608     pthread_attr_init (&attr);
609     return vlc_clone_attr (th, &attr, entry, data, priority);
610 }
611
612 /* Wait for a thread to complete (if needed), then destroys it.
613  * This is a cancellation point; in case of cancellation, the join does _not_
614  * occur.
615  * 
616  * WARNING: A thread cannot join itself (normally VLC will abort if this is
617  * attempted). Also, a detached thread cannot be joined.
618  *
619  * 1st parameter: handle thread handle
620  * 2nd parameter: p_result - pointer to write the thread return value or NULL
621  */
622 void vlc_join (vlc_thread_t handle, void **result)
623 {
624     int val = pthread_join (handle, result);
625     VLC_THREAD_ASSERT ("joining thread");
626 }
627
628 /* Create and start a new detached thread.
629  * A detached thread cannot be joined. Its resources will be automatically
630  * released whenever the thread exits (in particular, its call stack will be
631  * reclaimed).
632  *
633  * Detached thread are particularly useful when some work needs to be done
634  * asynchronously, that is likely to be completed much earlier than the thread
635  * can practically be joined. In this case, thread detach can spare memory.
636  *
637  * A detached thread may be cancelled, so as to expedite its termination.
638  * Be extremely careful if you do this: while a normal joinable thread can
639  * safely be cancelled after it has already exited, cancelling an already
640  * exited detached thread is undefined: The thread handle would is destroyed
641  * immediately when the detached thread exits. So you need to ensure that the
642  * detached thread is still running before cancellation is attempted.
643  *
644  * WARNING: Care must be taken that any resources used by the detached thread
645  * remains valid until the thread completes.
646  *
647  * Attention: A detached thread must eventually exit just like another other
648  * thread. In practice, LibVLC will wait for detached threads to exit before
649  * it unloads the plugins.
650  *
651  * 1st parameter: th [OUT] pointer to hold the thread handle, or NULL
652  * 2nd parameter: entry entry point for the thread
653  * 3rd parameter: data data parameter given to the entry point
654  * 4th parameter: priority thread priority value
655  * returns 0 on success, a standard error code on error. */
656 int vlc_clone_detach (vlc_thread_t *th, void *(*entry) (void *), void *data,
657                       int priority)
658 {
659     vlc_thread_t dummy;
660     pthread_attr_t attr;
661
662     if (th == NULL)
663         th = &dummy;
664
665     pthread_attr_init (&attr);
666     pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
667     return vlc_clone_attr (th, &attr, entry, data, priority);
668 }
669
670 int vlc_set_priority (vlc_thread_t th, int priority)
671 {
672     (void) th; (void) priority;
673     return VLC_SUCCESS;
674 }
675
676 /* Marks a thread as cancelled. Next time the target thread reaches a
677  * cancellation point (while not having disabled cancellation), it will
678  * run its cancellation cleanup handler, the thread variable destructors, and
679  * terminate. vlc_join() must be used afterward regardless of a thread being
680  * cancelled or not. */
681 void vlc_cancel (vlc_thread_t thread_id)
682 {
683     pthread_cancel (thread_id);
684 }
685
686 /* Save the current cancellation state (enabled or disabled), then disable
687  * cancellation for the calling thread.
688  * This function must be called before entering a piece of code that is not
689  * cancellation-safe, unless it can be proven that the calling thread will not
690  * be cancelled.
691  * returns Previous cancellation state (opaque value for vlc_restorecancel()). */
692 int vlc_savecancel (void)
693 {
694     int state;
695     int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
696
697     VLC_THREAD_ASSERT ("saving cancellation");
698     return state;
699 }
700
701 /* Restore the cancellation state for the calling thread.
702  * parameter: previous state as returned by vlc_savecancel(). */
703 void vlc_restorecancel (int state)
704 {
705 #ifndef NDEBUG
706     int oldstate, val;
707
708     val = pthread_setcancelstate (state, &oldstate);
709     /* This should fail if an invalid value for given for state */
710     VLC_THREAD_ASSERT ("restoring cancellation");
711
712     if (unlikely(oldstate != PTHREAD_CANCEL_DISABLE))
713          vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
714                            __func__, __FILE__, __LINE__);
715 #else
716     pthread_setcancelstate (state, NULL);
717 #endif
718 }
719
720 /* Issues an explicit deferred cancellation point.
721  * This has no effect if thread cancellation is disabled.
722  * This can be called when there is a rather slow non-sleeping operation.
723  * This is also used to force a cancellation point in a function that would
724  * otherwise "not always" be a one (block_FifoGet() is an example). */
725 void vlc_testcancel (void)
726 {
727     pthread_testcancel ();
728 }
729
730 void vlc_control_cancel (int cmd, ...)
731 {
732     (void) cmd;
733     vlc_assert_unreachable ();
734 }
735
736 /* Precision monotonic clock.
737  *
738  * In principles, the clock has a precision of 1 MHz. But the actual resolution
739  * may be much lower, especially when it comes to sleeping with mwait() or
740  * msleep(). Most general-purpose operating systems provide a resolution of
741  * only 100 to 1000 Hz.
742  *
743  * WARNING: The origin date (time value "zero") is not specified. It is
744  * typically the time the kernel started, but this is platform-dependent.
745  * If you need wall clock time, use gettimeofday() instead.
746  *
747  * returns a timestamp in microseconds. */
748 mtime_t mdate (void)
749 {
750     vlc_clock_setup();
751     uint64_t date = mach_absolute_time();
752
753     /* denom is uint32_t, switch to 64 bits to prevent overflow. */
754     uint64_t denom = vlc_clock_conversion_factor.denom;
755
756     /* Switch to microsecs */
757     denom *= 1000LL;
758
759     /* Split the division to prevent overflow */
760     lldiv_t d = lldiv (vlc_clock_conversion_factor.numer, denom);
761
762     return (d.quot * date) + ((d.rem * date) / denom);
763 }
764
765 #undef mwait
766 /* Wait until a deadline (possibly later due to OS scheduling).
767  * parameter: deadline timestamp to wait for (see mdate()) */
768 void mwait (mtime_t deadline)
769 {
770     deadline -= mdate ();
771     if (deadline > 0)
772         msleep (deadline);
773 }
774
775 #undef msleep
776 /* Wait for an interval of time.
777  * parameter: delay how long to wait (in microseconds) */
778 void msleep (mtime_t delay)
779 {
780     struct timespec ts = mtime_to_ts (delay);
781
782     /* nanosleep uses mach_absolute_time and mach_wait_until internally,
783        but also handles kernel errors. Thus we use just this. */
784     while (nanosleep (&ts, &ts) == -1)
785         assert (errno == EINTR);
786 }
787
788 /* Count CPUs.
789  * returns the number of available (logical) CPUs. */
790 unsigned vlc_GetCPUCount(void)
791 {
792     return sysconf(_SC_NPROCESSORS_CONF);
793 }