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