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