blob: ed810d6df259475c63596a57b346047ab27e8e66 [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 */
drhb912b282006-03-23 22:42:20 +000083 i64 offset; /* Seek offset */
drh9cbe6352005-11-29 03:13:21 +000084#ifdef SQLITE_UNIX_THREADS
drhf1a221e2006-01-15 17:27:17 +000085 pthread_t tid; /* The thread that "owns" this OsFile */
drh9cbe6352005-11-29 03:13:21 +000086#endif
87};
88
drh66560ad2006-01-06 14:32:19 +000089/*
90** Provide the ability to override some OS-layer functions during
91** testing. This is used to simulate OS crashes to verify that
92** commits are atomic even in the event of an OS crash.
93*/
94#ifdef SQLITE_CRASH_TEST
95 extern int sqlite3CrashTestEnable;
96 extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
97 extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
98 extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
99# define CRASH_TEST_OVERRIDE(X,A,B,C) \
100 if(sqlite3CrashTestEnable){ return X(A,B,C); }
101#else
102# define CRASH_TEST_OVERRIDE(X,A,B,C) /* no-op */
103#endif
104
drh0ccebe72005-06-07 22:22:50 +0000105
106/*
drh198bf392006-01-06 21:52:49 +0000107** Include code that is common to all os_*.c files
108*/
109#include "os_common.h"
110
111/*
drh0ccebe72005-06-07 22:22:50 +0000112** Do not include any of the File I/O interface procedures if the
drhf1a221e2006-01-15 17:27:17 +0000113** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
drh0ccebe72005-06-07 22:22:50 +0000114** will be in-memory only)
115*/
116#ifndef SQLITE_OMIT_DISKIO
117
118
119/*
120** Define various macros that are missing from some systems.
121*/
drhbbd42a62004-05-22 17:41:58 +0000122#ifndef O_LARGEFILE
123# define O_LARGEFILE 0
124#endif
125#ifdef SQLITE_DISABLE_LFS
126# undef O_LARGEFILE
127# define O_LARGEFILE 0
128#endif
129#ifndef O_NOFOLLOW
130# define O_NOFOLLOW 0
131#endif
132#ifndef O_BINARY
133# define O_BINARY 0
134#endif
135
136/*
137** The DJGPP compiler environment looks mostly like Unix, but it
138** lacks the fcntl() system call. So redefine fcntl() to be something
139** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000140** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000141*/
142#ifdef __DJGPP__
143# define fcntl(A,B,C) 0
144#endif
145
146/*
drh2b4b5962005-06-15 17:47:55 +0000147** The threadid macro resolves to the thread-id or to 0. Used for
148** testing and debugging only.
149*/
150#ifdef SQLITE_UNIX_THREADS
151#define threadid pthread_self()
152#else
153#define threadid 0
154#endif
155
156/*
157** Set or check the OsFile.tid field. This field is set when an OsFile
158** is first opened. All subsequent uses of the OsFile verify that the
159** same thread is operating on the OsFile. Some operating systems do
160** not allow locks to be overridden by other threads and that restriction
161** means that sqlite3* database handles cannot be moved from one thread
162** to another. This logic makes sure a user does not try to do that
163** by mistake.
drhf1a221e2006-01-15 17:27:17 +0000164**
165** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
166** another as long as we are running on a system that supports threads
167** overriding each others locks (which now the most common behavior)
168** or if no locks are held. But the OsFile.pLock field needs to be
169** recomputed because its key includes the thread-id. See the
170** transferOwnership() function below for additional information
drh2b4b5962005-06-15 17:47:55 +0000171*/
drh029b44b2006-01-15 00:13:15 +0000172#if defined(SQLITE_UNIX_THREADS)
drh9cbe6352005-11-29 03:13:21 +0000173# define SET_THREADID(X) (X)->tid = pthread_self()
drh029b44b2006-01-15 00:13:15 +0000174# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
175 !pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000176#else
177# define SET_THREADID(X)
178# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000179#endif
180
drhbbd42a62004-05-22 17:41:58 +0000181/*
182** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
183** section 6.5.2.2 lines 483 through 490 specify that when a process
184** sets or clears a lock, that operation overrides any prior locks set
185** by the same process. It does not explicitly say so, but this implies
186** that it overrides locks set by the same process using a different
187** file descriptor. Consider this test case:
188**
189** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
190** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
191**
192** Suppose ./file1 and ./file2 are really the same file (because
193** one is a hard or symbolic link to the other) then if you set
194** an exclusive lock on fd1, then try to get an exclusive lock
195** on fd2, it works. I would have expected the second lock to
196** fail since there was already a lock on the file due to fd1.
197** But not so. Since both locks came from the same process, the
198** second overrides the first, even though they were on different
199** file descriptors opened on different file names.
200**
201** Bummer. If you ask me, this is broken. Badly broken. It means
202** that we cannot use POSIX locks to synchronize file access among
203** competing threads of the same process. POSIX locks will work fine
204** to synchronize access for threads in separate processes, but not
205** threads within the same process.
206**
207** To work around the problem, SQLite has to manage file locks internally
208** on its own. Whenever a new database is opened, we have to find the
209** specific inode of the database file (the inode is determined by the
210** st_dev and st_ino fields of the stat structure that fstat() fills in)
211** and check for locks already existing on that inode. When locks are
212** created or removed, we have to look at our own internal record of the
213** locks to see if another thread has previously set a lock on that same
214** inode.
215**
216** The OsFile structure for POSIX is no longer just an integer file
217** descriptor. It is now a structure that holds the integer file
218** descriptor and a pointer to a structure that describes the internal
219** locks on the corresponding inode. There is one locking structure
220** per inode, so if the same inode is opened twice, both OsFile structures
221** point to the same locking structure. The locking structure keeps
222** a reference count (so we will know when to delete it) and a "cnt"
223** field that tells us its internal lock status. cnt==0 means the
224** file is unlocked. cnt==-1 means the file has an exclusive lock.
225** cnt>0 means there are cnt shared locks on the file.
226**
227** Any attempt to lock or unlock a file first checks the locking
228** structure. The fcntl() system call is only invoked to set a
229** POSIX lock if the internal lock structure transitions between
230** a locked and an unlocked state.
231**
232** 2004-Jan-11:
233** More recent discoveries about POSIX advisory locks. (The more
234** I discover, the more I realize the a POSIX advisory locks are
235** an abomination.)
236**
237** If you close a file descriptor that points to a file that has locks,
238** all locks on that file that are owned by the current process are
239** released. To work around this problem, each OsFile structure contains
240** a pointer to an openCnt structure. There is one openCnt structure
241** per open inode, which means that multiple OsFiles can point to a single
242** openCnt. When an attempt is made to close an OsFile, if there are
243** other OsFiles open on the same inode that are holding locks, the call
244** to close() the file descriptor is deferred until all of the locks clear.
245** The openCnt structure keeps a list of file descriptors that need to
246** be closed and that list is walked (and cleared) when the last lock
247** clears.
248**
249** First, under Linux threads, because each thread has a separate
250** process ID, lock operations in one thread do not override locks
251** to the same file in other threads. Linux threads behave like
252** separate processes in this respect. But, if you close a file
253** descriptor in linux threads, all locks are cleared, even locks
254** on other threads and even though the other threads have different
255** process IDs. Linux threads is inconsistent in this respect.
256** (I'm beginning to think that linux threads is an abomination too.)
257** The consequence of this all is that the hash table for the lockInfo
258** structure has to include the process id as part of its key because
259** locks in different threads are treated as distinct. But the
260** openCnt structure should not include the process id in its
261** key because close() clears lock on all threads, not just the current
262** thread. Were it not for this goofiness in linux threads, we could
263** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000264**
265** 2004-Jun-28:
266** On some versions of linux, threads can override each others locks.
267** On others not. Sometimes you can change the behavior on the same
268** system by setting the LD_ASSUME_KERNEL environment variable. The
269** POSIX standard is silent as to which behavior is correct, as far
270** as I can tell, so other versions of unix might show the same
271** inconsistency. There is no little doubt in my mind that posix
272** advisory locks and linux threads are profoundly broken.
273**
274** To work around the inconsistencies, we have to test at runtime
275** whether or not threads can override each others locks. This test
276** is run once, the first time any lock is attempted. A static
277** variable is set to record the results of this test for future
278** use.
drhbbd42a62004-05-22 17:41:58 +0000279*/
280
281/*
282** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000283** to locate a particular lockInfo structure given its inode.
284**
285** If threads cannot override each others locks, then we set the
286** lockKey.tid field to the thread ID. If threads can override
drhf1a221e2006-01-15 17:27:17 +0000287** each others locks then tid is always set to zero. tid is omitted
288** if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000289*/
290struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000291 dev_t dev; /* Device number */
292 ino_t ino; /* Inode number */
293#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000294 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000295#endif
drhbbd42a62004-05-22 17:41:58 +0000296};
297
298/*
299** An instance of the following structure is allocated for each open
300** inode on each thread with a different process ID. (Threads have
301** different process IDs on linux, but not on most other unixes.)
302**
303** A single inode can have multiple file descriptors, so each OsFile
304** structure contains a pointer to an instance of this object and this
305** object keeps a count of the number of OsFiles pointing to it.
306*/
307struct lockInfo {
308 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000309 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000310 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000311 int nRef; /* Number of pointers to this structure */
312};
313
314/*
315** An instance of the following structure serves as the key used
316** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000317** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000318*/
319struct openKey {
320 dev_t dev; /* Device number */
321 ino_t ino; /* Inode number */
322};
323
324/*
325** An instance of the following structure is allocated for each open
326** inode. This structure keeps track of the number of locks on that
327** inode. If a close is attempted against an inode that is holding
328** locks, the close is deferred until all locks clear by adding the
329** file descriptor to be closed to the pending list.
330*/
331struct openCnt {
332 struct openKey key; /* The lookup key */
333 int nRef; /* Number of pointers to this structure */
334 int nLock; /* Number of outstanding locks */
335 int nPending; /* Number of pending close() operations */
336 int *aPending; /* Malloced space holding fd's awaiting a close() */
337};
338
339/*
drhf1a221e2006-01-15 17:27:17 +0000340** These hash tables map inodes and file descriptors (really, lockKey and
341** openKey structures) into lockInfo and openCnt structures. Access to
342** these hash tables must be protected by a mutex.
drhbbd42a62004-05-22 17:41:58 +0000343*/
danielk1977750b03e2006-02-14 10:48:39 +0000344static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0,
345 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
346static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0,
347 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000348
349#ifdef SQLITE_UNIX_THREADS
350/*
351** This variable records whether or not threads can override each others
352** locks.
353**
354** 0: No. Threads cannot override each others locks.
355** 1: Yes. Threads can override each others locks.
356** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000357**
drh5062d3a2006-01-31 23:03:35 +0000358** On some systems, we know at compile-time if threads can override each
359** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
360** will be set appropriately. On other systems, we have to check at
361** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
362** undefined.
363**
drhf1a221e2006-01-15 17:27:17 +0000364** This variable normally has file scope only. But during testing, we make
365** it a global so that the test code can change its value in order to verify
366** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000367*/
drh5062d3a2006-01-31 23:03:35 +0000368#ifndef SQLITE_THREAD_OVERRIDE_LOCK
369# define SQLITE_THREAD_OVERRIDE_LOCK -1
370#endif
drh029b44b2006-01-15 00:13:15 +0000371#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000372int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000373#else
drh5062d3a2006-01-31 23:03:35 +0000374static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000375#endif
drh5fdae772004-06-29 03:29:00 +0000376
377/*
378** This structure holds information passed into individual test
379** threads by the testThreadLockingBehavior() routine.
380*/
381struct threadTestData {
382 int fd; /* File to be locked */
383 struct flock lock; /* The locking operation */
384 int result; /* Result of the locking operation */
385};
386
drh2b4b5962005-06-15 17:47:55 +0000387#ifdef SQLITE_LOCK_TRACE
388/*
389** Print out information about all locking operations.
390**
391** This routine is used for troubleshooting locks on multithreaded
392** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
393** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000394** turned off.
drh2b4b5962005-06-15 17:47:55 +0000395*/
396static int lockTrace(int fd, int op, struct flock *p){
397 char *zOpName, *zType;
398 int s;
399 int savedErrno;
400 if( op==F_GETLK ){
401 zOpName = "GETLK";
402 }else if( op==F_SETLK ){
403 zOpName = "SETLK";
404 }else{
405 s = fcntl(fd, op, p);
406 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
407 return s;
408 }
409 if( p->l_type==F_RDLCK ){
410 zType = "RDLCK";
411 }else if( p->l_type==F_WRLCK ){
412 zType = "WRLCK";
413 }else if( p->l_type==F_UNLCK ){
414 zType = "UNLCK";
415 }else{
416 assert( 0 );
417 }
418 assert( p->l_whence==SEEK_SET );
419 s = fcntl(fd, op, p);
420 savedErrno = errno;
421 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
422 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
423 (int)p->l_pid, s);
424 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
425 struct flock l2;
426 l2 = *p;
427 fcntl(fd, F_GETLK, &l2);
428 if( l2.l_type==F_RDLCK ){
429 zType = "RDLCK";
430 }else if( l2.l_type==F_WRLCK ){
431 zType = "WRLCK";
432 }else if( l2.l_type==F_UNLCK ){
433 zType = "UNLCK";
434 }else{
435 assert( 0 );
436 }
437 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
438 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
439 }
440 errno = savedErrno;
441 return s;
442}
443#define fcntl lockTrace
444#endif /* SQLITE_LOCK_TRACE */
445
drh5fdae772004-06-29 03:29:00 +0000446/*
447** The testThreadLockingBehavior() routine launches two separate
448** threads on this routine. This routine attempts to lock a file
449** descriptor then returns. The success or failure of that attempt
450** allows the testThreadLockingBehavior() procedure to determine
451** whether or not threads can override each others locks.
452*/
453static void *threadLockingTest(void *pArg){
454 struct threadTestData *pData = (struct threadTestData*)pArg;
455 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
456 return pArg;
457}
458
459/*
460** This procedure attempts to determine whether or not threads
461** can override each others locks then sets the
462** threadsOverrideEachOthersLocks variable appropriately.
463*/
danielk19774d5238f2006-01-27 06:32:00 +0000464static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000465 int fd;
466 struct threadTestData d[2];
467 pthread_t t[2];
468
469 fd = dup(fd_orig);
470 if( fd<0 ) return;
471 memset(d, 0, sizeof(d));
472 d[0].fd = fd;
473 d[0].lock.l_type = F_RDLCK;
474 d[0].lock.l_len = 1;
475 d[0].lock.l_start = 0;
476 d[0].lock.l_whence = SEEK_SET;
477 d[1] = d[0];
478 d[1].lock.l_type = F_WRLCK;
479 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
480 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
481 pthread_join(t[0], 0);
482 pthread_join(t[1], 0);
483 close(fd);
484 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
485}
486#endif /* SQLITE_UNIX_THREADS */
487
drhbbd42a62004-05-22 17:41:58 +0000488/*
489** Release a lockInfo structure previously allocated by findLockInfo().
490*/
491static void releaseLockInfo(struct lockInfo *pLock){
drh757b04e2006-01-18 17:25:45 +0000492 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000493 pLock->nRef--;
494 if( pLock->nRef==0 ){
495 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
danielk1977750b03e2006-02-14 10:48:39 +0000496 sqlite3ThreadSafeFree(pLock);
drhbbd42a62004-05-22 17:41:58 +0000497 }
498}
499
500/*
501** Release a openCnt structure previously allocated by findLockInfo().
502*/
503static void releaseOpenCnt(struct openCnt *pOpen){
drh757b04e2006-01-18 17:25:45 +0000504 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000505 pOpen->nRef--;
506 if( pOpen->nRef==0 ){
507 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000508 free(pOpen->aPending);
danielk1977750b03e2006-02-14 10:48:39 +0000509 sqlite3ThreadSafeFree(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000510 }
511}
512
513/*
514** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000515** describes that file descriptor. Create new ones if necessary. The
516** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000517**
518** Return the number of errors.
519*/
drh38f82712004-06-18 17:10:16 +0000520static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000521 int fd, /* The file descriptor used in the key */
522 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000523 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000524){
525 int rc;
526 struct lockKey key1;
527 struct openKey key2;
528 struct stat statbuf;
529 struct lockInfo *pLock;
530 struct openCnt *pOpen;
531 rc = fstat(fd, &statbuf);
532 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000533
drh757b04e2006-01-18 17:25:45 +0000534 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000535 memset(&key1, 0, sizeof(key1));
536 key1.dev = statbuf.st_dev;
537 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000538#ifdef SQLITE_UNIX_THREADS
539 if( threadsOverrideEachOthersLocks<0 ){
540 testThreadLockingBehavior(fd);
541 }
542 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
543#endif
drhbbd42a62004-05-22 17:41:58 +0000544 memset(&key2, 0, sizeof(key2));
545 key2.dev = statbuf.st_dev;
546 key2.ino = statbuf.st_ino;
547 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
548 if( pLock==0 ){
549 struct lockInfo *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000550 pLock = sqlite3ThreadSafeMalloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000551 if( pLock==0 ){
552 rc = 1;
553 goto exit_findlockinfo;
554 }
drhbbd42a62004-05-22 17:41:58 +0000555 pLock->key = key1;
556 pLock->nRef = 1;
557 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000558 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000559 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
560 if( pOld!=0 ){
561 assert( pOld==pLock );
danielk1977750b03e2006-02-14 10:48:39 +0000562 sqlite3ThreadSafeFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000563 rc = 1;
564 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000565 }
566 }else{
567 pLock->nRef++;
568 }
569 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000570 if( ppOpen!=0 ){
571 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000572 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000573 struct openCnt *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000574 pOpen = sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000575 if( pOpen==0 ){
576 releaseLockInfo(pLock);
577 rc = 1;
578 goto exit_findlockinfo;
579 }
580 pOpen->key = key2;
581 pOpen->nRef = 1;
582 pOpen->nLock = 0;
583 pOpen->nPending = 0;
584 pOpen->aPending = 0;
585 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
586 if( pOld!=0 ){
587 assert( pOld==pOpen );
danielk1977750b03e2006-02-14 10:48:39 +0000588 sqlite3ThreadSafeFree(pOpen);
drh029b44b2006-01-15 00:13:15 +0000589 releaseLockInfo(pLock);
590 rc = 1;
591 goto exit_findlockinfo;
592 }
593 }else{
594 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000595 }
drh029b44b2006-01-15 00:13:15 +0000596 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000597 }
danielk1977441b09a2006-01-05 13:48:29 +0000598
599exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000600 return rc;
drhbbd42a62004-05-22 17:41:58 +0000601}
602
drh64b1bea2006-01-15 02:30:57 +0000603#ifdef SQLITE_DEBUG
604/*
605** Helper function for printing out trace information from debugging
606** binaries. This returns the string represetation of the supplied
607** integer lock-type.
608*/
609static const char *locktypeName(int locktype){
610 switch( locktype ){
611 case NO_LOCK: return "NONE";
612 case SHARED_LOCK: return "SHARED";
613 case RESERVED_LOCK: return "RESERVED";
614 case PENDING_LOCK: return "PENDING";
615 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
616 }
617 return "ERROR";
618}
619#endif
620
drhbbd42a62004-05-22 17:41:58 +0000621/*
drh029b44b2006-01-15 00:13:15 +0000622** If we are currently in a different thread than the thread that the
623** unixFile argument belongs to, then transfer ownership of the unixFile
624** over to the current thread.
625**
626** A unixFile is only owned by a thread on systems where one thread is
627** unable to override locks created by a different thread. RedHat9 is
628** an example of such a system.
629**
630** Ownership transfer is only allowed if the unixFile is currently unlocked.
631** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000632** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000633*/
634#ifdef SQLITE_UNIX_THREADS
635static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000636 int rc;
drh029b44b2006-01-15 00:13:15 +0000637 pthread_t hSelf;
638 if( threadsOverrideEachOthersLocks ){
639 /* Ownership transfers not needed on this system */
640 return SQLITE_OK;
641 }
642 hSelf = pthread_self();
643 if( pthread_equal(pFile->tid, hSelf) ){
644 /* We are still in the same thread */
drh64b1bea2006-01-15 02:30:57 +0000645 TRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000646 return SQLITE_OK;
647 }
648 if( pFile->locktype!=NO_LOCK ){
649 /* We cannot change ownership while we are holding a lock! */
650 return SQLITE_MISUSE;
651 }
drh64b1bea2006-01-15 02:30:57 +0000652 TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
drh029b44b2006-01-15 00:13:15 +0000653 pFile->tid = hSelf;
654 releaseLockInfo(pFile->pLock);
drh64b1bea2006-01-15 02:30:57 +0000655 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
656 TRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
657 locktypeName(pFile->locktype),
658 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
659 return rc;
drh029b44b2006-01-15 00:13:15 +0000660}
661#else
drhf1a221e2006-01-15 17:27:17 +0000662 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000663# define transferOwnership(X) SQLITE_OK
664#endif
665
666/*
drhbbd42a62004-05-22 17:41:58 +0000667** Delete the named file
668*/
drh66560ad2006-01-06 14:32:19 +0000669int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000670 unlink(zFilename);
671 return SQLITE_OK;
672}
673
674/*
675** Return TRUE if the named file exists.
676*/
drh66560ad2006-01-06 14:32:19 +0000677int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000678 return access(zFilename, 0)==0;
679}
680
drh054889e2005-11-30 03:20:31 +0000681/* Forward declaration */
682static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000683
684/*
drhbbd42a62004-05-22 17:41:58 +0000685** Attempt to open a file for both reading and writing. If that
686** fails, try opening it read-only. If the file does not exist,
687** try to create it.
688**
689** On success, a handle for the open file is written to *id
690** and *pReadonly is set to 0 if the file was opened for reading and
691** writing or 1 if the file was opened read-only. The function returns
692** SQLITE_OK.
693**
694** On failure, the function returns SQLITE_CANTOPEN and leaves
695** *id and *pReadonly unchanged.
696*/
drh66560ad2006-01-06 14:32:19 +0000697int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000698 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000699 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000700 int *pReadonly
701){
702 int rc;
drh054889e2005-11-30 03:20:31 +0000703 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000704
drh66560ad2006-01-06 14:32:19 +0000705 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000706 assert( 0==*pId );
drh9cbe6352005-11-29 03:13:21 +0000707 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000708 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000709 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000710#ifdef EISDIR
711 if( errno==EISDIR ){
712 return SQLITE_CANTOPEN;
713 }
714#endif
drh9cbe6352005-11-29 03:13:21 +0000715 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
716 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000717 return SQLITE_CANTOPEN;
718 }
719 *pReadonly = 1;
720 }else{
721 *pReadonly = 0;
722 }
drh66560ad2006-01-06 14:32:19 +0000723 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000724 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000725 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000726 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000727 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000728 return SQLITE_NOMEM;
729 }
drh9cbe6352005-11-29 03:13:21 +0000730 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000731 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000732}
733
734
735/*
736** Attempt to open a new file for exclusive access by this process.
737** The file will be opened for both reading and writing. To avoid
738** a potential security problem, we do not allow the file to have
739** previously existed. Nor do we allow the file to be a symbolic
740** link.
741**
742** If delFlag is true, then make arrangements to automatically delete
743** the file when it is closed.
744**
745** On success, write the file handle into *id and return SQLITE_OK.
746**
747** On failure, return SQLITE_CANTOPEN.
748*/
drh66560ad2006-01-06 14:32:19 +0000749int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000750 int rc;
drh054889e2005-11-30 03:20:31 +0000751 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000752
drh66560ad2006-01-06 14:32:19 +0000753 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000754 assert( 0==*pId );
drh9cbe6352005-11-29 03:13:21 +0000755 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000756 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
757 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000758 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000759 return SQLITE_CANTOPEN;
760 }
drh66560ad2006-01-06 14:32:19 +0000761 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000762 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000763 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000764 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000765 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000766 unlink(zFilename);
767 return SQLITE_NOMEM;
768 }
drhbbd42a62004-05-22 17:41:58 +0000769 if( delFlag ){
770 unlink(zFilename);
771 }
drh9cbe6352005-11-29 03:13:21 +0000772 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000773 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000774}
775
776/*
777** Attempt to open a new file for read-only access.
778**
779** On success, write the file handle into *id and return SQLITE_OK.
780**
781** On failure, return SQLITE_CANTOPEN.
782*/
drh66560ad2006-01-06 14:32:19 +0000783int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000784 int rc;
drh054889e2005-11-30 03:20:31 +0000785 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000786
drh66560ad2006-01-06 14:32:19 +0000787 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000788 assert( 0==*pId );
drh9cbe6352005-11-29 03:13:21 +0000789 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 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000801 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000802}
803
804/*
805** Attempt to open a file descriptor for the directory that contains a
806** file. This file descriptor can be used to fsync() the directory
807** in order to make sure the creation of a new file is actually written
808** to disk.
809**
810** This routine is only meaningful for Unix. It is a no-op under
811** windows since windows does not support hard links.
812**
drh9cbe6352005-11-29 03:13:21 +0000813** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000814** updated with the new directory file descriptor and SQLITE_OK is
815** returned.
816**
817** On failure, the function returns SQLITE_CANTOPEN and leaves
818** *id unchanged.
819*/
drh9c06c952005-11-26 00:25:00 +0000820static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000821 OsFile *id,
822 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000823){
drh054889e2005-11-30 03:20:31 +0000824 unixFile *pFile = (unixFile*)id;
825 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000826 /* Do not open the directory if the corresponding file is not already
827 ** open. */
828 return SQLITE_CANTOPEN;
829 }
drh054889e2005-11-30 03:20:31 +0000830 SET_THREADID(pFile);
831 assert( pFile->dirfd<0 );
832 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
833 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000834 return SQLITE_CANTOPEN;
835 }
drh054889e2005-11-30 03:20:31 +0000836 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000837 return SQLITE_OK;
838}
839
840/*
drhab3f9fe2004-08-14 17:10:10 +0000841** If the following global variable points to a string which is the
842** name of a directory, then that directory will be used to store
843** temporary files.
drhf1a221e2006-01-15 17:27:17 +0000844**
845** See also the "PRAGMA temp_store_directory" SQL command.
drhab3f9fe2004-08-14 17:10:10 +0000846*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000847char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000848
849/*
drhbbd42a62004-05-22 17:41:58 +0000850** Create a temporary file name in zBuf. zBuf must be big enough to
851** hold at least SQLITE_TEMPNAME_SIZE characters.
852*/
drh66560ad2006-01-06 14:32:19 +0000853int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000854 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000855 0,
drhbbd42a62004-05-22 17:41:58 +0000856 "/var/tmp",
857 "/usr/tmp",
858 "/tmp",
859 ".",
860 };
drh57196282004-10-06 15:41:16 +0000861 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000862 "abcdefghijklmnopqrstuvwxyz"
863 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
864 "0123456789";
865 int i, j;
866 struct stat buf;
867 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000868 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000869 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000870 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000871 if( stat(azDirs[i], &buf) ) continue;
872 if( !S_ISDIR(buf.st_mode) ) continue;
873 if( access(azDirs[i], 07) ) continue;
874 zDir = azDirs[i];
875 break;
876 }
877 do{
878 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
879 j = strlen(zBuf);
880 sqlite3Randomness(15, &zBuf[j]);
881 for(i=0; i<15; i++, j++){
882 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
883 }
884 zBuf[j] = 0;
885 }while( access(zBuf,0)==0 );
886 return SQLITE_OK;
887}
888
889/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000890** Check that a given pathname is a directory and is writable
891**
892*/
drh66560ad2006-01-06 14:32:19 +0000893int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000894#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000895 struct stat buf;
896 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000897 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000898 if( stat(zBuf, &buf) ) return 0;
899 if( !S_ISDIR(buf.st_mode) ) return 0;
900 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000901#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000902 return 1;
903}
904
905/*
drhb912b282006-03-23 22:42:20 +0000906** Seek to the offset in id->offset then read cnt bytes into pBuf.
907** Return the number of bytes actually read. Update the offset.
908*/
909static int seekAndRead(unixFile *id, void *pBuf, int cnt){
910 int got;
911#ifdef USE_PREAD
912 got = pread(id->h, pBuf, cnt, id->offset);
913#else
914 lseek(id->h, id->offset, SEEK_SET);
915 got = read(id->h, pBuf, cnt);
916#endif
917 if( got>0 ){
918 id->offset += got;
919 }
920 return got;
921}
922
923/*
drhbbd42a62004-05-22 17:41:58 +0000924** Read data from a file into a buffer. Return SQLITE_OK if all
925** bytes were read successfully and SQLITE_IOERR if anything goes
926** wrong.
927*/
drh9c06c952005-11-26 00:25:00 +0000928static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000929 int got;
drh9cbe6352005-11-29 03:13:21 +0000930 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000931 TIMER_START;
drhb912b282006-03-23 22:42:20 +0000932 got = seekAndRead((unixFile*)id, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000933 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000934 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
935 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000936 SEEK(0);
drh59685932006-09-14 13:47:11 +0000937 SimulateIOError( got=0 );
drhbbd42a62004-05-22 17:41:58 +0000938 if( got==amt ){
939 return SQLITE_OK;
940 }else{
941 return SQLITE_IOERR;
942 }
943}
944
945/*
drhb912b282006-03-23 22:42:20 +0000946** Seek to the offset in id->offset then read cnt bytes into pBuf.
947** Return the number of bytes actually read. Update the offset.
948*/
949static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
950 int got;
951#ifdef USE_PREAD
952 got = pwrite(id->h, pBuf, cnt, id->offset);
953#else
954 lseek(id->h, id->offset, SEEK_SET);
955 got = write(id->h, pBuf, cnt);
956#endif
957 if( got>0 ){
958 id->offset += got;
959 }
960 return got;
961}
962
963
964/*
drhbbd42a62004-05-22 17:41:58 +0000965** Write data from a buffer into a file. Return SQLITE_OK on success
966** or some other error code on failure.
967*/
drh9c06c952005-11-26 00:25:00 +0000968static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000969 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000970 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000971 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000972 TIMER_START;
drhb912b282006-03-23 22:42:20 +0000973 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000974 amt -= wrote;
975 pBuf = &((char*)pBuf)[wrote];
976 }
977 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000978 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
979 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000980 SEEK(0);
drh59685932006-09-14 13:47:11 +0000981 SimulateIOError(( wrote=(-1), amt=1 ));
982 SimulateDiskfullError(( wrote=0, amt=1 ));
drhbbd42a62004-05-22 17:41:58 +0000983 if( amt>0 ){
drh59685932006-09-14 13:47:11 +0000984 if( wrote<0 ){
985 return SQLITE_IOERR;
986 }else{
987 return SQLITE_FULL;
988 }
drhbbd42a62004-05-22 17:41:58 +0000989 }
990 return SQLITE_OK;
991}
992
993/*
994** Move the read/write pointer in a file.
995*/
drh9c06c952005-11-26 00:25:00 +0000996static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000997 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000998 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000999#ifdef SQLITE_TEST
drh59685932006-09-14 13:47:11 +00001000 if( offset ) SimulateDiskfullError(return SQLITE_FULL);
drhb4746b92005-09-09 01:32:06 +00001001#endif
drhb912b282006-03-23 22:42:20 +00001002 ((unixFile*)id)->offset = offset;
drhbbd42a62004-05-22 17:41:58 +00001003 return SQLITE_OK;
1004}
1005
drhb851b2c2005-03-10 14:11:12 +00001006#ifdef SQLITE_TEST
1007/*
1008** Count the number of fullsyncs and normal syncs. This is used to test
1009** that syncs and fullsyncs are occuring at the right times.
1010*/
1011int sqlite3_sync_count = 0;
1012int sqlite3_fullsync_count = 0;
1013#endif
1014
drhf2f23912005-10-05 10:29:36 +00001015/*
1016** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
1017** Otherwise use fsync() in its place.
1018*/
1019#ifndef HAVE_FDATASYNC
1020# define fdatasync fsync
1021#endif
1022
drhac530b12006-02-11 01:25:50 +00001023/*
1024** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
1025** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
1026** only available on Mac OS X. But that could change.
1027*/
1028#ifdef F_FULLFSYNC
1029# define HAVE_FULLFSYNC 1
1030#else
1031# define HAVE_FULLFSYNC 0
1032#endif
1033
drhb851b2c2005-03-10 14:11:12 +00001034
drhbbd42a62004-05-22 17:41:58 +00001035/*
drhdd809b02004-07-17 21:44:57 +00001036** The fsync() system call does not work as advertised on many
1037** unix systems. The following procedure is an attempt to make
1038** it work better.
drh1398ad32005-01-19 23:24:50 +00001039**
1040** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1041** for testing when we want to run through the test suite quickly.
1042** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1043** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1044** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001045*/
drheb796a72005-09-08 12:38:41 +00001046static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001047 int rc;
drhb851b2c2005-03-10 14:11:12 +00001048
1049 /* Record the number of times that we do a normal fsync() and
1050 ** FULLSYNC. This is used during testing to verify that this procedure
1051 ** gets called with the correct arguments.
1052 */
1053#ifdef SQLITE_TEST
1054 if( fullSync ) sqlite3_fullsync_count++;
1055 sqlite3_sync_count++;
1056#endif
1057
1058 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1059 ** no-op
1060 */
1061#ifdef SQLITE_NO_SYNC
1062 rc = SQLITE_OK;
1063#else
1064
drhac530b12006-02-11 01:25:50 +00001065#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001066 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001067 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +00001068 }else{
1069 rc = 1;
1070 }
1071 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +00001072 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +00001073
drhc035e6e2005-09-22 15:45:04 +00001074#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +00001075 if( dataOnly ){
1076 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001077 }else{
drheb796a72005-09-08 12:38:41 +00001078 rc = fsync(fd);
1079 }
drhf30cc942005-03-11 17:52:34 +00001080#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +00001081#endif /* defined(SQLITE_NO_SYNC) */
1082
drhdd809b02004-07-17 21:44:57 +00001083 return rc;
1084}
1085
1086/*
drhbbd42a62004-05-22 17:41:58 +00001087** Make sure all writes to a particular file are committed to disk.
1088**
drheb796a72005-09-08 12:38:41 +00001089** If dataOnly==0 then both the file itself and its metadata (file
1090** size, access time, etc) are synced. If dataOnly!=0 then only the
1091** file data is synced.
1092**
drhbbd42a62004-05-22 17:41:58 +00001093** Under Unix, also make sure that the directory entry for the file
1094** has been created by fsync-ing the directory that contains the file.
1095** If we do not do this and we encounter a power failure, the directory
1096** entry for the journal might not exist after we reboot. The next
1097** SQLite to access the file will not know that the journal exists (because
1098** the directory entry for the journal was never created) and the transaction
1099** will not roll back - possibly leading to database corruption.
1100*/
drh9c06c952005-11-26 00:25:00 +00001101static int unixSync(OsFile *id, int dataOnly){
drh59685932006-09-14 13:47:11 +00001102 int rc;
drh054889e2005-11-30 03:20:31 +00001103 unixFile *pFile = (unixFile*)id;
1104 assert( pFile );
drh054889e2005-11-30 03:20:31 +00001105 TRACE2("SYNC %-3d\n", pFile->h);
drh59685932006-09-14 13:47:11 +00001106 rc = full_fsync(pFile->h, pFile->fullSync, dataOnly);
1107 SimulateIOError( rc=1 );
1108 if( rc ){
drhbbd42a62004-05-22 17:41:58 +00001109 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001110 }
drh054889e2005-11-30 03:20:31 +00001111 if( pFile->dirfd>=0 ){
drhac530b12006-02-11 01:25:50 +00001112 TRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
1113 HAVE_FULLFSYNC, pFile->fullSync);
danielk1977d7c03f72005-11-25 10:38:22 +00001114#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001115 /* The directory sync is only attempted if full_fsync is
1116 ** turned off or unavailable. If a full_fsync occurred above,
1117 ** then the directory sync is superfluous.
1118 */
1119 if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
1120 /*
1121 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001122 ** errors when applied to directories on certain file systems.
1123 ** A failed directory sync is not a big deal. So it seems
1124 ** better to ignore the error. Ticket #1657
1125 */
1126 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001127 }
danielk1977d7c03f72005-11-25 10:38:22 +00001128#endif
drh054889e2005-11-30 03:20:31 +00001129 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1130 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001131 }
drha2854222004-06-17 19:04:17 +00001132 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001133}
1134
1135/*
danielk1977962398d2004-06-14 09:35:16 +00001136** Sync the directory zDirname. This is a no-op on operating systems other
1137** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001138**
1139** This is used to make sure the master journal file has truely been deleted
1140** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001141** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001142*/
drh66560ad2006-01-06 14:32:19 +00001143int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001144#ifdef SQLITE_DISABLE_DIRSYNC
1145 return SQLITE_OK;
1146#else
danielk1977962398d2004-06-14 09:35:16 +00001147 int fd;
1148 int r;
drh8e855772005-05-17 11:25:31 +00001149 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001150 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001151 if( fd<0 ){
1152 return SQLITE_CANTOPEN;
1153 }
1154 r = fsync(fd);
1155 close(fd);
drh59685932006-09-14 13:47:11 +00001156 SimulateIOError( r=1 );
1157 if( r ){
1158 return SQLITE_IOERR;
1159 }else{
1160 return SQLITE_OK;
1161 }
danielk1977d7c03f72005-11-25 10:38:22 +00001162#endif
danielk1977962398d2004-06-14 09:35:16 +00001163}
1164
1165/*
drhbbd42a62004-05-22 17:41:58 +00001166** Truncate an open file to a specified size
1167*/
drh9c06c952005-11-26 00:25:00 +00001168static int unixTruncate(OsFile *id, i64 nByte){
drh59685932006-09-14 13:47:11 +00001169 int rc;
drh9cbe6352005-11-29 03:13:21 +00001170 assert( id );
drh59685932006-09-14 13:47:11 +00001171 rc = ftruncate(((unixFile*)id)->h, nByte);
1172 SimulateIOError( rc=1 );
1173 if( rc ){
1174 return SQLITE_IOERR;
1175 }else{
1176 return SQLITE_OK;
1177 }
drhbbd42a62004-05-22 17:41:58 +00001178}
1179
1180/*
1181** Determine the current size of a file in bytes
1182*/
drh9c06c952005-11-26 00:25:00 +00001183static int unixFileSize(OsFile *id, i64 *pSize){
drh59685932006-09-14 13:47:11 +00001184 int rc;
drhbbd42a62004-05-22 17:41:58 +00001185 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001186 assert( id );
drh59685932006-09-14 13:47:11 +00001187 rc = fstat(((unixFile*)id)->h, &buf);
1188 SimulateIOError( rc=1 );
1189 if( rc!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001190 return SQLITE_IOERR;
1191 }
1192 *pSize = buf.st_size;
1193 return SQLITE_OK;
1194}
1195
danielk19779a1d0ab2004-06-01 14:09:28 +00001196/*
danielk197713adf8a2004-06-03 16:08:41 +00001197** This routine checks if there is a RESERVED lock held on the specified
1198** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001199** non-zero. If the file is unlocked or holds only SHARED locks, then
1200** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001201*/
drh9c06c952005-11-26 00:25:00 +00001202static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001203 int r = 0;
drh054889e2005-11-30 03:20:31 +00001204 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001205
drh054889e2005-11-30 03:20:31 +00001206 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001207 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001208
1209 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001210 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001211 r = 1;
1212 }
1213
drh2ac3ee92004-06-07 16:27:46 +00001214 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001215 */
1216 if( !r ){
1217 struct flock lock;
1218 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001219 lock.l_start = RESERVED_BYTE;
1220 lock.l_len = 1;
1221 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001222 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001223 if( lock.l_type!=F_UNLCK ){
1224 r = 1;
1225 }
1226 }
1227
drh66560ad2006-01-06 14:32:19 +00001228 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001229 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001230
1231 return r;
1232}
1233
1234/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001235** Lock the file with the lock specified by parameter locktype - one
1236** of the following:
1237**
drh2ac3ee92004-06-07 16:27:46 +00001238** (1) SHARED_LOCK
1239** (2) RESERVED_LOCK
1240** (3) PENDING_LOCK
1241** (4) EXCLUSIVE_LOCK
1242**
drhb3e04342004-06-08 00:47:47 +00001243** Sometimes when requesting one lock state, additional lock states
1244** are inserted in between. The locking might fail on one of the later
1245** transitions leaving the lock state different from what it started but
1246** still short of its goal. The following chart shows the allowed
1247** transitions and the inserted intermediate states:
1248**
1249** UNLOCKED -> SHARED
1250** SHARED -> RESERVED
1251** SHARED -> (PENDING) -> EXCLUSIVE
1252** RESERVED -> (PENDING) -> EXCLUSIVE
1253** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001254**
drha6abd042004-06-09 17:37:22 +00001255** This routine will only increase a lock. Use the sqlite3OsUnlock()
1256** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001257*/
drh9c06c952005-11-26 00:25:00 +00001258static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001259 /* The following describes the implementation of the various locks and
1260 ** lock transitions in terms of the POSIX advisory shared and exclusive
1261 ** lock primitives (called read-locks and write-locks below, to avoid
1262 ** confusion with SQLite lock names). The algorithms are complicated
1263 ** slightly in order to be compatible with windows systems simultaneously
1264 ** accessing the same database file, in case that is ever required.
1265 **
1266 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1267 ** byte', each single bytes at well known offsets, and the 'shared byte
1268 ** range', a range of 510 bytes at a well known offset.
1269 **
1270 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1271 ** byte'. If this is successful, a random byte from the 'shared byte
1272 ** range' is read-locked and the lock on the 'pending byte' released.
1273 **
danielk197790ba3bd2004-06-25 08:32:25 +00001274 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1275 ** A RESERVED lock is implemented by grabbing a write-lock on the
1276 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001277 **
1278 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001279 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1280 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1281 ** obtained, but existing SHARED locks are allowed to persist. A process
1282 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1283 ** This property is used by the algorithm for rolling back a journal file
1284 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001285 **
danielk197790ba3bd2004-06-25 08:32:25 +00001286 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1287 ** implemented by obtaining a write-lock on the entire 'shared byte
1288 ** range'. Since all other locks require a read-lock on one of the bytes
1289 ** within this range, this ensures that no other locks are held on the
1290 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001291 **
1292 ** The reason a single byte cannot be used instead of the 'shared byte
1293 ** range' is that some versions of windows do not support read-locks. By
1294 ** locking a random byte from a range, concurrent SHARED locks may exist
1295 ** even if the locking primitive used is always a write-lock.
1296 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001297 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001298 unixFile *pFile = (unixFile*)id;
1299 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001300 struct flock lock;
1301 int s;
1302
drh054889e2005-11-30 03:20:31 +00001303 assert( pFile );
1304 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1305 locktypeName(locktype), locktypeName(pFile->locktype),
1306 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001307
1308 /* If there is already a lock of this type or more restrictive on the
1309 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001310 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001311 */
drh054889e2005-11-30 03:20:31 +00001312 if( pFile->locktype>=locktype ){
1313 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1314 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001315 return SQLITE_OK;
1316 }
1317
drhb3e04342004-06-08 00:47:47 +00001318 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001319 */
drh054889e2005-11-30 03:20:31 +00001320 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001321 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001322 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001323
drh054889e2005-11-30 03:20:31 +00001324 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001325 */
drh66560ad2006-01-06 14:32:19 +00001326 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001327
drh029b44b2006-01-15 00:13:15 +00001328 /* Make sure the current thread owns the pFile.
1329 */
1330 rc = transferOwnership(pFile);
1331 if( rc!=SQLITE_OK ){
1332 sqlite3OsLeaveMutex();
1333 return rc;
1334 }
drh64b1bea2006-01-15 02:30:57 +00001335 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001336
danielk19779a1d0ab2004-06-01 14:09:28 +00001337 /* If some thread using this PID has a lock via a different OsFile*
1338 ** handle that precludes the requested lock, return BUSY.
1339 */
drh054889e2005-11-30 03:20:31 +00001340 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001341 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001342 ){
1343 rc = SQLITE_BUSY;
1344 goto end_lock;
1345 }
1346
1347 /* If a SHARED lock is requested, and some thread using this PID already
1348 ** has a SHARED or RESERVED lock, then increment reference counts and
1349 ** return SQLITE_OK.
1350 */
1351 if( locktype==SHARED_LOCK &&
1352 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1353 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001354 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001355 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001356 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001357 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001358 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001359 goto end_lock;
1360 }
1361
danielk197713adf8a2004-06-03 16:08:41 +00001362 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001363
danielk19779a1d0ab2004-06-01 14:09:28 +00001364 lock.l_whence = SEEK_SET;
1365
drh3cde3bb2004-06-12 02:17:14 +00001366 /* A PENDING lock is needed before acquiring a SHARED lock and before
1367 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1368 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001369 */
drh3cde3bb2004-06-12 02:17:14 +00001370 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001371 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001372 ){
danielk1977489468c2004-06-28 08:25:47 +00001373 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001374 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001375 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001376 if( s ){
1377 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1378 goto end_lock;
1379 }
drh3cde3bb2004-06-12 02:17:14 +00001380 }
1381
1382
1383 /* If control gets to this point, then actually go ahead and make
1384 ** operating system calls for the specified lock.
1385 */
1386 if( locktype==SHARED_LOCK ){
1387 assert( pLock->cnt==0 );
1388 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001389
drh2ac3ee92004-06-07 16:27:46 +00001390 /* Now get the read-lock */
1391 lock.l_start = SHARED_FIRST;
1392 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001393 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001394
1395 /* Drop the temporary PENDING lock */
1396 lock.l_start = PENDING_BYTE;
1397 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001398 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001399 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001400 rc = SQLITE_IOERR; /* This should never happen */
1401 goto end_lock;
1402 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001403 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001404 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1405 }else{
drh054889e2005-11-30 03:20:31 +00001406 pFile->locktype = SHARED_LOCK;
1407 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001408 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001409 }
drh3cde3bb2004-06-12 02:17:14 +00001410 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1411 /* We are trying for an exclusive lock but another thread in this
1412 ** same process is still holding a shared lock. */
1413 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001414 }else{
drh3cde3bb2004-06-12 02:17:14 +00001415 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001416 ** assumed that there is a SHARED or greater lock on the file
1417 ** already.
1418 */
drh054889e2005-11-30 03:20:31 +00001419 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001420 lock.l_type = F_WRLCK;
1421 switch( locktype ){
1422 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001423 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001424 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001425 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001426 lock.l_start = SHARED_FIRST;
1427 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001428 break;
1429 default:
1430 assert(0);
1431 }
drh054889e2005-11-30 03:20:31 +00001432 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001433 if( s ){
1434 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1435 }
drhbbd42a62004-05-22 17:41:58 +00001436 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001437
danielk1977ecb2a962004-06-02 06:30:16 +00001438 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001439 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001440 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001441 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001442 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001443 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001444 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001445
1446end_lock:
drh66560ad2006-01-06 14:32:19 +00001447 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001448 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001449 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001450 return rc;
1451}
1452
1453/*
drh054889e2005-11-30 03:20:31 +00001454** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001455** must be either NO_LOCK or SHARED_LOCK.
1456**
1457** If the locking level of the file descriptor is already at or below
1458** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001459*/
drh9c06c952005-11-26 00:25:00 +00001460static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001461 struct lockInfo *pLock;
1462 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001463 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001464 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001465
drh054889e2005-11-30 03:20:31 +00001466 assert( pFile );
1467 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1468 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001469
1470 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001471 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001472 return SQLITE_OK;
1473 }
drhf1a221e2006-01-15 17:27:17 +00001474 if( CHECK_THREADID(pFile) ){
1475 return SQLITE_MISUSE;
1476 }
drh66560ad2006-01-06 14:32:19 +00001477 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001478 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001479 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001480 if( pFile->locktype>SHARED_LOCK ){
1481 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001482 if( locktype==SHARED_LOCK ){
1483 lock.l_type = F_RDLCK;
1484 lock.l_whence = SEEK_SET;
1485 lock.l_start = SHARED_FIRST;
1486 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001487 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001488 /* This should never happen */
1489 rc = SQLITE_IOERR;
1490 }
1491 }
drhbbd42a62004-05-22 17:41:58 +00001492 lock.l_type = F_UNLCK;
1493 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001494 lock.l_start = PENDING_BYTE;
1495 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001496 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001497 pLock->locktype = SHARED_LOCK;
1498 }else{
1499 rc = SQLITE_IOERR; /* This should never happen */
1500 }
drhbbd42a62004-05-22 17:41:58 +00001501 }
drha6abd042004-06-09 17:37:22 +00001502 if( locktype==NO_LOCK ){
1503 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001504
drha6abd042004-06-09 17:37:22 +00001505 /* Decrement the shared lock counter. Release the lock using an
1506 ** OS call only when all threads in this same process have released
1507 ** the lock.
1508 */
1509 pLock->cnt--;
1510 if( pLock->cnt==0 ){
1511 lock.l_type = F_UNLCK;
1512 lock.l_whence = SEEK_SET;
1513 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001514 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001515 pLock->locktype = NO_LOCK;
1516 }else{
1517 rc = SQLITE_IOERR; /* This should never happen */
1518 }
drha6abd042004-06-09 17:37:22 +00001519 }
1520
drhbbd42a62004-05-22 17:41:58 +00001521 /* Decrement the count of locks against this same file. When the
1522 ** count reaches zero, close any other file descriptors whose close
1523 ** was deferred because of outstanding locks.
1524 */
drh054889e2005-11-30 03:20:31 +00001525 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001526 pOpen->nLock--;
1527 assert( pOpen->nLock>=0 );
1528 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1529 int i;
1530 for(i=0; i<pOpen->nPending; i++){
1531 close(pOpen->aPending[i]);
1532 }
drh64b1bea2006-01-15 02:30:57 +00001533 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001534 pOpen->nPending = 0;
1535 pOpen->aPending = 0;
1536 }
1537 }
drh66560ad2006-01-06 14:32:19 +00001538 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001539 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001540 return rc;
drhbbd42a62004-05-22 17:41:58 +00001541}
1542
1543/*
danielk1977e3026632004-06-22 11:29:02 +00001544** Close a file.
1545*/
drh9cbe6352005-11-29 03:13:21 +00001546static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001547 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001548
drh9cbe6352005-11-29 03:13:21 +00001549 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001550 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001551 if( id->dirfd>=0 ) close(id->dirfd);
1552 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001553 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001554
drh38322302006-01-15 02:43:16 +00001555 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001556 /* If there are outstanding locks, do not actually close the file just
1557 ** yet because that would clear those locks. Instead, add the file
1558 ** descriptor to pOpen->aPending. It will be automatically closed when
1559 ** the last lock is cleared.
1560 */
1561 int *aNew;
1562 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001563 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001564 if( aNew==0 ){
1565 /* If a malloc fails, just leak the file descriptor */
1566 }else{
1567 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001568 pOpen->aPending[pOpen->nPending] = id->h;
1569 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001570 }
1571 }else{
1572 /* There are no outstanding locks so we can close the file immediately */
1573 close(id->h);
1574 }
1575 releaseLockInfo(id->pLock);
1576 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001577
drh66560ad2006-01-06 14:32:19 +00001578 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001579 id->isOpen = 0;
1580 TRACE2("CLOSE %-3d\n", id->h);
1581 OpenCounter(-1);
danielk1977750b03e2006-02-14 10:48:39 +00001582 sqlite3ThreadSafeFree(id);
drh9cbe6352005-11-29 03:13:21 +00001583 *pId = 0;
drh02afc862006-01-20 18:10:57 +00001584 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001585}
1586
1587/*
drh0ccebe72005-06-07 22:22:50 +00001588** Turn a relative pathname into a full pathname. Return a pointer
1589** to the full pathname stored in space obtained from sqliteMalloc().
1590** The calling function is responsible for freeing this space once it
1591** is no longer needed.
1592*/
drh66560ad2006-01-06 14:32:19 +00001593char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001594 char *zFull = 0;
1595 if( zRelative[0]=='/' ){
1596 sqlite3SetString(&zFull, zRelative, (char*)0);
1597 }else{
drh79158e12005-09-06 21:40:45 +00001598 char *zBuf = sqliteMalloc(5000);
1599 if( zBuf==0 ){
1600 return 0;
1601 }
drh0ccebe72005-06-07 22:22:50 +00001602 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001603 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001604 (char*)0);
drh79158e12005-09-06 21:40:45 +00001605 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001606 }
drh4eb9a972006-02-13 18:42:21 +00001607
1608#if 0
drh89ea9312006-02-13 17:03:47 +00001609 /*
1610 ** Remove "/./" path elements and convert "/A/./" path elements
1611 ** to just "/".
1612 */
1613 if( zFull ){
drh4eb9a972006-02-13 18:42:21 +00001614 int i, j;
drh89ea9312006-02-13 17:03:47 +00001615 for(i=j=0; zFull[i]; i++){
1616 if( zFull[i]=='/' ){
1617 if( zFull[i+1]=='/' ) continue;
1618 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
1619 i += 1;
1620 continue;
1621 }
1622 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
1623 while( j>0 && zFull[j-1]!='/' ){ j--; }
1624 i += 3;
1625 continue;
1626 }
1627 }
1628 zFull[j++] = zFull[i];
1629 }
1630 zFull[j] = 0;
1631 }
drh4eb9a972006-02-13 18:42:21 +00001632#endif
1633
drh0ccebe72005-06-07 22:22:50 +00001634 return zFull;
1635}
1636
drh18839212005-11-26 03:43:23 +00001637/*
drh9cbe6352005-11-29 03:13:21 +00001638** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001639*/
drh9cbe6352005-11-29 03:13:21 +00001640static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001641 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001642}
1643
1644/*
1645** Return the underlying file handle for an OsFile
1646*/
1647static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001648 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001649}
1650
1651/*
1652** Return an integer that indices the type of lock currently held
1653** by this handle. (Used for testing and analysis only.)
1654*/
1655static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001656 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001657}
drh0ccebe72005-06-07 22:22:50 +00001658
drh9c06c952005-11-26 00:25:00 +00001659/*
drh054889e2005-11-30 03:20:31 +00001660** This vector defines all the methods that can operate on an OsFile
1661** for unix.
drh9c06c952005-11-26 00:25:00 +00001662*/
drh054889e2005-11-30 03:20:31 +00001663static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001664 unixClose,
drh054889e2005-11-30 03:20:31 +00001665 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001666 unixRead,
1667 unixWrite,
1668 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001669 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001670 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001671 unixSetFullSync,
1672 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001673 unixFileSize,
1674 unixLock,
1675 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001676 unixLockState,
drh054889e2005-11-30 03:20:31 +00001677 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001678};
1679
drh054889e2005-11-30 03:20:31 +00001680/*
1681** Allocate memory for a unixFile. Initialize the new unixFile
1682** to the value given in pInit and return a pointer to the new
1683** OsFile. If we run out of memory, close the file and return NULL.
1684*/
1685static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1686 unixFile *pNew;
drh2f1a4d12006-01-23 16:24:54 +00001687 pInit->dirfd = -1;
1688 pInit->fullSync = 0;
1689 pInit->locktype = 0;
drhb912b282006-03-23 22:42:20 +00001690 pInit->offset = 0;
drh2f1a4d12006-01-23 16:24:54 +00001691 SET_THREADID(pInit);
danielk1977750b03e2006-02-14 10:48:39 +00001692 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00001693 if( pNew==0 ){
1694 close(pInit->h);
drh029b44b2006-01-15 00:13:15 +00001695 sqlite3OsEnterMutex();
danielk19772e588c72005-12-09 14:25:08 +00001696 releaseLockInfo(pInit->pLock);
1697 releaseOpenCnt(pInit->pOpen);
drh029b44b2006-01-15 00:13:15 +00001698 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001699 *pId = 0;
1700 return SQLITE_NOMEM;
1701 }else{
1702 *pNew = *pInit;
1703 pNew->pMethod = &sqlite3UnixIoMethod;
1704 *pId = (OsFile*)pNew;
1705 OpenCounter(+1);
1706 return SQLITE_OK;
1707 }
1708}
1709
drh9c06c952005-11-26 00:25:00 +00001710
drh0ccebe72005-06-07 22:22:50 +00001711#endif /* SQLITE_OMIT_DISKIO */
1712/***************************************************************************
1713** Everything above deals with file I/O. Everything that follows deals
1714** with other miscellanous aspects of the operating system interface
1715****************************************************************************/
1716
1717
1718/*
drhbbd42a62004-05-22 17:41:58 +00001719** Get information to seed the random number generator. The seed
1720** is written into the buffer zBuf[256]. The calling function must
1721** supply a sufficiently large buffer.
1722*/
drh66560ad2006-01-06 14:32:19 +00001723int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001724 /* We have to initialize zBuf to prevent valgrind from reporting
1725 ** errors. The reports issued by valgrind are incorrect - we would
1726 ** prefer that the randomness be increased by making use of the
1727 ** uninitialized space in zBuf - but valgrind errors tend to worry
1728 ** some users. Rather than argue, it seems easier just to initialize
1729 ** the whole array and silence valgrind, even if that means less randomness
1730 ** in the random seed.
1731 **
1732 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00001733 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00001734 ** tests repeatable.
1735 */
1736 memset(zBuf, 0, 256);
1737#if !defined(SQLITE_TEST)
1738 {
drh842b8642005-01-21 17:53:17 +00001739 int pid, fd;
1740 fd = open("/dev/urandom", O_RDONLY);
1741 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001742 time_t t;
1743 time(&t);
1744 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001745 pid = getpid();
1746 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1747 }else{
1748 read(fd, zBuf, 256);
1749 close(fd);
1750 }
drhbbd42a62004-05-22 17:41:58 +00001751 }
1752#endif
1753 return SQLITE_OK;
1754}
1755
1756/*
1757** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00001758** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00001759*/
drh66560ad2006-01-06 14:32:19 +00001760int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001761#if defined(HAVE_USLEEP) && HAVE_USLEEP
1762 usleep(ms*1000);
1763 return ms;
1764#else
1765 sleep((ms+999)/1000);
1766 return 1000*((ms+999)/1000);
1767#endif
1768}
1769
1770/*
drh5c111232006-02-10 04:33:12 +00001771** Static variables used for thread synchronization.
1772**
1773** inMutex the nesting depth of the recursive mutex. The thread
1774** holding mutexMain can read this variable at any time.
1775** But is must hold mutexAux to change this variable. Other
drh6a3d6702006-02-10 13:11:32 +00001776** threads must hold mutexAux to read the variable and can
1777** never write.
drh5c111232006-02-10 04:33:12 +00001778**
1779** mutexOwner The thread id of the thread holding mutexMain. Same
1780** access rules as for inMutex.
1781**
drh6a3d6702006-02-10 13:11:32 +00001782** mutexOwnerValid True if the value in mutexOwner is valid. The same
1783** access rules apply as for inMutex.
drh5c111232006-02-10 04:33:12 +00001784**
1785** mutexMain The main mutex. Hold this mutex in order to get exclusive
1786** access to SQLite data structures.
1787**
1788** mutexAux An auxiliary mutex needed to access variables defined above.
1789**
drh6a3d6702006-02-10 13:11:32 +00001790** Mutexes are always acquired in this order: mutexMain mutexAux. It
1791** is not necessary to acquire mutexMain in order to get mutexAux - just
1792** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
1793** Either get the mutexes with mutexMain first or get mutexAux only.
1794**
1795** When running on a platform where the three variables inMutex, mutexOwner,
1796** and mutexOwnerValid can be set atomically, the mutexAux is not required.
1797** On many systems, all three are 32-bit integers and writing to a 32-bit
1798** integer is atomic. I think. But there are no guarantees. So it seems
1799** safer to protect them using mutexAux.
drhbbd42a62004-05-22 17:41:58 +00001800*/
1801static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001802#ifdef SQLITE_UNIX_THREADS
drh6a3d6702006-02-10 13:11:32 +00001803static pthread_t mutexOwner; /* Thread holding mutexMain */
drh5c111232006-02-10 04:33:12 +00001804static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
1805static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
1806static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
drh79069752004-05-22 21:30:40 +00001807#endif
drhbbd42a62004-05-22 17:41:58 +00001808
1809/*
1810** The following pair of routine implement mutual exclusion for
1811** multi-threaded processes. Only a single thread is allowed to
1812** executed code that is surrounded by EnterMutex() and LeaveMutex().
1813**
1814** SQLite uses only a single Mutex. There is not much critical
1815** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00001816**
drh757b04e2006-01-18 17:25:45 +00001817** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00001818*/
drh66560ad2006-01-06 14:32:19 +00001819void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001820#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001821 pthread_mutex_lock(&mutexAux);
1822 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
1823 pthread_mutex_unlock(&mutexAux);
1824 pthread_mutex_lock(&mutexMain);
1825 assert( inMutex==0 );
1826 assert( !mutexOwnerValid );
1827 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001828 mutexOwner = pthread_self();
drh5c111232006-02-10 04:33:12 +00001829 mutexOwnerValid = 1;
drha3fad6f2006-01-18 14:06:37 +00001830 }
drha3fad6f2006-01-18 14:06:37 +00001831 inMutex++;
drh5c111232006-02-10 04:33:12 +00001832 pthread_mutex_unlock(&mutexAux);
1833#else
drhe9565a62006-02-11 02:03:52 +00001834 inMutex++;
drh5c111232006-02-10 04:33:12 +00001835#endif
drhbbd42a62004-05-22 17:41:58 +00001836}
drh66560ad2006-01-06 14:32:19 +00001837void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00001838 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00001839#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001840 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001841 inMutex--;
drh5c111232006-02-10 04:33:12 +00001842 assert( pthread_equal(mutexOwner, pthread_self()) );
drha3fad6f2006-01-18 14:06:37 +00001843 if( inMutex==0 ){
drh5c111232006-02-10 04:33:12 +00001844 assert( mutexOwnerValid );
1845 mutexOwnerValid = 0;
1846 pthread_mutex_unlock(&mutexMain);
drha3fad6f2006-01-18 14:06:37 +00001847 }
drh5c111232006-02-10 04:33:12 +00001848 pthread_mutex_unlock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001849#else
1850 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00001851#endif
1852}
1853
1854/*
drh757b04e2006-01-18 17:25:45 +00001855** Return TRUE if the mutex is currently held.
1856**
drh5c111232006-02-10 04:33:12 +00001857** If the thisThrd parameter is true, return true only if the
drh757b04e2006-01-18 17:25:45 +00001858** calling thread holds the mutex. If the parameter is false, return
1859** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00001860*/
drh5c111232006-02-10 04:33:12 +00001861int sqlite3UnixInMutex(int thisThrd){
drha3fad6f2006-01-18 14:06:37 +00001862#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001863 int rc;
1864 pthread_mutex_lock(&mutexAux);
1865 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
1866 pthread_mutex_unlock(&mutexAux);
1867 return rc;
drha3fad6f2006-01-18 14:06:37 +00001868#else
drh757b04e2006-01-18 17:25:45 +00001869 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00001870#endif
drh88f474a2006-01-02 20:00:12 +00001871}
1872
1873/*
drhb4bc7052006-01-11 23:40:33 +00001874** Remember the number of thread-specific-data blocks allocated.
1875** Use this to verify that we are not leaking thread-specific-data.
1876** Ticket #1601
1877*/
1878#ifdef SQLITE_TEST
1879int sqlite3_tsd_count = 0;
1880# ifdef SQLITE_UNIX_THREADS
1881 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
1882# define TSD_COUNTER(N) \
1883 pthread_mutex_lock(&tsd_counter_mutex); \
1884 sqlite3_tsd_count += N; \
1885 pthread_mutex_unlock(&tsd_counter_mutex);
1886# else
1887# define TSD_COUNTER(N) sqlite3_tsd_count += N
1888# endif
1889#else
1890# define TSD_COUNTER(N) /* no-op */
1891#endif
1892
drhb4bc7052006-01-11 23:40:33 +00001893/*
drhf1a221e2006-01-15 17:27:17 +00001894** If called with allocateFlag>0, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00001895** specific data for the current thread. Allocate and zero the
drhf1a221e2006-01-15 17:27:17 +00001896** thread-specific data if it does not already exist.
danielk197713a68c32005-12-15 10:11:30 +00001897**
drh6f7adc82006-01-11 21:41:20 +00001898** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00001899** specific data. Return it if it exists. If it does not exist,
1900** then return NULL.
1901**
1902** If called with allocateFlag<0, check to see if the thread specific
1903** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00001904** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00001905** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00001906*/
drh6f7adc82006-01-11 21:41:20 +00001907ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
danielk19774d5238f2006-01-27 06:32:00 +00001908 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
1909 ** from broken compilers */
danielk197713a68c32005-12-15 10:11:30 +00001910#ifdef SQLITE_UNIX_THREADS
1911 static pthread_key_t key;
1912 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001913 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001914
1915 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001916 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001917 if( !keyInit ){
1918 int rc;
drh6f7adc82006-01-11 21:41:20 +00001919 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001920 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001921 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001922 return 0;
1923 }
1924 keyInit = 1;
1925 }
drh66560ad2006-01-06 14:32:19 +00001926 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001927 }
1928
drh3fbb0b12006-01-06 00:36:00 +00001929 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00001930 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001931 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001932 if( !sqlite3TestMallocFail() ){
1933 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1934 }
1935#ifdef SQLITE_MEMDEBUG
1936 sqlite3_isFail = 0;
1937#endif
drh6f7adc82006-01-11 21:41:20 +00001938 if( pTsd ){
1939 *pTsd = zeroData;
1940 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00001941 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001942 }
danielk197713a68c32005-12-15 10:11:30 +00001943 }
drh70ff98a2006-01-12 01:25:18 +00001944 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001945 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001946 sqlite3OsFree(pTsd);
1947 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00001948 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001949 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001950 }
1951 return pTsd;
1952#else
drh6f7adc82006-01-11 21:41:20 +00001953 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00001954 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001955 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001956 if( !sqlite3TestMallocFail() ){
1957 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1958 }
1959#ifdef SQLITE_MEMDEBUG
1960 sqlite3_isFail = 0;
1961#endif
drh6f7adc82006-01-11 21:41:20 +00001962 if( pTsd ){
1963 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00001964 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001965 }
drh3fbb0b12006-01-06 00:36:00 +00001966 }
drh70ff98a2006-01-12 01:25:18 +00001967 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001968 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001969 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00001970 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001971 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001972 }
drh3fbb0b12006-01-06 00:36:00 +00001973 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001974#endif
1975}
1976
1977/*
drhbbd42a62004-05-22 17:41:58 +00001978** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001979** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001980*/
1981#ifdef SQLITE_TEST
1982int sqlite3_current_time = 0;
1983#endif
1984
1985/*
1986** Find the current time (in Universal Coordinated Time). Write the
1987** current time and date as a Julian Day number into *prNow and
1988** return 0. Return 1 if the time and date cannot be found.
1989*/
drh66560ad2006-01-06 14:32:19 +00001990int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001991#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001992 time_t t;
1993 time(&t);
1994 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001995#else
1996 struct timeval sNow;
1997 struct timezone sTz; /* Not used */
1998 gettimeofday(&sNow, &sTz);
1999 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
2000#endif
drhbbd42a62004-05-22 17:41:58 +00002001#ifdef SQLITE_TEST
2002 if( sqlite3_current_time ){
2003 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
2004 }
2005#endif
2006 return 0;
2007}
2008
drhbbd42a62004-05-22 17:41:58 +00002009#endif /* OS_UNIX */