]> git.sesse.net Git - vlc/blob - src/misc/pthread.c
Merge branch 1.0-bugfix
[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
39 #include <sched.h>
40 #ifdef __linux__
41 # include <sys/syscall.h> /* SYS_gettid */
42 #endif
43
44 #ifdef HAVE_EXECINFO_H
45 # include <execinfo.h>
46 #endif
47
48 #ifdef __APPLE__
49 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
50 #endif
51
52 /**
53  * Print a backtrace to the standard error for debugging purpose.
54  */
55 void vlc_trace (const char *fn, const char *file, unsigned line)
56 {
57      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
58      fflush (stderr); /* needed before switch to low-level I/O */
59 #ifdef HAVE_BACKTRACE
60      void *stack[20];
61      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
62      backtrace_symbols_fd (stack, len, 2);
63 #endif
64      fsync (2);
65 }
66
67 static inline unsigned long vlc_threadid (void)
68 {
69 #if defined (__linux__)
70      /* glibc does not provide a call for this */
71      return syscall (SYS_gettid);
72
73 #else
74      union { pthread_t th; unsigned long int i; } v = { };
75      v.th = pthread_self ();
76      return v.i;
77
78 #endif
79 }
80
81 #ifndef NDEBUG
82 /*****************************************************************************
83  * vlc_thread_fatal: Report an error from the threading layer
84  *****************************************************************************
85  * This is mostly meant for debugging.
86  *****************************************************************************/
87 static void
88 vlc_thread_fatal (const char *action, int error,
89                   const char *function, const char *file, unsigned line)
90 {
91     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
92              action, error, vlc_threadid ());
93     vlc_trace (function, file, line);
94
95     /* Sometimes strerror_r() crashes too, so make sure we print an error
96      * message before we invoke it */
97 #ifdef __GLIBC__
98     /* Avoid the strerror_r() prototype brain damage in glibc */
99     errno = error;
100     fprintf (stderr, " Error message: %m\n");
101 #else
102     char buf[1000];
103     const char *msg;
104
105     switch (strerror_r (error, buf, sizeof (buf)))
106     {
107         case 0:
108             msg = buf;
109             break;
110         case ERANGE: /* should never happen */
111             msg = "unknwon (too big to display)";
112             break;
113         default:
114             msg = "unknown (invalid error number)";
115             break;
116     }
117     fprintf (stderr, " Error message: %s\n", msg);
118 #endif
119     fflush (stderr);
120
121     abort ();
122 }
123
124 # define VLC_THREAD_ASSERT( action ) \
125     if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
126 #else
127 # define VLC_THREAD_ASSERT( action ) ((void)val)
128 #endif
129
130 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
131 /* This is not prototyped under glibc, though it exists. */
132 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
133 #endif
134
135 /*****************************************************************************
136  * vlc_mutex_init: initialize a mutex
137  *****************************************************************************/
138 int vlc_mutex_init( vlc_mutex_t *p_mutex )
139 {
140     pthread_mutexattr_t attr;
141     int                 i_result;
142
143     pthread_mutexattr_init( &attr );
144
145 #ifndef NDEBUG
146     /* Create error-checking mutex to detect problems more easily. */
147 # if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
148     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
149 # else
150     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
151 # endif
152 #endif
153     i_result = pthread_mutex_init( p_mutex, &attr );
154     pthread_mutexattr_destroy( &attr );
155     return i_result;
156 }
157
158 /*****************************************************************************
159  * vlc_mutex_init: initialize a recursive mutex (Do not use)
160  *****************************************************************************/
161 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
162 {
163     pthread_mutexattr_t attr;
164     int                 i_result;
165
166     pthread_mutexattr_init( &attr );
167 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
168     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
169 #else
170     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
171 #endif
172     i_result = pthread_mutex_init( p_mutex, &attr );
173     pthread_mutexattr_destroy( &attr );
174     return( i_result );
175 }
176
177
178 /**
179  * Destroys a mutex. The mutex must not be locked.
180  *
181  * @param p_mutex mutex to destroy
182  * @return always succeeds
183  */
184 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
185 {
186     int val = pthread_mutex_destroy( p_mutex );
187     VLC_THREAD_ASSERT ("destroying mutex");
188 }
189
190 #ifndef NDEBUG
191 # ifdef HAVE_VALGRIND_VALGRIND_H
192 #  include <valgrind/valgrind.h>
193 # else
194 #  define RUNNING_ON_VALGRIND (0)
195 # endif
196
197 void vlc_assert_locked (vlc_mutex_t *p_mutex)
198 {
199     if (RUNNING_ON_VALGRIND > 0)
200         return;
201     assert (pthread_mutex_lock (p_mutex) == EDEADLK);
202 }
203 #endif
204
205 /**
206  * Acquires a mutex. If needed, waits for any other thread to release it.
207  * Beware of deadlocks when locking multiple mutexes at the same time,
208  * or when using mutexes from callbacks.
209  * This function is not a cancellation-point.
210  *
211  * @param p_mutex mutex initialized with vlc_mutex_init() or
212  *                vlc_mutex_init_recursive()
213  */
214 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
215 {
216     int val = pthread_mutex_lock( p_mutex );
217     VLC_THREAD_ASSERT ("locking mutex");
218 }
219
220 /**
221  * Acquires a mutex if and only if it is not currently held by another thread.
222  * This function never sleeps and can be used in delay-critical code paths.
223  * This function is not a cancellation-point.
224  *
225  * <b>Beware</b>: If this function fails, then the mutex is held... by another
226  * thread. The calling thread must deal with the error appropriately. That
227  * typically implies postponing the operations that would have required the
228  * mutex. If the thread cannot defer those operations, then it must use
229  * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
230  *
231  * @param p_mutex mutex initialized with vlc_mutex_init() or
232  *                vlc_mutex_init_recursive()
233  * @return 0 if the mutex could be acquired, an error code otherwise.
234  */
235 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
236 {
237     int val = pthread_mutex_trylock( p_mutex );
238
239     if (val != EBUSY)
240         VLC_THREAD_ASSERT ("locking mutex");
241     return val;
242 }
243
244 /**
245  * Releases a mutex (or crashes if the mutex is not locked by the caller).
246  * @param p_mutex mutex locked with vlc_mutex_lock().
247  */
248 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
249 {
250     int val = pthread_mutex_unlock( p_mutex );
251     VLC_THREAD_ASSERT ("unlocking mutex");
252 }
253
254 /*****************************************************************************
255  * vlc_cond_init: initialize a condition variable
256  *****************************************************************************/
257 int vlc_cond_init( vlc_cond_t *p_condvar )
258 {
259     pthread_condattr_t attr;
260     int ret;
261
262     ret = pthread_condattr_init (&attr);
263     if (ret)
264         return ret;
265
266 #if !defined (_POSIX_CLOCK_SELECTION)
267    /* Fairly outdated POSIX support (that was defined in 2001) */
268 # define _POSIX_CLOCK_SELECTION (-1)
269 #endif
270 #if (_POSIX_CLOCK_SELECTION >= 0)
271     /* NOTE: This must be the same clock as the one in mtime.c */
272     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
273 #endif
274
275     ret = pthread_cond_init (p_condvar, &attr);
276     pthread_condattr_destroy (&attr);
277     return ret;
278 }
279
280 /**
281  * Destroys a condition variable. No threads shall be waiting or signaling the
282  * condition.
283  * @param p_condvar condition variable to destroy
284  */
285 void vlc_cond_destroy (vlc_cond_t *p_condvar)
286 {
287     int val = pthread_cond_destroy( p_condvar );
288     VLC_THREAD_ASSERT ("destroying condition");
289 }
290
291 /**
292  * Wakes up one thread waiting on a condition variable, if any.
293  * @param p_condvar condition variable
294  */
295 void vlc_cond_signal (vlc_cond_t *p_condvar)
296 {
297     int val = pthread_cond_signal( p_condvar );
298     VLC_THREAD_ASSERT ("signaling condition variable");
299 }
300
301 /**
302  * Wakes up all threads (if any) waiting on a condition variable.
303  * @param p_cond condition variable
304  */
305 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
306 {
307     pthread_cond_broadcast (p_condvar);
308 }
309
310 /**
311  * Waits for a condition variable. The calling thread will be suspended until
312  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
313  * condition variable, the thread is cancelled with vlc_cancel(), or the
314  * system causes a "spurious" unsolicited wake-up.
315  *
316  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
317  * a recursive mutex. Although it is possible to use the same mutex for
318  * multiple condition, it is not valid to use different mutexes for the same
319  * condition variable at the same time from different threads.
320  *
321  * In case of thread cancellation, the mutex is always locked before
322  * cancellation proceeds.
323  *
324  * The canonical way to use a condition variable to wait for event foobar is:
325  @code
326    vlc_mutex_lock (&lock);
327    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
328
329    while (!foobar)
330        vlc_cond_wait (&wait, &lock);
331
332    --- foobar is now true, do something about it here --
333
334    vlc_cleanup_run (); // release the mutex
335   @endcode
336  *
337  * @param p_condvar condition variable to wait on
338  * @param p_mutex mutex which is unlocked while waiting,
339  *                then locked again when waking up.
340  * @param deadline <b>absolute</b> timeout
341  *
342  * @return 0 if the condition was signaled, an error code in case of timeout.
343  */
344 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
345 {
346     int val = pthread_cond_wait( p_condvar, p_mutex );
347     VLC_THREAD_ASSERT ("waiting on condition");
348 }
349
350 /**
351  * Waits for a condition variable up to a certain date.
352  * This works like vlc_cond_wait(), except for the additional timeout.
353  *
354  * @param p_condvar condition variable to wait on
355  * @param p_mutex mutex which is unlocked while waiting,
356  *                then locked again when waking up.
357  * @param deadline <b>absolute</b> timeout
358  *
359  * @return 0 if the condition was signaled, an error code in case of timeout.
360  */
361 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
362                         mtime_t deadline)
363 {
364 #ifdef __APPLE__
365     /* mdate() is mac_absolute_time on OSX, which we must convert to do
366      * the same base than gettimeofday() which pthread_cond_timedwait
367      * relies on. */
368     mtime_t oldbase = mdate();
369     struct timeval tv;
370     gettimeofday(&tv, NULL);
371     mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
372     deadline = deadline - oldbase + newbase;
373 #endif
374     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
375     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
376
377     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
378     if (val != ETIMEDOUT)
379         VLC_THREAD_ASSERT ("timed-waiting on condition");
380     return val;
381 }
382
383 /**
384  * Allocates a thread-specific variable.
385  * @param key where to store the thread-specific variable handle
386  * @param destr a destruction callback. It is called whenever a thread exits
387  * and the thread-specific variable has a non-NULL value.
388  * @return 0 on success, a system error code otherwise. This function can
389  * actually fail because there is a fixed limit on the number of
390  * thread-specific variable in a process on most systems.
391  */
392 int vlc_threadvar_create (vlc_threadvar_t *key, void (*destr) (void *))
393 {
394     return pthread_key_create (key, destr);
395 }
396
397 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
398 {
399     pthread_key_delete (*p_tls);
400 }
401
402 /**
403  * Sets a thread-specific variable.
404  * @param key thread-local variable key (created with vlc_threadvar_create())
405  * @param value new value for the variable for the calling thread
406  * @return 0 on success, a system error code otherwise.
407  */
408 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
409 {
410     return pthread_setspecific (key, value);
411 }
412
413 /**
414  * Gets the value of a thread-local variable for the calling thread.
415  * This function cannot fail.
416  * @return the value associated with the given variable for the calling
417  * or NULL if there is no value.
418  */
419 void *vlc_threadvar_get (vlc_threadvar_t key)
420 {
421     return pthread_getspecific (key);
422 }
423
424 /**
425  * Creates and starts new thread.
426  *
427  * @param p_handle [OUT] pointer to write the handle of the created thread to
428  * @param entry entry point for the thread
429  * @param data data parameter given to the entry point
430  * @param priority thread priority value
431  * @return 0 on success, a standard error code on error.
432  */
433 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
434                int priority)
435 {
436     int ret;
437
438     pthread_attr_t attr;
439     pthread_attr_init (&attr);
440
441     /* Block the signals that signals interface plugin handles.
442      * If the LibVLC caller wants to handle some signals by itself, it should
443      * block these before whenever invoking LibVLC. And it must obviously not
444      * start the VLC signals interface plugin.
445      *
446      * LibVLC will normally ignore any interruption caused by an asynchronous
447      * signal during a system call. But there may well be some buggy cases
448      * where it fails to handle EINTR (bug reports welcome). Some underlying
449      * libraries might also not handle EINTR properly.
450      */
451     sigset_t oldset;
452     {
453         sigset_t set;
454         sigemptyset (&set);
455         sigdelset (&set, SIGHUP);
456         sigaddset (&set, SIGINT);
457         sigaddset (&set, SIGQUIT);
458         sigaddset (&set, SIGTERM);
459
460         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
461         pthread_sigmask (SIG_BLOCK, &set, &oldset);
462     }
463
464 #if defined (_POSIX_PRIORITY_SCHEDULING) && (_POSIX_PRIORITY_SCHEDULING >= 0) \
465  && defined (_POSIX_THREAD_PRIORITY_SCHEDULING) \
466  && (_POSIX_THREAD_PRIORITY_SCHEDULING >= 0)
467     {
468         struct sched_param sp = { .sched_priority = priority, };
469         int policy;
470
471         if (sp.sched_priority <= 0)
472             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
473         else
474             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
475
476         pthread_attr_setschedpolicy (&attr, policy);
477         pthread_attr_setschedparam (&attr, &sp);
478     }
479 #else
480     (void) priority;
481 #endif
482
483     /* The thread stack size.
484      * The lower the value, the less address space per thread, the highest
485      * maximum simultaneous threads per process. Too low values will cause
486      * stack overflows and weird crashes. Set with caution. Also keep in mind
487      * that 64-bits platforms consume more stack than 32-bits one.
488      *
489      * Thanks to on-demand paging, thread stack size only affects address space
490      * consumption. In terms of memory, threads only use what they need
491      * (rounded up to the page boundary).
492      *
493      * For example, on Linux i386, the default is 2 mega-bytes, which supports
494      * about 320 threads per processes. */
495 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
496
497 #ifdef VLC_STACKSIZE
498     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
499     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
500 #endif
501
502     ret = pthread_create (p_handle, &attr, entry, data);
503     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
504     pthread_attr_destroy (&attr);
505     return ret;
506 }
507
508 /**
509  * Marks a thread as cancelled. Next time the target thread reaches a
510  * cancellation point (while not having disabled cancellation), it will
511  * run its cancellation cleanup handler, the thread variable destructors, and
512  * terminate. vlc_join() must be used afterward regardless of a thread being
513  * cancelled or not.
514  */
515 void vlc_cancel (vlc_thread_t thread_id)
516 {
517     pthread_cancel (thread_id);
518 }
519
520 /**
521  * Waits for a thread to complete (if needed), and destroys it.
522  * This is a cancellation point; in case of cancellation, the join does _not_
523  * occur.
524  *
525  * @param handle thread handle
526  * @param p_result [OUT] pointer to write the thread return value or NULL
527  * @return 0 on success, a standard error code otherwise.
528  */
529 void vlc_join (vlc_thread_t handle, void **result)
530 {
531     int val = pthread_join (handle, result);
532     VLC_THREAD_ASSERT ("joining thread");
533 }
534
535 /**
536  * Save the current cancellation state (enabled or disabled), then disable
537  * cancellation for the calling thread.
538  * This function must be called before entering a piece of code that is not
539  * cancellation-safe, unless it can be proven that the calling thread will not
540  * be cancelled.
541  * @return Previous cancellation state (opaque value for vlc_restorecancel()).
542  */
543 int vlc_savecancel (void)
544 {
545     int state;
546     int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
547
548     VLC_THREAD_ASSERT ("saving cancellation");
549     return state;
550 }
551
552 /**
553  * Restore the cancellation state for the calling thread.
554  * @param state previous state as returned by vlc_savecancel().
555  * @return Nothing, always succeeds.
556  */
557 void vlc_restorecancel (int state)
558 {
559 #ifndef NDEBUG
560     int oldstate, val;
561
562     val = pthread_setcancelstate (state, &oldstate);
563     /* This should fail if an invalid value for given for state */
564     VLC_THREAD_ASSERT ("restoring cancellation");
565
566     if (oldstate != PTHREAD_CANCEL_DISABLE)
567          vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
568                            __func__, __FILE__, __LINE__);
569 #else
570     pthread_setcancelstate (state, NULL);
571 #endif
572 }
573
574 /**
575  * Issues an explicit deferred cancellation point.
576  * This has no effect if thread cancellation is disabled.
577  * This can be called when there is a rather slow non-sleeping operation.
578  * This is also used to force a cancellation point in a function that would
579  * otherwise "not always" be a one (block_FifoGet() is an example).
580  */
581 void vlc_testcancel (void)
582 {
583     pthread_testcancel ();
584 }
585
586 void vlc_control_cancel (int cmd, ...)
587 {
588     (void) cmd;
589     assert (0);
590 }