Fixed --import.
[pwmd.git] / src / mutex.h
blobc1f605cf70409021986a8adca7cb7858e895232f
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
4 Ben Kibbey <bjk@luxsci.net>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02110-1301 USA
20 #ifndef LOCK_H
21 #define LOCK_H
23 #include <pth.h>
24 #include <assert.h>
25 #include <errno.h>
26 #include "cache.h"
28 #ifdef MUTEX_DEBUG
29 #define MUTEX_LOCK_DEBUG(m) \
30 log_write("%s(%i): %s(): LOCK %p", __FILE__, __LINE__, __FUNCTION__, m);
31 #define MUTEX_UNLOCK_DEBUG(m) \
32 log_write("%s(%i): %s(): UNLOCK %p", __FILE__, __LINE__, __FUNCTION__, m);
33 #else
34 #define MUTEX_LOCK_DEBUG(m)
35 #define MUTEX_UNLOCK_DEBUG(m)
36 #endif
38 #define CACHE_LOCK(ctx) MUTEX_LOCK(&cache_mutex)
39 #define CACHE_UNLOCK MUTEX_UNLOCK(&cache_mutex)
41 #define MUTEX_LOCK(m) \
42 MUTEX_LOCK_DEBUG(m) \
43 if (!pth_mutex_acquire(m, FALSE, NULL)) { \
44 log_write("%s(%i): %s: LOCK", __FILE__, __LINE__, strerror(errno)); \
45 assert(0); \
46 } \
48 #define MUTEX_UNLOCK(m) \
49 MUTEX_UNLOCK_DEBUG(m) \
50 if (!pth_mutex_release(m) && errno != EDEADLK) { \
51 log_write("%s(%i): %s: UNLOCK", __FILE__, __LINE__, strerror(errno)); \
52 assert(0); \
55 #define MUTEX_LOCK_EV(client, m, rc) { \
56 pth_event_t ev = pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE, \
57 client->thd->fd); \
58 MUTEX_LOCK_DEBUG(m) \
59 if (!pth_mutex_acquire(m, FALSE, ev)) { \
60 rc = gpg_error_from_errno(errno); \
61 log_write("%s(%i): LOCK: %s", __FILE__, __LINE__, pwmd_strerror(rc));\
62 } \
63 pth_event_free(ev, PTH_FREE_ALL); \
66 #define MUTEX_TRYLOCK(client, m, rc) \
67 if (!pth_mutex_acquire(m, TRUE, NULL)) { \
68 if (errno == EBUSY) { \
69 if (client && client->ctx) {\
70 rc = send_status(client->ctx, STATUS_LOCKED, NULL); \
71 if (!rc) { \
72 MUTEX_LOCK_EV(client, m, rc); \
73 } \
74 } \
75 } \
76 else { \
77 log_write("%s(%i): %s: LOCK errno=%i", __FILE__, __LINE__, __FUNCTION__, errno); \
78 assert(0); \
79 } \
80 } \
81 else { \
82 MUTEX_LOCK_DEBUG(m) \
85 #endif