blob: ce3101ed102c72363b629834facb8623d9206b40 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
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.
10**
11******************************************************************************
12**
13** This file contains code that is specific to Unix systems.
14*/
drhbbd42a62004-05-22 17:41:58 +000015#include "sqliteInt.h"
drheb206252004-10-01 02:00:31 +000016#include "os.h"
17#if OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000018
drh9cbe6352005-11-29 03:13:21 +000019/*
20** These #defines should enable >2GB file support on Posix if the
21** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000022** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000023**
24** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
25** on the compiler command line. This is necessary if you are compiling
26** on a recent machine (ex: RedHat 7.2) but you want your code to work
27** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
28** without this option, LFS is enable. But LFS does not exist in the kernel
29** in RedHat 6.0, so the code won't work. Hence, for maximum binary
30** portability you should omit LFS.
drh9cbe6352005-11-29 03:13:21 +000031*/
32#ifndef SQLITE_DISABLE_LFS
33# define _LARGE_FILE 1
34# ifndef _FILE_OFFSET_BITS
35# define _FILE_OFFSET_BITS 64
36# endif
37# define _LARGEFILE_SOURCE 1
38#endif
drhbbd42a62004-05-22 17:41:58 +000039
drh9cbe6352005-11-29 03:13:21 +000040/*
41** standard include files.
42*/
43#include <sys/types.h>
44#include <sys/stat.h>
45#include <fcntl.h>
46#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000047#include <time.h>
drh19e2d372005-08-29 23:00:03 +000048#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000049#include <errno.h>
drh9cbe6352005-11-29 03:13:21 +000050
51/*
drhf1a221e2006-01-15 17:27:17 +000052** If we are to be thread-safe, include the pthreads header and define
53** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +000054*/
55#if defined(THREADSAFE) && THREADSAFE
56# include <pthread.h>
57# define SQLITE_UNIX_THREADS 1
58#endif
59
60/*
61** Default permissions when creating a new file
62*/
63#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
64# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
65#endif
66
67
68
69/*
drh054889e2005-11-30 03:20:31 +000070** The unixFile structure is subclass of OsFile specific for the unix
71** protability layer.
drh9cbe6352005-11-29 03:13:21 +000072*/
drh054889e2005-11-30 03:20:31 +000073typedef struct unixFile unixFile;
74struct unixFile {
75 IoMethod const *pMethod; /* Always the first entry */
drh9cbe6352005-11-29 03:13:21 +000076 struct openCnt *pOpen; /* Info about all open fd's on this inode */
77 struct lockInfo *pLock; /* Info about locks on this inode */
78 int h; /* The file descriptor */
79 unsigned char locktype; /* The type of lock held on this fd */
80 unsigned char isOpen; /* True if needs to be closed */
81 unsigned char fullSync; /* Use F_FULLSYNC if available */
82 int dirfd; /* File descriptor for the directory */
83#ifdef SQLITE_UNIX_THREADS
drhf1a221e2006-01-15 17:27:17 +000084 pthread_t tid; /* The thread that "owns" this OsFile */
drh9cbe6352005-11-29 03:13:21 +000085#endif
86};
87
drh66560ad2006-01-06 14:32:19 +000088/*
89** Provide the ability to override some OS-layer functions during
90** testing. This is used to simulate OS crashes to verify that
91** commits are atomic even in the event of an OS crash.
92*/
93#ifdef SQLITE_CRASH_TEST
94 extern int sqlite3CrashTestEnable;
95 extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
96 extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
97 extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
98# define CRASH_TEST_OVERRIDE(X,A,B,C) \
99 if(sqlite3CrashTestEnable){ return X(A,B,C); }
100#else
101# define CRASH_TEST_OVERRIDE(X,A,B,C) /* no-op */
102#endif
103
drh0ccebe72005-06-07 22:22:50 +0000104
105/*
drh198bf392006-01-06 21:52:49 +0000106** Include code that is common to all os_*.c files
107*/
108#include "os_common.h"
109
110/*
drh0ccebe72005-06-07 22:22:50 +0000111** Do not include any of the File I/O interface procedures if the
drhf1a221e2006-01-15 17:27:17 +0000112** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
drh0ccebe72005-06-07 22:22:50 +0000113** will be in-memory only)
114*/
115#ifndef SQLITE_OMIT_DISKIO
116
117
118/*
119** Define various macros that are missing from some systems.
120*/
drhbbd42a62004-05-22 17:41:58 +0000121#ifndef O_LARGEFILE
122# define O_LARGEFILE 0
123#endif
124#ifdef SQLITE_DISABLE_LFS
125# undef O_LARGEFILE
126# define O_LARGEFILE 0
127#endif
128#ifndef O_NOFOLLOW
129# define O_NOFOLLOW 0
130#endif
131#ifndef O_BINARY
132# define O_BINARY 0
133#endif
134
135/*
136** The DJGPP compiler environment looks mostly like Unix, but it
137** lacks the fcntl() system call. So redefine fcntl() to be something
138** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000139** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000140*/
141#ifdef __DJGPP__
142# define fcntl(A,B,C) 0
143#endif
144
145/*
drh2b4b5962005-06-15 17:47:55 +0000146** The threadid macro resolves to the thread-id or to 0. Used for
147** testing and debugging only.
148*/
149#ifdef SQLITE_UNIX_THREADS
150#define threadid pthread_self()
151#else
152#define threadid 0
153#endif
154
155/*
156** Set or check the OsFile.tid field. This field is set when an OsFile
157** is first opened. All subsequent uses of the OsFile verify that the
158** same thread is operating on the OsFile. Some operating systems do
159** not allow locks to be overridden by other threads and that restriction
160** means that sqlite3* database handles cannot be moved from one thread
161** to another. This logic makes sure a user does not try to do that
162** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000163**
164** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
165** another as long as we are running on a system that supports threads
166** overriding each others locks (which now the most common behavior)
167** or if no locks are held. But the OsFile.pLock field needs to be
168** recomputed because its key includes the thread-id. See the
169** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000170*/
drh029b44b2006-01-15 00:13:15 +0000171#if defined(SQLITE_UNIX_THREADS)
drh9cbe6352005-11-29 03:13:21 +0000172# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000173# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
174 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000175#else
176# define SET_THREADID(X)
177# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000178#endif
179
drhbbd42a62004-05-22 17:41:58 +0000180/*
181** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
182** section 6.5.2.2 lines 483 through 490 specify that when a process
183** sets or clears a lock, that operation overrides any prior locks set
184** by the same process. It does not explicitly say so, but this implies
185** that it overrides locks set by the same process using a different
186** file descriptor. Consider this test case:
187**
188** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
189** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
190**
191** Suppose ./file1 and ./file2 are really the same file (because
192** one is a hard or symbolic link to the other) then if you set
193** an exclusive lock on fd1, then try to get an exclusive lock
194** on fd2, it works. I would have expected the second lock to
195** fail since there was already a lock on the file due to fd1.
196** But not so. Since both locks came from the same process, the
197** second overrides the first, even though they were on different
198** file descriptors opened on different file names.
199**
200** Bummer. If you ask me, this is broken. Badly broken. It means
201** that we cannot use POSIX locks to synchronize file access among
202** competing threads of the same process. POSIX locks will work fine
203** to synchronize access for threads in separate processes, but not
204** threads within the same process.
205**
206** To work around the problem, SQLite has to manage file locks internally
207** on its own. Whenever a new database is opened, we have to find the
208** specific inode of the database file (the inode is determined by the
209** st_dev and st_ino fields of the stat structure that fstat() fills in)
210** and check for locks already existing on that inode. When locks are
211** created or removed, we have to look at our own internal record of the
212** locks to see if another thread has previously set a lock on that same
213** inode.
214**
215** The OsFile structure for POSIX is no longer just an integer file
216** descriptor. It is now a structure that holds the integer file
217** descriptor and a pointer to a structure that describes the internal
218** locks on the corresponding inode. There is one locking structure
219** per inode, so if the same inode is opened twice, both OsFile structures
220** point to the same locking structure. The locking structure keeps
221** a reference count (so we will know when to delete it) and a "cnt"
222** field that tells us its internal lock status. cnt==0 means the
223** file is unlocked. cnt==-1 means the file has an exclusive lock.
224** cnt>0 means there are cnt shared locks on the file.
225**
226** Any attempt to lock or unlock a file first checks the locking
227** structure. The fcntl() system call is only invoked to set a
228** POSIX lock if the internal lock structure transitions between
229** a locked and an unlocked state.
230**
231** 2004-Jan-11:
232** More recent discoveries about POSIX advisory locks. (The more
233** I discover, the more I realize the a POSIX advisory locks are
234** an abomination.)
235**
236** If you close a file descriptor that points to a file that has locks,
237** all locks on that file that are owned by the current process are
238** released. To work around this problem, each OsFile structure contains
239** a pointer to an openCnt structure. There is one openCnt structure
240** per open inode, which means that multiple OsFiles can point to a single
241** openCnt. When an attempt is made to close an OsFile, if there are
242** other OsFiles open on the same inode that are holding locks, the call
243** to close() the file descriptor is deferred until all of the locks clear.
244** The openCnt structure keeps a list of file descriptors that need to
245** be closed and that list is walked (and cleared) when the last lock
246** clears.
247**
248** First, under Linux threads, because each thread has a separate
249** process ID, lock operations in one thread do not override locks
250** to the same file in other threads. Linux threads behave like
251** separate processes in this respect. But, if you close a file
252** descriptor in linux threads, all locks are cleared, even locks
253** on other threads and even though the other threads have different
254** process IDs. Linux threads is inconsistent in this respect.
255** (I'm beginning to think that linux threads is an abomination too.)
256** The consequence of this all is that the hash table for the lockInfo
257** structure has to include the process id as part of its key because
258** locks in different threads are treated as distinct. But the
259** openCnt structure should not include the process id in its
260** key because close() clears lock on all threads, not just the current
261** thread. Were it not for this goofiness in linux threads, we could
262** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000263**
264** 2004-Jun-28:
265** On some versions of linux, threads can override each others locks.
266** On others not. Sometimes you can change the behavior on the same
267** system by setting the LD_ASSUME_KERNEL environment variable. The
268** POSIX standard is silent as to which behavior is correct, as far
269** as I can tell, so other versions of unix might show the same
270** inconsistency. There is no little doubt in my mind that posix
271** advisory locks and linux threads are profoundly broken.
272**
273** To work around the inconsistencies, we have to test at runtime
274** whether or not threads can override each others locks. This test
275** is run once, the first time any lock is attempted. A static
276** variable is set to record the results of this test for future
277** use.
drhbbd42a62004-05-22 17:41:58 +0000278*/
279
280/*
281** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000282** to locate a particular lockInfo structure given its inode.
283**
284** If threads cannot override each others locks, then we set the
285** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000286** each others locks then tid is always set to zero. tid is omitted
287** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000288*/
289struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000290 dev_t dev; /* Device number */
291 ino_t ino; /* Inode number */
292#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000293 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000294#endif
drhbbd42a62004-05-22 17:41:58 +0000295};
296
297/*
298** An instance of the following structure is allocated for each open
299** inode on each thread with a different process ID. (Threads have
300** different process IDs on linux, but not on most other unixes.)
301**
302** A single inode can have multiple file descriptors, so each OsFile
303** structure contains a pointer to an instance of this object and this
304** object keeps a count of the number of OsFiles pointing to it.
305*/
306struct lockInfo {
307 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000308 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000309 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000310 int nRef; /* Number of pointers to this structure */
311};
312
313/*
314** An instance of the following structure serves as the key used
315** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000316** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000317*/
318struct openKey {
319 dev_t dev; /* Device number */
320 ino_t ino; /* Inode number */
321};
322
323/*
324** An instance of the following structure is allocated for each open
325** inode. This structure keeps track of the number of locks on that
326** inode. If a close is attempted against an inode that is holding
327** locks, the close is deferred until all locks clear by adding the
328** file descriptor to be closed to the pending list.
329*/
330struct openCnt {
331 struct openKey key; /* The lookup key */
332 int nRef; /* Number of pointers to this structure */
333 int nLock; /* Number of outstanding locks */
334 int nPending; /* Number of pending close() operations */
335 int *aPending; /* Malloced space holding fd's awaiting a close() */
336};
337
338/*
drhf1a221e2006-01-15 17:27:17 +0000339** These hash tables map inodes and file descriptors (really, lockKey and
340** openKey structures) into lockInfo and openCnt structures. Access to
341** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000342*/
343static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
344static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
345
drh5fdae772004-06-29 03:29:00 +0000346
347#ifdef SQLITE_UNIX_THREADS
348/*
349** This variable records whether or not threads can override each others
350** locks.
351**
352** 0: No. Threads cannot override each others locks.
353** 1: Yes. Threads can override each others locks.
354** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000355**
drh5062d3a2006-01-31 23:03:35 +0000356** On some systems, we know at compile-time if threads can override each
357** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
358** will be set appropriately. On other systems, we have to check at
359** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
360** undefined.
361**
drhf1a221e2006-01-15 17:27:17 +0000362** This variable normally has file scope only. But during testing, we make
363** it a global so that the test code can change its value in order to verify
364** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000365*/
drh5062d3a2006-01-31 23:03:35 +0000366#ifndef SQLITE_THREAD_OVERRIDE_LOCK
367# define SQLITE_THREAD_OVERRIDE_LOCK -1
368#endif
drh029b44b2006-01-15 00:13:15 +0000369#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000370int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000371#else
drh5062d3a2006-01-31 23:03:35 +0000372static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000373#endif
drh5fdae772004-06-29 03:29:00 +0000374
375/*
376** This structure holds information passed into individual test
377** threads by the testThreadLockingBehavior() routine.
378*/
379struct threadTestData {
380 int fd; /* File to be locked */
381 struct flock lock; /* The locking operation */
382 int result; /* Result of the locking operation */
383};
384
drh2b4b5962005-06-15 17:47:55 +0000385#ifdef SQLITE_LOCK_TRACE
386/*
387** Print out information about all locking operations.
388**
389** This routine is used for troubleshooting locks on multithreaded
390** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
391** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000392** turned off.
drh2b4b5962005-06-15 17:47:55 +0000393*/
394static int lockTrace(int fd, int op, struct flock *p){
395 char *zOpName, *zType;
396 int s;
397 int savedErrno;
398 if( op==F_GETLK ){
399 zOpName = "GETLK";
400 }else if( op==F_SETLK ){
401 zOpName = "SETLK";
402 }else{
403 s = fcntl(fd, op, p);
404 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
405 return s;
406 }
407 if( p->l_type==F_RDLCK ){
408 zType = "RDLCK";
409 }else if( p->l_type==F_WRLCK ){
410 zType = "WRLCK";
411 }else if( p->l_type==F_UNLCK ){
412 zType = "UNLCK";
413 }else{
414 assert( 0 );
415 }
416 assert( p->l_whence==SEEK_SET );
417 s = fcntl(fd, op, p);
418 savedErrno = errno;
419 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
420 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
421 (int)p->l_pid, s);
422 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
423 struct flock l2;
424 l2 = *p;
425 fcntl(fd, F_GETLK, &l2);
426 if( l2.l_type==F_RDLCK ){
427 zType = "RDLCK";
428 }else if( l2.l_type==F_WRLCK ){
429 zType = "WRLCK";
430 }else if( l2.l_type==F_UNLCK ){
431 zType = "UNLCK";
432 }else{
433 assert( 0 );
434 }
435 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
436 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
437 }
438 errno = savedErrno;
439 return s;
440}
441#define fcntl lockTrace
442#endif /* SQLITE_LOCK_TRACE */
443
drh5fdae772004-06-29 03:29:00 +0000444/*
445** The testThreadLockingBehavior() routine launches two separate
446** threads on this routine. This routine attempts to lock a file
447** descriptor then returns. The success or failure of that attempt
448** allows the testThreadLockingBehavior() procedure to determine
449** whether or not threads can override each others locks.
450*/
451static void *threadLockingTest(void *pArg){
452 struct threadTestData *pData = (struct threadTestData*)pArg;
453 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
454 return pArg;
455}
456
457/*
458** This procedure attempts to determine whether or not threads
459** can override each others locks then sets the
460** threadsOverrideEachOthersLocks variable appropriately.
461*/
danielk19774d5238f2006-01-27 06:32:00 +0000462static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000463 int fd;
464 struct threadTestData d[2];
465 pthread_t t[2];
466
467 fd = dup(fd_orig);
468 if( fd<0 ) return;
469 memset(d, 0, sizeof(d));
470 d[0].fd = fd;
471 d[0].lock.l_type = F_RDLCK;
472 d[0].lock.l_len = 1;
473 d[0].lock.l_start = 0;
474 d[0].lock.l_whence = SEEK_SET;
475 d[1] = d[0];
476 d[1].lock.l_type = F_WRLCK;
477 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
478 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
479 pthread_join(t[0], 0);
480 pthread_join(t[1], 0);
481 close(fd);
482 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
483}
484#endif /* SQLITE_UNIX_THREADS */
485
drhbbd42a62004-05-22 17:41:58 +0000486/*
487** Release a lockInfo structure previously allocated by findLockInfo().
488*/
489static void releaseLockInfo(struct lockInfo *pLock){
drh757b04e2006-01-18 17:25:45 +0000490 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000491 pLock->nRef--;
492 if( pLock->nRef==0 ){
493 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
494 sqliteFree(pLock);
495 }
496}
497
498/*
499** Release a openCnt structure previously allocated by findLockInfo().
500*/
501static void releaseOpenCnt(struct openCnt *pOpen){
drh757b04e2006-01-18 17:25:45 +0000502 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000503 pOpen->nRef--;
504 if( pOpen->nRef==0 ){
505 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000506 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +0000507 sqliteFree(pOpen);
508 }
509}
510
511/*
512** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000513** describes that file descriptor. Create new ones if necessary. The
514** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000515**
516** Return the number of errors.
517*/
drh38f82712004-06-18 17:10:16 +0000518static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000519 int fd, /* The file descriptor used in the key */
520 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000521 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000522){
523 int rc;
524 struct lockKey key1;
525 struct openKey key2;
526 struct stat statbuf;
527 struct lockInfo *pLock;
528 struct openCnt *pOpen;
529 rc = fstat(fd, &statbuf);
530 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000531
drh757b04e2006-01-18 17:25:45 +0000532 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000533 memset(&key1, 0, sizeof(key1));
534 key1.dev = statbuf.st_dev;
535 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000536#ifdef SQLITE_UNIX_THREADS
537 if( threadsOverrideEachOthersLocks<0 ){
538 testThreadLockingBehavior(fd);
539 }
540 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
541#endif
drhbbd42a62004-05-22 17:41:58 +0000542 memset(&key2, 0, sizeof(key2));
543 key2.dev = statbuf.st_dev;
544 key2.ino = statbuf.st_ino;
545 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
546 if( pLock==0 ){
547 struct lockInfo *pOld;
548 pLock = sqliteMallocRaw( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000549 if( pLock==0 ){
550 rc = 1;
551 goto exit_findlockinfo;
552 }
drhbbd42a62004-05-22 17:41:58 +0000553 pLock->key = key1;
554 pLock->nRef = 1;
555 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000556 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000557 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
558 if( pOld!=0 ){
559 assert( pOld==pLock );
560 sqliteFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000561 rc = 1;
562 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000563 }
564 }else{
565 pLock->nRef++;
566 }
567 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000568 if( ppOpen!=0 ){
569 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000570 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000571 struct openCnt *pOld;
572 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
573 if( pOpen==0 ){
574 releaseLockInfo(pLock);
575 rc = 1;
576 goto exit_findlockinfo;
577 }
578 pOpen->key = key2;
579 pOpen->nRef = 1;
580 pOpen->nLock = 0;
581 pOpen->nPending = 0;
582 pOpen->aPending = 0;
583 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
584 if( pOld!=0 ){
585 assert( pOld==pOpen );
586 sqliteFree(pOpen);
587 releaseLockInfo(pLock);
588 rc = 1;
589 goto exit_findlockinfo;
590 }
591 }else{
592 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000593 }
drh029b44b2006-01-15 00:13:15 +0000594 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000595 }
danielk1977441b09a2006-01-05 13:48:29 +0000596
597exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000598 return rc;
drhbbd42a62004-05-22 17:41:58 +0000599}
600
drh64b1bea2006-01-15 02:30:57 +0000601#ifdef SQLITE_DEBUG
602/*
603** Helper function for printing out trace information from debugging
604** binaries. This returns the string represetation of the supplied
605** integer lock-type.
606*/
607static const char *locktypeName(int locktype){
608 switch( locktype ){
609 case NO_LOCK: return "NONE";
610 case SHARED_LOCK: return "SHARED";
611 case RESERVED_LOCK: return "RESERVED";
612 case PENDING_LOCK: return "PENDING";
613 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
614 }
615 return "ERROR";
616}
617#endif
618
drhbbd42a62004-05-22 17:41:58 +0000619/*
drh029b44b2006-01-15 00:13:15 +0000620** If we are currently in a different thread than the thread that the
621** unixFile argument belongs to, then transfer ownership of the unixFile
622** over to the current thread.
623**
624** A unixFile is only owned by a thread on systems where one thread is
625** unable to override locks created by a different thread. RedHat9 is
626** an example of such a system.
627**
628** Ownership transfer is only allowed if the unixFile is currently unlocked.
629** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000630** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000631*/
632#ifdef SQLITE_UNIX_THREADS
633static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000634 int rc;
drh029b44b2006-01-15 00:13:15 +0000635 pthread_t hSelf;
636 if( threadsOverrideEachOthersLocks ){
637 /* Ownership transfers not needed on this system */
638 return SQLITE_OK;
639 }
640 hSelf = pthread_self();
641 if( pthread_equal(pFile->tid, hSelf) ){
642 /* We are still in the same thread */
drh64b1bea2006-01-15 02:30:57 +0000643 TRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000644 return SQLITE_OK;
645 }
646 if( pFile->locktype!=NO_LOCK ){
647 /* We cannot change ownership while we are holding a lock! */
648 return SQLITE_MISUSE;
649 }
drh64b1bea2006-01-15 02:30:57 +0000650 TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
drh029b44b2006-01-15 00:13:15 +0000651 pFile->tid = hSelf;
652 releaseLockInfo(pFile->pLock);
drh64b1bea2006-01-15 02:30:57 +0000653 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
654 TRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
655 locktypeName(pFile->locktype),
656 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
657 return rc;
drh029b44b2006-01-15 00:13:15 +0000658}
659#else
drhf1a221e2006-01-15 17:27:17 +0000660 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000661# define transferOwnership(X) SQLITE_OK
662#endif
663
664/*
drhbbd42a62004-05-22 17:41:58 +0000665** Delete the named file
666*/
drh66560ad2006-01-06 14:32:19 +0000667int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000668 unlink(zFilename);
669 return SQLITE_OK;
670}
671
672/*
673** Return TRUE if the named file exists.
674*/
drh66560ad2006-01-06 14:32:19 +0000675int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000676 return access(zFilename, 0)==0;
677}
678
drh054889e2005-11-30 03:20:31 +0000679/* Forward declaration */
680static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000681
682/*
drhbbd42a62004-05-22 17:41:58 +0000683** Attempt to open a file for both reading and writing. If that
684** fails, try opening it read-only. If the file does not exist,
685** try to create it.
686**
687** On success, a handle for the open file is written to *id
688** and *pReadonly is set to 0 if the file was opened for reading and
689** writing or 1 if the file was opened read-only. The function returns
690** SQLITE_OK.
691**
692** On failure, the function returns SQLITE_CANTOPEN and leaves
693** *id and *pReadonly unchanged.
694*/
drh66560ad2006-01-06 14:32:19 +0000695int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000696 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000697 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000698 int *pReadonly
699){
700 int rc;
drh054889e2005-11-30 03:20:31 +0000701 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000702
drh66560ad2006-01-06 14:32:19 +0000703 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000704 assert( 0==*pId );
drh9cbe6352005-11-29 03:13:21 +0000705 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000706 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000707 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000708#ifdef EISDIR
709 if( errno==EISDIR ){
710 return SQLITE_CANTOPEN;
711 }
712#endif
drh9cbe6352005-11-29 03:13:21 +0000713 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
714 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000715 return SQLITE_CANTOPEN;
716 }
717 *pReadonly = 1;
718 }else{
719 *pReadonly = 0;
720 }
drh66560ad2006-01-06 14:32:19 +0000721 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000722 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000723 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000724 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000725 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000726 return SQLITE_NOMEM;
727 }
drh9cbe6352005-11-29 03:13:21 +0000728 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000729 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000730}
731
732
733/*
734** Attempt to open a new file for exclusive access by this process.
735** The file will be opened for both reading and writing. To avoid
736** a potential security problem, we do not allow the file to have
737** previously existed. Nor do we allow the file to be a symbolic
738** link.
739**
740** If delFlag is true, then make arrangements to automatically delete
741** the file when it is closed.
742**
743** On success, write the file handle into *id and return SQLITE_OK.
744**
745** On failure, return SQLITE_CANTOPEN.
746*/
drh66560ad2006-01-06 14:32:19 +0000747int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000748 int rc;
drh054889e2005-11-30 03:20:31 +0000749 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000750
drh66560ad2006-01-06 14:32:19 +0000751 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000752 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000753 if( access(zFilename, 0)==0 ){
754 return SQLITE_CANTOPEN;
755 }
drh9cbe6352005-11-29 03:13:21 +0000756 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000757 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
758 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000759 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000760 return SQLITE_CANTOPEN;
761 }
drh66560ad2006-01-06 14:32:19 +0000762 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000763 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000764 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000765 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000766 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000767 unlink(zFilename);
768 return SQLITE_NOMEM;
769 }
drhbbd42a62004-05-22 17:41:58 +0000770 if( delFlag ){
771 unlink(zFilename);
772 }
drh9cbe6352005-11-29 03:13:21 +0000773 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000774 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000775}
776
777/*
778** Attempt to open a new file for read-only access.
779**
780** On success, write the file handle into *id and return SQLITE_OK.
781**
782** On failure, return SQLITE_CANTOPEN.
783*/
drh66560ad2006-01-06 14:32:19 +0000784int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000785 int rc;
drh054889e2005-11-30 03:20:31 +0000786 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000787
drh66560ad2006-01-06 14:32:19 +0000788 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000789 assert( 0==*pId );
drh9cbe6352005-11-29 03:13:21 +0000790 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
791 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000792 return SQLITE_CANTOPEN;
793 }
drh66560ad2006-01-06 14:32:19 +0000794 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000795 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000796 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000797 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000798 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000799 return SQLITE_NOMEM;
800 }
drh9cbe6352005-11-29 03:13:21 +0000801 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000802 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000803}
804
805/*
806** Attempt to open a file descriptor for the directory that contains a
807** file. This file descriptor can be used to fsync() the directory
808** in order to make sure the creation of a new file is actually written
809** to disk.
810**
811** This routine is only meaningful for Unix. It is a no-op under
812** windows since windows does not support hard links.
813**
drh9cbe6352005-11-29 03:13:21 +0000814** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000815** updated with the new directory file descriptor and SQLITE_OK is
816** returned.
817**
818** On failure, the function returns SQLITE_CANTOPEN and leaves
819** *id unchanged.
820*/
drh9c06c952005-11-26 00:25:00 +0000821static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000822 OsFile *id,
823 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000824){
drh054889e2005-11-30 03:20:31 +0000825 unixFile *pFile = (unixFile*)id;
826 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000827 /* Do not open the directory if the corresponding file is not already
828 ** open. */
829 return SQLITE_CANTOPEN;
830 }
drh054889e2005-11-30 03:20:31 +0000831 SET_THREADID(pFile);
832 assert( pFile->dirfd<0 );
833 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
834 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000835 return SQLITE_CANTOPEN;
836 }
drh054889e2005-11-30 03:20:31 +0000837 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000838 return SQLITE_OK;
839}
840
841/*
drhab3f9fe2004-08-14 17:10:10 +0000842** If the following global variable points to a string which is the
843** name of a directory, then that directory will be used to store
844** temporary files.
drhf1a221e2006-01-15 17:27:17 +0000845**
846** See also the "PRAGMA temp_store_directory" SQL command.
drhab3f9fe2004-08-14 17:10:10 +0000847*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000848char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000849
850/*
drhbbd42a62004-05-22 17:41:58 +0000851** Create a temporary file name in zBuf. zBuf must be big enough to
852** hold at least SQLITE_TEMPNAME_SIZE characters.
853*/
drh66560ad2006-01-06 14:32:19 +0000854int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000855 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000856 0,
drhbbd42a62004-05-22 17:41:58 +0000857 "/var/tmp",
858 "/usr/tmp",
859 "/tmp",
860 ".",
861 };
drh57196282004-10-06 15:41:16 +0000862 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000863 "abcdefghijklmnopqrstuvwxyz"
864 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
865 "0123456789";
866 int i, j;
867 struct stat buf;
868 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000869 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000870 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000871 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000872 if( stat(azDirs[i], &buf) ) continue;
873 if( !S_ISDIR(buf.st_mode) ) continue;
874 if( access(azDirs[i], 07) ) continue;
875 zDir = azDirs[i];
876 break;
877 }
878 do{
879 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
880 j = strlen(zBuf);
881 sqlite3Randomness(15, &zBuf[j]);
882 for(i=0; i<15; i++, j++){
883 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
884 }
885 zBuf[j] = 0;
886 }while( access(zBuf,0)==0 );
887 return SQLITE_OK;
888}
889
890/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000891** Check that a given pathname is a directory and is writable
892**
893*/
drh66560ad2006-01-06 14:32:19 +0000894int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000895#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000896 struct stat buf;
897 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000898 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000899 if( stat(zBuf, &buf) ) return 0;
900 if( !S_ISDIR(buf.st_mode) ) return 0;
901 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000902#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000903 return 1;
904}
905
906/*
drhbbd42a62004-05-22 17:41:58 +0000907** Read data from a file into a buffer. Return SQLITE_OK if all
908** bytes were read successfully and SQLITE_IOERR if anything goes
909** wrong.
910*/
drh9c06c952005-11-26 00:25:00 +0000911static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000912 int got;
drh9cbe6352005-11-29 03:13:21 +0000913 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000914 SimulateIOError(SQLITE_IOERR);
915 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000916 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000917 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000918 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
919 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000920 SEEK(0);
921 /* if( got<0 ) got = 0; */
922 if( got==amt ){
923 return SQLITE_OK;
924 }else{
925 return SQLITE_IOERR;
926 }
927}
928
929/*
930** Write data from a buffer into a file. Return SQLITE_OK on success
931** or some other error code on failure.
932*/
drh9c06c952005-11-26 00:25:00 +0000933static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000934 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000935 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000936 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000937 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000938 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000939 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000940 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000941 amt -= wrote;
942 pBuf = &((char*)pBuf)[wrote];
943 }
944 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000945 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
946 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000947 SEEK(0);
948 if( amt>0 ){
949 return SQLITE_FULL;
950 }
951 return SQLITE_OK;
952}
953
954/*
955** Move the read/write pointer in a file.
956*/
drh9c06c952005-11-26 00:25:00 +0000957static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000958 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000959 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000960#ifdef SQLITE_TEST
961 if( offset ) SimulateDiskfullError
962#endif
drh054889e2005-11-30 03:20:31 +0000963 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000964 return SQLITE_OK;
965}
966
drhb851b2c2005-03-10 14:11:12 +0000967#ifdef SQLITE_TEST
968/*
969** Count the number of fullsyncs and normal syncs. This is used to test
970** that syncs and fullsyncs are occuring at the right times.
971*/
972int sqlite3_sync_count = 0;
973int sqlite3_fullsync_count = 0;
974#endif
975
drhf2f23912005-10-05 10:29:36 +0000976/*
977** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
978** Otherwise use fsync() in its place.
979*/
980#ifndef HAVE_FDATASYNC
981# define fdatasync fsync
982#endif
983
drhac530b12006-02-11 01:25:50 +0000984/*
985** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
986** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
987** only available on Mac OS X. But that could change.
988*/
989#ifdef F_FULLFSYNC
990# define HAVE_FULLFSYNC 1
991#else
992# define HAVE_FULLFSYNC 0
993#endif
994
drhb851b2c2005-03-10 14:11:12 +0000995
drhbbd42a62004-05-22 17:41:58 +0000996/*
drhdd809b02004-07-17 21:44:57 +0000997** The fsync() system call does not work as advertised on many
998** unix systems. The following procedure is an attempt to make
999** it work better.
drh1398ad32005-01-19 23:24:50 +00001000**
1001** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1002** for testing when we want to run through the test suite quickly.
1003** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1004** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1005** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001006*/
drheb796a72005-09-08 12:38:41 +00001007static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001008 int rc;
drhb851b2c2005-03-10 14:11:12 +00001009
1010 /* Record the number of times that we do a normal fsync() and
1011 ** FULLSYNC. This is used during testing to verify that this procedure
1012 ** gets called with the correct arguments.
1013 */
1014#ifdef SQLITE_TEST
1015 if( fullSync ) sqlite3_fullsync_count++;
1016 sqlite3_sync_count++;
1017#endif
1018
1019 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1020 ** no-op
1021 */
1022#ifdef SQLITE_NO_SYNC
1023 rc = SQLITE_OK;
1024#else
1025
drhac530b12006-02-11 01:25:50 +00001026#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001027 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001028 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +00001029 }else{
1030 rc = 1;
1031 }
1032 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +00001033 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +00001034
drhc035e6e2005-09-22 15:45:04 +00001035#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +00001036 if( dataOnly ){
1037 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001038 }else{
drheb796a72005-09-08 12:38:41 +00001039 rc = fsync(fd);
1040 }
drhf30cc942005-03-11 17:52:34 +00001041#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +00001042#endif /* defined(SQLITE_NO_SYNC) */
1043
drhdd809b02004-07-17 21:44:57 +00001044 return rc;
1045}
1046
1047/*
drhbbd42a62004-05-22 17:41:58 +00001048** Make sure all writes to a particular file are committed to disk.
1049**
drheb796a72005-09-08 12:38:41 +00001050** If dataOnly==0 then both the file itself and its metadata (file
1051** size, access time, etc) are synced. If dataOnly!=0 then only the
1052** file data is synced.
1053**
drhbbd42a62004-05-22 17:41:58 +00001054** Under Unix, also make sure that the directory entry for the file
1055** has been created by fsync-ing the directory that contains the file.
1056** If we do not do this and we encounter a power failure, the directory
1057** entry for the journal might not exist after we reboot. The next
1058** SQLite to access the file will not know that the journal exists (because
1059** the directory entry for the journal was never created) and the transaction
1060** will not roll back - possibly leading to database corruption.
1061*/
drh9c06c952005-11-26 00:25:00 +00001062static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +00001063 unixFile *pFile = (unixFile*)id;
1064 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +00001065 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001066 TRACE2("SYNC %-3d\n", pFile->h);
1067 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +00001068 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001069 }
drh054889e2005-11-30 03:20:31 +00001070 if( pFile->dirfd>=0 ){
drhac530b12006-02-11 01:25:50 +00001071 TRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
1072 HAVE_FULLFSYNC, pFile->fullSync);
danielk1977d7c03f72005-11-25 10:38:22 +00001073#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001074 /* The directory sync is only attempted if full_fsync is
1075 ** turned off or unavailable. If a full_fsync occurred above,
1076 ** then the directory sync is superfluous.
1077 */
1078 if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
1079 /*
1080 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001081 ** errors when applied to directories on certain file systems.
1082 ** A failed directory sync is not a big deal. So it seems
1083 ** better to ignore the error. Ticket #1657
1084 */
1085 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001086 }
danielk1977d7c03f72005-11-25 10:38:22 +00001087#endif
drh054889e2005-11-30 03:20:31 +00001088 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1089 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001090 }
drha2854222004-06-17 19:04:17 +00001091 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001092}
1093
1094/*
danielk1977962398d2004-06-14 09:35:16 +00001095** Sync the directory zDirname. This is a no-op on operating systems other
1096** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001097**
1098** This is used to make sure the master journal file has truely been deleted
1099** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001100** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001101*/
drh66560ad2006-01-06 14:32:19 +00001102int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001103#ifdef SQLITE_DISABLE_DIRSYNC
1104 return SQLITE_OK;
1105#else
danielk1977962398d2004-06-14 09:35:16 +00001106 int fd;
1107 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001108 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001109 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001110 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001111 if( fd<0 ){
1112 return SQLITE_CANTOPEN;
1113 }
1114 r = fsync(fd);
1115 close(fd);
1116 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001117#endif
danielk1977962398d2004-06-14 09:35:16 +00001118}
1119
1120/*
drhbbd42a62004-05-22 17:41:58 +00001121** Truncate an open file to a specified size
1122*/
drh9c06c952005-11-26 00:25:00 +00001123static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001124 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001125 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001126 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001127}
1128
1129/*
1130** Determine the current size of a file in bytes
1131*/
drh9c06c952005-11-26 00:25:00 +00001132static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001133 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001134 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001135 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001136 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001137 return SQLITE_IOERR;
1138 }
1139 *pSize = buf.st_size;
1140 return SQLITE_OK;
1141}
1142
danielk19779a1d0ab2004-06-01 14:09:28 +00001143/*
danielk197713adf8a2004-06-03 16:08:41 +00001144** This routine checks if there is a RESERVED lock held on the specified
1145** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001146** non-zero. If the file is unlocked or holds only SHARED locks, then
1147** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001148*/
drh9c06c952005-11-26 00:25:00 +00001149static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001150 int r = 0;
drh054889e2005-11-30 03:20:31 +00001151 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001152
drh054889e2005-11-30 03:20:31 +00001153 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001154 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001155
1156 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001157 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001158 r = 1;
1159 }
1160
drh2ac3ee92004-06-07 16:27:46 +00001161 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001162 */
1163 if( !r ){
1164 struct flock lock;
1165 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001166 lock.l_start = RESERVED_BYTE;
1167 lock.l_len = 1;
1168 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001169 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001170 if( lock.l_type!=F_UNLCK ){
1171 r = 1;
1172 }
1173 }
1174
drh66560ad2006-01-06 14:32:19 +00001175 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001176 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001177
1178 return r;
1179}
1180
1181/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001182** Lock the file with the lock specified by parameter locktype - one
1183** of the following:
1184**
drh2ac3ee92004-06-07 16:27:46 +00001185** (1) SHARED_LOCK
1186** (2) RESERVED_LOCK
1187** (3) PENDING_LOCK
1188** (4) EXCLUSIVE_LOCK
1189**
drhb3e04342004-06-08 00:47:47 +00001190** Sometimes when requesting one lock state, additional lock states
1191** are inserted in between. The locking might fail on one of the later
1192** transitions leaving the lock state different from what it started but
1193** still short of its goal. The following chart shows the allowed
1194** transitions and the inserted intermediate states:
1195**
1196** UNLOCKED -> SHARED
1197** SHARED -> RESERVED
1198** SHARED -> (PENDING) -> EXCLUSIVE
1199** RESERVED -> (PENDING) -> EXCLUSIVE
1200** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001201**
drha6abd042004-06-09 17:37:22 +00001202** This routine will only increase a lock. Use the sqlite3OsUnlock()
1203** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001204*/
drh9c06c952005-11-26 00:25:00 +00001205static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001206 /* The following describes the implementation of the various locks and
1207 ** lock transitions in terms of the POSIX advisory shared and exclusive
1208 ** lock primitives (called read-locks and write-locks below, to avoid
1209 ** confusion with SQLite lock names). The algorithms are complicated
1210 ** slightly in order to be compatible with windows systems simultaneously
1211 ** accessing the same database file, in case that is ever required.
1212 **
1213 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1214 ** byte', each single bytes at well known offsets, and the 'shared byte
1215 ** range', a range of 510 bytes at a well known offset.
1216 **
1217 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1218 ** byte'. If this is successful, a random byte from the 'shared byte
1219 ** range' is read-locked and the lock on the 'pending byte' released.
1220 **
danielk197790ba3bd2004-06-25 08:32:25 +00001221 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1222 ** A RESERVED lock is implemented by grabbing a write-lock on the
1223 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001224 **
1225 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001226 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1227 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1228 ** obtained, but existing SHARED locks are allowed to persist. A process
1229 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1230 ** This property is used by the algorithm for rolling back a journal file
1231 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001232 **
danielk197790ba3bd2004-06-25 08:32:25 +00001233 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1234 ** implemented by obtaining a write-lock on the entire 'shared byte
1235 ** range'. Since all other locks require a read-lock on one of the bytes
1236 ** within this range, this ensures that no other locks are held on the
1237 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001238 **
1239 ** The reason a single byte cannot be used instead of the 'shared byte
1240 ** range' is that some versions of windows do not support read-locks. By
1241 ** locking a random byte from a range, concurrent SHARED locks may exist
1242 ** even if the locking primitive used is always a write-lock.
1243 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001244 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001245 unixFile *pFile = (unixFile*)id;
1246 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001247 struct flock lock;
1248 int s;
1249
drh054889e2005-11-30 03:20:31 +00001250 assert( pFile );
1251 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1252 locktypeName(locktype), locktypeName(pFile->locktype),
1253 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001254
1255 /* If there is already a lock of this type or more restrictive on the
1256 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001257 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001258 */
drh054889e2005-11-30 03:20:31 +00001259 if( pFile->locktype>=locktype ){
1260 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1261 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001262 return SQLITE_OK;
1263 }
1264
drhb3e04342004-06-08 00:47:47 +00001265 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001266 */
drh054889e2005-11-30 03:20:31 +00001267 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001268 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001269 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001270
drh054889e2005-11-30 03:20:31 +00001271 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001272 */
drh66560ad2006-01-06 14:32:19 +00001273 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001274
drh029b44b2006-01-15 00:13:15 +00001275 /* Make sure the current thread owns the pFile.
1276 */
1277 rc = transferOwnership(pFile);
1278 if( rc!=SQLITE_OK ){
1279 sqlite3OsLeaveMutex();
1280 return rc;
1281 }
drh64b1bea2006-01-15 02:30:57 +00001282 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001283
danielk19779a1d0ab2004-06-01 14:09:28 +00001284 /* If some thread using this PID has a lock via a different OsFile*
1285 ** handle that precludes the requested lock, return BUSY.
1286 */
drh054889e2005-11-30 03:20:31 +00001287 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001288 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001289 ){
1290 rc = SQLITE_BUSY;
1291 goto end_lock;
1292 }
1293
1294 /* If a SHARED lock is requested, and some thread using this PID already
1295 ** has a SHARED or RESERVED lock, then increment reference counts and
1296 ** return SQLITE_OK.
1297 */
1298 if( locktype==SHARED_LOCK &&
1299 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1300 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001301 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001302 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001303 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001304 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001305 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001306 goto end_lock;
1307 }
1308
danielk197713adf8a2004-06-03 16:08:41 +00001309 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001310
danielk19779a1d0ab2004-06-01 14:09:28 +00001311 lock.l_whence = SEEK_SET;
1312
drh3cde3bb2004-06-12 02:17:14 +00001313 /* A PENDING lock is needed before acquiring a SHARED lock and before
1314 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1315 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001316 */
drh3cde3bb2004-06-12 02:17:14 +00001317 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001318 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001319 ){
danielk1977489468c2004-06-28 08:25:47 +00001320 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001321 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001322 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001323 if( s ){
1324 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1325 goto end_lock;
1326 }
drh3cde3bb2004-06-12 02:17:14 +00001327 }
1328
1329
1330 /* If control gets to this point, then actually go ahead and make
1331 ** operating system calls for the specified lock.
1332 */
1333 if( locktype==SHARED_LOCK ){
1334 assert( pLock->cnt==0 );
1335 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001336
drh2ac3ee92004-06-07 16:27:46 +00001337 /* Now get the read-lock */
1338 lock.l_start = SHARED_FIRST;
1339 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001340 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001341
1342 /* Drop the temporary PENDING lock */
1343 lock.l_start = PENDING_BYTE;
1344 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001345 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001346 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001347 rc = SQLITE_IOERR; /* This should never happen */
1348 goto end_lock;
1349 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001351 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1352 }else{
drh054889e2005-11-30 03:20:31 +00001353 pFile->locktype = SHARED_LOCK;
1354 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001355 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001356 }
drh3cde3bb2004-06-12 02:17:14 +00001357 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1358 /* We are trying for an exclusive lock but another thread in this
1359 ** same process is still holding a shared lock. */
1360 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001361 }else{
drh3cde3bb2004-06-12 02:17:14 +00001362 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001363 ** assumed that there is a SHARED or greater lock on the file
1364 ** already.
1365 */
drh054889e2005-11-30 03:20:31 +00001366 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001367 lock.l_type = F_WRLCK;
1368 switch( locktype ){
1369 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001370 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001371 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001372 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001373 lock.l_start = SHARED_FIRST;
1374 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001375 break;
1376 default:
1377 assert(0);
1378 }
drh054889e2005-11-30 03:20:31 +00001379 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001380 if( s ){
1381 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1382 }
drhbbd42a62004-05-22 17:41:58 +00001383 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001384
danielk1977ecb2a962004-06-02 06:30:16 +00001385 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001386 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001387 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001388 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001389 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001390 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001391 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001392
1393end_lock:
drh66560ad2006-01-06 14:32:19 +00001394 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001395 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001396 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001397 return rc;
1398}
1399
1400/*
drh054889e2005-11-30 03:20:31 +00001401** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001402** must be either NO_LOCK or SHARED_LOCK.
1403**
1404** If the locking level of the file descriptor is already at or below
1405** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001406*/
drh9c06c952005-11-26 00:25:00 +00001407static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001408 struct lockInfo *pLock;
1409 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001410 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001411 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001412
drh054889e2005-11-30 03:20:31 +00001413 assert( pFile );
1414 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1415 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001416
1417 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001418 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001419 return SQLITE_OK;
1420 }
drhf1a221e2006-01-15 17:27:17 +00001421 if( CHECK_THREADID(pFile) ){
1422 return SQLITE_MISUSE;
1423 }
drh66560ad2006-01-06 14:32:19 +00001424 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001425 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001426 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001427 if( pFile->locktype>SHARED_LOCK ){
1428 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001429 if( locktype==SHARED_LOCK ){
1430 lock.l_type = F_RDLCK;
1431 lock.l_whence = SEEK_SET;
1432 lock.l_start = SHARED_FIRST;
1433 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001434 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001435 /* This should never happen */
1436 rc = SQLITE_IOERR;
1437 }
1438 }
drhbbd42a62004-05-22 17:41:58 +00001439 lock.l_type = F_UNLCK;
1440 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001441 lock.l_start = PENDING_BYTE;
1442 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001443 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001444 pLock->locktype = SHARED_LOCK;
1445 }else{
1446 rc = SQLITE_IOERR; /* This should never happen */
1447 }
drhbbd42a62004-05-22 17:41:58 +00001448 }
drha6abd042004-06-09 17:37:22 +00001449 if( locktype==NO_LOCK ){
1450 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001451
drha6abd042004-06-09 17:37:22 +00001452 /* Decrement the shared lock counter. Release the lock using an
1453 ** OS call only when all threads in this same process have released
1454 ** the lock.
1455 */
1456 pLock->cnt--;
1457 if( pLock->cnt==0 ){
1458 lock.l_type = F_UNLCK;
1459 lock.l_whence = SEEK_SET;
1460 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001461 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001462 pLock->locktype = NO_LOCK;
1463 }else{
1464 rc = SQLITE_IOERR; /* This should never happen */
1465 }
drha6abd042004-06-09 17:37:22 +00001466 }
1467
drhbbd42a62004-05-22 17:41:58 +00001468 /* Decrement the count of locks against this same file. When the
1469 ** count reaches zero, close any other file descriptors whose close
1470 ** was deferred because of outstanding locks.
1471 */
drh054889e2005-11-30 03:20:31 +00001472 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001473 pOpen->nLock--;
1474 assert( pOpen->nLock>=0 );
1475 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1476 int i;
1477 for(i=0; i<pOpen->nPending; i++){
1478 close(pOpen->aPending[i]);
1479 }
drh64b1bea2006-01-15 02:30:57 +00001480 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001481 pOpen->nPending = 0;
1482 pOpen->aPending = 0;
1483 }
1484 }
drh66560ad2006-01-06 14:32:19 +00001485 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001486 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001487 return rc;
drhbbd42a62004-05-22 17:41:58 +00001488}
1489
1490/*
danielk1977e3026632004-06-22 11:29:02 +00001491** Close a file.
1492*/
drh9cbe6352005-11-29 03:13:21 +00001493static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001494 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001495
drh9cbe6352005-11-29 03:13:21 +00001496 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001497 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001498 if( id->dirfd>=0 ) close(id->dirfd);
1499 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001500 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001501
drh38322302006-01-15 02:43:16 +00001502 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001503 /* If there are outstanding locks, do not actually close the file just
1504 ** yet because that would clear those locks. Instead, add the file
1505 ** descriptor to pOpen->aPending. It will be automatically closed when
1506 ** the last lock is cleared.
1507 */
1508 int *aNew;
1509 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001510 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001511 if( aNew==0 ){
1512 /* If a malloc fails, just leak the file descriptor */
1513 }else{
1514 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001515 pOpen->aPending[pOpen->nPending] = id->h;
1516 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001517 }
1518 }else{
1519 /* There are no outstanding locks so we can close the file immediately */
1520 close(id->h);
1521 }
1522 releaseLockInfo(id->pLock);
1523 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001524
drh66560ad2006-01-06 14:32:19 +00001525 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001526 id->isOpen = 0;
1527 TRACE2("CLOSE %-3d\n", id->h);
1528 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001529 sqliteFree(id);
1530 *pId = 0;
drh02afc862006-01-20 18:10:57 +00001531 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001532}
1533
1534/*
drh0ccebe72005-06-07 22:22:50 +00001535** Turn a relative pathname into a full pathname. Return a pointer
1536** to the full pathname stored in space obtained from sqliteMalloc().
1537** The calling function is responsible for freeing this space once it
1538** is no longer needed.
1539*/
drh66560ad2006-01-06 14:32:19 +00001540char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001541 char *zFull = 0;
1542 if( zRelative[0]=='/' ){
1543 sqlite3SetString(&zFull, zRelative, (char*)0);
1544 }else{
drh79158e12005-09-06 21:40:45 +00001545 char *zBuf = sqliteMalloc(5000);
1546 if( zBuf==0 ){
1547 return 0;
1548 }
drh0ccebe72005-06-07 22:22:50 +00001549 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001550 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001551 (char*)0);
drh79158e12005-09-06 21:40:45 +00001552 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001553 }
drh4eb9a972006-02-13 18:42:21 +00001554
1555#if 0
drh89ea9312006-02-13 17:03:47 +00001556 /*
1557 ** Remove "/./" path elements and convert "/A/./" path elements
1558 ** to just "/".
1559 */
1560 if( zFull ){
drh4eb9a972006-02-13 18:42:21 +00001561 int i, j;
drh89ea9312006-02-13 17:03:47 +00001562 for(i=j=0; zFull[i]; i++){
1563 if( zFull[i]=='/' ){
1564 if( zFull[i+1]=='/' ) continue;
1565 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
1566 i += 1;
1567 continue;
1568 }
1569 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
1570 while( j>0 && zFull[j-1]!='/' ){ j--; }
1571 i += 3;
1572 continue;
1573 }
1574 }
1575 zFull[j++] = zFull[i];
1576 }
1577 zFull[j] = 0;
1578 }
drh4eb9a972006-02-13 18:42:21 +00001579#endif
1580
drh0ccebe72005-06-07 22:22:50 +00001581 return zFull;
1582}
1583
drh18839212005-11-26 03:43:23 +00001584/*
drh9cbe6352005-11-29 03:13:21 +00001585** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001586*/
drh9cbe6352005-11-29 03:13:21 +00001587static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001588 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001589}
1590
1591/*
1592** Return the underlying file handle for an OsFile
1593*/
1594static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001595 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001596}
1597
1598/*
1599** Return an integer that indices the type of lock currently held
1600** by this handle. (Used for testing and analysis only.)
1601*/
1602static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001603 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001604}
drh0ccebe72005-06-07 22:22:50 +00001605
drh9c06c952005-11-26 00:25:00 +00001606/*
drh054889e2005-11-30 03:20:31 +00001607** This vector defines all the methods that can operate on an OsFile
1608** for unix.
drh9c06c952005-11-26 00:25:00 +00001609*/
drh054889e2005-11-30 03:20:31 +00001610static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001611 unixClose,
drh054889e2005-11-30 03:20:31 +00001612 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001613 unixRead,
1614 unixWrite,
1615 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001616 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001617 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001618 unixSetFullSync,
1619 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001620 unixFileSize,
1621 unixLock,
1622 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001623 unixLockState,
drh054889e2005-11-30 03:20:31 +00001624 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001625};
1626
drh054889e2005-11-30 03:20:31 +00001627/*
1628** Allocate memory for a unixFile. Initialize the new unixFile
1629** to the value given in pInit and return a pointer to the new
1630** OsFile. If we run out of memory, close the file and return NULL.
1631*/
1632static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1633 unixFile *pNew;
drh2f1a4d12006-01-23 16:24:54 +00001634 pInit->dirfd = -1;
1635 pInit->fullSync = 0;
1636 pInit->locktype = 0;
1637 SET_THREADID(pInit);
drh054889e2005-11-30 03:20:31 +00001638 pNew = sqliteMalloc( sizeof(unixFile) );
1639 if( pNew==0 ){
1640 close(pInit->h);
drh029b44b2006-01-15 00:13:15 +00001641 sqlite3OsEnterMutex();
danielk19772e588c72005-12-09 14:25:08 +00001642 releaseLockInfo(pInit->pLock);
1643 releaseOpenCnt(pInit->pOpen);
drh029b44b2006-01-15 00:13:15 +00001644 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001645 *pId = 0;
1646 return SQLITE_NOMEM;
1647 }else{
1648 *pNew = *pInit;
1649 pNew->pMethod = &sqlite3UnixIoMethod;
1650 *pId = (OsFile*)pNew;
1651 OpenCounter(+1);
1652 return SQLITE_OK;
1653 }
1654}
1655
drh9c06c952005-11-26 00:25:00 +00001656
drh0ccebe72005-06-07 22:22:50 +00001657#endif /* SQLITE_OMIT_DISKIO */
1658/***************************************************************************
1659** Everything above deals with file I/O. Everything that follows deals
1660** with other miscellanous aspects of the operating system interface
1661****************************************************************************/
1662
1663
1664/*
drhbbd42a62004-05-22 17:41:58 +00001665** Get information to seed the random number generator. The seed
1666** is written into the buffer zBuf[256]. The calling function must
1667** supply a sufficiently large buffer.
1668*/
drh66560ad2006-01-06 14:32:19 +00001669int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001670 /* We have to initialize zBuf to prevent valgrind from reporting
1671 ** errors. The reports issued by valgrind are incorrect - we would
1672 ** prefer that the randomness be increased by making use of the
1673 ** uninitialized space in zBuf - but valgrind errors tend to worry
1674 ** some users. Rather than argue, it seems easier just to initialize
1675 ** the whole array and silence valgrind, even if that means less randomness
1676 ** in the random seed.
1677 **
1678 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00001679 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00001680 ** tests repeatable.
1681 */
1682 memset(zBuf, 0, 256);
1683#if !defined(SQLITE_TEST)
1684 {
drh842b8642005-01-21 17:53:17 +00001685 int pid, fd;
1686 fd = open("/dev/urandom", O_RDONLY);
1687 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001688 time_t t;
1689 time(&t);
1690 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001691 pid = getpid();
1692 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1693 }else{
1694 read(fd, zBuf, 256);
1695 close(fd);
1696 }
drhbbd42a62004-05-22 17:41:58 +00001697 }
1698#endif
1699 return SQLITE_OK;
1700}
1701
1702/*
1703** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00001704** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00001705*/
drh66560ad2006-01-06 14:32:19 +00001706int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001707#if defined(HAVE_USLEEP) && HAVE_USLEEP
1708 usleep(ms*1000);
1709 return ms;
1710#else
1711 sleep((ms+999)/1000);
1712 return 1000*((ms+999)/1000);
1713#endif
1714}
1715
1716/*
drh5c111232006-02-10 04:33:12 +00001717** Static variables used for thread synchronization.
1718**
1719** inMutex the nesting depth of the recursive mutex. The thread
1720** holding mutexMain can read this variable at any time.
1721** But is must hold mutexAux to change this variable. Other
drh6a3d6702006-02-10 13:11:32 +00001722** threads must hold mutexAux to read the variable and can
1723** never write.
drh5c111232006-02-10 04:33:12 +00001724**
1725** mutexOwner The thread id of the thread holding mutexMain. Same
1726** access rules as for inMutex.
1727**
drh6a3d6702006-02-10 13:11:32 +00001728** mutexOwnerValid True if the value in mutexOwner is valid. The same
1729** access rules apply as for inMutex.
drh5c111232006-02-10 04:33:12 +00001730**
1731** mutexMain The main mutex. Hold this mutex in order to get exclusive
1732** access to SQLite data structures.
1733**
1734** mutexAux An auxiliary mutex needed to access variables defined above.
1735**
drh6a3d6702006-02-10 13:11:32 +00001736** Mutexes are always acquired in this order: mutexMain mutexAux. It
1737** is not necessary to acquire mutexMain in order to get mutexAux - just
1738** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
1739** Either get the mutexes with mutexMain first or get mutexAux only.
1740**
1741** When running on a platform where the three variables inMutex, mutexOwner,
1742** and mutexOwnerValid can be set atomically, the mutexAux is not required.
1743** On many systems, all three are 32-bit integers and writing to a 32-bit
1744** integer is atomic. I think. But there are no guarantees. So it seems
1745** safer to protect them using mutexAux.
drhbbd42a62004-05-22 17:41:58 +00001746*/
1747static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001748#ifdef SQLITE_UNIX_THREADS
drh6a3d6702006-02-10 13:11:32 +00001749static pthread_t mutexOwner; /* Thread holding mutexMain */
drh5c111232006-02-10 04:33:12 +00001750static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
1751static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
1752static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
drh79069752004-05-22 21:30:40 +00001753#endif
drhbbd42a62004-05-22 17:41:58 +00001754
1755/*
1756** The following pair of routine implement mutual exclusion for
1757** multi-threaded processes. Only a single thread is allowed to
1758** executed code that is surrounded by EnterMutex() and LeaveMutex().
1759**
1760** SQLite uses only a single Mutex. There is not much critical
1761** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00001762**
drh757b04e2006-01-18 17:25:45 +00001763** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00001764*/
drh66560ad2006-01-06 14:32:19 +00001765void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001766#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001767 pthread_mutex_lock(&mutexAux);
1768 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
1769 pthread_mutex_unlock(&mutexAux);
1770 pthread_mutex_lock(&mutexMain);
1771 assert( inMutex==0 );
1772 assert( !mutexOwnerValid );
1773 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001774 mutexOwner = pthread_self();
drh5c111232006-02-10 04:33:12 +00001775 mutexOwnerValid = 1;
drha3fad6f2006-01-18 14:06:37 +00001776 }
drha3fad6f2006-01-18 14:06:37 +00001777 inMutex++;
drh5c111232006-02-10 04:33:12 +00001778 pthread_mutex_unlock(&mutexAux);
1779#else
drhe9565a62006-02-11 02:03:52 +00001780 inMutex++;
drh5c111232006-02-10 04:33:12 +00001781#endif
drhbbd42a62004-05-22 17:41:58 +00001782}
drh66560ad2006-01-06 14:32:19 +00001783void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00001784 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00001785#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001786 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001787 inMutex--;
drh5c111232006-02-10 04:33:12 +00001788 assert( pthread_equal(mutexOwner, pthread_self()) );
drha3fad6f2006-01-18 14:06:37 +00001789 if( inMutex==0 ){
drh5c111232006-02-10 04:33:12 +00001790 assert( mutexOwnerValid );
1791 mutexOwnerValid = 0;
1792 pthread_mutex_unlock(&mutexMain);
drha3fad6f2006-01-18 14:06:37 +00001793 }
drh5c111232006-02-10 04:33:12 +00001794 pthread_mutex_unlock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001795#else
1796 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00001797#endif
1798}
1799
1800/*
drh757b04e2006-01-18 17:25:45 +00001801** Return TRUE if the mutex is currently held.
1802**
drh5c111232006-02-10 04:33:12 +00001803** If the thisThrd parameter is true, return true only if the
drh757b04e2006-01-18 17:25:45 +00001804** calling thread holds the mutex. If the parameter is false, return
1805** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00001806*/
drh5c111232006-02-10 04:33:12 +00001807int sqlite3UnixInMutex(int thisThrd){
drha3fad6f2006-01-18 14:06:37 +00001808#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001809 int rc;
1810 pthread_mutex_lock(&mutexAux);
1811 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
1812 pthread_mutex_unlock(&mutexAux);
1813 return rc;
drha3fad6f2006-01-18 14:06:37 +00001814#else
drh757b04e2006-01-18 17:25:45 +00001815 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00001816#endif
drh88f474a2006-01-02 20:00:12 +00001817}
1818
1819/*
drhb4bc7052006-01-11 23:40:33 +00001820** Remember the number of thread-specific-data blocks allocated.
1821** Use this to verify that we are not leaking thread-specific-data.
1822** Ticket #1601
1823*/
1824#ifdef SQLITE_TEST
1825int sqlite3_tsd_count = 0;
1826# ifdef SQLITE_UNIX_THREADS
1827 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
1828# define TSD_COUNTER(N) \
1829 pthread_mutex_lock(&tsd_counter_mutex); \
1830 sqlite3_tsd_count += N; \
1831 pthread_mutex_unlock(&tsd_counter_mutex);
1832# else
1833# define TSD_COUNTER(N) sqlite3_tsd_count += N
1834# endif
1835#else
1836# define TSD_COUNTER(N) /* no-op */
1837#endif
1838
drhb4bc7052006-01-11 23:40:33 +00001839/*
drhf1a221e2006-01-15 17:27:17 +00001840** If called with allocateFlag>0, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00001841** specific data for the current thread. Allocate and zero the
drhf1a221e2006-01-15 17:27:17 +00001842** thread-specific data if it does not already exist.
danielk197713a68c32005-12-15 10:11:30 +00001843**
drh6f7adc82006-01-11 21:41:20 +00001844** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00001845** specific data. Return it if it exists. If it does not exist,
1846** then return NULL.
1847**
1848** If called with allocateFlag<0, check to see if the thread specific
1849** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00001850** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00001851** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00001852*/
drh6f7adc82006-01-11 21:41:20 +00001853ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
danielk19774d5238f2006-01-27 06:32:00 +00001854 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
1855 ** from broken compilers */
danielk197713a68c32005-12-15 10:11:30 +00001856#ifdef SQLITE_UNIX_THREADS
1857 static pthread_key_t key;
1858 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001859 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001860
1861 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001862 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001863 if( !keyInit ){
1864 int rc;
drh6f7adc82006-01-11 21:41:20 +00001865 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001866 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001867 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001868 return 0;
1869 }
1870 keyInit = 1;
1871 }
drh66560ad2006-01-06 14:32:19 +00001872 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001873 }
1874
drh3fbb0b12006-01-06 00:36:00 +00001875 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00001876 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001877 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001878 if( !sqlite3TestMallocFail() ){
1879 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1880 }
1881#ifdef SQLITE_MEMDEBUG
1882 sqlite3_isFail = 0;
1883#endif
drh6f7adc82006-01-11 21:41:20 +00001884 if( pTsd ){
1885 *pTsd = zeroData;
1886 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00001887 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001888 }
danielk197713a68c32005-12-15 10:11:30 +00001889 }
drh70ff98a2006-01-12 01:25:18 +00001890 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001891 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001892 sqlite3OsFree(pTsd);
1893 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00001894 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001895 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001896 }
1897 return pTsd;
1898#else
drh6f7adc82006-01-11 21:41:20 +00001899 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00001900 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001901 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001902 if( !sqlite3TestMallocFail() ){
1903 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1904 }
1905#ifdef SQLITE_MEMDEBUG
1906 sqlite3_isFail = 0;
1907#endif
drh6f7adc82006-01-11 21:41:20 +00001908 if( pTsd ){
1909 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00001910 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001911 }
drh3fbb0b12006-01-06 00:36:00 +00001912 }
drh70ff98a2006-01-12 01:25:18 +00001913 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001914 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001915 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00001916 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001917 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001918 }
drh3fbb0b12006-01-06 00:36:00 +00001919 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001920#endif
1921}
1922
1923/*
drhbbd42a62004-05-22 17:41:58 +00001924** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001925** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001926*/
1927#ifdef SQLITE_TEST
1928int sqlite3_current_time = 0;
1929#endif
1930
1931/*
1932** Find the current time (in Universal Coordinated Time). Write the
1933** current time and date as a Julian Day number into *prNow and
1934** return 0. Return 1 if the time and date cannot be found.
1935*/
drh66560ad2006-01-06 14:32:19 +00001936int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001937#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001938 time_t t;
1939 time(&t);
1940 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001941#else
1942 struct timeval sNow;
1943 struct timezone sTz; /* Not used */
1944 gettimeofday(&sNow, &sTz);
1945 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1946#endif
drhbbd42a62004-05-22 17:41:58 +00001947#ifdef SQLITE_TEST
1948 if( sqlite3_current_time ){
1949 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1950 }
1951#endif
1952 return 0;
1953}
1954
drhbbd42a62004-05-22 17:41:58 +00001955#endif /* OS_UNIX */