2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
27 #ifdef HAVE_SYS_TIME_H
35 #ifdef HAVE_SYS_SELECT_H
36 #include <sys/select.h>
38 #include <sys/types.h>
47 #define INIT_TIMESPEC(t, ts) do { \
48 long s = (t*100000000)/1000000000; \
49 long l = (t*100000000)%1000000000; \
50 clock_gettime(CLOCK_REALTIME, &ts); \
52 if (ts.tv_nsec + l >= 1000000000) { \
61 #define MUTEX_LOCK_DEBUG(m) do { \
62 log_write("%s(%i): %s(): LOCK %p", __FILE__, __LINE__, \
66 #define MUTEX_UNLOCK_DEBUG(m) do { \
67 log_write("%s(%i): %s(): UNLOCK %p", __FILE__, __LINE__, \
71 #define MUTEX_LOCK_DEBUG(m)
72 #define MUTEX_UNLOCK_DEBUG(m)
75 #define MUTEX_LOCK(m) do { \
76 MUTEX_LOCK_DEBUG(m); \
77 pthread_mutex_lock(m); \
80 #define MUTEX_UNLOCK(m) do { \
81 MUTEX_UNLOCK_DEBUG(m); \
82 pthread_mutex_unlock(m); \
85 #define TIMED_LOCK_DURATION 100000
86 #define MUTEX_TIMED_LOCK(ctx, m, timeout, rc) do { \
87 long ka = (long)config_get_integer ("global", "keepalive_interval"); \
88 for (long elapsed = 0; ; elapsed++) { \
89 struct timeval tv = { 0, TIMED_LOCK_DURATION }; \
90 if (pthread_mutex_trylock(m) == EBUSY) { \
91 if (timeout == -1 || elapsed >= timeout) { \
92 rc = GPG_ERR_LOCKED; \
95 select (0, NULL, NULL, NULL, &tv); \
96 if (ctx && ka && elapsed && !((elapsed+1*10) % (ka*10))) { \
97 rc = send_status (ctx, STATUS_KEEPALIVE, NULL); \
103 MUTEX_LOCK_DEBUG(m); \
109 #define MUTEX_TRYLOCK(ctx, m, rc, t) do { \
112 if ((n = pthread_mutex_trylock(m)) == EBUSY) { \
115 rc = send_status(ctx, STATUS_LOCKED, NULL); \
116 if (!rc && t != 0) { \
117 MUTEX_TIMED_LOCK(ctx, m, t, rc); \
120 MUTEX_LOCK_DEBUG(m); \
124 rc = GPG_ERR_LOCKED; \
127 rc = gpg_error_from_errno(n); \
129 MUTEX_LOCK_DEBUG(m); \