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