Back to index

lightning-sunbird  0.9+nobinonly
os_unix.c
Go to the documentation of this file.
00001 /*
00002 ** 2004 May 22
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 ******************************************************************************
00012 **
00013 ** This file contains code that is specific to Unix systems.
00014 */
00015 #include "sqliteInt.h"
00016 #include "os.h"
00017 #if OS_UNIX              /* This file is used on unix only */
00018 
00019 /*
00020 ** These #defines should enable >2GB file support on Posix if the
00021 ** underlying operating system supports it.  If the OS lacks
00022 ** large file support, these should be no-ops.
00023 **
00024 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
00025 ** on the compiler command line.  This is necessary if you are compiling
00026 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
00027 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
00028 ** without this option, LFS is enable.  But LFS does not exist in the kernel
00029 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
00030 ** portability you should omit LFS.
00031 */
00032 #ifndef SQLITE_DISABLE_LFS
00033 # define _LARGE_FILE       1
00034 # ifndef _FILE_OFFSET_BITS
00035 #   define _FILE_OFFSET_BITS 64
00036 # endif
00037 # define _LARGEFILE_SOURCE 1
00038 #endif
00039 
00040 /*
00041 ** standard include files.
00042 */
00043 #include <sys/types.h>
00044 #include <sys/stat.h>
00045 #include <fcntl.h>
00046 #include <unistd.h>
00047 #include <time.h>
00048 #include <sys/time.h>
00049 #include <errno.h>
00050 
00051 /*
00052 ** If we are to be thread-safe, include the pthreads header and define
00053 ** the SQLITE_UNIX_THREADS macro.
00054 */
00055 #if defined(THREADSAFE) && THREADSAFE
00056 # include <pthread.h>
00057 # define SQLITE_UNIX_THREADS 1
00058 #endif
00059 
00060 /*
00061 ** Default permissions when creating a new file
00062 */
00063 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
00064 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
00065 #endif
00066 
00067 
00068 
00069 /*
00070 ** The unixFile structure is subclass of OsFile specific for the unix
00071 ** protability layer.
00072 */
00073 typedef struct unixFile unixFile;
00074 struct unixFile {
00075   IoMethod const *pMethod;  /* Always the first entry */
00076   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
00077   struct lockInfo *pLock;   /* Info about locks on this inode */
00078   int h;                    /* The file descriptor */
00079   unsigned char locktype;   /* The type of lock held on this fd */
00080   unsigned char isOpen;     /* True if needs to be closed */
00081   unsigned char fullSync;   /* Use F_FULLSYNC if available */
00082   int dirfd;                /* File descriptor for the directory */
00083   i64 offset;               /* Seek offset */
00084 #ifdef SQLITE_UNIX_THREADS
00085   pthread_t tid;            /* The thread that "owns" this OsFile */
00086 #endif
00087 };
00088 
00089 /*
00090 ** Provide the ability to override some OS-layer functions during
00091 ** testing.  This is used to simulate OS crashes to verify that 
00092 ** commits are atomic even in the event of an OS crash.
00093 */
00094 #ifdef SQLITE_CRASH_TEST
00095   extern int sqlite3CrashTestEnable;
00096   extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
00097   extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
00098   extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
00099 # define CRASH_TEST_OVERRIDE(X,A,B,C) \
00100     if(sqlite3CrashTestEnable){ return X(A,B,C); }
00101 #else
00102 # define CRASH_TEST_OVERRIDE(X,A,B,C)  /* no-op */
00103 #endif
00104 
00105 
00106 /*
00107 ** Include code that is common to all os_*.c files
00108 */
00109 #include "os_common.h"
00110 
00111 /*
00112 ** Do not include any of the File I/O interface procedures if the
00113 ** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
00114 ** will be in-memory only)
00115 */
00116 #ifndef SQLITE_OMIT_DISKIO
00117 
00118 
00119 /*
00120 ** Define various macros that are missing from some systems.
00121 */
00122 #ifndef O_LARGEFILE
00123 # define O_LARGEFILE 0
00124 #endif
00125 #ifdef SQLITE_DISABLE_LFS
00126 # undef O_LARGEFILE
00127 # define O_LARGEFILE 0
00128 #endif
00129 #ifndef O_NOFOLLOW
00130 # define O_NOFOLLOW 0
00131 #endif
00132 #ifndef O_BINARY
00133 # define O_BINARY 0
00134 #endif
00135 
00136 /*
00137 ** The DJGPP compiler environment looks mostly like Unix, but it
00138 ** lacks the fcntl() system call.  So redefine fcntl() to be something
00139 ** that always succeeds.  This means that locking does not occur under
00140 ** DJGPP.  But it's DOS - what did you expect?
00141 */
00142 #ifdef __DJGPP__
00143 # define fcntl(A,B,C) 0
00144 #endif
00145 
00146 /*
00147 ** The threadid macro resolves to the thread-id or to 0.  Used for
00148 ** testing and debugging only.
00149 */
00150 #ifdef SQLITE_UNIX_THREADS
00151 #define threadid pthread_self()
00152 #else
00153 #define threadid 0
00154 #endif
00155 
00156 /*
00157 ** Set or check the OsFile.tid field.  This field is set when an OsFile
00158 ** is first opened.  All subsequent uses of the OsFile verify that the
00159 ** same thread is operating on the OsFile.  Some operating systems do
00160 ** not allow locks to be overridden by other threads and that restriction
00161 ** means that sqlite3* database handles cannot be moved from one thread
00162 ** to another.  This logic makes sure a user does not try to do that
00163 ** by mistake.
00164 **
00165 ** Version 3.3.1 (2006-01-15):  OsFiles can be moved from one thread to
00166 ** another as long as we are running on a system that supports threads
00167 ** overriding each others locks (which now the most common behavior)
00168 ** or if no locks are held.  But the OsFile.pLock field needs to be
00169 ** recomputed because its key includes the thread-id.  See the 
00170 ** transferOwnership() function below for additional information
00171 */
00172 #if defined(SQLITE_UNIX_THREADS)
00173 # define SET_THREADID(X)   (X)->tid = pthread_self()
00174 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
00175                             !pthread_equal((X)->tid, pthread_self()))
00176 #else
00177 # define SET_THREADID(X)
00178 # define CHECK_THREADID(X) 0
00179 #endif
00180 
00181 /*
00182 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
00183 ** section 6.5.2.2 lines 483 through 490 specify that when a process
00184 ** sets or clears a lock, that operation overrides any prior locks set
00185 ** by the same process.  It does not explicitly say so, but this implies
00186 ** that it overrides locks set by the same process using a different
00187 ** file descriptor.  Consider this test case:
00188 **
00189 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
00190 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
00191 **
00192 ** Suppose ./file1 and ./file2 are really the same file (because
00193 ** one is a hard or symbolic link to the other) then if you set
00194 ** an exclusive lock on fd1, then try to get an exclusive lock
00195 ** on fd2, it works.  I would have expected the second lock to
00196 ** fail since there was already a lock on the file due to fd1.
00197 ** But not so.  Since both locks came from the same process, the
00198 ** second overrides the first, even though they were on different
00199 ** file descriptors opened on different file names.
00200 **
00201 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
00202 ** that we cannot use POSIX locks to synchronize file access among
00203 ** competing threads of the same process.  POSIX locks will work fine
00204 ** to synchronize access for threads in separate processes, but not
00205 ** threads within the same process.
00206 **
00207 ** To work around the problem, SQLite has to manage file locks internally
00208 ** on its own.  Whenever a new database is opened, we have to find the
00209 ** specific inode of the database file (the inode is determined by the
00210 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
00211 ** and check for locks already existing on that inode.  When locks are
00212 ** created or removed, we have to look at our own internal record of the
00213 ** locks to see if another thread has previously set a lock on that same
00214 ** inode.
00215 **
00216 ** The OsFile structure for POSIX is no longer just an integer file
00217 ** descriptor.  It is now a structure that holds the integer file
00218 ** descriptor and a pointer to a structure that describes the internal
00219 ** locks on the corresponding inode.  There is one locking structure
00220 ** per inode, so if the same inode is opened twice, both OsFile structures
00221 ** point to the same locking structure.  The locking structure keeps
00222 ** a reference count (so we will know when to delete it) and a "cnt"
00223 ** field that tells us its internal lock status.  cnt==0 means the
00224 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
00225 ** cnt>0 means there are cnt shared locks on the file.
00226 **
00227 ** Any attempt to lock or unlock a file first checks the locking
00228 ** structure.  The fcntl() system call is only invoked to set a 
00229 ** POSIX lock if the internal lock structure transitions between
00230 ** a locked and an unlocked state.
00231 **
00232 ** 2004-Jan-11:
00233 ** More recent discoveries about POSIX advisory locks.  (The more
00234 ** I discover, the more I realize the a POSIX advisory locks are
00235 ** an abomination.)
00236 **
00237 ** If you close a file descriptor that points to a file that has locks,
00238 ** all locks on that file that are owned by the current process are
00239 ** released.  To work around this problem, each OsFile structure contains
00240 ** a pointer to an openCnt structure.  There is one openCnt structure
00241 ** per open inode, which means that multiple OsFiles can point to a single
00242 ** openCnt.  When an attempt is made to close an OsFile, if there are
00243 ** other OsFiles open on the same inode that are holding locks, the call
00244 ** to close() the file descriptor is deferred until all of the locks clear.
00245 ** The openCnt structure keeps a list of file descriptors that need to
00246 ** be closed and that list is walked (and cleared) when the last lock
00247 ** clears.
00248 **
00249 ** First, under Linux threads, because each thread has a separate
00250 ** process ID, lock operations in one thread do not override locks
00251 ** to the same file in other threads.  Linux threads behave like
00252 ** separate processes in this respect.  But, if you close a file
00253 ** descriptor in linux threads, all locks are cleared, even locks
00254 ** on other threads and even though the other threads have different
00255 ** process IDs.  Linux threads is inconsistent in this respect.
00256 ** (I'm beginning to think that linux threads is an abomination too.)
00257 ** The consequence of this all is that the hash table for the lockInfo
00258 ** structure has to include the process id as part of its key because
00259 ** locks in different threads are treated as distinct.  But the 
00260 ** openCnt structure should not include the process id in its
00261 ** key because close() clears lock on all threads, not just the current
00262 ** thread.  Were it not for this goofiness in linux threads, we could
00263 ** combine the lockInfo and openCnt structures into a single structure.
00264 **
00265 ** 2004-Jun-28:
00266 ** On some versions of linux, threads can override each others locks.
00267 ** On others not.  Sometimes you can change the behavior on the same
00268 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
00269 ** POSIX standard is silent as to which behavior is correct, as far
00270 ** as I can tell, so other versions of unix might show the same
00271 ** inconsistency.  There is no little doubt in my mind that posix
00272 ** advisory locks and linux threads are profoundly broken.
00273 **
00274 ** To work around the inconsistencies, we have to test at runtime 
00275 ** whether or not threads can override each others locks.  This test
00276 ** is run once, the first time any lock is attempted.  A static 
00277 ** variable is set to record the results of this test for future
00278 ** use.
00279 */
00280 
00281 /*
00282 ** An instance of the following structure serves as the key used
00283 ** to locate a particular lockInfo structure given its inode.
00284 **
00285 ** If threads cannot override each others locks, then we set the
00286 ** lockKey.tid field to the thread ID.  If threads can override
00287 ** each others locks then tid is always set to zero.  tid is omitted
00288 ** if we compile without threading support.
00289 */
00290 struct lockKey {
00291   dev_t dev;       /* Device number */
00292   ino_t ino;       /* Inode number */
00293 #ifdef SQLITE_UNIX_THREADS
00294   pthread_t tid;   /* Thread ID or zero if threads can override each other */
00295 #endif
00296 };
00297 
00298 /*
00299 ** An instance of the following structure is allocated for each open
00300 ** inode on each thread with a different process ID.  (Threads have
00301 ** different process IDs on linux, but not on most other unixes.)
00302 **
00303 ** A single inode can have multiple file descriptors, so each OsFile
00304 ** structure contains a pointer to an instance of this object and this
00305 ** object keeps a count of the number of OsFiles pointing to it.
00306 */
00307 struct lockInfo {
00308   struct lockKey key;  /* The lookup key */
00309   int cnt;             /* Number of SHARED locks held */
00310   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
00311   int nRef;            /* Number of pointers to this structure */
00312 };
00313 
00314 /*
00315 ** An instance of the following structure serves as the key used
00316 ** to locate a particular openCnt structure given its inode.  This
00317 ** is the same as the lockKey except that the thread ID is omitted.
00318 */
00319 struct openKey {
00320   dev_t dev;   /* Device number */
00321   ino_t ino;   /* Inode number */
00322 };
00323 
00324 /*
00325 ** An instance of the following structure is allocated for each open
00326 ** inode.  This structure keeps track of the number of locks on that
00327 ** inode.  If a close is attempted against an inode that is holding
00328 ** locks, the close is deferred until all locks clear by adding the
00329 ** file descriptor to be closed to the pending list.
00330 */
00331 struct openCnt {
00332   struct openKey key;   /* The lookup key */
00333   int nRef;             /* Number of pointers to this structure */
00334   int nLock;            /* Number of outstanding locks */
00335   int nPending;         /* Number of pending close() operations */
00336   int *aPending;        /* Malloced space holding fd's awaiting a close() */
00337 };
00338 
00339 /* 
00340 ** These hash tables map inodes and file descriptors (really, lockKey and
00341 ** openKey structures) into lockInfo and openCnt structures.  Access to 
00342 ** these hash tables must be protected by a mutex.
00343 */
00344 static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 
00345     sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
00346 static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 
00347     sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
00348 
00349 #ifdef SQLITE_UNIX_THREADS
00350 /*
00351 ** This variable records whether or not threads can override each others
00352 ** locks.
00353 **
00354 **    0:  No.  Threads cannot override each others locks.
00355 **    1:  Yes.  Threads can override each others locks.
00356 **   -1:  We don't know yet.
00357 **
00358 ** On some systems, we know at compile-time if threads can override each
00359 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
00360 ** will be set appropriately.  On other systems, we have to check at
00361 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
00362 ** undefined.
00363 **
00364 ** This variable normally has file scope only.  But during testing, we make
00365 ** it a global so that the test code can change its value in order to verify
00366 ** that the right stuff happens in either case.
00367 */
00368 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
00369 # define SQLITE_THREAD_OVERRIDE_LOCK -1
00370 #endif
00371 #ifdef SQLITE_TEST
00372 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
00373 #else
00374 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
00375 #endif
00376 
00377 /*
00378 ** This structure holds information passed into individual test
00379 ** threads by the testThreadLockingBehavior() routine.
00380 */
00381 struct threadTestData {
00382   int fd;                /* File to be locked */
00383   struct flock lock;     /* The locking operation */
00384   int result;            /* Result of the locking operation */
00385 };
00386 
00387 #ifdef SQLITE_LOCK_TRACE
00388 /*
00389 ** Print out information about all locking operations.
00390 **
00391 ** This routine is used for troubleshooting locks on multithreaded
00392 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
00393 ** command-line option on the compiler.  This code is normally
00394 ** turned off.
00395 */
00396 static int lockTrace(int fd, int op, struct flock *p){
00397   char *zOpName, *zType;
00398   int s;
00399   int savedErrno;
00400   if( op==F_GETLK ){
00401     zOpName = "GETLK";
00402   }else if( op==F_SETLK ){
00403     zOpName = "SETLK";
00404   }else{
00405     s = fcntl(fd, op, p);
00406     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
00407     return s;
00408   }
00409   if( p->l_type==F_RDLCK ){
00410     zType = "RDLCK";
00411   }else if( p->l_type==F_WRLCK ){
00412     zType = "WRLCK";
00413   }else if( p->l_type==F_UNLCK ){
00414     zType = "UNLCK";
00415   }else{
00416     assert( 0 );
00417   }
00418   assert( p->l_whence==SEEK_SET );
00419   s = fcntl(fd, op, p);
00420   savedErrno = errno;
00421   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
00422      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
00423      (int)p->l_pid, s);
00424   if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
00425     struct flock l2;
00426     l2 = *p;
00427     fcntl(fd, F_GETLK, &l2);
00428     if( l2.l_type==F_RDLCK ){
00429       zType = "RDLCK";
00430     }else if( l2.l_type==F_WRLCK ){
00431       zType = "WRLCK";
00432     }else if( l2.l_type==F_UNLCK ){
00433       zType = "UNLCK";
00434     }else{
00435       assert( 0 );
00436     }
00437     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
00438        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
00439   }
00440   errno = savedErrno;
00441   return s;
00442 }
00443 #define fcntl lockTrace
00444 #endif /* SQLITE_LOCK_TRACE */
00445 
00446 /*
00447 ** The testThreadLockingBehavior() routine launches two separate
00448 ** threads on this routine.  This routine attempts to lock a file
00449 ** descriptor then returns.  The success or failure of that attempt
00450 ** allows the testThreadLockingBehavior() procedure to determine
00451 ** whether or not threads can override each others locks.
00452 */
00453 static void *threadLockingTest(void *pArg){
00454   struct threadTestData *pData = (struct threadTestData*)pArg;
00455   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
00456   return pArg;
00457 }
00458 
00459 /*
00460 ** This procedure attempts to determine whether or not threads
00461 ** can override each others locks then sets the 
00462 ** threadsOverrideEachOthersLocks variable appropriately.
00463 */
00464 static void testThreadLockingBehavior(int fd_orig){
00465   int fd;
00466   struct threadTestData d[2];
00467   pthread_t t[2];
00468 
00469   fd = dup(fd_orig);
00470   if( fd<0 ) return;
00471   memset(d, 0, sizeof(d));
00472   d[0].fd = fd;
00473   d[0].lock.l_type = F_RDLCK;
00474   d[0].lock.l_len = 1;
00475   d[0].lock.l_start = 0;
00476   d[0].lock.l_whence = SEEK_SET;
00477   d[1] = d[0];
00478   d[1].lock.l_type = F_WRLCK;
00479   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
00480   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
00481   pthread_join(t[0], 0);
00482   pthread_join(t[1], 0);
00483   close(fd);
00484   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
00485 }
00486 #endif /* SQLITE_UNIX_THREADS */
00487 
00488 /*
00489 ** Release a lockInfo structure previously allocated by findLockInfo().
00490 */
00491 static void releaseLockInfo(struct lockInfo *pLock){
00492   assert( sqlite3OsInMutex(1) );
00493   pLock->nRef--;
00494   if( pLock->nRef==0 ){
00495     sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
00496     sqlite3ThreadSafeFree(pLock);
00497   }
00498 }
00499 
00500 /*
00501 ** Release a openCnt structure previously allocated by findLockInfo().
00502 */
00503 static void releaseOpenCnt(struct openCnt *pOpen){
00504   assert( sqlite3OsInMutex(1) );
00505   pOpen->nRef--;
00506   if( pOpen->nRef==0 ){
00507     sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
00508     free(pOpen->aPending);
00509     sqlite3ThreadSafeFree(pOpen);
00510   }
00511 }
00512 
00513 /*
00514 ** Given a file descriptor, locate lockInfo and openCnt structures that
00515 ** describes that file descriptor.  Create new ones if necessary.  The
00516 ** return values might be uninitialized if an error occurs.
00517 **
00518 ** Return the number of errors.
00519 */
00520 static int findLockInfo(
00521   int fd,                      /* The file descriptor used in the key */
00522   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
00523   struct openCnt **ppOpen      /* Return the openCnt structure here */
00524 ){
00525   int rc;
00526   struct lockKey key1;
00527   struct openKey key2;
00528   struct stat statbuf;
00529   struct lockInfo *pLock;
00530   struct openCnt *pOpen;
00531   rc = fstat(fd, &statbuf);
00532   if( rc!=0 ) return 1;
00533 
00534   assert( sqlite3OsInMutex(1) );
00535   memset(&key1, 0, sizeof(key1));
00536   key1.dev = statbuf.st_dev;
00537   key1.ino = statbuf.st_ino;
00538 #ifdef SQLITE_UNIX_THREADS
00539   if( threadsOverrideEachOthersLocks<0 ){
00540     testThreadLockingBehavior(fd);
00541   }
00542   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
00543 #endif
00544   memset(&key2, 0, sizeof(key2));
00545   key2.dev = statbuf.st_dev;
00546   key2.ino = statbuf.st_ino;
00547   pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
00548   if( pLock==0 ){
00549     struct lockInfo *pOld;
00550     pLock = sqlite3ThreadSafeMalloc( sizeof(*pLock) );
00551     if( pLock==0 ){
00552       rc = 1;
00553       goto exit_findlockinfo;
00554     }
00555     pLock->key = key1;
00556     pLock->nRef = 1;
00557     pLock->cnt = 0;
00558     pLock->locktype = 0;
00559     pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
00560     if( pOld!=0 ){
00561       assert( pOld==pLock );
00562       sqlite3ThreadSafeFree(pLock);
00563       rc = 1;
00564       goto exit_findlockinfo;
00565     }
00566   }else{
00567     pLock->nRef++;
00568   }
00569   *ppLock = pLock;
00570   if( ppOpen!=0 ){
00571     pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
00572     if( pOpen==0 ){
00573       struct openCnt *pOld;
00574       pOpen = sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
00575       if( pOpen==0 ){
00576         releaseLockInfo(pLock);
00577         rc = 1;
00578         goto exit_findlockinfo;
00579       }
00580       pOpen->key = key2;
00581       pOpen->nRef = 1;
00582       pOpen->nLock = 0;
00583       pOpen->nPending = 0;
00584       pOpen->aPending = 0;
00585       pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
00586       if( pOld!=0 ){
00587         assert( pOld==pOpen );
00588         sqlite3ThreadSafeFree(pOpen);
00589         releaseLockInfo(pLock);
00590         rc = 1;
00591         goto exit_findlockinfo;
00592       }
00593     }else{
00594       pOpen->nRef++;
00595     }
00596     *ppOpen = pOpen;
00597   }
00598 
00599 exit_findlockinfo:
00600   return rc;
00601 }
00602 
00603 #ifdef SQLITE_DEBUG
00604 /*
00605 ** Helper function for printing out trace information from debugging
00606 ** binaries. This returns the string represetation of the supplied
00607 ** integer lock-type.
00608 */
00609 static const char *locktypeName(int locktype){
00610   switch( locktype ){
00611   case NO_LOCK: return "NONE";
00612   case SHARED_LOCK: return "SHARED";
00613   case RESERVED_LOCK: return "RESERVED";
00614   case PENDING_LOCK: return "PENDING";
00615   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
00616   }
00617   return "ERROR";
00618 }
00619 #endif
00620 
00621 /*
00622 ** If we are currently in a different thread than the thread that the
00623 ** unixFile argument belongs to, then transfer ownership of the unixFile
00624 ** over to the current thread.
00625 **
00626 ** A unixFile is only owned by a thread on systems where one thread is
00627 ** unable to override locks created by a different thread.  RedHat9 is
00628 ** an example of such a system.
00629 **
00630 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
00631 ** If the unixFile is locked and an ownership is wrong, then return
00632 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
00633 */
00634 #ifdef SQLITE_UNIX_THREADS
00635 static int transferOwnership(unixFile *pFile){
00636   int rc;
00637   pthread_t hSelf;
00638   if( threadsOverrideEachOthersLocks ){
00639     /* Ownership transfers not needed on this system */
00640     return SQLITE_OK;
00641   }
00642   hSelf = pthread_self();
00643   if( pthread_equal(pFile->tid, hSelf) ){
00644     /* We are still in the same thread */
00645     TRACE1("No-transfer, same thread\n");
00646     return SQLITE_OK;
00647   }
00648   if( pFile->locktype!=NO_LOCK ){
00649     /* We cannot change ownership while we are holding a lock! */
00650     return SQLITE_MISUSE;
00651   }
00652   TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
00653   pFile->tid = hSelf;
00654   releaseLockInfo(pFile->pLock);
00655   rc = findLockInfo(pFile->h, &pFile->pLock, 0);
00656   TRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
00657      locktypeName(pFile->locktype),
00658      locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
00659   return rc;
00660 }
00661 #else
00662   /* On single-threaded builds, ownership transfer is a no-op */
00663 # define transferOwnership(X) SQLITE_OK
00664 #endif
00665 
00666 /*
00667 ** Delete the named file
00668 */
00669 int sqlite3UnixDelete(const char *zFilename){
00670   unlink(zFilename);
00671   return SQLITE_OK;
00672 }
00673 
00674 /*
00675 ** Return TRUE if the named file exists.
00676 */
00677 int sqlite3UnixFileExists(const char *zFilename){
00678   return access(zFilename, 0)==0;
00679 }
00680 
00681 /* Forward declaration */
00682 static int allocateUnixFile(unixFile *pInit, OsFile **pId);
00683 
00684 /*
00685 ** Attempt to open a file for both reading and writing.  If that
00686 ** fails, try opening it read-only.  If the file does not exist,
00687 ** try to create it.
00688 **
00689 ** On success, a handle for the open file is written to *id
00690 ** and *pReadonly is set to 0 if the file was opened for reading and
00691 ** writing or 1 if the file was opened read-only.  The function returns
00692 ** SQLITE_OK.
00693 **
00694 ** On failure, the function returns SQLITE_CANTOPEN and leaves
00695 ** *id and *pReadonly unchanged.
00696 */
00697 int sqlite3UnixOpenReadWrite(
00698   const char *zFilename,
00699   OsFile **pId,
00700   int *pReadonly
00701 ){
00702   int rc;
00703   unixFile f;
00704 
00705   CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
00706   assert( 0==*pId );
00707   f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
00708                           SQLITE_DEFAULT_FILE_PERMISSIONS);
00709   if( f.h<0 ){
00710 #ifdef EISDIR
00711     if( errno==EISDIR ){
00712       return SQLITE_CANTOPEN;
00713     }
00714 #endif
00715     f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
00716     if( f.h<0 ){
00717       return SQLITE_CANTOPEN; 
00718     }
00719     *pReadonly = 1;
00720   }else{
00721     *pReadonly = 0;
00722   }
00723   sqlite3OsEnterMutex();
00724   rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
00725   sqlite3OsLeaveMutex();
00726   if( rc ){
00727     close(f.h);
00728     return SQLITE_NOMEM;
00729   }
00730   TRACE3("OPEN    %-3d %s\n", f.h, zFilename);
00731   return allocateUnixFile(&f, pId);
00732 }
00733 
00734 
00735 /*
00736 ** Attempt to open a new file for exclusive access by this process.
00737 ** The file will be opened for both reading and writing.  To avoid
00738 ** a potential security problem, we do not allow the file to have
00739 ** previously existed.  Nor do we allow the file to be a symbolic
00740 ** link.
00741 **
00742 ** If delFlag is true, then make arrangements to automatically delete
00743 ** the file when it is closed.
00744 **
00745 ** On success, write the file handle into *id and return SQLITE_OK.
00746 **
00747 ** On failure, return SQLITE_CANTOPEN.
00748 */
00749 int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
00750   int rc;
00751   unixFile f;
00752 
00753   CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
00754   assert( 0==*pId );
00755   f.h = open(zFilename,
00756                 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
00757                 SQLITE_DEFAULT_FILE_PERMISSIONS);
00758   if( f.h<0 ){
00759     return SQLITE_CANTOPEN;
00760   }
00761   sqlite3OsEnterMutex();
00762   rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
00763   sqlite3OsLeaveMutex();
00764   if( rc ){
00765     close(f.h);
00766     unlink(zFilename);
00767     return SQLITE_NOMEM;
00768   }
00769   if( delFlag ){
00770     unlink(zFilename);
00771   }
00772   TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
00773   return allocateUnixFile(&f, pId);
00774 }
00775 
00776 /*
00777 ** Attempt to open a new file for read-only access.
00778 **
00779 ** On success, write the file handle into *id and return SQLITE_OK.
00780 **
00781 ** On failure, return SQLITE_CANTOPEN.
00782 */
00783 int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
00784   int rc;
00785   unixFile f;
00786 
00787   CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
00788   assert( 0==*pId );
00789   f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
00790   if( f.h<0 ){
00791     return SQLITE_CANTOPEN;
00792   }
00793   sqlite3OsEnterMutex();
00794   rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
00795   sqlite3OsLeaveMutex();
00796   if( rc ){
00797     close(f.h);
00798     return SQLITE_NOMEM;
00799   }
00800   TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
00801   return allocateUnixFile(&f, pId);
00802 }
00803 
00804 /*
00805 ** Attempt to open a file descriptor for the directory that contains a
00806 ** file.  This file descriptor can be used to fsync() the directory
00807 ** in order to make sure the creation of a new file is actually written
00808 ** to disk.
00809 **
00810 ** This routine is only meaningful for Unix.  It is a no-op under
00811 ** windows since windows does not support hard links.
00812 **
00813 ** On success, a handle for a previously open file at *id is
00814 ** updated with the new directory file descriptor and SQLITE_OK is
00815 ** returned.
00816 **
00817 ** On failure, the function returns SQLITE_CANTOPEN and leaves
00818 ** *id unchanged.
00819 */
00820 static int unixOpenDirectory(
00821   OsFile *id,
00822   const char *zDirname
00823 ){
00824   unixFile *pFile = (unixFile*)id;
00825   if( pFile==0 ){
00826     /* Do not open the directory if the corresponding file is not already
00827     ** open. */
00828     return SQLITE_CANTOPEN;
00829   }
00830   SET_THREADID(pFile);
00831   assert( pFile->dirfd<0 );
00832   pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
00833   if( pFile->dirfd<0 ){
00834     return SQLITE_CANTOPEN; 
00835   }
00836   TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
00837   return SQLITE_OK;
00838 }
00839 
00840 /*
00841 ** If the following global variable points to a string which is the
00842 ** name of a directory, then that directory will be used to store
00843 ** temporary files.
00844 **
00845 ** See also the "PRAGMA temp_store_directory" SQL command.
00846 */
00847 char *sqlite3_temp_directory = 0;
00848 
00849 /*
00850 ** Create a temporary file name in zBuf.  zBuf must be big enough to
00851 ** hold at least SQLITE_TEMPNAME_SIZE characters.
00852 */
00853 int sqlite3UnixTempFileName(char *zBuf){
00854   static const char *azDirs[] = {
00855      0,
00856      "/var/tmp",
00857      "/usr/tmp",
00858      "/tmp",
00859      ".",
00860   };
00861   static const unsigned char zChars[] =
00862     "abcdefghijklmnopqrstuvwxyz"
00863     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
00864     "0123456789";
00865   int i, j;
00866   struct stat buf;
00867   const char *zDir = ".";
00868   azDirs[0] = sqlite3_temp_directory;
00869   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
00870     if( azDirs[i]==0 ) continue;
00871     if( stat(azDirs[i], &buf) ) continue;
00872     if( !S_ISDIR(buf.st_mode) ) continue;
00873     if( access(azDirs[i], 07) ) continue;
00874     zDir = azDirs[i];
00875     break;
00876   }
00877   do{
00878     sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
00879     j = strlen(zBuf);
00880     sqlite3Randomness(15, &zBuf[j]);
00881     for(i=0; i<15; i++, j++){
00882       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
00883     }
00884     zBuf[j] = 0;
00885   }while( access(zBuf,0)==0 );
00886   return SQLITE_OK; 
00887 }
00888 
00889 /*
00890 ** Check that a given pathname is a directory and is writable 
00891 **
00892 */
00893 int sqlite3UnixIsDirWritable(char *zBuf){
00894 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
00895   struct stat buf;
00896   if( zBuf==0 ) return 0;
00897   if( zBuf[0]==0 ) return 0;
00898   if( stat(zBuf, &buf) ) return 0;
00899   if( !S_ISDIR(buf.st_mode) ) return 0;
00900   if( access(zBuf, 07) ) return 0;
00901 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
00902   return 1;
00903 }
00904 
00905 /*
00906 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
00907 ** Return the number of bytes actually read.  Update the offset.
00908 */
00909 static int seekAndRead(unixFile *id, void *pBuf, int cnt){
00910   int got;
00911 #ifdef USE_PREAD
00912   got = pread(id->h, pBuf, cnt, id->offset);
00913 #else
00914   lseek(id->h, id->offset, SEEK_SET);
00915   got = read(id->h, pBuf, cnt);
00916 #endif
00917   if( got>0 ){
00918     id->offset += got;
00919   }
00920   return got;
00921 }
00922 
00923 /*
00924 ** Read data from a file into a buffer.  Return SQLITE_OK if all
00925 ** bytes were read successfully and SQLITE_IOERR if anything goes
00926 ** wrong.
00927 */
00928 static int unixRead(OsFile *id, void *pBuf, int amt){
00929   int got;
00930   assert( id );
00931   SimulateIOError(SQLITE_IOERR);
00932   TIMER_START;
00933   got = seekAndRead((unixFile*)id, pBuf, amt);
00934   TIMER_END;
00935   TRACE5("READ    %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
00936           last_page, TIMER_ELAPSED);
00937   SEEK(0);
00938   /* if( got<0 ) got = 0; */
00939   if( got==amt ){
00940     return SQLITE_OK;
00941   }else{
00942     return SQLITE_IOERR;
00943   }
00944 }
00945 
00946 /*
00947 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
00948 ** Return the number of bytes actually read.  Update the offset.
00949 */
00950 static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
00951   int got;
00952 #ifdef USE_PREAD
00953   got = pwrite(id->h, pBuf, cnt, id->offset);
00954 #else
00955   lseek(id->h, id->offset, SEEK_SET);
00956   got = write(id->h, pBuf, cnt);
00957 #endif
00958   if( got>0 ){
00959     id->offset += got;
00960   }
00961   return got;
00962 }
00963 
00964 
00965 /*
00966 ** Write data from a buffer into a file.  Return SQLITE_OK on success
00967 ** or some other error code on failure.
00968 */
00969 static int unixWrite(OsFile *id, const void *pBuf, int amt){
00970   int wrote = 0;
00971   assert( id );
00972   assert( amt>0 );
00973   SimulateIOError(SQLITE_IOERR);
00974   SimulateDiskfullError;
00975   TIMER_START;
00976   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
00977     amt -= wrote;
00978     pBuf = &((char*)pBuf)[wrote];
00979   }
00980   TIMER_END;
00981   TRACE5("WRITE   %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
00982           last_page, TIMER_ELAPSED);
00983   SEEK(0);
00984   if( amt>0 ){
00985     return SQLITE_FULL;
00986   }
00987   return SQLITE_OK;
00988 }
00989 
00990 /*
00991 ** Move the read/write pointer in a file.
00992 */
00993 static int unixSeek(OsFile *id, i64 offset){
00994   assert( id );
00995   SEEK(offset/1024 + 1);
00996 #ifdef SQLITE_TEST
00997   if( offset ) SimulateDiskfullError
00998 #endif
00999   ((unixFile*)id)->offset = offset;
01000   return SQLITE_OK;
01001 }
01002 
01003 #ifdef SQLITE_TEST
01004 /*
01005 ** Count the number of fullsyncs and normal syncs.  This is used to test
01006 ** that syncs and fullsyncs are occuring at the right times.
01007 */
01008 int sqlite3_sync_count = 0;
01009 int sqlite3_fullsync_count = 0;
01010 #endif
01011 
01012 /*
01013 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
01014 ** Otherwise use fsync() in its place.
01015 */
01016 #ifndef HAVE_FDATASYNC
01017 # define fdatasync fsync
01018 #endif
01019 
01020 /*
01021 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
01022 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
01023 ** only available on Mac OS X.  But that could change.
01024 */
01025 #ifdef F_FULLFSYNC
01026 # define HAVE_FULLFSYNC 1
01027 #else
01028 # define HAVE_FULLFSYNC 0
01029 #endif
01030 
01031 
01032 /*
01033 ** The fsync() system call does not work as advertised on many
01034 ** unix systems.  The following procedure is an attempt to make
01035 ** it work better.
01036 **
01037 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
01038 ** for testing when we want to run through the test suite quickly.
01039 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
01040 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
01041 ** or power failure will likely corrupt the database file.
01042 */
01043 static int full_fsync(int fd, int fullSync, int dataOnly){
01044   int rc;
01045 
01046   /* Record the number of times that we do a normal fsync() and 
01047   ** FULLSYNC.  This is used during testing to verify that this procedure
01048   ** gets called with the correct arguments.
01049   */
01050 #ifdef SQLITE_TEST
01051   if( fullSync ) sqlite3_fullsync_count++;
01052   sqlite3_sync_count++;
01053 #endif
01054 
01055   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
01056   ** no-op
01057   */
01058 #ifdef SQLITE_NO_SYNC
01059   rc = SQLITE_OK;
01060 #else
01061 
01062 #if HAVE_FULLFSYNC
01063   if( fullSync ){
01064     rc = fcntl(fd, F_FULLFSYNC, 0);
01065   }else{
01066     rc = 1;
01067   }
01068   /* If the FULLSYNC failed, try to do a normal fsync() */
01069   if( rc ) rc = fsync(fd);
01070 
01071 #else /* if !defined(F_FULLSYNC) */
01072   if( dataOnly ){
01073     rc = fdatasync(fd);
01074   }else{
01075     rc = fsync(fd);
01076   }
01077 #endif /* defined(F_FULLFSYNC) */
01078 #endif /* defined(SQLITE_NO_SYNC) */
01079 
01080   return rc;
01081 }
01082 
01083 /*
01084 ** Make sure all writes to a particular file are committed to disk.
01085 **
01086 ** If dataOnly==0 then both the file itself and its metadata (file
01087 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
01088 ** file data is synced.
01089 **
01090 ** Under Unix, also make sure that the directory entry for the file
01091 ** has been created by fsync-ing the directory that contains the file.
01092 ** If we do not do this and we encounter a power failure, the directory
01093 ** entry for the journal might not exist after we reboot.  The next
01094 ** SQLite to access the file will not know that the journal exists (because
01095 ** the directory entry for the journal was never created) and the transaction
01096 ** will not roll back - possibly leading to database corruption.
01097 */
01098 static int unixSync(OsFile *id, int dataOnly){
01099   unixFile *pFile = (unixFile*)id;
01100   assert( pFile );
01101   SimulateIOError(SQLITE_IOERR);
01102   TRACE2("SYNC    %-3d\n", pFile->h);
01103   if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
01104     return SQLITE_IOERR;
01105   }
01106   if( pFile->dirfd>=0 ){
01107     TRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
01108             HAVE_FULLFSYNC, pFile->fullSync);
01109 #ifndef SQLITE_DISABLE_DIRSYNC
01110     /* The directory sync is only attempted if full_fsync is
01111     ** turned off or unavailable.  If a full_fsync occurred above,
01112     ** then the directory sync is superfluous.
01113     */
01114     if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
01115        /*
01116        ** We have received multiple reports of fsync() returning
01117        ** errors when applied to directories on certain file systems.
01118        ** A failed directory sync is not a big deal.  So it seems
01119        ** better to ignore the error.  Ticket #1657
01120        */
01121        /* return SQLITE_IOERR; */
01122     }
01123 #endif
01124     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
01125     pFile->dirfd = -1;    /* when we are done. */
01126   }
01127   return SQLITE_OK;
01128 }
01129 
01130 /*
01131 ** Sync the directory zDirname. This is a no-op on operating systems other
01132 ** than UNIX.
01133 **
01134 ** This is used to make sure the master journal file has truely been deleted
01135 ** before making changes to individual journals on a multi-database commit.
01136 ** The F_FULLFSYNC option is not needed here.
01137 */
01138 int sqlite3UnixSyncDirectory(const char *zDirname){
01139 #ifdef SQLITE_DISABLE_DIRSYNC
01140   return SQLITE_OK;
01141 #else
01142   int fd;
01143   int r;
01144   SimulateIOError(SQLITE_IOERR);
01145   fd = open(zDirname, O_RDONLY|O_BINARY, 0);
01146   TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
01147   if( fd<0 ){
01148     return SQLITE_CANTOPEN; 
01149   }
01150   r = fsync(fd);
01151   close(fd);
01152   return ((r==0)?SQLITE_OK:SQLITE_IOERR);
01153 #endif
01154 }
01155 
01156 /*
01157 ** Truncate an open file to a specified size
01158 */
01159 static int unixTruncate(OsFile *id, i64 nByte){
01160   assert( id );
01161   SimulateIOError(SQLITE_IOERR);
01162   return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
01163 }
01164 
01165 /*
01166 ** Determine the current size of a file in bytes
01167 */
01168 static int unixFileSize(OsFile *id, i64 *pSize){
01169   struct stat buf;
01170   assert( id );
01171   SimulateIOError(SQLITE_IOERR);
01172   if( fstat(((unixFile*)id)->h, &buf)!=0 ){
01173     return SQLITE_IOERR;
01174   }
01175   *pSize = buf.st_size;
01176   return SQLITE_OK;
01177 }
01178 
01179 /*
01180 ** This routine checks if there is a RESERVED lock held on the specified
01181 ** file by this or any other process. If such a lock is held, return
01182 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
01183 ** return zero.
01184 */
01185 static int unixCheckReservedLock(OsFile *id){
01186   int r = 0;
01187   unixFile *pFile = (unixFile*)id;
01188 
01189   assert( pFile );
01190   sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
01191 
01192   /* Check if a thread in this process holds such a lock */
01193   if( pFile->pLock->locktype>SHARED_LOCK ){
01194     r = 1;
01195   }
01196 
01197   /* Otherwise see if some other process holds it.
01198   */
01199   if( !r ){
01200     struct flock lock;
01201     lock.l_whence = SEEK_SET;
01202     lock.l_start = RESERVED_BYTE;
01203     lock.l_len = 1;
01204     lock.l_type = F_WRLCK;
01205     fcntl(pFile->h, F_GETLK, &lock);
01206     if( lock.l_type!=F_UNLCK ){
01207       r = 1;
01208     }
01209   }
01210   
01211   sqlite3OsLeaveMutex();
01212   TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
01213 
01214   return r;
01215 }
01216 
01217 /*
01218 ** Lock the file with the lock specified by parameter locktype - one
01219 ** of the following:
01220 **
01221 **     (1) SHARED_LOCK
01222 **     (2) RESERVED_LOCK
01223 **     (3) PENDING_LOCK
01224 **     (4) EXCLUSIVE_LOCK
01225 **
01226 ** Sometimes when requesting one lock state, additional lock states
01227 ** are inserted in between.  The locking might fail on one of the later
01228 ** transitions leaving the lock state different from what it started but
01229 ** still short of its goal.  The following chart shows the allowed
01230 ** transitions and the inserted intermediate states:
01231 **
01232 **    UNLOCKED -> SHARED
01233 **    SHARED -> RESERVED
01234 **    SHARED -> (PENDING) -> EXCLUSIVE
01235 **    RESERVED -> (PENDING) -> EXCLUSIVE
01236 **    PENDING -> EXCLUSIVE
01237 **
01238 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
01239 ** routine to lower a locking level.
01240 */
01241 static int unixLock(OsFile *id, int locktype){
01242   /* The following describes the implementation of the various locks and
01243   ** lock transitions in terms of the POSIX advisory shared and exclusive
01244   ** lock primitives (called read-locks and write-locks below, to avoid
01245   ** confusion with SQLite lock names). The algorithms are complicated
01246   ** slightly in order to be compatible with windows systems simultaneously
01247   ** accessing the same database file, in case that is ever required.
01248   **
01249   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
01250   ** byte', each single bytes at well known offsets, and the 'shared byte
01251   ** range', a range of 510 bytes at a well known offset.
01252   **
01253   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
01254   ** byte'.  If this is successful, a random byte from the 'shared byte
01255   ** range' is read-locked and the lock on the 'pending byte' released.
01256   **
01257   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
01258   ** A RESERVED lock is implemented by grabbing a write-lock on the
01259   ** 'reserved byte'. 
01260   **
01261   ** A process may only obtain a PENDING lock after it has obtained a
01262   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
01263   ** on the 'pending byte'. This ensures that no new SHARED locks can be
01264   ** obtained, but existing SHARED locks are allowed to persist. A process
01265   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
01266   ** This property is used by the algorithm for rolling back a journal file
01267   ** after a crash.
01268   **
01269   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
01270   ** implemented by obtaining a write-lock on the entire 'shared byte
01271   ** range'. Since all other locks require a read-lock on one of the bytes
01272   ** within this range, this ensures that no other locks are held on the
01273   ** database. 
01274   **
01275   ** The reason a single byte cannot be used instead of the 'shared byte
01276   ** range' is that some versions of windows do not support read-locks. By
01277   ** locking a random byte from a range, concurrent SHARED locks may exist
01278   ** even if the locking primitive used is always a write-lock.
01279   */
01280   int rc = SQLITE_OK;
01281   unixFile *pFile = (unixFile*)id;
01282   struct lockInfo *pLock = pFile->pLock;
01283   struct flock lock;
01284   int s;
01285 
01286   assert( pFile );
01287   TRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
01288       locktypeName(locktype), locktypeName(pFile->locktype),
01289       locktypeName(pLock->locktype), pLock->cnt , getpid());
01290 
01291   /* If there is already a lock of this type or more restrictive on the
01292   ** OsFile, do nothing. Don't use the end_lock: exit path, as
01293   ** sqlite3OsEnterMutex() hasn't been called yet.
01294   */
01295   if( pFile->locktype>=locktype ){
01296     TRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
01297             locktypeName(locktype));
01298     return SQLITE_OK;
01299   }
01300 
01301   /* Make sure the locking sequence is correct
01302   */
01303   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
01304   assert( locktype!=PENDING_LOCK );
01305   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
01306 
01307   /* This mutex is needed because pFile->pLock is shared across threads
01308   */
01309   sqlite3OsEnterMutex();
01310 
01311   /* Make sure the current thread owns the pFile.
01312   */
01313   rc = transferOwnership(pFile);
01314   if( rc!=SQLITE_OK ){
01315     sqlite3OsLeaveMutex();
01316     return rc;
01317   }
01318   pLock = pFile->pLock;
01319 
01320   /* If some thread using this PID has a lock via a different OsFile*
01321   ** handle that precludes the requested lock, return BUSY.
01322   */
01323   if( (pFile->locktype!=pLock->locktype && 
01324           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
01325   ){
01326     rc = SQLITE_BUSY;
01327     goto end_lock;
01328   }
01329 
01330   /* If a SHARED lock is requested, and some thread using this PID already
01331   ** has a SHARED or RESERVED lock, then increment reference counts and
01332   ** return SQLITE_OK.
01333   */
01334   if( locktype==SHARED_LOCK && 
01335       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
01336     assert( locktype==SHARED_LOCK );
01337     assert( pFile->locktype==0 );
01338     assert( pLock->cnt>0 );
01339     pFile->locktype = SHARED_LOCK;
01340     pLock->cnt++;
01341     pFile->pOpen->nLock++;
01342     goto end_lock;
01343   }
01344 
01345   lock.l_len = 1L;
01346 
01347   lock.l_whence = SEEK_SET;
01348 
01349   /* A PENDING lock is needed before acquiring a SHARED lock and before
01350   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
01351   ** be released.
01352   */
01353   if( locktype==SHARED_LOCK 
01354       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
01355   ){
01356     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
01357     lock.l_start = PENDING_BYTE;
01358     s = fcntl(pFile->h, F_SETLK, &lock);
01359     if( s ){
01360       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
01361       goto end_lock;
01362     }
01363   }
01364 
01365 
01366   /* If control gets to this point, then actually go ahead and make
01367   ** operating system calls for the specified lock.
01368   */
01369   if( locktype==SHARED_LOCK ){
01370     assert( pLock->cnt==0 );
01371     assert( pLock->locktype==0 );
01372 
01373     /* Now get the read-lock */
01374     lock.l_start = SHARED_FIRST;
01375     lock.l_len = SHARED_SIZE;
01376     s = fcntl(pFile->h, F_SETLK, &lock);
01377 
01378     /* Drop the temporary PENDING lock */
01379     lock.l_start = PENDING_BYTE;
01380     lock.l_len = 1L;
01381     lock.l_type = F_UNLCK;
01382     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
01383       rc = SQLITE_IOERR;  /* This should never happen */
01384       goto end_lock;
01385     }
01386     if( s ){
01387       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
01388     }else{
01389       pFile->locktype = SHARED_LOCK;
01390       pFile->pOpen->nLock++;
01391       pLock->cnt = 1;
01392     }
01393   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
01394     /* We are trying for an exclusive lock but another thread in this
01395     ** same process is still holding a shared lock. */
01396     rc = SQLITE_BUSY;
01397   }else{
01398     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
01399     ** assumed that there is a SHARED or greater lock on the file
01400     ** already.
01401     */
01402     assert( 0!=pFile->locktype );
01403     lock.l_type = F_WRLCK;
01404     switch( locktype ){
01405       case RESERVED_LOCK:
01406         lock.l_start = RESERVED_BYTE;
01407         break;
01408       case EXCLUSIVE_LOCK:
01409         lock.l_start = SHARED_FIRST;
01410         lock.l_len = SHARED_SIZE;
01411         break;
01412       default:
01413         assert(0);
01414     }
01415     s = fcntl(pFile->h, F_SETLK, &lock);
01416     if( s ){
01417       rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
01418     }
01419   }
01420   
01421   if( rc==SQLITE_OK ){
01422     pFile->locktype = locktype;
01423     pLock->locktype = locktype;
01424   }else if( locktype==EXCLUSIVE_LOCK ){
01425     pFile->locktype = PENDING_LOCK;
01426     pLock->locktype = PENDING_LOCK;
01427   }
01428 
01429 end_lock:
01430   sqlite3OsLeaveMutex();
01431   TRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
01432       rc==SQLITE_OK ? "ok" : "failed");
01433   return rc;
01434 }
01435 
01436 /*
01437 ** Lower the locking level on file descriptor pFile to locktype.  locktype
01438 ** must be either NO_LOCK or SHARED_LOCK.
01439 **
01440 ** If the locking level of the file descriptor is already at or below
01441 ** the requested locking level, this routine is a no-op.
01442 */
01443 static int unixUnlock(OsFile *id, int locktype){
01444   struct lockInfo *pLock;
01445   struct flock lock;
01446   int rc = SQLITE_OK;
01447   unixFile *pFile = (unixFile*)id;
01448 
01449   assert( pFile );
01450   TRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
01451       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
01452 
01453   assert( locktype<=SHARED_LOCK );
01454   if( pFile->locktype<=locktype ){
01455     return SQLITE_OK;
01456   }
01457   if( CHECK_THREADID(pFile) ){
01458     return SQLITE_MISUSE;
01459   }
01460   sqlite3OsEnterMutex();
01461   pLock = pFile->pLock;
01462   assert( pLock->cnt!=0 );
01463   if( pFile->locktype>SHARED_LOCK ){
01464     assert( pLock->locktype==pFile->locktype );
01465     if( locktype==SHARED_LOCK ){
01466       lock.l_type = F_RDLCK;
01467       lock.l_whence = SEEK_SET;
01468       lock.l_start = SHARED_FIRST;
01469       lock.l_len = SHARED_SIZE;
01470       if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
01471         /* This should never happen */
01472         rc = SQLITE_IOERR;
01473       }
01474     }
01475     lock.l_type = F_UNLCK;
01476     lock.l_whence = SEEK_SET;
01477     lock.l_start = PENDING_BYTE;
01478     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
01479     if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
01480       pLock->locktype = SHARED_LOCK;
01481     }else{
01482       rc = SQLITE_IOERR;  /* This should never happen */
01483     }
01484   }
01485   if( locktype==NO_LOCK ){
01486     struct openCnt *pOpen;
01487 
01488     /* Decrement the shared lock counter.  Release the lock using an
01489     ** OS call only when all threads in this same process have released
01490     ** the lock.
01491     */
01492     pLock->cnt--;
01493     if( pLock->cnt==0 ){
01494       lock.l_type = F_UNLCK;
01495       lock.l_whence = SEEK_SET;
01496       lock.l_start = lock.l_len = 0L;
01497       if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
01498         pLock->locktype = NO_LOCK;
01499       }else{
01500         rc = SQLITE_IOERR;  /* This should never happen */
01501       }
01502     }
01503 
01504     /* Decrement the count of locks against this same file.  When the
01505     ** count reaches zero, close any other file descriptors whose close
01506     ** was deferred because of outstanding locks.
01507     */
01508     pOpen = pFile->pOpen;
01509     pOpen->nLock--;
01510     assert( pOpen->nLock>=0 );
01511     if( pOpen->nLock==0 && pOpen->nPending>0 ){
01512       int i;
01513       for(i=0; i<pOpen->nPending; i++){
01514         close(pOpen->aPending[i]);
01515       }
01516       free(pOpen->aPending);
01517       pOpen->nPending = 0;
01518       pOpen->aPending = 0;
01519     }
01520   }
01521   sqlite3OsLeaveMutex();
01522   pFile->locktype = locktype;
01523   return rc;
01524 }
01525 
01526 /*
01527 ** Close a file.
01528 */
01529 static int unixClose(OsFile **pId){
01530   unixFile *id = (unixFile*)*pId;
01531 
01532   if( !id ) return SQLITE_OK;
01533   unixUnlock(*pId, NO_LOCK);
01534   if( id->dirfd>=0 ) close(id->dirfd);
01535   id->dirfd = -1;
01536   sqlite3OsEnterMutex();
01537 
01538   if( id->pOpen->nLock ){
01539     /* If there are outstanding locks, do not actually close the file just
01540     ** yet because that would clear those locks.  Instead, add the file
01541     ** descriptor to pOpen->aPending.  It will be automatically closed when
01542     ** the last lock is cleared.
01543     */
01544     int *aNew;
01545     struct openCnt *pOpen = id->pOpen;
01546     aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
01547     if( aNew==0 ){
01548       /* If a malloc fails, just leak the file descriptor */
01549     }else{
01550       pOpen->aPending = aNew;
01551       pOpen->aPending[pOpen->nPending] = id->h;
01552       pOpen->nPending++;
01553     }
01554   }else{
01555     /* There are no outstanding locks so we can close the file immediately */
01556     close(id->h);
01557   }
01558   releaseLockInfo(id->pLock);
01559   releaseOpenCnt(id->pOpen);
01560 
01561   sqlite3OsLeaveMutex();
01562   id->isOpen = 0;
01563   TRACE2("CLOSE   %-3d\n", id->h);
01564   OpenCounter(-1);
01565   sqlite3ThreadSafeFree(id);
01566   *pId = 0;
01567   return SQLITE_OK;
01568 }
01569 
01570 /*
01571 ** Turn a relative pathname into a full pathname.  Return a pointer
01572 ** to the full pathname stored in space obtained from sqliteMalloc().
01573 ** The calling function is responsible for freeing this space once it
01574 ** is no longer needed.
01575 */
01576 char *sqlite3UnixFullPathname(const char *zRelative){
01577   char *zFull = 0;
01578   if( zRelative[0]=='/' ){
01579     sqlite3SetString(&zFull, zRelative, (char*)0);
01580   }else{
01581     char *zBuf = sqliteMalloc(5000);
01582     if( zBuf==0 ){
01583       return 0;
01584     }
01585     zBuf[0] = 0;
01586     sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
01587                     (char*)0);
01588     sqliteFree(zBuf);
01589   }
01590 
01591 #if 0
01592   /*
01593   ** Remove "/./" path elements and convert "/A/./" path elements
01594   ** to just "/".
01595   */
01596   if( zFull ){
01597     int i, j;
01598     for(i=j=0; zFull[i]; i++){
01599       if( zFull[i]=='/' ){
01600         if( zFull[i+1]=='/' ) continue;
01601         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
01602           i += 1;
01603           continue;
01604         }
01605         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
01606           while( j>0 && zFull[j-1]!='/' ){ j--; }
01607           i += 3;
01608           continue;
01609         }
01610       }
01611       zFull[j++] = zFull[i];
01612     }
01613     zFull[j] = 0;
01614   }
01615 #endif
01616 
01617   return zFull;
01618 }
01619 
01620 /*
01621 ** Change the value of the fullsync flag in the given file descriptor.
01622 */
01623 static void unixSetFullSync(OsFile *id, int v){
01624   ((unixFile*)id)->fullSync = v;
01625 }
01626 
01627 /*
01628 ** Return the underlying file handle for an OsFile
01629 */
01630 static int unixFileHandle(OsFile *id){
01631   return ((unixFile*)id)->h;
01632 }
01633 
01634 /*
01635 ** Return an integer that indices the type of lock currently held
01636 ** by this handle.  (Used for testing and analysis only.)
01637 */
01638 static int unixLockState(OsFile *id){
01639   return ((unixFile*)id)->locktype;
01640 }
01641 
01642 /*
01643 ** This vector defines all the methods that can operate on an OsFile
01644 ** for unix.
01645 */
01646 static const IoMethod sqlite3UnixIoMethod = {
01647   unixClose,
01648   unixOpenDirectory,
01649   unixRead,
01650   unixWrite,
01651   unixSeek,
01652   unixTruncate,
01653   unixSync,
01654   unixSetFullSync,
01655   unixFileHandle,
01656   unixFileSize,
01657   unixLock,
01658   unixUnlock,
01659   unixLockState,
01660   unixCheckReservedLock,
01661 };
01662 
01663 /*
01664 ** Allocate memory for a unixFile.  Initialize the new unixFile
01665 ** to the value given in pInit and return a pointer to the new
01666 ** OsFile.  If we run out of memory, close the file and return NULL.
01667 */
01668 static int allocateUnixFile(unixFile *pInit, OsFile **pId){
01669   unixFile *pNew;
01670   pInit->dirfd = -1;
01671   pInit->fullSync = 0;
01672   pInit->locktype = 0;
01673   pInit->offset = 0;
01674   SET_THREADID(pInit);
01675   pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
01676   if( pNew==0 ){
01677     close(pInit->h);
01678     sqlite3OsEnterMutex();
01679     releaseLockInfo(pInit->pLock);
01680     releaseOpenCnt(pInit->pOpen);
01681     sqlite3OsLeaveMutex();
01682     *pId = 0;
01683     return SQLITE_NOMEM;
01684   }else{
01685     *pNew = *pInit;
01686     pNew->pMethod = &sqlite3UnixIoMethod;
01687     *pId = (OsFile*)pNew;
01688     OpenCounter(+1);
01689     return SQLITE_OK;
01690   }
01691 }
01692 
01693 
01694 #endif /* SQLITE_OMIT_DISKIO */
01695 /***************************************************************************
01696 ** Everything above deals with file I/O.  Everything that follows deals
01697 ** with other miscellanous aspects of the operating system interface
01698 ****************************************************************************/
01699 
01700 
01701 /*
01702 ** Get information to seed the random number generator.  The seed
01703 ** is written into the buffer zBuf[256].  The calling function must
01704 ** supply a sufficiently large buffer.
01705 */
01706 int sqlite3UnixRandomSeed(char *zBuf){
01707   /* We have to initialize zBuf to prevent valgrind from reporting
01708   ** errors.  The reports issued by valgrind are incorrect - we would
01709   ** prefer that the randomness be increased by making use of the
01710   ** uninitialized space in zBuf - but valgrind errors tend to worry
01711   ** some users.  Rather than argue, it seems easier just to initialize
01712   ** the whole array and silence valgrind, even if that means less randomness
01713   ** in the random seed.
01714   **
01715   ** When testing, initializing zBuf[] to zero is all we do.  That means
01716   ** that we always use the same random number sequence.  This makes the
01717   ** tests repeatable.
01718   */
01719   memset(zBuf, 0, 256);
01720 #if !defined(SQLITE_TEST)
01721   {
01722     int pid, fd;
01723     fd = open("/dev/urandom", O_RDONLY);
01724     if( fd<0 ){
01725       time_t t;
01726       time(&t);
01727       memcpy(zBuf, &t, sizeof(t));
01728       pid = getpid();
01729       memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
01730     }else{
01731       read(fd, zBuf, 256);
01732       close(fd);
01733     }
01734   }
01735 #endif
01736   return SQLITE_OK;
01737 }
01738 
01739 /*
01740 ** Sleep for a little while.  Return the amount of time slept.
01741 ** The argument is the number of milliseconds we want to sleep.
01742 */
01743 int sqlite3UnixSleep(int ms){
01744 #if defined(HAVE_USLEEP) && HAVE_USLEEP
01745   usleep(ms*1000);
01746   return ms;
01747 #else
01748   sleep((ms+999)/1000);
01749   return 1000*((ms+999)/1000);
01750 #endif
01751 }
01752 
01753 /*
01754 ** Static variables used for thread synchronization.
01755 **
01756 ** inMutex      the nesting depth of the recursive mutex.  The thread
01757 **              holding mutexMain can read this variable at any time.
01758 **              But is must hold mutexAux to change this variable.  Other
01759 **              threads must hold mutexAux to read the variable and can
01760 **              never write.
01761 **
01762 ** mutexOwner   The thread id of the thread holding mutexMain.  Same
01763 **              access rules as for inMutex.
01764 **
01765 ** mutexOwnerValid   True if the value in mutexOwner is valid.  The same
01766 **                   access rules apply as for inMutex.
01767 **
01768 ** mutexMain    The main mutex.  Hold this mutex in order to get exclusive
01769 **              access to SQLite data structures.
01770 **
01771 ** mutexAux     An auxiliary mutex needed to access variables defined above.
01772 **
01773 ** Mutexes are always acquired in this order: mutexMain mutexAux.   It
01774 ** is not necessary to acquire mutexMain in order to get mutexAux - just
01775 ** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
01776 ** Either get the mutexes with mutexMain first or get mutexAux only.
01777 **
01778 ** When running on a platform where the three variables inMutex, mutexOwner,
01779 ** and mutexOwnerValid can be set atomically, the mutexAux is not required.
01780 ** On many systems, all three are 32-bit integers and writing to a 32-bit
01781 ** integer is atomic.  I think.  But there are no guarantees.  So it seems
01782 ** safer to protect them using mutexAux.
01783 */
01784 static int inMutex = 0;
01785 #ifdef SQLITE_UNIX_THREADS
01786 static pthread_t mutexOwner;          /* Thread holding mutexMain */
01787 static int mutexOwnerValid = 0;       /* True if mutexOwner is valid */
01788 static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
01789 static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER;  /* Aux mutex */
01790 #endif
01791 
01792 /*
01793 ** The following pair of routine implement mutual exclusion for
01794 ** multi-threaded processes.  Only a single thread is allowed to
01795 ** executed code that is surrounded by EnterMutex() and LeaveMutex().
01796 **
01797 ** SQLite uses only a single Mutex.  There is not much critical
01798 ** code and what little there is executes quickly and without blocking.
01799 **
01800 ** As of version 3.3.2, this mutex must be recursive.
01801 */
01802 void sqlite3UnixEnterMutex(){
01803 #ifdef SQLITE_UNIX_THREADS
01804   pthread_mutex_lock(&mutexAux);
01805   if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
01806     pthread_mutex_unlock(&mutexAux);
01807     pthread_mutex_lock(&mutexMain);
01808     assert( inMutex==0 );
01809     assert( !mutexOwnerValid );
01810     pthread_mutex_lock(&mutexAux);
01811     mutexOwner = pthread_self();
01812     mutexOwnerValid = 1;
01813   }
01814   inMutex++;
01815   pthread_mutex_unlock(&mutexAux);
01816 #else
01817   inMutex++;
01818 #endif
01819 }
01820 void sqlite3UnixLeaveMutex(){
01821   assert( inMutex>0 );
01822 #ifdef SQLITE_UNIX_THREADS
01823   pthread_mutex_lock(&mutexAux);
01824   inMutex--;
01825   assert( pthread_equal(mutexOwner, pthread_self()) );
01826   if( inMutex==0 ){
01827     assert( mutexOwnerValid );
01828     mutexOwnerValid = 0;
01829     pthread_mutex_unlock(&mutexMain);
01830   }
01831   pthread_mutex_unlock(&mutexAux);
01832 #else
01833   inMutex--;
01834 #endif
01835 }
01836 
01837 /*
01838 ** Return TRUE if the mutex is currently held.
01839 **
01840 ** If the thisThrd parameter is true, return true only if the
01841 ** calling thread holds the mutex.  If the parameter is false, return
01842 ** true if any thread holds the mutex.
01843 */
01844 int sqlite3UnixInMutex(int thisThrd){
01845 #ifdef SQLITE_UNIX_THREADS
01846   int rc;
01847   pthread_mutex_lock(&mutexAux);
01848   rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
01849   pthread_mutex_unlock(&mutexAux);
01850   return rc;
01851 #else
01852   return inMutex>0;
01853 #endif
01854 }
01855 
01856 /*
01857 ** Remember the number of thread-specific-data blocks allocated.
01858 ** Use this to verify that we are not leaking thread-specific-data.
01859 ** Ticket #1601
01860 */
01861 #ifdef SQLITE_TEST
01862 int sqlite3_tsd_count = 0;
01863 # ifdef SQLITE_UNIX_THREADS
01864     static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
01865 #   define TSD_COUNTER(N) \
01866              pthread_mutex_lock(&tsd_counter_mutex); \
01867              sqlite3_tsd_count += N; \
01868              pthread_mutex_unlock(&tsd_counter_mutex);
01869 # else
01870 #   define TSD_COUNTER(N)  sqlite3_tsd_count += N
01871 # endif
01872 #else
01873 # define TSD_COUNTER(N)  /* no-op */
01874 #endif
01875 
01876 /*
01877 ** If called with allocateFlag>0, then return a pointer to thread
01878 ** specific data for the current thread.  Allocate and zero the
01879 ** thread-specific data if it does not already exist.
01880 **
01881 ** If called with allocateFlag==0, then check the current thread
01882 ** specific data.  Return it if it exists.  If it does not exist,
01883 ** then return NULL.
01884 **
01885 ** If called with allocateFlag<0, check to see if the thread specific
01886 ** data is allocated and is all zero.  If it is then deallocate it.
01887 ** Return a pointer to the thread specific data or NULL if it is
01888 ** unallocated or gets deallocated.
01889 */
01890 ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
01891   static const ThreadData zeroData = {0};  /* Initializer to silence warnings
01892                                            ** from broken compilers */
01893 #ifdef SQLITE_UNIX_THREADS
01894   static pthread_key_t key;
01895   static int keyInit = 0;
01896   ThreadData *pTsd;
01897 
01898   if( !keyInit ){
01899     sqlite3OsEnterMutex();
01900     if( !keyInit ){
01901       int rc;
01902       rc = pthread_key_create(&key, 0);
01903       if( rc ){
01904         sqlite3OsLeaveMutex();
01905         return 0;
01906       }
01907       keyInit = 1;
01908     }
01909     sqlite3OsLeaveMutex();
01910   }
01911 
01912   pTsd = pthread_getspecific(key);
01913   if( allocateFlag>0 ){
01914     if( pTsd==0 ){
01915       if( !sqlite3TestMallocFail() ){
01916         pTsd = sqlite3OsMalloc(sizeof(zeroData));
01917       }
01918 #ifdef SQLITE_MEMDEBUG
01919       sqlite3_isFail = 0;
01920 #endif
01921       if( pTsd ){
01922         *pTsd = zeroData;
01923         pthread_setspecific(key, pTsd);
01924         TSD_COUNTER(+1);
01925       }
01926     }
01927   }else if( pTsd!=0 && allocateFlag<0 
01928             && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
01929     sqlite3OsFree(pTsd);
01930     pthread_setspecific(key, 0);
01931     TSD_COUNTER(-1);
01932     pTsd = 0;
01933   }
01934   return pTsd;
01935 #else
01936   static ThreadData *pTsd = 0;
01937   if( allocateFlag>0 ){
01938     if( pTsd==0 ){
01939       if( !sqlite3TestMallocFail() ){
01940         pTsd = sqlite3OsMalloc( sizeof(zeroData) );
01941       }
01942 #ifdef SQLITE_MEMDEBUG
01943       sqlite3_isFail = 0;
01944 #endif
01945       if( pTsd ){
01946         *pTsd = zeroData;
01947         TSD_COUNTER(+1);
01948       }
01949     }
01950   }else if( pTsd!=0 && allocateFlag<0
01951             && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
01952     sqlite3OsFree(pTsd);
01953     TSD_COUNTER(-1);
01954     pTsd = 0;
01955   }
01956   return pTsd;
01957 #endif
01958 }
01959 
01960 /*
01961 ** The following variable, if set to a non-zero value, becomes the result
01962 ** returned from sqlite3OsCurrentTime().  This is used for testing.
01963 */
01964 #ifdef SQLITE_TEST
01965 int sqlite3_current_time = 0;
01966 #endif
01967 
01968 /*
01969 ** Find the current time (in Universal Coordinated Time).  Write the
01970 ** current time and date as a Julian Day number into *prNow and
01971 ** return 0.  Return 1 if the time and date cannot be found.
01972 */
01973 int sqlite3UnixCurrentTime(double *prNow){
01974 #ifdef NO_GETTOD
01975   time_t t;
01976   time(&t);
01977   *prNow = t/86400.0 + 2440587.5;
01978 #else
01979   struct timeval sNow;
01980   struct timezone sTz;  /* Not used */
01981   gettimeofday(&sNow, &sTz);
01982   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
01983 #endif
01984 #ifdef SQLITE_TEST
01985   if( sqlite3_current_time ){
01986     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
01987   }
01988 #endif
01989   return 0;
01990 }
01991 
01992 #endif /* OS_UNIX */