blob: e33f0f7c525476bcad3537f07e20d36629353641 [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
drhb851b2c2005-03-10 14:11:12 +0000984
drhbbd42a62004-05-22 17:41:58 +0000985/*
drhdd809b02004-07-17 21:44:57 +0000986** The fsync() system call does not work as advertised on many
987** unix systems. The following procedure is an attempt to make
988** it work better.
drh1398ad32005-01-19 23:24:50 +0000989**
990** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
991** for testing when we want to run through the test suite quickly.
992** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
993** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
994** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000995*/
drheb796a72005-09-08 12:38:41 +0000996static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000997 int rc;
drhb851b2c2005-03-10 14:11:12 +0000998
999 /* Record the number of times that we do a normal fsync() and
1000 ** FULLSYNC. This is used during testing to verify that this procedure
1001 ** gets called with the correct arguments.
1002 */
1003#ifdef SQLITE_TEST
1004 if( fullSync ) sqlite3_fullsync_count++;
1005 sqlite3_sync_count++;
1006#endif
1007
1008 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1009 ** no-op
1010 */
1011#ifdef SQLITE_NO_SYNC
1012 rc = SQLITE_OK;
1013#else
1014
drhdd809b02004-07-17 21:44:57 +00001015#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001016 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001017 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +00001018 }else{
1019 rc = 1;
1020 }
1021 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +00001022 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +00001023
drhc035e6e2005-09-22 15:45:04 +00001024#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +00001025 if( dataOnly ){
1026 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001027 }else{
drheb796a72005-09-08 12:38:41 +00001028 rc = fsync(fd);
1029 }
drhf30cc942005-03-11 17:52:34 +00001030#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +00001031#endif /* defined(SQLITE_NO_SYNC) */
1032
drhdd809b02004-07-17 21:44:57 +00001033 return rc;
1034}
1035
1036/*
drhbbd42a62004-05-22 17:41:58 +00001037** Make sure all writes to a particular file are committed to disk.
1038**
drheb796a72005-09-08 12:38:41 +00001039** If dataOnly==0 then both the file itself and its metadata (file
1040** size, access time, etc) are synced. If dataOnly!=0 then only the
1041** file data is synced.
1042**
drhbbd42a62004-05-22 17:41:58 +00001043** Under Unix, also make sure that the directory entry for the file
1044** has been created by fsync-ing the directory that contains the file.
1045** If we do not do this and we encounter a power failure, the directory
1046** entry for the journal might not exist after we reboot. The next
1047** SQLite to access the file will not know that the journal exists (because
1048** the directory entry for the journal was never created) and the transaction
1049** will not roll back - possibly leading to database corruption.
1050*/
drh9c06c952005-11-26 00:25:00 +00001051static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +00001052 unixFile *pFile = (unixFile*)id;
1053 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +00001054 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001055 TRACE2("SYNC %-3d\n", pFile->h);
1056 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +00001057 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001058 }
drh054889e2005-11-30 03:20:31 +00001059 if( pFile->dirfd>=0 ){
1060 TRACE2("DIRSYNC %-3d\n", pFile->dirfd);
danielk1977d7c03f72005-11-25 10:38:22 +00001061#ifndef SQLITE_DISABLE_DIRSYNC
drh054889e2005-11-30 03:20:31 +00001062 if( full_fsync(pFile->dirfd, pFile->fullSync, 0) ){
drh86631a52006-02-09 23:05:51 +00001063 /* We have received multiple reports of fsync() returning
1064 ** errors when applied to directories on certain file systems.
1065 ** A failed directory sync is not a big deal. So it seems
1066 ** better to ignore the error. Ticket #1657
1067 */
1068 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001069 }
danielk1977d7c03f72005-11-25 10:38:22 +00001070#endif
drh054889e2005-11-30 03:20:31 +00001071 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1072 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001073 }
drha2854222004-06-17 19:04:17 +00001074 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001075}
1076
1077/*
danielk1977962398d2004-06-14 09:35:16 +00001078** Sync the directory zDirname. This is a no-op on operating systems other
1079** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001080**
1081** This is used to make sure the master journal file has truely been deleted
1082** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001083** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001084*/
drh66560ad2006-01-06 14:32:19 +00001085int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001086#ifdef SQLITE_DISABLE_DIRSYNC
1087 return SQLITE_OK;
1088#else
danielk1977962398d2004-06-14 09:35:16 +00001089 int fd;
1090 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001091 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001092 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001093 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001094 if( fd<0 ){
1095 return SQLITE_CANTOPEN;
1096 }
1097 r = fsync(fd);
1098 close(fd);
1099 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001100#endif
danielk1977962398d2004-06-14 09:35:16 +00001101}
1102
1103/*
drhbbd42a62004-05-22 17:41:58 +00001104** Truncate an open file to a specified size
1105*/
drh9c06c952005-11-26 00:25:00 +00001106static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001107 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001108 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001109 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001110}
1111
1112/*
1113** Determine the current size of a file in bytes
1114*/
drh9c06c952005-11-26 00:25:00 +00001115static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001116 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001117 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001118 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001119 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001120 return SQLITE_IOERR;
1121 }
1122 *pSize = buf.st_size;
1123 return SQLITE_OK;
1124}
1125
danielk19779a1d0ab2004-06-01 14:09:28 +00001126/*
danielk197713adf8a2004-06-03 16:08:41 +00001127** This routine checks if there is a RESERVED lock held on the specified
1128** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001129** non-zero. If the file is unlocked or holds only SHARED locks, then
1130** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001131*/
drh9c06c952005-11-26 00:25:00 +00001132static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001133 int r = 0;
drh054889e2005-11-30 03:20:31 +00001134 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001135
drh054889e2005-11-30 03:20:31 +00001136 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001137 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001138
1139 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001140 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001141 r = 1;
1142 }
1143
drh2ac3ee92004-06-07 16:27:46 +00001144 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001145 */
1146 if( !r ){
1147 struct flock lock;
1148 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001149 lock.l_start = RESERVED_BYTE;
1150 lock.l_len = 1;
1151 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001152 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001153 if( lock.l_type!=F_UNLCK ){
1154 r = 1;
1155 }
1156 }
1157
drh66560ad2006-01-06 14:32:19 +00001158 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001159 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001160
1161 return r;
1162}
1163
1164/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001165** Lock the file with the lock specified by parameter locktype - one
1166** of the following:
1167**
drh2ac3ee92004-06-07 16:27:46 +00001168** (1) SHARED_LOCK
1169** (2) RESERVED_LOCK
1170** (3) PENDING_LOCK
1171** (4) EXCLUSIVE_LOCK
1172**
drhb3e04342004-06-08 00:47:47 +00001173** Sometimes when requesting one lock state, additional lock states
1174** are inserted in between. The locking might fail on one of the later
1175** transitions leaving the lock state different from what it started but
1176** still short of its goal. The following chart shows the allowed
1177** transitions and the inserted intermediate states:
1178**
1179** UNLOCKED -> SHARED
1180** SHARED -> RESERVED
1181** SHARED -> (PENDING) -> EXCLUSIVE
1182** RESERVED -> (PENDING) -> EXCLUSIVE
1183** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001184**
drha6abd042004-06-09 17:37:22 +00001185** This routine will only increase a lock. Use the sqlite3OsUnlock()
1186** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001187*/
drh9c06c952005-11-26 00:25:00 +00001188static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001189 /* The following describes the implementation of the various locks and
1190 ** lock transitions in terms of the POSIX advisory shared and exclusive
1191 ** lock primitives (called read-locks and write-locks below, to avoid
1192 ** confusion with SQLite lock names). The algorithms are complicated
1193 ** slightly in order to be compatible with windows systems simultaneously
1194 ** accessing the same database file, in case that is ever required.
1195 **
1196 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1197 ** byte', each single bytes at well known offsets, and the 'shared byte
1198 ** range', a range of 510 bytes at a well known offset.
1199 **
1200 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1201 ** byte'. If this is successful, a random byte from the 'shared byte
1202 ** range' is read-locked and the lock on the 'pending byte' released.
1203 **
danielk197790ba3bd2004-06-25 08:32:25 +00001204 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1205 ** A RESERVED lock is implemented by grabbing a write-lock on the
1206 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001207 **
1208 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001209 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1210 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1211 ** obtained, but existing SHARED locks are allowed to persist. A process
1212 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1213 ** This property is used by the algorithm for rolling back a journal file
1214 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001215 **
danielk197790ba3bd2004-06-25 08:32:25 +00001216 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1217 ** implemented by obtaining a write-lock on the entire 'shared byte
1218 ** range'. Since all other locks require a read-lock on one of the bytes
1219 ** within this range, this ensures that no other locks are held on the
1220 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001221 **
1222 ** The reason a single byte cannot be used instead of the 'shared byte
1223 ** range' is that some versions of windows do not support read-locks. By
1224 ** locking a random byte from a range, concurrent SHARED locks may exist
1225 ** even if the locking primitive used is always a write-lock.
1226 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001227 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001228 unixFile *pFile = (unixFile*)id;
1229 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001230 struct flock lock;
1231 int s;
1232
drh054889e2005-11-30 03:20:31 +00001233 assert( pFile );
1234 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1235 locktypeName(locktype), locktypeName(pFile->locktype),
1236 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001237
1238 /* If there is already a lock of this type or more restrictive on the
1239 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001240 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001241 */
drh054889e2005-11-30 03:20:31 +00001242 if( pFile->locktype>=locktype ){
1243 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1244 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001245 return SQLITE_OK;
1246 }
1247
drhb3e04342004-06-08 00:47:47 +00001248 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001249 */
drh054889e2005-11-30 03:20:31 +00001250 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001251 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001252 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001253
drh054889e2005-11-30 03:20:31 +00001254 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001255 */
drh66560ad2006-01-06 14:32:19 +00001256 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001257
drh029b44b2006-01-15 00:13:15 +00001258 /* Make sure the current thread owns the pFile.
1259 */
1260 rc = transferOwnership(pFile);
1261 if( rc!=SQLITE_OK ){
1262 sqlite3OsLeaveMutex();
1263 return rc;
1264 }
drh64b1bea2006-01-15 02:30:57 +00001265 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001266
danielk19779a1d0ab2004-06-01 14:09:28 +00001267 /* If some thread using this PID has a lock via a different OsFile*
1268 ** handle that precludes the requested lock, return BUSY.
1269 */
drh054889e2005-11-30 03:20:31 +00001270 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001271 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001272 ){
1273 rc = SQLITE_BUSY;
1274 goto end_lock;
1275 }
1276
1277 /* If a SHARED lock is requested, and some thread using this PID already
1278 ** has a SHARED or RESERVED lock, then increment reference counts and
1279 ** return SQLITE_OK.
1280 */
1281 if( locktype==SHARED_LOCK &&
1282 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1283 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001284 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001285 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001286 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001287 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001288 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001289 goto end_lock;
1290 }
1291
danielk197713adf8a2004-06-03 16:08:41 +00001292 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001293
danielk19779a1d0ab2004-06-01 14:09:28 +00001294 lock.l_whence = SEEK_SET;
1295
drh3cde3bb2004-06-12 02:17:14 +00001296 /* A PENDING lock is needed before acquiring a SHARED lock and before
1297 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1298 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001299 */
drh3cde3bb2004-06-12 02:17:14 +00001300 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001301 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001302 ){
danielk1977489468c2004-06-28 08:25:47 +00001303 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001304 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001305 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001306 if( s ){
1307 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1308 goto end_lock;
1309 }
drh3cde3bb2004-06-12 02:17:14 +00001310 }
1311
1312
1313 /* If control gets to this point, then actually go ahead and make
1314 ** operating system calls for the specified lock.
1315 */
1316 if( locktype==SHARED_LOCK ){
1317 assert( pLock->cnt==0 );
1318 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001319
drh2ac3ee92004-06-07 16:27:46 +00001320 /* Now get the read-lock */
1321 lock.l_start = SHARED_FIRST;
1322 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001323 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001324
1325 /* Drop the temporary PENDING lock */
1326 lock.l_start = PENDING_BYTE;
1327 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001328 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001329 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001330 rc = SQLITE_IOERR; /* This should never happen */
1331 goto end_lock;
1332 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001333 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001334 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1335 }else{
drh054889e2005-11-30 03:20:31 +00001336 pFile->locktype = SHARED_LOCK;
1337 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001338 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001339 }
drh3cde3bb2004-06-12 02:17:14 +00001340 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1341 /* We are trying for an exclusive lock but another thread in this
1342 ** same process is still holding a shared lock. */
1343 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001344 }else{
drh3cde3bb2004-06-12 02:17:14 +00001345 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001346 ** assumed that there is a SHARED or greater lock on the file
1347 ** already.
1348 */
drh054889e2005-11-30 03:20:31 +00001349 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 lock.l_type = F_WRLCK;
1351 switch( locktype ){
1352 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001353 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001354 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001355 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001356 lock.l_start = SHARED_FIRST;
1357 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001358 break;
1359 default:
1360 assert(0);
1361 }
drh054889e2005-11-30 03:20:31 +00001362 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001363 if( s ){
1364 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1365 }
drhbbd42a62004-05-22 17:41:58 +00001366 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001367
danielk1977ecb2a962004-06-02 06:30:16 +00001368 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001369 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001370 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001371 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001372 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001373 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001374 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001375
1376end_lock:
drh66560ad2006-01-06 14:32:19 +00001377 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001378 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001379 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001380 return rc;
1381}
1382
1383/*
drh054889e2005-11-30 03:20:31 +00001384** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001385** must be either NO_LOCK or SHARED_LOCK.
1386**
1387** If the locking level of the file descriptor is already at or below
1388** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001389*/
drh9c06c952005-11-26 00:25:00 +00001390static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001391 struct lockInfo *pLock;
1392 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001393 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001394 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001395
drh054889e2005-11-30 03:20:31 +00001396 assert( pFile );
1397 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1398 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001399
1400 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001401 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001402 return SQLITE_OK;
1403 }
drhf1a221e2006-01-15 17:27:17 +00001404 if( CHECK_THREADID(pFile) ){
1405 return SQLITE_MISUSE;
1406 }
drh66560ad2006-01-06 14:32:19 +00001407 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001408 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001409 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001410 if( pFile->locktype>SHARED_LOCK ){
1411 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001412 if( locktype==SHARED_LOCK ){
1413 lock.l_type = F_RDLCK;
1414 lock.l_whence = SEEK_SET;
1415 lock.l_start = SHARED_FIRST;
1416 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001417 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001418 /* This should never happen */
1419 rc = SQLITE_IOERR;
1420 }
1421 }
drhbbd42a62004-05-22 17:41:58 +00001422 lock.l_type = F_UNLCK;
1423 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001424 lock.l_start = PENDING_BYTE;
1425 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001426 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001427 pLock->locktype = SHARED_LOCK;
1428 }else{
1429 rc = SQLITE_IOERR; /* This should never happen */
1430 }
drhbbd42a62004-05-22 17:41:58 +00001431 }
drha6abd042004-06-09 17:37:22 +00001432 if( locktype==NO_LOCK ){
1433 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001434
drha6abd042004-06-09 17:37:22 +00001435 /* Decrement the shared lock counter. Release the lock using an
1436 ** OS call only when all threads in this same process have released
1437 ** the lock.
1438 */
1439 pLock->cnt--;
1440 if( pLock->cnt==0 ){
1441 lock.l_type = F_UNLCK;
1442 lock.l_whence = SEEK_SET;
1443 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001444 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001445 pLock->locktype = NO_LOCK;
1446 }else{
1447 rc = SQLITE_IOERR; /* This should never happen */
1448 }
drha6abd042004-06-09 17:37:22 +00001449 }
1450
drhbbd42a62004-05-22 17:41:58 +00001451 /* Decrement the count of locks against this same file. When the
1452 ** count reaches zero, close any other file descriptors whose close
1453 ** was deferred because of outstanding locks.
1454 */
drh054889e2005-11-30 03:20:31 +00001455 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001456 pOpen->nLock--;
1457 assert( pOpen->nLock>=0 );
1458 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1459 int i;
1460 for(i=0; i<pOpen->nPending; i++){
1461 close(pOpen->aPending[i]);
1462 }
drh64b1bea2006-01-15 02:30:57 +00001463 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001464 pOpen->nPending = 0;
1465 pOpen->aPending = 0;
1466 }
1467 }
drh66560ad2006-01-06 14:32:19 +00001468 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001469 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001470 return rc;
drhbbd42a62004-05-22 17:41:58 +00001471}
1472
1473/*
danielk1977e3026632004-06-22 11:29:02 +00001474** Close a file.
1475*/
drh9cbe6352005-11-29 03:13:21 +00001476static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001477 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001478
drh9cbe6352005-11-29 03:13:21 +00001479 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001480 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001481 if( id->dirfd>=0 ) close(id->dirfd);
1482 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001483 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001484
drh38322302006-01-15 02:43:16 +00001485 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001486 /* If there are outstanding locks, do not actually close the file just
1487 ** yet because that would clear those locks. Instead, add the file
1488 ** descriptor to pOpen->aPending. It will be automatically closed when
1489 ** the last lock is cleared.
1490 */
1491 int *aNew;
1492 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001493 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001494 if( aNew==0 ){
1495 /* If a malloc fails, just leak the file descriptor */
1496 }else{
1497 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001498 pOpen->aPending[pOpen->nPending] = id->h;
1499 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001500 }
1501 }else{
1502 /* There are no outstanding locks so we can close the file immediately */
1503 close(id->h);
1504 }
1505 releaseLockInfo(id->pLock);
1506 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001507
drh66560ad2006-01-06 14:32:19 +00001508 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001509 id->isOpen = 0;
1510 TRACE2("CLOSE %-3d\n", id->h);
1511 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001512 sqliteFree(id);
1513 *pId = 0;
drh02afc862006-01-20 18:10:57 +00001514 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001515}
1516
1517/*
drh0ccebe72005-06-07 22:22:50 +00001518** Turn a relative pathname into a full pathname. Return a pointer
1519** to the full pathname stored in space obtained from sqliteMalloc().
1520** The calling function is responsible for freeing this space once it
1521** is no longer needed.
1522*/
drh66560ad2006-01-06 14:32:19 +00001523char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001524 char *zFull = 0;
1525 if( zRelative[0]=='/' ){
1526 sqlite3SetString(&zFull, zRelative, (char*)0);
1527 }else{
drh79158e12005-09-06 21:40:45 +00001528 char *zBuf = sqliteMalloc(5000);
1529 if( zBuf==0 ){
1530 return 0;
1531 }
drh0ccebe72005-06-07 22:22:50 +00001532 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001533 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001534 (char*)0);
drh79158e12005-09-06 21:40:45 +00001535 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001536 }
1537 return zFull;
1538}
1539
drh18839212005-11-26 03:43:23 +00001540/*
drh9cbe6352005-11-29 03:13:21 +00001541** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001542*/
drh9cbe6352005-11-29 03:13:21 +00001543static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001544 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001545}
1546
1547/*
1548** Return the underlying file handle for an OsFile
1549*/
1550static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001551 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001552}
1553
1554/*
1555** Return an integer that indices the type of lock currently held
1556** by this handle. (Used for testing and analysis only.)
1557*/
1558static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001559 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001560}
drh0ccebe72005-06-07 22:22:50 +00001561
drh9c06c952005-11-26 00:25:00 +00001562/*
drh054889e2005-11-30 03:20:31 +00001563** This vector defines all the methods that can operate on an OsFile
1564** for unix.
drh9c06c952005-11-26 00:25:00 +00001565*/
drh054889e2005-11-30 03:20:31 +00001566static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001567 unixClose,
drh054889e2005-11-30 03:20:31 +00001568 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001569 unixRead,
1570 unixWrite,
1571 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001572 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001573 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001574 unixSetFullSync,
1575 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001576 unixFileSize,
1577 unixLock,
1578 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001579 unixLockState,
drh054889e2005-11-30 03:20:31 +00001580 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001581};
1582
drh054889e2005-11-30 03:20:31 +00001583/*
1584** Allocate memory for a unixFile. Initialize the new unixFile
1585** to the value given in pInit and return a pointer to the new
1586** OsFile. If we run out of memory, close the file and return NULL.
1587*/
1588static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1589 unixFile *pNew;
drh2f1a4d12006-01-23 16:24:54 +00001590 pInit->dirfd = -1;
1591 pInit->fullSync = 0;
1592 pInit->locktype = 0;
1593 SET_THREADID(pInit);
drh054889e2005-11-30 03:20:31 +00001594 pNew = sqliteMalloc( sizeof(unixFile) );
1595 if( pNew==0 ){
1596 close(pInit->h);
drh029b44b2006-01-15 00:13:15 +00001597 sqlite3OsEnterMutex();
danielk19772e588c72005-12-09 14:25:08 +00001598 releaseLockInfo(pInit->pLock);
1599 releaseOpenCnt(pInit->pOpen);
drh029b44b2006-01-15 00:13:15 +00001600 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001601 *pId = 0;
1602 return SQLITE_NOMEM;
1603 }else{
1604 *pNew = *pInit;
1605 pNew->pMethod = &sqlite3UnixIoMethod;
1606 *pId = (OsFile*)pNew;
1607 OpenCounter(+1);
1608 return SQLITE_OK;
1609 }
1610}
1611
drh9c06c952005-11-26 00:25:00 +00001612
drh0ccebe72005-06-07 22:22:50 +00001613#endif /* SQLITE_OMIT_DISKIO */
1614/***************************************************************************
1615** Everything above deals with file I/O. Everything that follows deals
1616** with other miscellanous aspects of the operating system interface
1617****************************************************************************/
1618
1619
1620/*
drhbbd42a62004-05-22 17:41:58 +00001621** Get information to seed the random number generator. The seed
1622** is written into the buffer zBuf[256]. The calling function must
1623** supply a sufficiently large buffer.
1624*/
drh66560ad2006-01-06 14:32:19 +00001625int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001626 /* We have to initialize zBuf to prevent valgrind from reporting
1627 ** errors. The reports issued by valgrind are incorrect - we would
1628 ** prefer that the randomness be increased by making use of the
1629 ** uninitialized space in zBuf - but valgrind errors tend to worry
1630 ** some users. Rather than argue, it seems easier just to initialize
1631 ** the whole array and silence valgrind, even if that means less randomness
1632 ** in the random seed.
1633 **
1634 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00001635 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00001636 ** tests repeatable.
1637 */
1638 memset(zBuf, 0, 256);
1639#if !defined(SQLITE_TEST)
1640 {
drh842b8642005-01-21 17:53:17 +00001641 int pid, fd;
1642 fd = open("/dev/urandom", O_RDONLY);
1643 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001644 time_t t;
1645 time(&t);
1646 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001647 pid = getpid();
1648 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1649 }else{
1650 read(fd, zBuf, 256);
1651 close(fd);
1652 }
drhbbd42a62004-05-22 17:41:58 +00001653 }
1654#endif
1655 return SQLITE_OK;
1656}
1657
1658/*
1659** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00001660** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00001661*/
drh66560ad2006-01-06 14:32:19 +00001662int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001663#if defined(HAVE_USLEEP) && HAVE_USLEEP
1664 usleep(ms*1000);
1665 return ms;
1666#else
1667 sleep((ms+999)/1000);
1668 return 1000*((ms+999)/1000);
1669#endif
1670}
1671
1672/*
drh5c111232006-02-10 04:33:12 +00001673** Static variables used for thread synchronization.
1674**
1675** inMutex the nesting depth of the recursive mutex. The thread
1676** holding mutexMain can read this variable at any time.
1677** But is must hold mutexAux to change this variable. Other
drh6a3d6702006-02-10 13:11:32 +00001678** threads must hold mutexAux to read the variable and can
1679** never write.
drh5c111232006-02-10 04:33:12 +00001680**
1681** mutexOwner The thread id of the thread holding mutexMain. Same
1682** access rules as for inMutex.
1683**
drh6a3d6702006-02-10 13:11:32 +00001684** mutexOwnerValid True if the value in mutexOwner is valid. The same
1685** access rules apply as for inMutex.
drh5c111232006-02-10 04:33:12 +00001686**
1687** mutexMain The main mutex. Hold this mutex in order to get exclusive
1688** access to SQLite data structures.
1689**
1690** mutexAux An auxiliary mutex needed to access variables defined above.
1691**
drh6a3d6702006-02-10 13:11:32 +00001692** Mutexes are always acquired in this order: mutexMain mutexAux. It
1693** is not necessary to acquire mutexMain in order to get mutexAux - just
1694** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
1695** Either get the mutexes with mutexMain first or get mutexAux only.
1696**
1697** When running on a platform where the three variables inMutex, mutexOwner,
1698** and mutexOwnerValid can be set atomically, the mutexAux is not required.
1699** On many systems, all three are 32-bit integers and writing to a 32-bit
1700** integer is atomic. I think. But there are no guarantees. So it seems
1701** safer to protect them using mutexAux.
drhbbd42a62004-05-22 17:41:58 +00001702*/
1703static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001704#ifdef SQLITE_UNIX_THREADS
drh6a3d6702006-02-10 13:11:32 +00001705static pthread_t mutexOwner; /* Thread holding mutexMain */
drh5c111232006-02-10 04:33:12 +00001706static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
1707static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
1708static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
drh79069752004-05-22 21:30:40 +00001709#endif
drhbbd42a62004-05-22 17:41:58 +00001710
1711/*
1712** The following pair of routine implement mutual exclusion for
1713** multi-threaded processes. Only a single thread is allowed to
1714** executed code that is surrounded by EnterMutex() and LeaveMutex().
1715**
1716** SQLite uses only a single Mutex. There is not much critical
1717** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00001718**
drh757b04e2006-01-18 17:25:45 +00001719** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00001720*/
drh66560ad2006-01-06 14:32:19 +00001721void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001722#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001723 pthread_mutex_lock(&mutexAux);
1724 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
1725 pthread_mutex_unlock(&mutexAux);
1726 pthread_mutex_lock(&mutexMain);
1727 assert( inMutex==0 );
1728 assert( !mutexOwnerValid );
1729 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001730 mutexOwner = pthread_self();
drh5c111232006-02-10 04:33:12 +00001731 mutexOwnerValid = 1;
drha3fad6f2006-01-18 14:06:37 +00001732 }
drha3fad6f2006-01-18 14:06:37 +00001733 inMutex++;
drh5c111232006-02-10 04:33:12 +00001734 pthread_mutex_unlock(&mutexAux);
1735#else
1736 inMutex++
1737#endif
drhbbd42a62004-05-22 17:41:58 +00001738}
drh66560ad2006-01-06 14:32:19 +00001739void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00001740 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00001741#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001742 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001743 inMutex--;
drh5c111232006-02-10 04:33:12 +00001744 assert( pthread_equal(mutexOwner, pthread_self()) );
drha3fad6f2006-01-18 14:06:37 +00001745 if( inMutex==0 ){
drh5c111232006-02-10 04:33:12 +00001746 assert( mutexOwnerValid );
1747 mutexOwnerValid = 0;
1748 pthread_mutex_unlock(&mutexMain);
drha3fad6f2006-01-18 14:06:37 +00001749 }
drh5c111232006-02-10 04:33:12 +00001750 pthread_mutex_unlock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001751#else
1752 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00001753#endif
1754}
1755
1756/*
drh757b04e2006-01-18 17:25:45 +00001757** Return TRUE if the mutex is currently held.
1758**
drh5c111232006-02-10 04:33:12 +00001759** If the thisThrd parameter is true, return true only if the
drh757b04e2006-01-18 17:25:45 +00001760** calling thread holds the mutex. If the parameter is false, return
1761** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00001762*/
drh5c111232006-02-10 04:33:12 +00001763int sqlite3UnixInMutex(int thisThrd){
drha3fad6f2006-01-18 14:06:37 +00001764#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001765 int rc;
1766 pthread_mutex_lock(&mutexAux);
1767 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
1768 pthread_mutex_unlock(&mutexAux);
1769 return rc;
drha3fad6f2006-01-18 14:06:37 +00001770#else
drh757b04e2006-01-18 17:25:45 +00001771 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00001772#endif
drh88f474a2006-01-02 20:00:12 +00001773}
1774
1775/*
drhb4bc7052006-01-11 23:40:33 +00001776** Remember the number of thread-specific-data blocks allocated.
1777** Use this to verify that we are not leaking thread-specific-data.
1778** Ticket #1601
1779*/
1780#ifdef SQLITE_TEST
1781int sqlite3_tsd_count = 0;
1782# ifdef SQLITE_UNIX_THREADS
1783 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
1784# define TSD_COUNTER(N) \
1785 pthread_mutex_lock(&tsd_counter_mutex); \
1786 sqlite3_tsd_count += N; \
1787 pthread_mutex_unlock(&tsd_counter_mutex);
1788# else
1789# define TSD_COUNTER(N) sqlite3_tsd_count += N
1790# endif
1791#else
1792# define TSD_COUNTER(N) /* no-op */
1793#endif
1794
drhb4bc7052006-01-11 23:40:33 +00001795/*
drhf1a221e2006-01-15 17:27:17 +00001796** If called with allocateFlag>0, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00001797** specific data for the current thread. Allocate and zero the
drhf1a221e2006-01-15 17:27:17 +00001798** thread-specific data if it does not already exist.
danielk197713a68c32005-12-15 10:11:30 +00001799**
drh6f7adc82006-01-11 21:41:20 +00001800** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00001801** specific data. Return it if it exists. If it does not exist,
1802** then return NULL.
1803**
1804** If called with allocateFlag<0, check to see if the thread specific
1805** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00001806** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00001807** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00001808*/
drh6f7adc82006-01-11 21:41:20 +00001809ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
danielk19774d5238f2006-01-27 06:32:00 +00001810 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
1811 ** from broken compilers */
danielk197713a68c32005-12-15 10:11:30 +00001812#ifdef SQLITE_UNIX_THREADS
1813 static pthread_key_t key;
1814 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001815 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001816
1817 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001818 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001819 if( !keyInit ){
1820 int rc;
drh6f7adc82006-01-11 21:41:20 +00001821 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001822 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001823 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001824 return 0;
1825 }
1826 keyInit = 1;
1827 }
drh66560ad2006-01-06 14:32:19 +00001828 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001829 }
1830
drh3fbb0b12006-01-06 00:36:00 +00001831 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00001832 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001833 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001834 if( !sqlite3TestMallocFail() ){
1835 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1836 }
1837#ifdef SQLITE_MEMDEBUG
1838 sqlite3_isFail = 0;
1839#endif
drh6f7adc82006-01-11 21:41:20 +00001840 if( pTsd ){
1841 *pTsd = zeroData;
1842 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00001843 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001844 }
danielk197713a68c32005-12-15 10:11:30 +00001845 }
drh70ff98a2006-01-12 01:25:18 +00001846 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001847 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001848 sqlite3OsFree(pTsd);
1849 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00001850 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001851 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001852 }
1853 return pTsd;
1854#else
drh6f7adc82006-01-11 21:41:20 +00001855 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00001856 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001857 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001858 if( !sqlite3TestMallocFail() ){
1859 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1860 }
1861#ifdef SQLITE_MEMDEBUG
1862 sqlite3_isFail = 0;
1863#endif
drh6f7adc82006-01-11 21:41:20 +00001864 if( pTsd ){
1865 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00001866 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001867 }
drh3fbb0b12006-01-06 00:36:00 +00001868 }
drh70ff98a2006-01-12 01:25:18 +00001869 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001870 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001871 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00001872 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001873 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001874 }
drh3fbb0b12006-01-06 00:36:00 +00001875 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001876#endif
1877}
1878
1879/*
drhbbd42a62004-05-22 17:41:58 +00001880** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001881** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001882*/
1883#ifdef SQLITE_TEST
1884int sqlite3_current_time = 0;
1885#endif
1886
1887/*
1888** Find the current time (in Universal Coordinated Time). Write the
1889** current time and date as a Julian Day number into *prNow and
1890** return 0. Return 1 if the time and date cannot be found.
1891*/
drh66560ad2006-01-06 14:32:19 +00001892int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001893#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001894 time_t t;
1895 time(&t);
1896 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001897#else
1898 struct timeval sNow;
1899 struct timezone sTz; /* Not used */
1900 gettimeofday(&sNow, &sTz);
1901 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1902#endif
drhbbd42a62004-05-22 17:41:58 +00001903#ifdef SQLITE_TEST
1904 if( sqlite3_current_time ){
1905 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1906 }
1907#endif
1908 return 0;
1909}
1910
drhbbd42a62004-05-22 17:41:58 +00001911#endif /* OS_UNIX */