1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd 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.
13 Pwmd 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.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
28 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
37 #define MUTEX_LOCK_DEBUG(m) do { \
38 log_write("%s(%i): %s(): LOCK %p", __FILE__, __LINE__, __FUNCTION__, m);
40 #define MUTEX_UNLOCK_DEBUG(m) do { \
41 log_write("%s(%i): %s(): UNLOCK %p", __FILE__, __LINE__, __FUNCTION__, m);
44 #define MUTEX_LOCK_DEBUG(m)
45 #define MUTEX_UNLOCK_DEBUG(m)
48 #define MUTEX_LOCK(m) do { \
49 MUTEX_LOCK_DEBUG(m); \
50 pthread_mutex_lock(m); \
53 #define MUTEX_UNLOCK(m) do { \
54 MUTEX_UNLOCK_DEBUG(m); \
55 pthread_mutex_unlock(m); \
58 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
59 #define MUTEX_TIMED_LOCK(m, timeout, rc) do { \
61 clock_gettime(CLOCK_REALTIME, &ts); \
62 time_t s = (timeout*100000000)/1000000000;\
63 long l = (timeout*100000000)%1000000000; \
66 if (ts.tv_nsec >= 1000000000) {\
68 ts.tv_nsec -= 1000000000; \
70 gint n = pthread_mutex_timedlock(m, &ts); \
71 if (n == ETIMEDOUT) { \
75 MUTEX_LOCK_DEBUG(m); \
78 log_write("%s(%i): %s", __FILE__, __LINE__, pwmd_strerror(gpg_error_from_errno(n))); \
79 rc = gpg_error_from_errno(n);\
83 #define TIMED_LOCK_DURATION 100000
84 #define MUTEX_TIMED_LOCK(m, timeout, rc) do { \
85 for (glong elapsed = 0; ; elapsed++) { \
86 if (pthread_mutex_trylock(m) == EBUSY) { \
87 if (timeout == -1 || elapsed >= timeout) { \
88 rc = GPG_ERR_LOCKED; \
91 usleep(TIMED_LOCK_DURATION); \
94 MUTEX_LOCK_DEBUG(m); \
101 #define MUTEX_TRYLOCK(ctx, m, rc, t) do { \
103 if ((n = pthread_mutex_trylock(m)) == EBUSY) { \
104 if (t != -1 && ctx) { \
105 rc = send_status(ctx, STATUS_LOCKED, NULL); \
106 if (!rc && t != 0) { \
107 MUTEX_TIMED_LOCK(m, t, rc); \
114 rc = GPG_ERR_LOCKED; \
117 rc = gpg_error_from_errno(n);\
119 MUTEX_LOCK_DEBUG(m); \