blob: b9c0121383083069cfed0e96236b83e46a137f7e [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**
356** This variable normally has file scope only. But during testing, we make
357** it a global so that the test code can change its value in order to verify
358** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000359*/
drh029b44b2006-01-15 00:13:15 +0000360#ifdef SQLITE_TEST
361int threadsOverrideEachOthersLocks = -1;
362#else
drh5fdae772004-06-29 03:29:00 +0000363static int threadsOverrideEachOthersLocks = -1;
drh029b44b2006-01-15 00:13:15 +0000364#endif
drh5fdae772004-06-29 03:29:00 +0000365
366/*
367** This structure holds information passed into individual test
368** threads by the testThreadLockingBehavior() routine.
369*/
370struct threadTestData {
371 int fd; /* File to be locked */
372 struct flock lock; /* The locking operation */
373 int result; /* Result of the locking operation */
374};
375
drh2b4b5962005-06-15 17:47:55 +0000376#ifdef SQLITE_LOCK_TRACE
377/*
378** Print out information about all locking operations.
379**
380** This routine is used for troubleshooting locks on multithreaded
381** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
382** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000383** turned off.
drh2b4b5962005-06-15 17:47:55 +0000384*/
385static int lockTrace(int fd, int op, struct flock *p){
386 char *zOpName, *zType;
387 int s;
388 int savedErrno;
389 if( op==F_GETLK ){
390 zOpName = "GETLK";
391 }else if( op==F_SETLK ){
392 zOpName = "SETLK";
393 }else{
394 s = fcntl(fd, op, p);
395 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
396 return s;
397 }
398 if( p->l_type==F_RDLCK ){
399 zType = "RDLCK";
400 }else if( p->l_type==F_WRLCK ){
401 zType = "WRLCK";
402 }else if( p->l_type==F_UNLCK ){
403 zType = "UNLCK";
404 }else{
405 assert( 0 );
406 }
407 assert( p->l_whence==SEEK_SET );
408 s = fcntl(fd, op, p);
409 savedErrno = errno;
410 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
411 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
412 (int)p->l_pid, s);
413 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
414 struct flock l2;
415 l2 = *p;
416 fcntl(fd, F_GETLK, &l2);
417 if( l2.l_type==F_RDLCK ){
418 zType = "RDLCK";
419 }else if( l2.l_type==F_WRLCK ){
420 zType = "WRLCK";
421 }else if( l2.l_type==F_UNLCK ){
422 zType = "UNLCK";
423 }else{
424 assert( 0 );
425 }
426 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
427 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
428 }
429 errno = savedErrno;
430 return s;
431}
432#define fcntl lockTrace
433#endif /* SQLITE_LOCK_TRACE */
434
drh5fdae772004-06-29 03:29:00 +0000435/*
436** The testThreadLockingBehavior() routine launches two separate
437** threads on this routine. This routine attempts to lock a file
438** descriptor then returns. The success or failure of that attempt
439** allows the testThreadLockingBehavior() procedure to determine
440** whether or not threads can override each others locks.
441*/
442static void *threadLockingTest(void *pArg){
443 struct threadTestData *pData = (struct threadTestData*)pArg;
444 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
445 return pArg;
446}
447
448/*
449** This procedure attempts to determine whether or not threads
450** can override each others locks then sets the
451** threadsOverrideEachOthersLocks variable appropriately.
452*/
453static void testThreadLockingBehavior(fd_orig){
454 int fd;
455 struct threadTestData d[2];
456 pthread_t t[2];
457
458 fd = dup(fd_orig);
459 if( fd<0 ) return;
460 memset(d, 0, sizeof(d));
461 d[0].fd = fd;
462 d[0].lock.l_type = F_RDLCK;
463 d[0].lock.l_len = 1;
464 d[0].lock.l_start = 0;
465 d[0].lock.l_whence = SEEK_SET;
466 d[1] = d[0];
467 d[1].lock.l_type = F_WRLCK;
468 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
469 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
470 pthread_join(t[0], 0);
471 pthread_join(t[1], 0);
472 close(fd);
473 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
474}
475#endif /* SQLITE_UNIX_THREADS */
476
drhbbd42a62004-05-22 17:41:58 +0000477/*
478** Release a lockInfo structure previously allocated by findLockInfo().
479*/
480static void releaseLockInfo(struct lockInfo *pLock){
drh757b04e2006-01-18 17:25:45 +0000481 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000482 pLock->nRef--;
483 if( pLock->nRef==0 ){
484 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
485 sqliteFree(pLock);
486 }
487}
488
489/*
490** Release a openCnt structure previously allocated by findLockInfo().
491*/
492static void releaseOpenCnt(struct openCnt *pOpen){
drh757b04e2006-01-18 17:25:45 +0000493 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000494 pOpen->nRef--;
495 if( pOpen->nRef==0 ){
496 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000497 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +0000498 sqliteFree(pOpen);
499 }
500}
501
502/*
503** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000504** describes that file descriptor. Create new ones if necessary. The
505** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000506**
507** Return the number of errors.
508*/
drh38f82712004-06-18 17:10:16 +0000509static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000510 int fd, /* The file descriptor used in the key */
511 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000512 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000513){
514 int rc;
515 struct lockKey key1;
516 struct openKey key2;
517 struct stat statbuf;
518 struct lockInfo *pLock;
519 struct openCnt *pOpen;
520 rc = fstat(fd, &statbuf);
521 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000522
drh757b04e2006-01-18 17:25:45 +0000523 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000524 memset(&key1, 0, sizeof(key1));
525 key1.dev = statbuf.st_dev;
526 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000527#ifdef SQLITE_UNIX_THREADS
528 if( threadsOverrideEachOthersLocks<0 ){
529 testThreadLockingBehavior(fd);
530 }
531 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
532#endif
drhbbd42a62004-05-22 17:41:58 +0000533 memset(&key2, 0, sizeof(key2));
534 key2.dev = statbuf.st_dev;
535 key2.ino = statbuf.st_ino;
536 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
537 if( pLock==0 ){
538 struct lockInfo *pOld;
539 pLock = sqliteMallocRaw( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000540 if( pLock==0 ){
541 rc = 1;
542 goto exit_findlockinfo;
543 }
drhbbd42a62004-05-22 17:41:58 +0000544 pLock->key = key1;
545 pLock->nRef = 1;
546 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000547 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000548 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
549 if( pOld!=0 ){
550 assert( pOld==pLock );
551 sqliteFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000552 rc = 1;
553 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000554 }
555 }else{
556 pLock->nRef++;
557 }
558 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000559 if( ppOpen!=0 ){
560 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000561 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000562 struct openCnt *pOld;
563 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
564 if( pOpen==0 ){
565 releaseLockInfo(pLock);
566 rc = 1;
567 goto exit_findlockinfo;
568 }
569 pOpen->key = key2;
570 pOpen->nRef = 1;
571 pOpen->nLock = 0;
572 pOpen->nPending = 0;
573 pOpen->aPending = 0;
574 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
575 if( pOld!=0 ){
576 assert( pOld==pOpen );
577 sqliteFree(pOpen);
578 releaseLockInfo(pLock);
579 rc = 1;
580 goto exit_findlockinfo;
581 }
582 }else{
583 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000584 }
drh029b44b2006-01-15 00:13:15 +0000585 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000586 }
danielk1977441b09a2006-01-05 13:48:29 +0000587
588exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000589 return rc;
drhbbd42a62004-05-22 17:41:58 +0000590}
591
drh64b1bea2006-01-15 02:30:57 +0000592#ifdef SQLITE_DEBUG
593/*
594** Helper function for printing out trace information from debugging
595** binaries. This returns the string represetation of the supplied
596** integer lock-type.
597*/
598static const char *locktypeName(int locktype){
599 switch( locktype ){
600 case NO_LOCK: return "NONE";
601 case SHARED_LOCK: return "SHARED";
602 case RESERVED_LOCK: return "RESERVED";
603 case PENDING_LOCK: return "PENDING";
604 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
605 }
606 return "ERROR";
607}
608#endif
609
drhbbd42a62004-05-22 17:41:58 +0000610/*
drh029b44b2006-01-15 00:13:15 +0000611** If we are currently in a different thread than the thread that the
612** unixFile argument belongs to, then transfer ownership of the unixFile
613** over to the current thread.
614**
615** A unixFile is only owned by a thread on systems where one thread is
616** unable to override locks created by a different thread. RedHat9 is
617** an example of such a system.
618**
619** Ownership transfer is only allowed if the unixFile is currently unlocked.
620** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000621** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000622*/
623#ifdef SQLITE_UNIX_THREADS
624static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000625 int rc;
drh029b44b2006-01-15 00:13:15 +0000626 pthread_t hSelf;
627 if( threadsOverrideEachOthersLocks ){
628 /* Ownership transfers not needed on this system */
629 return SQLITE_OK;
630 }
631 hSelf = pthread_self();
632 if( pthread_equal(pFile->tid, hSelf) ){
633 /* We are still in the same thread */
drh64b1bea2006-01-15 02:30:57 +0000634 TRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000635 return SQLITE_OK;
636 }
637 if( pFile->locktype!=NO_LOCK ){
638 /* We cannot change ownership while we are holding a lock! */
639 return SQLITE_MISUSE;
640 }
drh64b1bea2006-01-15 02:30:57 +0000641 TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
drh029b44b2006-01-15 00:13:15 +0000642 pFile->tid = hSelf;
643 releaseLockInfo(pFile->pLock);
drh64b1bea2006-01-15 02:30:57 +0000644 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
645 TRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
646 locktypeName(pFile->locktype),
647 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
648 return rc;
drh029b44b2006-01-15 00:13:15 +0000649}
650#else
drhf1a221e2006-01-15 17:27:17 +0000651 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000652# define transferOwnership(X) SQLITE_OK
653#endif
654
655/*
drhbbd42a62004-05-22 17:41:58 +0000656** Delete the named file
657*/
drh66560ad2006-01-06 14:32:19 +0000658int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000659 unlink(zFilename);
660 return SQLITE_OK;
661}
662
663/*
664** Return TRUE if the named file exists.
665*/
drh66560ad2006-01-06 14:32:19 +0000666int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000667 return access(zFilename, 0)==0;
668}
669
drh054889e2005-11-30 03:20:31 +0000670/* Forward declaration */
671static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000672
673/*
drhbbd42a62004-05-22 17:41:58 +0000674** Attempt to open a file for both reading and writing. If that
675** fails, try opening it read-only. If the file does not exist,
676** try to create it.
677**
678** On success, a handle for the open file is written to *id
679** and *pReadonly is set to 0 if the file was opened for reading and
680** writing or 1 if the file was opened read-only. The function returns
681** SQLITE_OK.
682**
683** On failure, the function returns SQLITE_CANTOPEN and leaves
684** *id and *pReadonly unchanged.
685*/
drh66560ad2006-01-06 14:32:19 +0000686int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000687 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000688 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000689 int *pReadonly
690){
691 int rc;
drh054889e2005-11-30 03:20:31 +0000692 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000693
drh66560ad2006-01-06 14:32:19 +0000694 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000695 assert( 0==*pId );
696 f.dirfd = -1;
697 SET_THREADID(&f);
698 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000699 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000700 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000701#ifdef EISDIR
702 if( errno==EISDIR ){
703 return SQLITE_CANTOPEN;
704 }
705#endif
drh9cbe6352005-11-29 03:13:21 +0000706 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
707 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000708 return SQLITE_CANTOPEN;
709 }
710 *pReadonly = 1;
711 }else{
712 *pReadonly = 0;
713 }
drh66560ad2006-01-06 14:32:19 +0000714 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000715 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000716 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000717 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000718 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000719 return SQLITE_NOMEM;
720 }
drh9cbe6352005-11-29 03:13:21 +0000721 f.locktype = 0;
722 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000723 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000724}
725
726
727/*
728** Attempt to open a new file for exclusive access by this process.
729** The file will be opened for both reading and writing. To avoid
730** a potential security problem, we do not allow the file to have
731** previously existed. Nor do we allow the file to be a symbolic
732** link.
733**
734** If delFlag is true, then make arrangements to automatically delete
735** the file when it is closed.
736**
737** On success, write the file handle into *id and return SQLITE_OK.
738**
739** On failure, return SQLITE_CANTOPEN.
740*/
drh66560ad2006-01-06 14:32:19 +0000741int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000742 int rc;
drh054889e2005-11-30 03:20:31 +0000743 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000744
drh66560ad2006-01-06 14:32:19 +0000745 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000746 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000747 if( access(zFilename, 0)==0 ){
748 return SQLITE_CANTOPEN;
749 }
drh9cbe6352005-11-29 03:13:21 +0000750 SET_THREADID(&f);
751 f.dirfd = -1;
752 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000753 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
754 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000755 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000756 return SQLITE_CANTOPEN;
757 }
drh66560ad2006-01-06 14:32:19 +0000758 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000759 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000760 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000761 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000762 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000763 unlink(zFilename);
764 return SQLITE_NOMEM;
765 }
drh9cbe6352005-11-29 03:13:21 +0000766 f.locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000767 if( delFlag ){
768 unlink(zFilename);
769 }
drh9cbe6352005-11-29 03:13:21 +0000770 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000771 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000772}
773
774/*
775** Attempt to open a new file for read-only access.
776**
777** On success, write the file handle into *id and return SQLITE_OK.
778**
779** On failure, return SQLITE_CANTOPEN.
780*/
drh66560ad2006-01-06 14:32:19 +0000781int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000782 int rc;
drh054889e2005-11-30 03:20:31 +0000783 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000784
drh66560ad2006-01-06 14:32:19 +0000785 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000786 assert( 0==*pId );
787 SET_THREADID(&f);
788 f.dirfd = -1;
789 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
790 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000791 return SQLITE_CANTOPEN;
792 }
drh66560ad2006-01-06 14:32:19 +0000793 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000794 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000795 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000796 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000797 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000798 return SQLITE_NOMEM;
799 }
drh9cbe6352005-11-29 03:13:21 +0000800 f.locktype = 0;
801 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
danielk1977261919c2005-12-06 12:52:59 +0000802
drh054889e2005-11-30 03:20:31 +0000803 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000804}
805
806/*
807** Attempt to open a file descriptor for the directory that contains a
808** file. This file descriptor can be used to fsync() the directory
809** in order to make sure the creation of a new file is actually written
810** to disk.
811**
812** This routine is only meaningful for Unix. It is a no-op under
813** windows since windows does not support hard links.
814**
drh9cbe6352005-11-29 03:13:21 +0000815** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000816** updated with the new directory file descriptor and SQLITE_OK is
817** returned.
818**
819** On failure, the function returns SQLITE_CANTOPEN and leaves
820** *id unchanged.
821*/
drh9c06c952005-11-26 00:25:00 +0000822static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000823 OsFile *id,
824 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000825){
drh054889e2005-11-30 03:20:31 +0000826 unixFile *pFile = (unixFile*)id;
827 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000828 /* Do not open the directory if the corresponding file is not already
829 ** open. */
830 return SQLITE_CANTOPEN;
831 }
drh054889e2005-11-30 03:20:31 +0000832 SET_THREADID(pFile);
833 assert( pFile->dirfd<0 );
834 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
835 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000836 return SQLITE_CANTOPEN;
837 }
drh054889e2005-11-30 03:20:31 +0000838 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000839 return SQLITE_OK;
840}
841
842/*
drhab3f9fe2004-08-14 17:10:10 +0000843** If the following global variable points to a string which is the
844** name of a directory, then that directory will be used to store
845** temporary files.
drhf1a221e2006-01-15 17:27:17 +0000846**
847** See also the "PRAGMA temp_store_directory" SQL command.
drhab3f9fe2004-08-14 17:10:10 +0000848*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000849char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000850
851/*
drhbbd42a62004-05-22 17:41:58 +0000852** Create a temporary file name in zBuf. zBuf must be big enough to
853** hold at least SQLITE_TEMPNAME_SIZE characters.
854*/
drh66560ad2006-01-06 14:32:19 +0000855int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000856 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000857 0,
drhbbd42a62004-05-22 17:41:58 +0000858 "/var/tmp",
859 "/usr/tmp",
860 "/tmp",
861 ".",
862 };
drh57196282004-10-06 15:41:16 +0000863 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000864 "abcdefghijklmnopqrstuvwxyz"
865 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
866 "0123456789";
867 int i, j;
868 struct stat buf;
869 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000870 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000871 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000872 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000873 if( stat(azDirs[i], &buf) ) continue;
874 if( !S_ISDIR(buf.st_mode) ) continue;
875 if( access(azDirs[i], 07) ) continue;
876 zDir = azDirs[i];
877 break;
878 }
879 do{
880 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
881 j = strlen(zBuf);
882 sqlite3Randomness(15, &zBuf[j]);
883 for(i=0; i<15; i++, j++){
884 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
885 }
886 zBuf[j] = 0;
887 }while( access(zBuf,0)==0 );
888 return SQLITE_OK;
889}
890
891/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000892** Check that a given pathname is a directory and is writable
893**
894*/
drh66560ad2006-01-06 14:32:19 +0000895int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000896#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000897 struct stat buf;
898 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000899 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000900 if( stat(zBuf, &buf) ) return 0;
901 if( !S_ISDIR(buf.st_mode) ) return 0;
902 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000903#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000904 return 1;
905}
906
907/*
drhbbd42a62004-05-22 17:41:58 +0000908** Read data from a file into a buffer. Return SQLITE_OK if all
909** bytes were read successfully and SQLITE_IOERR if anything goes
910** wrong.
911*/
drh9c06c952005-11-26 00:25:00 +0000912static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000913 int got;
drh9cbe6352005-11-29 03:13:21 +0000914 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000915 SimulateIOError(SQLITE_IOERR);
916 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000917 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000918 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000919 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
920 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000921 SEEK(0);
922 /* if( got<0 ) got = 0; */
923 if( got==amt ){
924 return SQLITE_OK;
925 }else{
926 return SQLITE_IOERR;
927 }
928}
929
930/*
931** Write data from a buffer into a file. Return SQLITE_OK on success
932** or some other error code on failure.
933*/
drh9c06c952005-11-26 00:25:00 +0000934static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000935 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000936 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000937 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000938 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000939 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000940 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000941 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000942 amt -= wrote;
943 pBuf = &((char*)pBuf)[wrote];
944 }
945 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000946 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
947 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000948 SEEK(0);
949 if( amt>0 ){
950 return SQLITE_FULL;
951 }
952 return SQLITE_OK;
953}
954
955/*
956** Move the read/write pointer in a file.
957*/
drh9c06c952005-11-26 00:25:00 +0000958static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000959 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000960 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000961#ifdef SQLITE_TEST
962 if( offset ) SimulateDiskfullError
963#endif
drh054889e2005-11-30 03:20:31 +0000964 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000965 return SQLITE_OK;
966}
967
drhb851b2c2005-03-10 14:11:12 +0000968#ifdef SQLITE_TEST
969/*
970** Count the number of fullsyncs and normal syncs. This is used to test
971** that syncs and fullsyncs are occuring at the right times.
972*/
973int sqlite3_sync_count = 0;
974int sqlite3_fullsync_count = 0;
975#endif
976
drhf2f23912005-10-05 10:29:36 +0000977/*
978** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
979** Otherwise use fsync() in its place.
980*/
981#ifndef HAVE_FDATASYNC
982# define fdatasync fsync
983#endif
984
drhb851b2c2005-03-10 14:11:12 +0000985
drhbbd42a62004-05-22 17:41:58 +0000986/*
drhdd809b02004-07-17 21:44:57 +0000987** The fsync() system call does not work as advertised on many
988** unix systems. The following procedure is an attempt to make
989** it work better.
drh1398ad32005-01-19 23:24:50 +0000990**
991** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
992** for testing when we want to run through the test suite quickly.
993** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
994** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
995** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000996*/
drheb796a72005-09-08 12:38:41 +0000997static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000998 int rc;
drhb851b2c2005-03-10 14:11:12 +0000999
1000 /* Record the number of times that we do a normal fsync() and
1001 ** FULLSYNC. This is used during testing to verify that this procedure
1002 ** gets called with the correct arguments.
1003 */
1004#ifdef SQLITE_TEST
1005 if( fullSync ) sqlite3_fullsync_count++;
1006 sqlite3_sync_count++;
1007#endif
1008
1009 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1010 ** no-op
1011 */
1012#ifdef SQLITE_NO_SYNC
1013 rc = SQLITE_OK;
1014#else
1015
drhdd809b02004-07-17 21:44:57 +00001016#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001017 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001018 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +00001019 }else{
1020 rc = 1;
1021 }
1022 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +00001023 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +00001024
drhc035e6e2005-09-22 15:45:04 +00001025#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +00001026 if( dataOnly ){
1027 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001028 }else{
drheb796a72005-09-08 12:38:41 +00001029 rc = fsync(fd);
1030 }
drhf30cc942005-03-11 17:52:34 +00001031#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +00001032#endif /* defined(SQLITE_NO_SYNC) */
1033
drhdd809b02004-07-17 21:44:57 +00001034 return rc;
1035}
1036
1037/*
drhbbd42a62004-05-22 17:41:58 +00001038** Make sure all writes to a particular file are committed to disk.
1039**
drheb796a72005-09-08 12:38:41 +00001040** If dataOnly==0 then both the file itself and its metadata (file
1041** size, access time, etc) are synced. If dataOnly!=0 then only the
1042** file data is synced.
1043**
drhbbd42a62004-05-22 17:41:58 +00001044** Under Unix, also make sure that the directory entry for the file
1045** has been created by fsync-ing the directory that contains the file.
1046** If we do not do this and we encounter a power failure, the directory
1047** entry for the journal might not exist after we reboot. The next
1048** SQLite to access the file will not know that the journal exists (because
1049** the directory entry for the journal was never created) and the transaction
1050** will not roll back - possibly leading to database corruption.
1051*/
drh9c06c952005-11-26 00:25:00 +00001052static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +00001053 unixFile *pFile = (unixFile*)id;
1054 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +00001055 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001056 TRACE2("SYNC %-3d\n", pFile->h);
1057 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +00001058 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001059 }
drh054889e2005-11-30 03:20:31 +00001060 if( pFile->dirfd>=0 ){
1061 TRACE2("DIRSYNC %-3d\n", pFile->dirfd);
danielk1977d7c03f72005-11-25 10:38:22 +00001062#ifndef SQLITE_DISABLE_DIRSYNC
drh054889e2005-11-30 03:20:31 +00001063 if( full_fsync(pFile->dirfd, pFile->fullSync, 0) ){
danielk19770964b232005-11-25 08:47:57 +00001064 return SQLITE_IOERR;
1065 }
danielk1977d7c03f72005-11-25 10:38:22 +00001066#endif
drh054889e2005-11-30 03:20:31 +00001067 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1068 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001069 }
drha2854222004-06-17 19:04:17 +00001070 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001071}
1072
1073/*
danielk1977962398d2004-06-14 09:35:16 +00001074** Sync the directory zDirname. This is a no-op on operating systems other
1075** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001076**
1077** This is used to make sure the master journal file has truely been deleted
1078** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001079** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001080*/
drh66560ad2006-01-06 14:32:19 +00001081int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001082#ifdef SQLITE_DISABLE_DIRSYNC
1083 return SQLITE_OK;
1084#else
danielk1977962398d2004-06-14 09:35:16 +00001085 int fd;
1086 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001087 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001088 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001089 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001090 if( fd<0 ){
1091 return SQLITE_CANTOPEN;
1092 }
1093 r = fsync(fd);
1094 close(fd);
1095 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001096#endif
danielk1977962398d2004-06-14 09:35:16 +00001097}
1098
1099/*
drhbbd42a62004-05-22 17:41:58 +00001100** Truncate an open file to a specified size
1101*/
drh9c06c952005-11-26 00:25:00 +00001102static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001103 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001104 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001105 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001106}
1107
1108/*
1109** Determine the current size of a file in bytes
1110*/
drh9c06c952005-11-26 00:25:00 +00001111static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001112 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001113 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001114 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001115 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001116 return SQLITE_IOERR;
1117 }
1118 *pSize = buf.st_size;
1119 return SQLITE_OK;
1120}
1121
danielk19779a1d0ab2004-06-01 14:09:28 +00001122/*
danielk197713adf8a2004-06-03 16:08:41 +00001123** This routine checks if there is a RESERVED lock held on the specified
1124** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001125** non-zero. If the file is unlocked or holds only SHARED locks, then
1126** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001127*/
drh9c06c952005-11-26 00:25:00 +00001128static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001129 int r = 0;
drh054889e2005-11-30 03:20:31 +00001130 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001131
drh054889e2005-11-30 03:20:31 +00001132 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001133 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001134
1135 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001136 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001137 r = 1;
1138 }
1139
drh2ac3ee92004-06-07 16:27:46 +00001140 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001141 */
1142 if( !r ){
1143 struct flock lock;
1144 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001145 lock.l_start = RESERVED_BYTE;
1146 lock.l_len = 1;
1147 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001148 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001149 if( lock.l_type!=F_UNLCK ){
1150 r = 1;
1151 }
1152 }
1153
drh66560ad2006-01-06 14:32:19 +00001154 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001155 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001156
1157 return r;
1158}
1159
1160/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001161** Lock the file with the lock specified by parameter locktype - one
1162** of the following:
1163**
drh2ac3ee92004-06-07 16:27:46 +00001164** (1) SHARED_LOCK
1165** (2) RESERVED_LOCK
1166** (3) PENDING_LOCK
1167** (4) EXCLUSIVE_LOCK
1168**
drhb3e04342004-06-08 00:47:47 +00001169** Sometimes when requesting one lock state, additional lock states
1170** are inserted in between. The locking might fail on one of the later
1171** transitions leaving the lock state different from what it started but
1172** still short of its goal. The following chart shows the allowed
1173** transitions and the inserted intermediate states:
1174**
1175** UNLOCKED -> SHARED
1176** SHARED -> RESERVED
1177** SHARED -> (PENDING) -> EXCLUSIVE
1178** RESERVED -> (PENDING) -> EXCLUSIVE
1179** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001180**
drha6abd042004-06-09 17:37:22 +00001181** This routine will only increase a lock. Use the sqlite3OsUnlock()
1182** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001183*/
drh9c06c952005-11-26 00:25:00 +00001184static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001185 /* The following describes the implementation of the various locks and
1186 ** lock transitions in terms of the POSIX advisory shared and exclusive
1187 ** lock primitives (called read-locks and write-locks below, to avoid
1188 ** confusion with SQLite lock names). The algorithms are complicated
1189 ** slightly in order to be compatible with windows systems simultaneously
1190 ** accessing the same database file, in case that is ever required.
1191 **
1192 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1193 ** byte', each single bytes at well known offsets, and the 'shared byte
1194 ** range', a range of 510 bytes at a well known offset.
1195 **
1196 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1197 ** byte'. If this is successful, a random byte from the 'shared byte
1198 ** range' is read-locked and the lock on the 'pending byte' released.
1199 **
danielk197790ba3bd2004-06-25 08:32:25 +00001200 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1201 ** A RESERVED lock is implemented by grabbing a write-lock on the
1202 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001203 **
1204 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001205 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1206 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1207 ** obtained, but existing SHARED locks are allowed to persist. A process
1208 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1209 ** This property is used by the algorithm for rolling back a journal file
1210 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001211 **
danielk197790ba3bd2004-06-25 08:32:25 +00001212 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1213 ** implemented by obtaining a write-lock on the entire 'shared byte
1214 ** range'. Since all other locks require a read-lock on one of the bytes
1215 ** within this range, this ensures that no other locks are held on the
1216 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001217 **
1218 ** The reason a single byte cannot be used instead of the 'shared byte
1219 ** range' is that some versions of windows do not support read-locks. By
1220 ** locking a random byte from a range, concurrent SHARED locks may exist
1221 ** even if the locking primitive used is always a write-lock.
1222 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001224 unixFile *pFile = (unixFile*)id;
1225 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001226 struct flock lock;
1227 int s;
1228
drh054889e2005-11-30 03:20:31 +00001229 assert( pFile );
1230 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1231 locktypeName(locktype), locktypeName(pFile->locktype),
1232 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001233
1234 /* If there is already a lock of this type or more restrictive on the
1235 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001236 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001237 */
drh054889e2005-11-30 03:20:31 +00001238 if( pFile->locktype>=locktype ){
1239 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1240 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001241 return SQLITE_OK;
1242 }
1243
drhb3e04342004-06-08 00:47:47 +00001244 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001245 */
drh054889e2005-11-30 03:20:31 +00001246 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001247 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001248 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001249
drh054889e2005-11-30 03:20:31 +00001250 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001251 */
drh66560ad2006-01-06 14:32:19 +00001252 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001253
drh029b44b2006-01-15 00:13:15 +00001254 /* Make sure the current thread owns the pFile.
1255 */
1256 rc = transferOwnership(pFile);
1257 if( rc!=SQLITE_OK ){
1258 sqlite3OsLeaveMutex();
1259 return rc;
1260 }
drh64b1bea2006-01-15 02:30:57 +00001261 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001262
danielk19779a1d0ab2004-06-01 14:09:28 +00001263 /* If some thread using this PID has a lock via a different OsFile*
1264 ** handle that precludes the requested lock, return BUSY.
1265 */
drh054889e2005-11-30 03:20:31 +00001266 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001267 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001268 ){
1269 rc = SQLITE_BUSY;
1270 goto end_lock;
1271 }
1272
1273 /* If a SHARED lock is requested, and some thread using this PID already
1274 ** has a SHARED or RESERVED lock, then increment reference counts and
1275 ** return SQLITE_OK.
1276 */
1277 if( locktype==SHARED_LOCK &&
1278 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1279 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001280 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001281 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001282 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001283 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001284 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001285 goto end_lock;
1286 }
1287
danielk197713adf8a2004-06-03 16:08:41 +00001288 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001289
danielk19779a1d0ab2004-06-01 14:09:28 +00001290 lock.l_whence = SEEK_SET;
1291
drh3cde3bb2004-06-12 02:17:14 +00001292 /* A PENDING lock is needed before acquiring a SHARED lock and before
1293 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1294 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001295 */
drh3cde3bb2004-06-12 02:17:14 +00001296 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001297 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001298 ){
danielk1977489468c2004-06-28 08:25:47 +00001299 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001300 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001301 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001302 if( s ){
1303 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1304 goto end_lock;
1305 }
drh3cde3bb2004-06-12 02:17:14 +00001306 }
1307
1308
1309 /* If control gets to this point, then actually go ahead and make
1310 ** operating system calls for the specified lock.
1311 */
1312 if( locktype==SHARED_LOCK ){
1313 assert( pLock->cnt==0 );
1314 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001315
drh2ac3ee92004-06-07 16:27:46 +00001316 /* Now get the read-lock */
1317 lock.l_start = SHARED_FIRST;
1318 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001319 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001320
1321 /* Drop the temporary PENDING lock */
1322 lock.l_start = PENDING_BYTE;
1323 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001324 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001325 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001326 rc = SQLITE_IOERR; /* This should never happen */
1327 goto end_lock;
1328 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001329 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001330 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1331 }else{
drh054889e2005-11-30 03:20:31 +00001332 pFile->locktype = SHARED_LOCK;
1333 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001334 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001335 }
drh3cde3bb2004-06-12 02:17:14 +00001336 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1337 /* We are trying for an exclusive lock but another thread in this
1338 ** same process is still holding a shared lock. */
1339 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001340 }else{
drh3cde3bb2004-06-12 02:17:14 +00001341 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001342 ** assumed that there is a SHARED or greater lock on the file
1343 ** already.
1344 */
drh054889e2005-11-30 03:20:31 +00001345 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001346 lock.l_type = F_WRLCK;
1347 switch( locktype ){
1348 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001349 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001351 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001352 lock.l_start = SHARED_FIRST;
1353 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001354 break;
1355 default:
1356 assert(0);
1357 }
drh054889e2005-11-30 03:20:31 +00001358 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001359 if( s ){
1360 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1361 }
drhbbd42a62004-05-22 17:41:58 +00001362 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001363
danielk1977ecb2a962004-06-02 06:30:16 +00001364 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001365 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001366 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001367 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001368 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001369 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001370 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001371
1372end_lock:
drh66560ad2006-01-06 14:32:19 +00001373 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001374 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001375 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001376 return rc;
1377}
1378
1379/*
drh054889e2005-11-30 03:20:31 +00001380** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001381** must be either NO_LOCK or SHARED_LOCK.
1382**
1383** If the locking level of the file descriptor is already at or below
1384** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001385*/
drh9c06c952005-11-26 00:25:00 +00001386static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001387 struct lockInfo *pLock;
1388 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001389 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001390 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001391
drh054889e2005-11-30 03:20:31 +00001392 assert( pFile );
1393 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1394 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001395
1396 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001397 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001398 return SQLITE_OK;
1399 }
drhf1a221e2006-01-15 17:27:17 +00001400 if( CHECK_THREADID(pFile) ){
1401 return SQLITE_MISUSE;
1402 }
drh66560ad2006-01-06 14:32:19 +00001403 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001404 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001405 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001406 if( pFile->locktype>SHARED_LOCK ){
1407 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001408 if( locktype==SHARED_LOCK ){
1409 lock.l_type = F_RDLCK;
1410 lock.l_whence = SEEK_SET;
1411 lock.l_start = SHARED_FIRST;
1412 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001413 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001414 /* This should never happen */
1415 rc = SQLITE_IOERR;
1416 }
1417 }
drhbbd42a62004-05-22 17:41:58 +00001418 lock.l_type = F_UNLCK;
1419 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001420 lock.l_start = PENDING_BYTE;
1421 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001422 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001423 pLock->locktype = SHARED_LOCK;
1424 }else{
1425 rc = SQLITE_IOERR; /* This should never happen */
1426 }
drhbbd42a62004-05-22 17:41:58 +00001427 }
drha6abd042004-06-09 17:37:22 +00001428 if( locktype==NO_LOCK ){
1429 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001430
drha6abd042004-06-09 17:37:22 +00001431 /* Decrement the shared lock counter. Release the lock using an
1432 ** OS call only when all threads in this same process have released
1433 ** the lock.
1434 */
1435 pLock->cnt--;
1436 if( pLock->cnt==0 ){
1437 lock.l_type = F_UNLCK;
1438 lock.l_whence = SEEK_SET;
1439 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001440 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001441 pLock->locktype = NO_LOCK;
1442 }else{
1443 rc = SQLITE_IOERR; /* This should never happen */
1444 }
drha6abd042004-06-09 17:37:22 +00001445 }
1446
drhbbd42a62004-05-22 17:41:58 +00001447 /* Decrement the count of locks against this same file. When the
1448 ** count reaches zero, close any other file descriptors whose close
1449 ** was deferred because of outstanding locks.
1450 */
drh054889e2005-11-30 03:20:31 +00001451 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001452 pOpen->nLock--;
1453 assert( pOpen->nLock>=0 );
1454 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1455 int i;
1456 for(i=0; i<pOpen->nPending; i++){
1457 close(pOpen->aPending[i]);
1458 }
drh64b1bea2006-01-15 02:30:57 +00001459 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001460 pOpen->nPending = 0;
1461 pOpen->aPending = 0;
1462 }
1463 }
drh66560ad2006-01-06 14:32:19 +00001464 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001465 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001466 return rc;
drhbbd42a62004-05-22 17:41:58 +00001467}
1468
1469/*
danielk1977e3026632004-06-22 11:29:02 +00001470** Close a file.
1471*/
drh9cbe6352005-11-29 03:13:21 +00001472static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001473 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001474
drh9cbe6352005-11-29 03:13:21 +00001475 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001476 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001477 if( id->dirfd>=0 ) close(id->dirfd);
1478 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001479 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001480
drh38322302006-01-15 02:43:16 +00001481 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001482 /* If there are outstanding locks, do not actually close the file just
1483 ** yet because that would clear those locks. Instead, add the file
1484 ** descriptor to pOpen->aPending. It will be automatically closed when
1485 ** the last lock is cleared.
1486 */
1487 int *aNew;
1488 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001489 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001490 if( aNew==0 ){
1491 /* If a malloc fails, just leak the file descriptor */
1492 }else{
1493 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001494 pOpen->aPending[pOpen->nPending] = id->h;
1495 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001496 }
1497 }else{
1498 /* There are no outstanding locks so we can close the file immediately */
1499 close(id->h);
1500 }
1501 releaseLockInfo(id->pLock);
1502 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001503
drh66560ad2006-01-06 14:32:19 +00001504 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001505 id->isOpen = 0;
1506 TRACE2("CLOSE %-3d\n", id->h);
1507 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001508 sqliteFree(id);
1509 *pId = 0;
drh02afc862006-01-20 18:10:57 +00001510 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001511}
1512
1513/*
drh0ccebe72005-06-07 22:22:50 +00001514** Turn a relative pathname into a full pathname. Return a pointer
1515** to the full pathname stored in space obtained from sqliteMalloc().
1516** The calling function is responsible for freeing this space once it
1517** is no longer needed.
1518*/
drh66560ad2006-01-06 14:32:19 +00001519char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001520 char *zFull = 0;
1521 if( zRelative[0]=='/' ){
1522 sqlite3SetString(&zFull, zRelative, (char*)0);
1523 }else{
drh79158e12005-09-06 21:40:45 +00001524 char *zBuf = sqliteMalloc(5000);
1525 if( zBuf==0 ){
1526 return 0;
1527 }
drh0ccebe72005-06-07 22:22:50 +00001528 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001529 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001530 (char*)0);
drh79158e12005-09-06 21:40:45 +00001531 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001532 }
1533 return zFull;
1534}
1535
drh18839212005-11-26 03:43:23 +00001536/*
drh9cbe6352005-11-29 03:13:21 +00001537** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001538*/
drh9cbe6352005-11-29 03:13:21 +00001539static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001540 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001541}
1542
1543/*
1544** Return the underlying file handle for an OsFile
1545*/
1546static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001547 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001548}
1549
1550/*
1551** Return an integer that indices the type of lock currently held
1552** by this handle. (Used for testing and analysis only.)
1553*/
1554static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001555 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001556}
drh0ccebe72005-06-07 22:22:50 +00001557
drh9c06c952005-11-26 00:25:00 +00001558/*
drh054889e2005-11-30 03:20:31 +00001559** This vector defines all the methods that can operate on an OsFile
1560** for unix.
drh9c06c952005-11-26 00:25:00 +00001561*/
drh054889e2005-11-30 03:20:31 +00001562static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001563 unixClose,
drh054889e2005-11-30 03:20:31 +00001564 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001565 unixRead,
1566 unixWrite,
1567 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001568 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001569 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001570 unixSetFullSync,
1571 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001572 unixFileSize,
1573 unixLock,
1574 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001575 unixLockState,
drh054889e2005-11-30 03:20:31 +00001576 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001577};
1578
drh054889e2005-11-30 03:20:31 +00001579/*
1580** Allocate memory for a unixFile. Initialize the new unixFile
1581** to the value given in pInit and return a pointer to the new
1582** OsFile. If we run out of memory, close the file and return NULL.
1583*/
1584static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1585 unixFile *pNew;
1586 pNew = sqliteMalloc( sizeof(unixFile) );
1587 if( pNew==0 ){
1588 close(pInit->h);
drh029b44b2006-01-15 00:13:15 +00001589 sqlite3OsEnterMutex();
danielk19772e588c72005-12-09 14:25:08 +00001590 releaseLockInfo(pInit->pLock);
1591 releaseOpenCnt(pInit->pOpen);
drh029b44b2006-01-15 00:13:15 +00001592 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001593 *pId = 0;
1594 return SQLITE_NOMEM;
1595 }else{
1596 *pNew = *pInit;
1597 pNew->pMethod = &sqlite3UnixIoMethod;
1598 *pId = (OsFile*)pNew;
1599 OpenCounter(+1);
1600 return SQLITE_OK;
1601 }
1602}
1603
drh9c06c952005-11-26 00:25:00 +00001604
drh0ccebe72005-06-07 22:22:50 +00001605#endif /* SQLITE_OMIT_DISKIO */
1606/***************************************************************************
1607** Everything above deals with file I/O. Everything that follows deals
1608** with other miscellanous aspects of the operating system interface
1609****************************************************************************/
1610
1611
1612/*
drhbbd42a62004-05-22 17:41:58 +00001613** Get information to seed the random number generator. The seed
1614** is written into the buffer zBuf[256]. The calling function must
1615** supply a sufficiently large buffer.
1616*/
drh66560ad2006-01-06 14:32:19 +00001617int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001618 /* We have to initialize zBuf to prevent valgrind from reporting
1619 ** errors. The reports issued by valgrind are incorrect - we would
1620 ** prefer that the randomness be increased by making use of the
1621 ** uninitialized space in zBuf - but valgrind errors tend to worry
1622 ** some users. Rather than argue, it seems easier just to initialize
1623 ** the whole array and silence valgrind, even if that means less randomness
1624 ** in the random seed.
1625 **
1626 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00001627 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00001628 ** tests repeatable.
1629 */
1630 memset(zBuf, 0, 256);
1631#if !defined(SQLITE_TEST)
1632 {
drh842b8642005-01-21 17:53:17 +00001633 int pid, fd;
1634 fd = open("/dev/urandom", O_RDONLY);
1635 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001636 time_t t;
1637 time(&t);
1638 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001639 pid = getpid();
1640 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1641 }else{
1642 read(fd, zBuf, 256);
1643 close(fd);
1644 }
drhbbd42a62004-05-22 17:41:58 +00001645 }
1646#endif
1647 return SQLITE_OK;
1648}
1649
1650/*
1651** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00001652** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00001653*/
drh66560ad2006-01-06 14:32:19 +00001654int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001655#if defined(HAVE_USLEEP) && HAVE_USLEEP
1656 usleep(ms*1000);
1657 return ms;
1658#else
1659 sleep((ms+999)/1000);
1660 return 1000*((ms+999)/1000);
1661#endif
1662}
1663
1664/*
1665** Static variables used for thread synchronization
1666*/
1667static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001668#ifdef SQLITE_UNIX_THREADS
drha3fad6f2006-01-18 14:06:37 +00001669static pthread_t mutexOwner;
1670static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
1671static pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001672#endif
drhbbd42a62004-05-22 17:41:58 +00001673
1674/*
1675** The following pair of routine implement mutual exclusion for
1676** multi-threaded processes. Only a single thread is allowed to
1677** executed code that is surrounded by EnterMutex() and LeaveMutex().
1678**
1679** SQLite uses only a single Mutex. There is not much critical
1680** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00001681**
drh757b04e2006-01-18 17:25:45 +00001682** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00001683*/
drh66560ad2006-01-06 14:32:19 +00001684void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001685#ifdef SQLITE_UNIX_THREADS
drha3fad6f2006-01-18 14:06:37 +00001686 pthread_mutex_lock(&mutex1);
1687 if( inMutex==0 ){
1688 pthread_mutex_lock(&mutex2);
1689 mutexOwner = pthread_self();
1690 }
1691 pthread_mutex_unlock(&mutex1);
drhbbd42a62004-05-22 17:41:58 +00001692#endif
drha3fad6f2006-01-18 14:06:37 +00001693 inMutex++;
drhbbd42a62004-05-22 17:41:58 +00001694}
drh66560ad2006-01-06 14:32:19 +00001695void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00001696 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00001697#ifdef SQLITE_UNIX_THREADS
drha3fad6f2006-01-18 14:06:37 +00001698 assert( pthread_equal(mutexOwner, pthread_self()) );
1699 pthread_mutex_lock(&mutex1);
1700 inMutex--;
1701 if( inMutex==0 ){
1702 pthread_mutex_unlock(&mutex2);
1703 }
1704 pthread_mutex_unlock(&mutex1);
1705#else
1706 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00001707#endif
1708}
1709
1710/*
drh757b04e2006-01-18 17:25:45 +00001711** Return TRUE if the mutex is currently held.
1712**
1713** If the thisThreadOnly parameter is true, return true only if the
1714** calling thread holds the mutex. If the parameter is false, return
1715** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00001716*/
drh757b04e2006-01-18 17:25:45 +00001717int sqlite3UnixInMutex(int thisThreadOnly){
drha3fad6f2006-01-18 14:06:37 +00001718#ifdef SQLITE_UNIX_THREADS
drh757b04e2006-01-18 17:25:45 +00001719 return inMutex>0 &&
1720 (thisThreadOnly==0 || pthread_equal(mutexOwner, pthread_self()));
drha3fad6f2006-01-18 14:06:37 +00001721#else
drh757b04e2006-01-18 17:25:45 +00001722 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00001723#endif
drh88f474a2006-01-02 20:00:12 +00001724}
1725
1726/*
drhb4bc7052006-01-11 23:40:33 +00001727** Remember the number of thread-specific-data blocks allocated.
1728** Use this to verify that we are not leaking thread-specific-data.
1729** Ticket #1601
1730*/
1731#ifdef SQLITE_TEST
1732int sqlite3_tsd_count = 0;
1733# ifdef SQLITE_UNIX_THREADS
1734 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
1735# define TSD_COUNTER(N) \
1736 pthread_mutex_lock(&tsd_counter_mutex); \
1737 sqlite3_tsd_count += N; \
1738 pthread_mutex_unlock(&tsd_counter_mutex);
1739# else
1740# define TSD_COUNTER(N) sqlite3_tsd_count += N
1741# endif
1742#else
1743# define TSD_COUNTER(N) /* no-op */
1744#endif
1745
drhb4bc7052006-01-11 23:40:33 +00001746/*
drhf1a221e2006-01-15 17:27:17 +00001747** If called with allocateFlag>0, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00001748** specific data for the current thread. Allocate and zero the
drhf1a221e2006-01-15 17:27:17 +00001749** thread-specific data if it does not already exist.
danielk197713a68c32005-12-15 10:11:30 +00001750**
drh6f7adc82006-01-11 21:41:20 +00001751** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00001752** specific data. Return it if it exists. If it does not exist,
1753** then return NULL.
1754**
1755** If called with allocateFlag<0, check to see if the thread specific
1756** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00001757** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00001758** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00001759*/
drh6f7adc82006-01-11 21:41:20 +00001760ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
1761 static const ThreadData zeroData;
danielk197713a68c32005-12-15 10:11:30 +00001762#ifdef SQLITE_UNIX_THREADS
1763 static pthread_key_t key;
1764 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001765 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001766
1767 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001768 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001769 if( !keyInit ){
1770 int rc;
drh6f7adc82006-01-11 21:41:20 +00001771 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001772 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001773 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001774 return 0;
1775 }
1776 keyInit = 1;
1777 }
drh66560ad2006-01-06 14:32:19 +00001778 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001779 }
1780
drh3fbb0b12006-01-06 00:36:00 +00001781 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00001782 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001783 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001784 if( !sqlite3TestMallocFail() ){
1785 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1786 }
1787#ifdef SQLITE_MEMDEBUG
1788 sqlite3_isFail = 0;
1789#endif
drh6f7adc82006-01-11 21:41:20 +00001790 if( pTsd ){
1791 *pTsd = zeroData;
1792 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00001793 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001794 }
danielk197713a68c32005-12-15 10:11:30 +00001795 }
drh70ff98a2006-01-12 01:25:18 +00001796 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001797 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001798 sqlite3OsFree(pTsd);
1799 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00001800 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001801 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001802 }
1803 return pTsd;
1804#else
drh6f7adc82006-01-11 21:41:20 +00001805 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00001806 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001807 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001808 if( !sqlite3TestMallocFail() ){
1809 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1810 }
1811#ifdef SQLITE_MEMDEBUG
1812 sqlite3_isFail = 0;
1813#endif
drh6f7adc82006-01-11 21:41:20 +00001814 if( pTsd ){
1815 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00001816 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001817 }
drh3fbb0b12006-01-06 00:36:00 +00001818 }
drh70ff98a2006-01-12 01:25:18 +00001819 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001820 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001821 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00001822 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001823 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001824 }
drh3fbb0b12006-01-06 00:36:00 +00001825 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001826#endif
1827}
1828
1829/*
drhbbd42a62004-05-22 17:41:58 +00001830** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001831** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001832*/
1833#ifdef SQLITE_TEST
1834int sqlite3_current_time = 0;
1835#endif
1836
1837/*
1838** Find the current time (in Universal Coordinated Time). Write the
1839** current time and date as a Julian Day number into *prNow and
1840** return 0. Return 1 if the time and date cannot be found.
1841*/
drh66560ad2006-01-06 14:32:19 +00001842int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001843#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001844 time_t t;
1845 time(&t);
1846 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001847#else
1848 struct timeval sNow;
1849 struct timezone sTz; /* Not used */
1850 gettimeofday(&sNow, &sTz);
1851 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1852#endif
drhbbd42a62004-05-22 17:41:58 +00001853#ifdef SQLITE_TEST
1854 if( sqlite3_current_time ){
1855 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1856 }
1857#endif
1858 return 0;
1859}
1860
drhbbd42a62004-05-22 17:41:58 +00001861#endif /* OS_UNIX */