]> git.sesse.net Git - vlc/blob - src/misc/pthread.c
Use var_Inherit* instead of var_CreateGet*.
[vlc] / src / misc / pthread.c
1 /*****************************************************************************
2  * pthread.c : pthread back-end for LibVLC
3  *****************************************************************************
4  * Copyright (C) 1999-2009 the VideoLAN team
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  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32
33 #include "libvlc.h"
34 #include <stdarg.h>
35 #include <assert.h>
36 #include <unistd.h> /* fsync() */
37 #include <signal.h>
38 #include <errno.h>
39
40 #include <sched.h>
41 #ifdef __linux__
42 # include <sys/syscall.h> /* SYS_gettid */
43 #endif
44
45 #ifdef HAVE_EXECINFO_H
46 # include <execinfo.h>
47 #endif
48
49 #ifdef __APPLE__
50 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
51 # include <mach/mach_init.h> /* mach_task_self in semaphores */
52 #endif
53
54 /**
55  * Print a backtrace to the standard error for debugging purpose.
56  */
57 void vlc_trace (const char *fn, const char *file, unsigned line)
58 {
59      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
60      fflush (stderr); /* needed before switch to low-level I/O */
61 #ifdef HAVE_BACKTRACE
62      void *stack[20];
63      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
64      backtrace_symbols_fd (stack, len, 2);
65 #endif
66      fsync (2);
67 }
68
69 static inline unsigned long vlc_threadid (void)
70 {
71 #if defined (__linux__)
72      /* glibc does not provide a call for this */
73      return syscall (SYS_gettid);
74
75 #else
76      union { pthread_t th; unsigned long int i; } v = { };
77      v.th = pthread_self ();
78      return v.i;
79
80 #endif
81 }
82
83 #ifndef NDEBUG
84 /*****************************************************************************
85  * vlc_thread_fatal: Report an error from the threading layer
86  *****************************************************************************
87  * This is mostly meant for debugging.
88  *****************************************************************************/
89 static void
90 vlc_thread_fatal (const char *action, int error,
91                   const char *function, const char *file, unsigned line)
92 {
93     int canc = vlc_savecancel ();
94     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
95              action, error, vlc_threadid ());
96     vlc_trace (function, file, line);
97
98     /* Sometimes strerror_r() crashes too, so make sure we print an error
99      * message before we invoke it */
100 #ifdef __GLIBC__
101     /* Avoid the strerror_r() prototype brain damage in glibc */
102     errno = error;
103     fprintf (stderr, " Error message: %m\n");
104 #else
105     char buf[1000];
106     const char *msg;
107
108     switch (strerror_r (error, buf, sizeof (buf)))
109     {
110         case 0:
111             msg = buf;
112             break;
113         case ERANGE: /* should never happen */
114             msg = "unknwon (too big to display)";
115             break;
116         default:
117             msg = "unknown (invalid error number)";
118             break;
119     }
120     fprintf (stderr, " Error message: %s\n", msg);
121 #endif
122     fflush (stderr);
123
124     vlc_restorecancel (canc);
125     abort ();
126 }
127
128 # define VLC_THREAD_ASSERT( action ) \
129     if (unlikely(val)) \
130         vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
131 #else
132 # define VLC_THREAD_ASSERT( action ) ((void)val)
133 #endif
134
135 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
136 /* This is not prototyped under glibc, though it exists. */
137 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
138 #endif
139
140 /*****************************************************************************
141  * vlc_mutex_init: initialize a mutex
142  *****************************************************************************/
143 void vlc_mutex_init( vlc_mutex_t *p_mutex )
144 {
145     pthread_mutexattr_t attr;
146
147     if (unlikely(pthread_mutexattr_init (&attr)))
148         abort();
149 #ifdef NDEBUG
150     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_NORMAL );
151 #else
152     /* Create error-checking mutex to detect problems more easily. */
153 # if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
154     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
155 # else
156     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
157 # endif
158 #endif
159     if (unlikely(pthread_mutex_init (p_mutex, &attr)))
160         abort();
161     pthread_mutexattr_destroy( &attr );
162 }
163
164 /*****************************************************************************
165  * vlc_mutex_init: initialize a recursive mutex (Do not use)
166  *****************************************************************************/
167 void vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
168 {
169     pthread_mutexattr_t attr;
170
171     if (unlikely(pthread_mutexattr_init (&attr)))
172         abort();
173 #if defined (__GLIBC__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 6)
174     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
175 #else
176     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
177 #endif
178     if (unlikely(pthread_mutex_init (p_mutex, &attr)))
179         abort();
180     pthread_mutexattr_destroy( &attr );
181 }
182
183
184 /**
185  * Destroys a mutex. The mutex must not be locked.
186  *
187  * @param p_mutex mutex to destroy
188  * @return always succeeds
189  */
190 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
191 {
192     int val = pthread_mutex_destroy( p_mutex );
193     VLC_THREAD_ASSERT ("destroying mutex");
194 }
195
196 #ifndef NDEBUG
197 # ifdef HAVE_VALGRIND_VALGRIND_H
198 #  include <valgrind/valgrind.h>
199 # else
200 #  define RUNNING_ON_VALGRIND (0)
201 # endif
202
203 void vlc_assert_locked (vlc_mutex_t *p_mutex)
204 {
205     if (RUNNING_ON_VALGRIND > 0)
206         return;
207     assert (pthread_mutex_lock (p_mutex) == EDEADLK);
208 }
209 #endif
210
211 /**
212  * Acquires a mutex. If needed, waits for any other thread to release it.
213  * Beware of deadlocks when locking multiple mutexes at the same time,
214  * or when using mutexes from callbacks.
215  * This function is not a cancellation-point.
216  *
217  * @param p_mutex mutex initialized with vlc_mutex_init() or
218  *                vlc_mutex_init_recursive()
219  */
220 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
221 {
222     int val = pthread_mutex_lock( p_mutex );
223     VLC_THREAD_ASSERT ("locking mutex");
224 }
225
226 /**
227  * Acquires a mutex if and only if it is not currently held by another thread.
228  * This function never sleeps and can be used in delay-critical code paths.
229  * This function is not a cancellation-point.
230  *
231  * <b>Beware</b>: If this function fails, then the mutex is held... by another
232  * thread. The calling thread must deal with the error appropriately. That
233  * typically implies postponing the operations that would have required the
234  * mutex. If the thread cannot defer those operations, then it must use
235  * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
236  *
237  * @param p_mutex mutex initialized with vlc_mutex_init() or
238  *                vlc_mutex_init_recursive()
239  * @return 0 if the mutex could be acquired, an error code otherwise.
240  */
241 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
242 {
243     int val = pthread_mutex_trylock( p_mutex );
244
245     if (val != EBUSY)
246         VLC_THREAD_ASSERT ("locking mutex");
247     return val;
248 }
249
250 /**
251  * Releases a mutex (or crashes if the mutex is not locked by the caller).
252  * @param p_mutex mutex locked with vlc_mutex_lock().
253  */
254 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
255 {
256     int val = pthread_mutex_unlock( p_mutex );
257     VLC_THREAD_ASSERT ("unlocking mutex");
258 }
259
260 /**
261  * Initializes a condition variable.
262  */
263 void vlc_cond_init (vlc_cond_t *p_condvar)
264 {
265     pthread_condattr_t attr;
266
267     if (unlikely(pthread_condattr_init (&attr)))
268         abort ();
269 #if !defined (_POSIX_CLOCK_SELECTION)
270    /* Fairly outdated POSIX support (that was defined in 2001) */
271 # define _POSIX_CLOCK_SELECTION (-1)
272 #endif
273 #if (_POSIX_CLOCK_SELECTION >= 0)
274     /* NOTE: This must be the same clock as the one in mtime.c */
275     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
276 #endif
277
278     if (unlikely(pthread_cond_init (p_condvar, &attr)))
279         abort ();
280     pthread_condattr_destroy (&attr);
281 }
282
283 /**
284  * Initializes a condition variable.
285  * Contrary to vlc_cond_init(), the wall clock will be used as a reference for
286  * the vlc_cond_timedwait() time-out parameter.
287  */
288 void vlc_cond_init_daytime (vlc_cond_t *p_condvar)
289 {
290     if (unlikely(pthread_cond_init (p_condvar, NULL)))
291         abort ();
292 }
293
294 /**
295  * Destroys a condition variable. No threads shall be waiting or signaling the
296  * condition.
297  * @param p_condvar condition variable to destroy
298  */
299 void vlc_cond_destroy (vlc_cond_t *p_condvar)
300 {
301     int val = pthread_cond_destroy( p_condvar );
302     VLC_THREAD_ASSERT ("destroying condition");
303 }
304
305 /**
306  * Wakes up one thread waiting on a condition variable, if any.
307  * @param p_condvar condition variable
308  */
309 void vlc_cond_signal (vlc_cond_t *p_condvar)
310 {
311     int val = pthread_cond_signal( p_condvar );
312     VLC_THREAD_ASSERT ("signaling condition variable");
313 }
314
315 /**
316  * Wakes up all threads (if any) waiting on a condition variable.
317  * @param p_cond condition variable
318  */
319 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
320 {
321     pthread_cond_broadcast (p_condvar);
322 }
323
324 /**
325  * Waits for a condition variable. The calling thread will be suspended until
326  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
327  * condition variable, the thread is cancelled with vlc_cancel(), or the
328  * system causes a "spurious" unsolicited wake-up.
329  *
330  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
331  * a recursive mutex. Although it is possible to use the same mutex for
332  * multiple condition, it is not valid to use different mutexes for the same
333  * condition variable at the same time from different threads.
334  *
335  * In case of thread cancellation, the mutex is always locked before
336  * cancellation proceeds.
337  *
338  * The canonical way to use a condition variable to wait for event foobar is:
339  @code
340    vlc_mutex_lock (&lock);
341    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
342
343    while (!foobar)
344        vlc_cond_wait (&wait, &lock);
345
346    --- foobar is now true, do something about it here --
347
348    vlc_cleanup_run (); // release the mutex
349   @endcode
350  *
351  * @param p_condvar condition variable to wait on
352  * @param p_mutex mutex which is unlocked while waiting,
353  *                then locked again when waking up.
354  * @param deadline <b>absolute</b> timeout
355  *
356  * @return 0 if the condition was signaled, an error code in case of timeout.
357  */
358 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
359 {
360     int val = pthread_cond_wait( p_condvar, p_mutex );
361     VLC_THREAD_ASSERT ("waiting on condition");
362 }
363
364 /**
365  * Waits for a condition variable up to a certain date.
366  * This works like vlc_cond_wait(), except for the additional time-out.
367  *
368  * If the variable was initialized with vlc_cond_init(), the timeout has the
369  * same arbitrary origin as mdate(). If the variable was initialized with
370  * vlc_cond_init_daytime(), the timeout is expressed from the Unix epoch.
371  *
372  * @param p_condvar condition variable to wait on
373  * @param p_mutex mutex which is unlocked while waiting,
374  *                then locked again when waking up.
375  * @param deadline <b>absolute</b> timeout
376  *
377  * @return 0 if the condition was signaled, an error code in case of timeout.
378  */
379 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
380                         mtime_t deadline)
381 {
382 #if defined(__APPLE__) && !defined(__powerpc__) && !defined( __ppc__ ) && !defined( __ppc64__ )
383     /* mdate() is the monotonic clock, timedwait origin is gettimeofday() which
384      * isn't monotonic. Use imedwait_relative_np() instead
385     */
386     mtime_t base = mdate();
387     deadline -= base;
388     if (deadline < 0)
389         deadline = 0;
390     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
391     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
392
393     int val = pthread_cond_timedwait_relative_np(p_condvar, p_mutex, &ts);
394     if (val != ETIMEDOUT)
395         VLC_THREAD_ASSERT ("timed-waiting on condition");
396     return val;
397 #else
398     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
399     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
400     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
401     if (val != ETIMEDOUT)
402         VLC_THREAD_ASSERT ("timed-waiting on condition");
403     return val;
404 #endif
405 }
406
407 /**
408  * Initializes a semaphore.
409  */
410 void vlc_sem_init (vlc_sem_t *sem, unsigned value)
411 {
412 #if defined(__APPLE__)
413     if (unlikely(semaphore_create(mach_task_self(), sem, SYNC_POLICY_FIFO, value) != KERN_SUCCESS))
414         abort ();
415 #else
416     if (unlikely(sem_init (sem, 0, value)))
417         abort ();
418 #endif
419 }
420
421 /**
422  * Destroys a semaphore.
423  */
424 void vlc_sem_destroy (vlc_sem_t *sem)
425 {
426     int val;
427
428 #if defined(__APPLE__)
429     if (likely(semaphore_destroy(mach_task_self(), *sem) == KERN_SUCCESS))
430         return;
431
432     val = EINVAL;
433 #else
434     if (likely(sem_destroy (sem) == 0))
435         return;
436
437     val = errno;
438 #endif
439
440     VLC_THREAD_ASSERT ("destroying semaphore");
441 }
442
443 /**
444  * Increments the value of a semaphore.
445  * @return 0 on success, EOVERFLOW in case of integer overflow
446  */
447 int vlc_sem_post (vlc_sem_t *sem)
448 {
449     int val;
450
451 #if defined(__APPLE__)
452     if (likely(semaphore_signal(*sem) == KERN_SUCCESS))
453         return 0;
454
455     val = EINVAL;
456 #else
457     if (likely(sem_post (sem) == 0))
458         return 0;
459
460     val = errno;
461 #endif
462
463     if (unlikely(val != EOVERFLOW))
464         VLC_THREAD_ASSERT ("unlocking semaphore");
465     return val;
466 }
467
468 /**
469  * Atomically wait for the semaphore to become non-zero (if needed),
470  * then decrements it.
471  */
472 void vlc_sem_wait (vlc_sem_t *sem)
473 {
474     int val;
475
476 #if defined(__APPLE__)
477     if (likely(semaphore_wait(*sem) == KERN_SUCCESS))
478         return;
479
480     val = EINVAL;
481 #else
482     do
483         if (likely(sem_wait (sem) == 0))
484             return;
485     while ((val = errno) == EINTR);
486 #endif
487
488     VLC_THREAD_ASSERT ("locking semaphore");
489 }
490
491 /**
492  * Initializes a read/write lock.
493  */
494 void vlc_rwlock_init (vlc_rwlock_t *lock)
495 {
496     if (unlikely(pthread_rwlock_init (lock, NULL)))
497         abort ();
498 }
499
500 /**
501  * Destroys an initialized unused read/write lock.
502  */
503 void vlc_rwlock_destroy (vlc_rwlock_t *lock)
504 {
505     int val = pthread_rwlock_destroy (lock);
506     VLC_THREAD_ASSERT ("destroying R/W lock");
507 }
508
509 /**
510  * Acquires a read/write lock for reading. Recursion is allowed.
511  */
512 void vlc_rwlock_rdlock (vlc_rwlock_t *lock)
513 {
514     int val = pthread_rwlock_rdlock (lock);
515     VLC_THREAD_ASSERT ("acquiring R/W lock for reading");
516 }
517
518 /**
519  * Acquires a read/write lock for writing. Recursion is not allowed.
520  */
521 void vlc_rwlock_wrlock (vlc_rwlock_t *lock)
522 {
523     int val = pthread_rwlock_wrlock (lock);
524     VLC_THREAD_ASSERT ("acquiring R/W lock for writing");
525 }
526
527 /**
528  * Releases a read/write lock.
529  */
530 void vlc_rwlock_unlock (vlc_rwlock_t *lock)
531 {
532     int val = pthread_rwlock_unlock (lock);
533     VLC_THREAD_ASSERT ("releasing R/W lock");
534 }
535
536 /**
537  * Allocates a thread-specific variable.
538  * @param key where to store the thread-specific variable handle
539  * @param destr a destruction callback. It is called whenever a thread exits
540  * and the thread-specific variable has a non-NULL value.
541  * @return 0 on success, a system error code otherwise. This function can
542  * actually fail because there is a fixed limit on the number of
543  * thread-specific variable in a process on most systems.
544  */
545 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
546 {
547     return pthread_key_create (key, destr);
548 }
549
550 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
551 {
552     pthread_key_delete (*p_tls);
553 }
554
555 /**
556  * Sets a thread-specific variable.
557  * @param key thread-local variable key (created with vlc_threadvar_create())
558  * @param value new value for the variable for the calling thread
559  * @return 0 on success, a system error code otherwise.
560  */
561 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
562 {
563     return pthread_setspecific (key, value);
564 }
565
566 /**
567  * Gets the value of a thread-local variable for the calling thread.
568  * This function cannot fail.
569  * @return the value associated with the given variable for the calling
570  * or NULL if there is no value.
571  */
572 void *vlc_threadvar_get (vlc_threadvar_t key)
573 {
574     return pthread_getspecific (key);
575 }
576
577 static bool rt_priorities = false;
578 static int rt_offset;
579
580 void vlc_threads_setup (libvlc_int_t *p_libvlc)
581 {
582     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
583     static bool initialized = false;
584
585     vlc_mutex_lock (&lock);
586     /* Initializes real-time priorities before any thread is created,
587      * just once per process. */
588     if (!initialized)
589     {
590 #ifndef __APPLE__
591         if (var_InheritBool (p_libvlc, "rt-priority"))
592 #endif
593         {
594             rt_offset = var_InheritInteger (p_libvlc, "rt-offset");
595             rt_priorities = true;
596         }
597         initialized = true;
598     }
599     vlc_mutex_unlock (&lock);
600 }
601
602 /**
603  * Creates and starts new thread.
604  *
605  * @param p_handle [OUT] pointer to write the handle of the created thread to
606  * @param entry entry point for the thread
607  * @param data data parameter given to the entry point
608  * @param priority thread priority value
609  * @return 0 on success, a standard error code on error.
610  */
611 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
612                int priority)
613 {
614     int ret;
615
616     pthread_attr_t attr;
617     pthread_attr_init (&attr);
618
619     /* Block the signals that signals interface plugin handles.
620      * If the LibVLC caller wants to handle some signals by itself, it should
621      * block these before whenever invoking LibVLC. And it must obviously not
622      * start the VLC signals interface plugin.
623      *
624      * LibVLC will normally ignore any interruption caused by an asynchronous
625      * signal during a system call. But there may well be some buggy cases
626      * where it fails to handle EINTR (bug reports welcome). Some underlying
627      * libraries might also not handle EINTR properly.
628      */
629     sigset_t oldset;
630     {
631         sigset_t set;
632         sigemptyset (&set);
633         sigdelset (&set, SIGHUP);
634         sigaddset (&set, SIGINT);
635         sigaddset (&set, SIGQUIT);
636         sigaddset (&set, SIGTERM);
637
638         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
639         pthread_sigmask (SIG_BLOCK, &set, &oldset);
640     }
641
642 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
643  && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
644  && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
645     if (rt_priorities)
646     {
647         struct sched_param sp = { .sched_priority = priority + rt_offset, };
648         int policy;
649
650         if (sp.sched_priority <= 0)
651             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
652         else
653             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
654
655         pthread_attr_setschedpolicy (&attr, policy);
656         pthread_attr_setschedparam (&attr, &sp);
657     }
658 #else
659     (void) priority;
660 #endif
661
662     /* The thread stack size.
663      * The lower the value, the less address space per thread, the highest
664      * maximum simultaneous threads per process. Too low values will cause
665      * stack overflows and weird crashes. Set with caution. Also keep in mind
666      * that 64-bits platforms consume more stack than 32-bits one.
667      *
668      * Thanks to on-demand paging, thread stack size only affects address space
669      * consumption. In terms of memory, threads only use what they need
670      * (rounded up to the page boundary).
671      *
672      * For example, on Linux i386, the default is 2 mega-bytes, which supports
673      * about 320 threads per processes. */
674 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
675
676 #ifdef VLC_STACKSIZE
677     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
678     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
679 #endif
680
681     ret = pthread_create (p_handle, &attr, entry, data);
682     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
683     pthread_attr_destroy (&attr);
684     return ret;
685 }
686
687 /**
688  * Marks a thread as cancelled. Next time the target thread reaches a
689  * cancellation point (while not having disabled cancellation), it will
690  * run its cancellation cleanup handler, the thread variable destructors, and
691  * terminate. vlc_join() must be used afterward regardless of a thread being
692  * cancelled or not.
693  */
694 void vlc_cancel (vlc_thread_t thread_id)
695 {
696     pthread_cancel (thread_id);
697 #ifdef HAVE_MAEMO
698     pthread_kill (thread_id, SIGRTMIN);
699 #endif
700 }
701
702 /**
703  * Waits for a thread to complete (if needed), then destroys it.
704  * This is a cancellation point; in case of cancellation, the join does _not_
705  * occur.
706  * @warning
707  * A thread cannot join itself (normally VLC will abort if this is attempted).
708  * Also, a detached thread <b>cannot</b> be joined.
709  *
710  * @param handle thread handle
711  * @param p_result [OUT] pointer to write the thread return value or NULL
712  */
713 void vlc_join (vlc_thread_t handle, void **result)
714 {
715     int val = pthread_join (handle, result);
716     VLC_THREAD_ASSERT ("joining thread");
717 }
718
719 /**
720  * Detaches a thread. When the specified thread completes, it will be
721  * automatically destroyed (in particular, its stack will be reclaimed),
722  * instead of waiting for another thread to call vlc_join(). If the thread has
723  * already completed, it will be destroyed immediately.
724  *
725  * When a thread performs some work asynchronously and may complete much
726  * earlier than it can be joined, detaching the thread can save memory.
727  * However, care must be taken that any resources used by a detached thread
728  * remains valid until the thread completes. This will typically involve some
729  * kind of thread-safe signaling.
730  *
731  * A thread may detach itself.
732  *
733  * @param handle thread handle
734  */
735 void vlc_detach (vlc_thread_t handle)
736 {
737     int val = pthread_detach (handle);
738     VLC_THREAD_ASSERT ("detaching thread");
739 }
740
741 /**
742  * Save the current cancellation state (enabled or disabled), then disable
743  * cancellation for the calling thread.
744  * This function must be called before entering a piece of code that is not
745  * cancellation-safe, unless it can be proven that the calling thread will not
746  * be cancelled.
747  * @return Previous cancellation state (opaque value for vlc_restorecancel()).
748  */
749 int vlc_savecancel (void)
750 {
751     int state;
752     int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
753
754     VLC_THREAD_ASSERT ("saving cancellation");
755     return state;
756 }
757
758 /**
759  * Restore the cancellation state for the calling thread.
760  * @param state previous state as returned by vlc_savecancel().
761  * @return Nothing, always succeeds.
762  */
763 void vlc_restorecancel (int state)
764 {
765 #ifndef NDEBUG
766     int oldstate, val;
767
768     val = pthread_setcancelstate (state, &oldstate);
769     /* This should fail if an invalid value for given for state */
770     VLC_THREAD_ASSERT ("restoring cancellation");
771
772     if (unlikely(oldstate != PTHREAD_CANCEL_DISABLE))
773          vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
774                            __func__, __FILE__, __LINE__);
775 #else
776     pthread_setcancelstate (state, NULL);
777 #endif
778 }
779
780 /**
781  * Issues an explicit deferred cancellation point.
782  * This has no effect if thread cancellation is disabled.
783  * This can be called when there is a rather slow non-sleeping operation.
784  * This is also used to force a cancellation point in a function that would
785  * otherwise "not always" be a one (block_FifoGet() is an example).
786  */
787 void vlc_testcancel (void)
788 {
789     pthread_testcancel ();
790 }
791
792 void vlc_control_cancel (int cmd, ...)
793 {
794     (void) cmd;
795     assert (0);
796 }
797
798
799 struct vlc_timer
800 {
801     vlc_thread_t thread;
802     vlc_mutex_t  lock;
803     vlc_cond_t   wait;
804     void       (*func) (void *);
805     void        *data;
806     mtime_t      value, interval;
807     unsigned     users;
808     unsigned     overruns;
809 };
810
811 static void *vlc_timer_do (void *data)
812 {
813     struct vlc_timer *timer = data;
814
815     timer->func (timer->data);
816
817     vlc_mutex_lock (&timer->lock);
818     assert (timer->users > 0);
819     if (--timer->users == 0)
820         vlc_cond_signal (&timer->wait);
821     vlc_mutex_unlock (&timer->lock);
822     return NULL;
823 }
824
825 static void *vlc_timer_thread (void *data)
826 {
827     struct vlc_timer *timer = data;
828     mtime_t value, interval;
829
830     vlc_mutex_lock (&timer->lock);
831     value = timer->value;
832     interval = timer->interval;
833     vlc_mutex_unlock (&timer->lock);
834
835     for (;;)
836     {
837          vlc_thread_t th;
838
839          mwait (value);
840
841          vlc_mutex_lock (&timer->lock);
842          if (vlc_clone (&th, vlc_timer_do, timer, VLC_THREAD_PRIORITY_INPUT))
843              timer->overruns++;
844          else
845          {
846              vlc_detach (th);
847              timer->users++;
848          }
849          vlc_mutex_unlock (&timer->lock);
850
851          if (interval == 0)
852              return NULL;
853
854          value += interval;
855     }
856 }
857
858 /**
859  * Initializes an asynchronous timer.
860  * @warning Asynchronous timers are processed from an unspecified thread.
861  * Also, multiple occurences of an interval timer can run concurrently.
862  *
863  * @param id pointer to timer to be initialized
864  * @param func function that the timer will call
865  * @param data parameter for the timer function
866  * @return 0 on success, a system error code otherwise.
867  */
868 int vlc_timer_create (vlc_timer_t *id, void (*func) (void *), void *data)
869 {
870     struct vlc_timer *timer = malloc (sizeof (*timer));
871
872     if (unlikely(timer == NULL))
873         return ENOMEM;
874     vlc_mutex_init (&timer->lock);
875     vlc_cond_init (&timer->wait);
876     assert (func);
877     timer->func = func;
878     timer->data = data;
879     timer->value = 0;
880     timer->interval = 0;
881     timer->users = 0;
882     timer->overruns = 0;
883     *id = timer;
884     return 0;
885 }
886
887 /**
888  * Destroys an initialized timer. If needed, the timer is first disarmed.
889  * This function is undefined if the specified timer is not initialized.
890  *
891  * @warning This function <b>must</b> be called before the timer data can be
892  * freed and before the timer callback function can be unloaded.
893  *
894  * @param timer timer to destroy
895  */
896 void vlc_timer_destroy (vlc_timer_t timer)
897 {
898     vlc_timer_schedule (timer, false, 0, 0);
899     vlc_mutex_lock (&timer->lock);
900     while (timer->users != 0)
901         vlc_cond_wait (&timer->wait, &timer->lock);
902     vlc_mutex_unlock (&timer->lock);
903
904     vlc_cond_destroy (&timer->wait);
905     vlc_mutex_destroy (&timer->lock);
906     free (timer);
907 }
908
909 /**
910  * Arm or disarm an initialized timer.
911  * This functions overrides any previous call to itself.
912  *
913  * @note A timer can fire later than requested due to system scheduling
914  * limitations. An interval timer can fail to trigger sometimes, either because
915  * the system is busy or suspended, or because a previous iteration of the
916  * timer is still running. See also vlc_timer_getoverrun().
917  *
918  * @param timer initialized timer
919  * @param absolute the timer value origin is the same as mdate() if true,
920  *                 the timer value is relative to now if false.
921  * @param value zero to disarm the timer, otherwise the initial time to wait
922  *              before firing the timer.
923  * @param interval zero to fire the timer just once, otherwise the timer
924  *                 repetition interval.
925  */
926 void vlc_timer_schedule (vlc_timer_t timer, bool absolute,
927                          mtime_t value, mtime_t interval)
928 {
929     static vlc_mutex_t lock = VLC_STATIC_MUTEX;
930
931     vlc_mutex_lock (&lock);
932     vlc_mutex_lock (&timer->lock);
933     if (timer->value)
934     {
935         vlc_mutex_unlock (&timer->lock);
936         vlc_cancel (timer->thread);
937         vlc_join (timer->thread, NULL);
938         vlc_mutex_lock (&timer->lock);
939         timer->value = 0;
940     }
941     if ((value != 0)
942      && (vlc_clone (&timer->thread, vlc_timer_thread, timer,
943                     VLC_THREAD_PRIORITY_INPUT) == 0))
944     {
945         timer->value = (absolute ? 0 : mdate ()) + value;
946         timer->interval = interval;
947     }
948     vlc_mutex_unlock (&timer->lock);
949     vlc_mutex_unlock (&lock);
950 }
951
952 /**
953  * Fetch and reset the overrun counter for a timer.
954  * @param timer initialized timer
955  * @return the timer overrun counter, i.e. the number of times that the timer
956  * should have run but did not since the last actual run. If all is well, this
957  * is zero.
958  */
959 unsigned vlc_timer_getoverrun (vlc_timer_t timer)
960 {
961     unsigned ret;
962
963     vlc_mutex_lock (&timer->lock);
964     ret = timer->overruns;
965     timer->overruns = 0;
966     vlc_mutex_unlock (&timer->lock);
967     return ret;
968 }