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