move hmac setting to flags on cipher context
[sqlcipher.git] / src / mutex_unix.c
blobeca7295831c2f0ee48ba54d062914d06a1dd8ebe
1 /*
2 ** 2007 August 28
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains the C functions that implement mutexes for pthreads
14 #include "sqliteInt.h"
17 ** The code in this file is only used if we are compiling threadsafe
18 ** under unix with pthreads.
20 ** Note that this implementation requires a version of pthreads that
21 ** supports recursive mutexes.
23 #ifdef SQLITE_MUTEX_PTHREADS
25 #include <pthread.h>
28 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
29 ** are necessary under two condidtions: (1) Debug builds and (2) using
30 ** home-grown mutexes. Encapsulate these conditions into a single #define.
32 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
33 # define SQLITE_MUTEX_NREF 1
34 #else
35 # define SQLITE_MUTEX_NREF 0
36 #endif
39 ** Each recursive mutex is an instance of the following structure.
41 struct sqlite3_mutex {
42 pthread_mutex_t mutex; /* Mutex controlling the lock */
43 #if SQLITE_MUTEX_NREF
44 int id; /* Mutex type */
45 volatile int nRef; /* Number of entrances */
46 volatile pthread_t owner; /* Thread that is within this mutex */
47 int trace; /* True to trace changes */
48 #endif
50 #if SQLITE_MUTEX_NREF
51 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
52 #else
53 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
54 #endif
57 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
58 ** intended for use only inside assert() statements. On some platforms,
59 ** there might be race conditions that can cause these routines to
60 ** deliver incorrect results. In particular, if pthread_equal() is
61 ** not an atomic operation, then these routines might delivery
62 ** incorrect results. On most platforms, pthread_equal() is a
63 ** comparison of two integers and is therefore atomic. But we are
64 ** told that HPUX is not such a platform. If so, then these routines
65 ** will not always work correctly on HPUX.
67 ** On those platforms where pthread_equal() is not atomic, SQLite
68 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
69 ** make sure no assert() statements are evaluated and hence these
70 ** routines are never called.
72 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
73 static int pthreadMutexHeld(sqlite3_mutex *p){
74 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
76 static int pthreadMutexNotheld(sqlite3_mutex *p){
77 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
79 #endif
82 ** Initialize and deinitialize the mutex subsystem.
84 static int pthreadMutexInit(void){ return SQLITE_OK; }
85 static int pthreadMutexEnd(void){ return SQLITE_OK; }
88 ** The sqlite3_mutex_alloc() routine allocates a new
89 ** mutex and returns a pointer to it. If it returns NULL
90 ** that means that a mutex could not be allocated. SQLite
91 ** will unwind its stack and return an error. The argument
92 ** to sqlite3_mutex_alloc() is one of these integer constants:
94 ** <ul>
95 ** <li> SQLITE_MUTEX_FAST
96 ** <li> SQLITE_MUTEX_RECURSIVE
97 ** <li> SQLITE_MUTEX_STATIC_MASTER
98 ** <li> SQLITE_MUTEX_STATIC_MEM
99 ** <li> SQLITE_MUTEX_STATIC_MEM2
100 ** <li> SQLITE_MUTEX_STATIC_PRNG
101 ** <li> SQLITE_MUTEX_STATIC_LRU
102 ** <li> SQLITE_MUTEX_STATIC_PMEM
103 ** </ul>
105 ** The first two constants cause sqlite3_mutex_alloc() to create
106 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
107 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
108 ** The mutex implementation does not need to make a distinction
109 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
110 ** not want to. But SQLite will only request a recursive mutex in
111 ** cases where it really needs one. If a faster non-recursive mutex
112 ** implementation is available on the host platform, the mutex subsystem
113 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
115 ** The other allowed parameters to sqlite3_mutex_alloc() each return
116 ** a pointer to a static preexisting mutex. Six static mutexes are
117 ** used by the current version of SQLite. Future versions of SQLite
118 ** may add additional static mutexes. Static mutexes are for internal
119 ** use by SQLite only. Applications that use SQLite mutexes should
120 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
121 ** SQLITE_MUTEX_RECURSIVE.
123 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
124 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
125 ** returns a different mutex on every call. But for the static
126 ** mutex types, the same mutex is returned on every call that has
127 ** the same type number.
129 static sqlite3_mutex *pthreadMutexAlloc(int iType){
130 static sqlite3_mutex staticMutexes[] = {
131 SQLITE3_MUTEX_INITIALIZER,
132 SQLITE3_MUTEX_INITIALIZER,
133 SQLITE3_MUTEX_INITIALIZER,
134 SQLITE3_MUTEX_INITIALIZER,
135 SQLITE3_MUTEX_INITIALIZER,
136 SQLITE3_MUTEX_INITIALIZER
138 sqlite3_mutex *p;
139 switch( iType ){
140 case SQLITE_MUTEX_RECURSIVE: {
141 p = sqlite3MallocZero( sizeof(*p) );
142 if( p ){
143 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
144 /* If recursive mutexes are not available, we will have to
145 ** build our own. See below. */
146 pthread_mutex_init(&p->mutex, 0);
147 #else
148 /* Use a recursive mutex if it is available */
149 pthread_mutexattr_t recursiveAttr;
150 pthread_mutexattr_init(&recursiveAttr);
151 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
152 pthread_mutex_init(&p->mutex, &recursiveAttr);
153 pthread_mutexattr_destroy(&recursiveAttr);
154 #endif
155 #if SQLITE_MUTEX_NREF
156 p->id = iType;
157 #endif
159 break;
161 case SQLITE_MUTEX_FAST: {
162 p = sqlite3MallocZero( sizeof(*p) );
163 if( p ){
164 #if SQLITE_MUTEX_NREF
165 p->id = iType;
166 #endif
167 pthread_mutex_init(&p->mutex, 0);
169 break;
171 default: {
172 assert( iType-2 >= 0 );
173 assert( iType-2 < ArraySize(staticMutexes) );
174 p = &staticMutexes[iType-2];
175 #if SQLITE_MUTEX_NREF
176 p->id = iType;
177 #endif
178 break;
181 return p;
186 ** This routine deallocates a previously
187 ** allocated mutex. SQLite is careful to deallocate every
188 ** mutex that it allocates.
190 static void pthreadMutexFree(sqlite3_mutex *p){
191 assert( p->nRef==0 );
192 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
193 pthread_mutex_destroy(&p->mutex);
194 sqlite3_free(p);
198 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
199 ** to enter a mutex. If another thread is already within the mutex,
200 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
201 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
202 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
203 ** be entered multiple times by the same thread. In such cases the,
204 ** mutex must be exited an equal number of times before another thread
205 ** can enter. If the same thread tries to enter any other kind of mutex
206 ** more than once, the behavior is undefined.
208 static void pthreadMutexEnter(sqlite3_mutex *p){
209 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
211 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
212 /* If recursive mutexes are not available, then we have to grow
213 ** our own. This implementation assumes that pthread_equal()
214 ** is atomic - that it cannot be deceived into thinking self
215 ** and p->owner are equal if p->owner changes between two values
216 ** that are not equal to self while the comparison is taking place.
217 ** This implementation also assumes a coherent cache - that
218 ** separate processes cannot read different values from the same
219 ** address at the same time. If either of these two conditions
220 ** are not met, then the mutexes will fail and problems will result.
223 pthread_t self = pthread_self();
224 if( p->nRef>0 && pthread_equal(p->owner, self) ){
225 p->nRef++;
226 }else{
227 pthread_mutex_lock(&p->mutex);
228 assert( p->nRef==0 );
229 p->owner = self;
230 p->nRef = 1;
233 #else
234 /* Use the built-in recursive mutexes if they are available.
236 pthread_mutex_lock(&p->mutex);
237 #if SQLITE_MUTEX_NREF
238 assert( p->nRef>0 || p->owner==0 );
239 p->owner = pthread_self();
240 p->nRef++;
241 #endif
242 #endif
244 #ifdef SQLITE_DEBUG
245 if( p->trace ){
246 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
248 #endif
250 static int pthreadMutexTry(sqlite3_mutex *p){
251 int rc;
252 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
254 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
255 /* If recursive mutexes are not available, then we have to grow
256 ** our own. This implementation assumes that pthread_equal()
257 ** is atomic - that it cannot be deceived into thinking self
258 ** and p->owner are equal if p->owner changes between two values
259 ** that are not equal to self while the comparison is taking place.
260 ** This implementation also assumes a coherent cache - that
261 ** separate processes cannot read different values from the same
262 ** address at the same time. If either of these two conditions
263 ** are not met, then the mutexes will fail and problems will result.
266 pthread_t self = pthread_self();
267 if( p->nRef>0 && pthread_equal(p->owner, self) ){
268 p->nRef++;
269 rc = SQLITE_OK;
270 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
271 assert( p->nRef==0 );
272 p->owner = self;
273 p->nRef = 1;
274 rc = SQLITE_OK;
275 }else{
276 rc = SQLITE_BUSY;
279 #else
280 /* Use the built-in recursive mutexes if they are available.
282 if( pthread_mutex_trylock(&p->mutex)==0 ){
283 #if SQLITE_MUTEX_NREF
284 p->owner = pthread_self();
285 p->nRef++;
286 #endif
287 rc = SQLITE_OK;
288 }else{
289 rc = SQLITE_BUSY;
291 #endif
293 #ifdef SQLITE_DEBUG
294 if( rc==SQLITE_OK && p->trace ){
295 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
297 #endif
298 return rc;
302 ** The sqlite3_mutex_leave() routine exits a mutex that was
303 ** previously entered by the same thread. The behavior
304 ** is undefined if the mutex is not currently entered or
305 ** is not currently allocated. SQLite will never do either.
307 static void pthreadMutexLeave(sqlite3_mutex *p){
308 assert( pthreadMutexHeld(p) );
309 #if SQLITE_MUTEX_NREF
310 p->nRef--;
311 if( p->nRef==0 ) p->owner = 0;
312 #endif
313 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
315 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
316 if( p->nRef==0 ){
317 pthread_mutex_unlock(&p->mutex);
319 #else
320 pthread_mutex_unlock(&p->mutex);
321 #endif
323 #ifdef SQLITE_DEBUG
324 if( p->trace ){
325 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
327 #endif
330 sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
331 static const sqlite3_mutex_methods sMutex = {
332 pthreadMutexInit,
333 pthreadMutexEnd,
334 pthreadMutexAlloc,
335 pthreadMutexFree,
336 pthreadMutexEnter,
337 pthreadMutexTry,
338 pthreadMutexLeave,
339 #ifdef SQLITE_DEBUG
340 pthreadMutexHeld,
341 pthreadMutexNotheld
342 #else
345 #endif
348 return &sMutex;
351 #endif /* SQLITE_MUTEX_PTHREADS */