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