Bug 18121 - Use a monotonic clock for pthread timeouts
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-pthread.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-sysdeps-pthread.c Implements threads using pthreads (internal to libdbus)
3  * 
4  * Copyright (C) 2002, 2003, 2006  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-sysdeps.h"
26 #include "dbus-threads.h"
27
28 #include <sys/time.h>
29 #include <pthread.h>
30 #include <string.h>
31
32 #ifdef HAVE_ERRNO_H
33 #include <errno.h>
34 #endif
35
36 #include <config.h>
37
38 /* Whether we have a "monotonic" clock; i.e. a clock not affected by
39  * changes in system time.
40  * This is initialized once in check_monotonic_clock below.
41  * https://bugs.freedesktop.org/show_bug.cgi?id=18121
42  */
43 static dbus_bool_t have_monotonic_clock = 0;
44
45 typedef struct {
46   pthread_mutex_t lock; /**< lock protecting count field */
47   volatile int count;   /**< count of how many times lock holder has recursively locked */
48   volatile pthread_t holder; /**< holder of the lock if count >0,
49                                 valid but arbitrary thread if count
50                                 has ever been >0, uninitialized memory
51                                 if count has never been >0 */
52 } DBusMutexPThread;
53
54 typedef struct {
55   pthread_cond_t cond; /**< the condition */
56 } DBusCondVarPThread;
57
58 #define DBUS_MUTEX(m)         ((DBusMutex*) m)
59 #define DBUS_MUTEX_PTHREAD(m) ((DBusMutexPThread*) m)
60
61 #define DBUS_COND_VAR(c)         ((DBusCondVar*) c)
62 #define DBUS_COND_VAR_PTHREAD(c) ((DBusCondVarPThread*) c)
63
64
65 #ifdef DBUS_DISABLE_ASSERT
66 /* (tmp != 0) is a no-op usage to silence compiler */
67 #define PTHREAD_CHECK(func_name, result_or_call)    \
68     do { int tmp = (result_or_call); if (tmp != 0) {;} } while (0)
69 #else
70 #define PTHREAD_CHECK(func_name, result_or_call) do {                                  \
71     int tmp = (result_or_call);                                                        \
72     if (tmp != 0) {                                                                    \
73       _dbus_warn_check_failed ("pthread function %s failed with %d %s in %s\n",        \
74                                func_name, tmp, strerror(tmp), _DBUS_FUNCTION_NAME);    \
75     }                                                                                  \
76 } while (0)
77 #endif /* !DBUS_DISABLE_ASSERT */
78
79 static DBusMutex*
80 _dbus_pthread_mutex_new (void)
81 {
82   DBusMutexPThread *pmutex;
83   int result;
84   
85   pmutex = dbus_new (DBusMutexPThread, 1);
86   if (pmutex == NULL)
87     return NULL;
88
89   result = pthread_mutex_init (&pmutex->lock, NULL);
90
91   if (result == ENOMEM || result == EAGAIN)
92     {
93       dbus_free (pmutex);
94       return NULL;
95     }
96   else
97     {
98       PTHREAD_CHECK ("pthread_mutex_init", result);
99     }
100
101   /* Only written */
102   pmutex->count = 0;
103
104   /* There's no portable way to have a "null" pthread afaik so we
105    * can't set pmutex->holder to anything sensible.  We only access it
106    * once the lock is held (which means we've set it).
107    */
108   
109   return DBUS_MUTEX (pmutex);
110 }
111
112 static void
113 _dbus_pthread_mutex_free (DBusMutex *mutex)
114 {
115   DBusMutexPThread *pmutex = DBUS_MUTEX_PTHREAD (mutex);
116
117   _dbus_assert (pmutex->count == 0);
118   
119   PTHREAD_CHECK ("pthread_mutex_destroy", pthread_mutex_destroy (&pmutex->lock));
120
121   dbus_free (pmutex);
122 }
123
124 static void
125 _dbus_pthread_mutex_lock (DBusMutex *mutex)
126 {
127   DBusMutexPThread *pmutex = DBUS_MUTEX_PTHREAD (mutex);
128   pthread_t self = pthread_self ();
129
130   /* If the count is > 0 then someone had the lock, maybe us. If it is
131    * 0, then it might immediately change right after we read it,
132    * but it will be changed by another thread; i.e. if we read 0,
133    * we assume that this thread doesn't have the lock.
134    *
135    * Not 100% sure this is safe, but ... seems like it should be.
136    */
137   if (pmutex->count == 0)
138     {
139       /* We know we don't have the lock; someone may have the lock. */
140       
141       PTHREAD_CHECK ("pthread_mutex_lock", pthread_mutex_lock (&pmutex->lock));
142
143       /* We now have the lock. Count must be 0 since it must be 0 when
144        * the lock is released by another thread, and we just now got
145        * the lock.
146        */
147       _dbus_assert (pmutex->count == 0);
148       
149       pmutex->holder = self;
150       pmutex->count = 1;
151     }
152   else
153     {
154       /* We know someone had the lock, possibly us. Thus
155        * pmutex->holder is not pointing to junk, though it may not be
156        * the lock holder anymore if the lock holder is not us.  If the
157        * lock holder is us, then we definitely have the lock.
158        */
159
160       if (pthread_equal (pmutex->holder, self))
161         {
162           /* We already have the lock. */
163           _dbus_assert (pmutex->count > 0);
164         }
165       else
166         {
167           /* Wait for the lock */
168           PTHREAD_CHECK ("pthread_mutex_lock", pthread_mutex_lock (&pmutex->lock));
169           pmutex->holder = self;
170           _dbus_assert (pmutex->count == 0);
171         }
172
173       pmutex->count += 1;
174     }
175 }
176
177 static void
178 _dbus_pthread_mutex_unlock (DBusMutex *mutex)
179 {
180   DBusMutexPThread *pmutex = DBUS_MUTEX_PTHREAD (mutex);
181
182   _dbus_assert (pmutex->count > 0);
183   
184   pmutex->count -= 1;
185
186   if (pmutex->count == 0)
187     PTHREAD_CHECK ("pthread_mutex_unlock", pthread_mutex_unlock (&pmutex->lock));
188   
189   /* We leave pmutex->holder set to ourselves, its content is undefined if count is 0 */
190 }
191
192 static DBusCondVar *
193 _dbus_pthread_condvar_new (void)
194 {
195   DBusCondVarPThread *pcond;
196   pthread_condattr_t attr;
197   int result;
198   
199   pcond = dbus_new (DBusCondVarPThread, 1);
200   if (pcond == NULL)
201     return NULL;
202
203   pthread_condattr_init (&attr);
204 #ifdef HAVE_MONOTONIC_CLOCK
205   if (have_monotonic_clock)
206     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
207 #endif
208
209   result = pthread_cond_init (&pcond->cond, &attr);
210   pthread_condattr_destroy (&attr);
211
212   if (result == EAGAIN || result == ENOMEM)
213     {
214       dbus_free (pcond);
215       return NULL;
216     }
217   else
218     {
219       PTHREAD_CHECK ("pthread_cond_init", result);
220     }
221   
222   return DBUS_COND_VAR (pcond);
223 }
224
225 static void
226 _dbus_pthread_condvar_free (DBusCondVar *cond)
227 {  
228   DBusCondVarPThread *pcond = DBUS_COND_VAR_PTHREAD (cond);
229   
230   PTHREAD_CHECK ("pthread_cond_destroy", pthread_cond_destroy (&pcond->cond));
231
232   dbus_free (pcond);
233 }
234
235 static void
236 _dbus_pthread_condvar_wait (DBusCondVar *cond,
237                             DBusMutex   *mutex)
238 {
239   DBusMutexPThread *pmutex = DBUS_MUTEX_PTHREAD (mutex);
240   DBusCondVarPThread *pcond = DBUS_COND_VAR_PTHREAD (cond);
241   int old_count;
242   
243   _dbus_assert (pmutex->count > 0);
244   _dbus_assert (pthread_equal (pmutex->holder, pthread_self ()));
245
246   old_count = pmutex->count;
247   pmutex->count = 0;            /* allow other threads to lock */
248   PTHREAD_CHECK ("pthread_cond_wait", pthread_cond_wait (&pcond->cond, &pmutex->lock));
249   _dbus_assert (pmutex->count == 0);
250   pmutex->count = old_count;
251   pmutex->holder = pthread_self(); /* other threads may have locked the mutex in the meantime */
252 }
253
254 static dbus_bool_t
255 _dbus_pthread_condvar_wait_timeout (DBusCondVar               *cond,
256                                     DBusMutex                 *mutex,
257                                     int                        timeout_milliseconds)
258 {
259   DBusMutexPThread *pmutex = DBUS_MUTEX_PTHREAD (mutex);
260   DBusCondVarPThread *pcond = DBUS_COND_VAR_PTHREAD (cond);
261   struct timeval time_now;
262   struct timespec end_time;
263   int result;
264   int old_count;
265   
266   _dbus_assert (pmutex->count > 0);
267   _dbus_assert (pthread_equal (pmutex->holder, pthread_self ()));  
268
269 #ifdef HAVE_MONOTONIC_CLOCK
270   if (have_monotonic_clock)
271     {
272       struct timespec monotonic_timer;
273       clock_gettime (CLOCK_MONOTONIC,&monotonic_timer);
274       time_now.tv_sec = monotonic_timer.tv_sec;
275       time_now.tv_usec = monotonic_timer.tv_nsec / 1000;
276     }
277   else
278     /* This else falls through to gettimeofday */
279 #endif
280   gettimeofday (&time_now, NULL);
281   
282   end_time.tv_sec = time_now.tv_sec + timeout_milliseconds / 1000;
283   end_time.tv_nsec = (time_now.tv_usec + (timeout_milliseconds % 1000) * 1000) * 1000;
284   if (end_time.tv_nsec > 1000*1000*1000)
285     {
286       end_time.tv_sec += 1;
287       end_time.tv_nsec -= 1000*1000*1000;
288     }
289
290   old_count = pmutex->count;
291   pmutex->count = 0;
292   result = pthread_cond_timedwait (&pcond->cond, &pmutex->lock, &end_time);
293   
294   if (result != ETIMEDOUT)
295     {
296       PTHREAD_CHECK ("pthread_cond_timedwait", result);
297     }
298
299   _dbus_assert (pmutex->count == 0);
300   pmutex->count = old_count;
301   pmutex->holder = pthread_self(); /* other threads may have locked the mutex in the meantime */
302   
303   /* return true if we did not time out */
304   return result != ETIMEDOUT;
305 }
306
307 static void
308 _dbus_pthread_condvar_wake_one (DBusCondVar *cond)
309 {
310   DBusCondVarPThread *pcond = DBUS_COND_VAR_PTHREAD (cond);
311
312   PTHREAD_CHECK ("pthread_cond_signal", pthread_cond_signal (&pcond->cond));
313 }
314
315 static void
316 _dbus_pthread_condvar_wake_all (DBusCondVar *cond)
317 {
318   DBusCondVarPThread *pcond = DBUS_COND_VAR_PTHREAD (cond);
319   
320   PTHREAD_CHECK ("pthread_cond_broadcast", pthread_cond_broadcast (&pcond->cond));
321 }
322
323 static const DBusThreadFunctions pthread_functions =
324 {
325   DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_NEW_MASK |
326   DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_FREE_MASK |
327   DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_LOCK_MASK |
328   DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_UNLOCK_MASK |
329   DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK |
330   DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK |
331   DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK |
332   DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK |
333   DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK|
334   DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK,
335   NULL, NULL, NULL, NULL,
336   _dbus_pthread_condvar_new,
337   _dbus_pthread_condvar_free,
338   _dbus_pthread_condvar_wait,
339   _dbus_pthread_condvar_wait_timeout,
340   _dbus_pthread_condvar_wake_one,
341   _dbus_pthread_condvar_wake_all,
342   _dbus_pthread_mutex_new,
343   _dbus_pthread_mutex_free,
344   _dbus_pthread_mutex_lock,
345   _dbus_pthread_mutex_unlock
346 };
347
348 static void
349 check_monotonic_clock (void)
350 {
351 #ifdef HAVE_MONOTONIC_CLOCK
352   struct timespec dummy;
353   if (clock_getres (CLOCK_MONOTONIC, &dummy) == 0)
354     have_monotonic_clock = TRUE;
355 #endif
356 }
357
358 dbus_bool_t
359 _dbus_threads_init_platform_specific (void)
360 {
361   check_monotonic_clock ();
362   return dbus_threads_init (&pthread_functions);
363 }