blob: c61efb81e6d4569e4a3a0a9187cf05aa6b207ce5 [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*/
danielk1977750b03e2006-02-14 10:48:39 +0000343static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0,
344 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
345static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0,
346 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
drh5fdae772004-06-29 03:29:00 +0000347
348#ifdef SQLITE_UNIX_THREADS
349/*
350** This variable records whether or not threads can override each others
351** locks.
352**
353** 0: No. Threads cannot override each others locks.
354** 1: Yes. Threads can override each others locks.
355** -1: We don't know yet.
drhf1a221e2006-01-15 17:27:17 +0000356**
drh5062d3a2006-01-31 23:03:35 +0000357** On some systems, we know at compile-time if threads can override each
358** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
359** will be set appropriately. On other systems, we have to check at
360** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
361** undefined.
362**
drhf1a221e2006-01-15 17:27:17 +0000363** This variable normally has file scope only. But during testing, we make
364** it a global so that the test code can change its value in order to verify
365** that the right stuff happens in either case.
drh5fdae772004-06-29 03:29:00 +0000366*/
drh5062d3a2006-01-31 23:03:35 +0000367#ifndef SQLITE_THREAD_OVERRIDE_LOCK
368# define SQLITE_THREAD_OVERRIDE_LOCK -1
369#endif
drh029b44b2006-01-15 00:13:15 +0000370#ifdef SQLITE_TEST
drh5062d3a2006-01-31 23:03:35 +0000371int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000372#else
drh5062d3a2006-01-31 23:03:35 +0000373static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
drh029b44b2006-01-15 00:13:15 +0000374#endif
drh5fdae772004-06-29 03:29:00 +0000375
376/*
377** This structure holds information passed into individual test
378** threads by the testThreadLockingBehavior() routine.
379*/
380struct threadTestData {
381 int fd; /* File to be locked */
382 struct flock lock; /* The locking operation */
383 int result; /* Result of the locking operation */
384};
385
drh2b4b5962005-06-15 17:47:55 +0000386#ifdef SQLITE_LOCK_TRACE
387/*
388** Print out information about all locking operations.
389**
390** This routine is used for troubleshooting locks on multithreaded
391** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
392** command-line option on the compiler. This code is normally
drhf1a221e2006-01-15 17:27:17 +0000393** turned off.
drh2b4b5962005-06-15 17:47:55 +0000394*/
395static int lockTrace(int fd, int op, struct flock *p){
396 char *zOpName, *zType;
397 int s;
398 int savedErrno;
399 if( op==F_GETLK ){
400 zOpName = "GETLK";
401 }else if( op==F_SETLK ){
402 zOpName = "SETLK";
403 }else{
404 s = fcntl(fd, op, p);
405 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
406 return s;
407 }
408 if( p->l_type==F_RDLCK ){
409 zType = "RDLCK";
410 }else if( p->l_type==F_WRLCK ){
411 zType = "WRLCK";
412 }else if( p->l_type==F_UNLCK ){
413 zType = "UNLCK";
414 }else{
415 assert( 0 );
416 }
417 assert( p->l_whence==SEEK_SET );
418 s = fcntl(fd, op, p);
419 savedErrno = errno;
420 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
421 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
422 (int)p->l_pid, s);
423 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
424 struct flock l2;
425 l2 = *p;
426 fcntl(fd, F_GETLK, &l2);
427 if( l2.l_type==F_RDLCK ){
428 zType = "RDLCK";
429 }else if( l2.l_type==F_WRLCK ){
430 zType = "WRLCK";
431 }else if( l2.l_type==F_UNLCK ){
432 zType = "UNLCK";
433 }else{
434 assert( 0 );
435 }
436 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
437 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
438 }
439 errno = savedErrno;
440 return s;
441}
442#define fcntl lockTrace
443#endif /* SQLITE_LOCK_TRACE */
444
drh5fdae772004-06-29 03:29:00 +0000445/*
446** The testThreadLockingBehavior() routine launches two separate
447** threads on this routine. This routine attempts to lock a file
448** descriptor then returns. The success or failure of that attempt
449** allows the testThreadLockingBehavior() procedure to determine
450** whether or not threads can override each others locks.
451*/
452static void *threadLockingTest(void *pArg){
453 struct threadTestData *pData = (struct threadTestData*)pArg;
454 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
455 return pArg;
456}
457
458/*
459** This procedure attempts to determine whether or not threads
460** can override each others locks then sets the
461** threadsOverrideEachOthersLocks variable appropriately.
462*/
danielk19774d5238f2006-01-27 06:32:00 +0000463static void testThreadLockingBehavior(int fd_orig){
drh5fdae772004-06-29 03:29:00 +0000464 int fd;
465 struct threadTestData d[2];
466 pthread_t t[2];
467
468 fd = dup(fd_orig);
469 if( fd<0 ) return;
470 memset(d, 0, sizeof(d));
471 d[0].fd = fd;
472 d[0].lock.l_type = F_RDLCK;
473 d[0].lock.l_len = 1;
474 d[0].lock.l_start = 0;
475 d[0].lock.l_whence = SEEK_SET;
476 d[1] = d[0];
477 d[1].lock.l_type = F_WRLCK;
478 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
479 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
480 pthread_join(t[0], 0);
481 pthread_join(t[1], 0);
482 close(fd);
483 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
484}
485#endif /* SQLITE_UNIX_THREADS */
486
drhbbd42a62004-05-22 17:41:58 +0000487/*
488** Release a lockInfo structure previously allocated by findLockInfo().
489*/
490static void releaseLockInfo(struct lockInfo *pLock){
drh757b04e2006-01-18 17:25:45 +0000491 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000492 pLock->nRef--;
493 if( pLock->nRef==0 ){
494 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
danielk1977750b03e2006-02-14 10:48:39 +0000495 sqlite3ThreadSafeFree(pLock);
drhbbd42a62004-05-22 17:41:58 +0000496 }
497}
498
499/*
500** Release a openCnt structure previously allocated by findLockInfo().
501*/
502static void releaseOpenCnt(struct openCnt *pOpen){
drh757b04e2006-01-18 17:25:45 +0000503 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000504 pOpen->nRef--;
505 if( pOpen->nRef==0 ){
506 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
drh64b1bea2006-01-15 02:30:57 +0000507 free(pOpen->aPending);
danielk1977750b03e2006-02-14 10:48:39 +0000508 sqlite3ThreadSafeFree(pOpen);
drhbbd42a62004-05-22 17:41:58 +0000509 }
510}
511
512/*
513** Given a file descriptor, locate lockInfo and openCnt structures that
drh029b44b2006-01-15 00:13:15 +0000514** describes that file descriptor. Create new ones if necessary. The
515** return values might be uninitialized if an error occurs.
drhbbd42a62004-05-22 17:41:58 +0000516**
517** Return the number of errors.
518*/
drh38f82712004-06-18 17:10:16 +0000519static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000520 int fd, /* The file descriptor used in the key */
521 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000522 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000523){
524 int rc;
525 struct lockKey key1;
526 struct openKey key2;
527 struct stat statbuf;
528 struct lockInfo *pLock;
529 struct openCnt *pOpen;
530 rc = fstat(fd, &statbuf);
531 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000532
drh757b04e2006-01-18 17:25:45 +0000533 assert( sqlite3OsInMutex(1) );
drhbbd42a62004-05-22 17:41:58 +0000534 memset(&key1, 0, sizeof(key1));
535 key1.dev = statbuf.st_dev;
536 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000537#ifdef SQLITE_UNIX_THREADS
538 if( threadsOverrideEachOthersLocks<0 ){
539 testThreadLockingBehavior(fd);
540 }
541 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
542#endif
drhbbd42a62004-05-22 17:41:58 +0000543 memset(&key2, 0, sizeof(key2));
544 key2.dev = statbuf.st_dev;
545 key2.ino = statbuf.st_ino;
546 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
547 if( pLock==0 ){
548 struct lockInfo *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000549 pLock = sqlite3ThreadSafeMalloc( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000550 if( pLock==0 ){
551 rc = 1;
552 goto exit_findlockinfo;
553 }
drhbbd42a62004-05-22 17:41:58 +0000554 pLock->key = key1;
555 pLock->nRef = 1;
556 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000557 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000558 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
559 if( pOld!=0 ){
560 assert( pOld==pLock );
danielk1977750b03e2006-02-14 10:48:39 +0000561 sqlite3ThreadSafeFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000562 rc = 1;
563 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000564 }
565 }else{
566 pLock->nRef++;
567 }
568 *ppLock = pLock;
drh029b44b2006-01-15 00:13:15 +0000569 if( ppOpen!=0 ){
570 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
drhbbd42a62004-05-22 17:41:58 +0000571 if( pOpen==0 ){
drh029b44b2006-01-15 00:13:15 +0000572 struct openCnt *pOld;
danielk1977750b03e2006-02-14 10:48:39 +0000573 pOpen = sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
drh029b44b2006-01-15 00:13:15 +0000574 if( pOpen==0 ){
575 releaseLockInfo(pLock);
576 rc = 1;
577 goto exit_findlockinfo;
578 }
579 pOpen->key = key2;
580 pOpen->nRef = 1;
581 pOpen->nLock = 0;
582 pOpen->nPending = 0;
583 pOpen->aPending = 0;
584 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
585 if( pOld!=0 ){
586 assert( pOld==pOpen );
danielk1977750b03e2006-02-14 10:48:39 +0000587 sqlite3ThreadSafeFree(pOpen);
drh029b44b2006-01-15 00:13:15 +0000588 releaseLockInfo(pLock);
589 rc = 1;
590 goto exit_findlockinfo;
591 }
592 }else{
593 pOpen->nRef++;
drhbbd42a62004-05-22 17:41:58 +0000594 }
drh029b44b2006-01-15 00:13:15 +0000595 *ppOpen = pOpen;
drhbbd42a62004-05-22 17:41:58 +0000596 }
danielk1977441b09a2006-01-05 13:48:29 +0000597
598exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000599 return rc;
drhbbd42a62004-05-22 17:41:58 +0000600}
601
drh64b1bea2006-01-15 02:30:57 +0000602#ifdef SQLITE_DEBUG
603/*
604** Helper function for printing out trace information from debugging
605** binaries. This returns the string represetation of the supplied
606** integer lock-type.
607*/
608static const char *locktypeName(int locktype){
609 switch( locktype ){
610 case NO_LOCK: return "NONE";
611 case SHARED_LOCK: return "SHARED";
612 case RESERVED_LOCK: return "RESERVED";
613 case PENDING_LOCK: return "PENDING";
614 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
615 }
616 return "ERROR";
617}
618#endif
619
drhbbd42a62004-05-22 17:41:58 +0000620/*
drh029b44b2006-01-15 00:13:15 +0000621** If we are currently in a different thread than the thread that the
622** unixFile argument belongs to, then transfer ownership of the unixFile
623** over to the current thread.
624**
625** A unixFile is only owned by a thread on systems where one thread is
626** unable to override locks created by a different thread. RedHat9 is
627** an example of such a system.
628**
629** Ownership transfer is only allowed if the unixFile is currently unlocked.
630** If the unixFile is locked and an ownership is wrong, then return
drhf1a221e2006-01-15 17:27:17 +0000631** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
drh029b44b2006-01-15 00:13:15 +0000632*/
633#ifdef SQLITE_UNIX_THREADS
634static int transferOwnership(unixFile *pFile){
drh64b1bea2006-01-15 02:30:57 +0000635 int rc;
drh029b44b2006-01-15 00:13:15 +0000636 pthread_t hSelf;
637 if( threadsOverrideEachOthersLocks ){
638 /* Ownership transfers not needed on this system */
639 return SQLITE_OK;
640 }
641 hSelf = pthread_self();
642 if( pthread_equal(pFile->tid, hSelf) ){
643 /* We are still in the same thread */
drh64b1bea2006-01-15 02:30:57 +0000644 TRACE1("No-transfer, same thread\n");
drh029b44b2006-01-15 00:13:15 +0000645 return SQLITE_OK;
646 }
647 if( pFile->locktype!=NO_LOCK ){
648 /* We cannot change ownership while we are holding a lock! */
649 return SQLITE_MISUSE;
650 }
drh64b1bea2006-01-15 02:30:57 +0000651 TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
drh029b44b2006-01-15 00:13:15 +0000652 pFile->tid = hSelf;
653 releaseLockInfo(pFile->pLock);
drh64b1bea2006-01-15 02:30:57 +0000654 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
655 TRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
656 locktypeName(pFile->locktype),
657 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
658 return rc;
drh029b44b2006-01-15 00:13:15 +0000659}
660#else
drhf1a221e2006-01-15 17:27:17 +0000661 /* On single-threaded builds, ownership transfer is a no-op */
drh029b44b2006-01-15 00:13:15 +0000662# define transferOwnership(X) SQLITE_OK
663#endif
664
665/*
drhbbd42a62004-05-22 17:41:58 +0000666** Delete the named file
667*/
drh66560ad2006-01-06 14:32:19 +0000668int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000669 unlink(zFilename);
670 return SQLITE_OK;
671}
672
673/*
674** Return TRUE if the named file exists.
675*/
drh66560ad2006-01-06 14:32:19 +0000676int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000677 return access(zFilename, 0)==0;
678}
679
drh054889e2005-11-30 03:20:31 +0000680/* Forward declaration */
681static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000682
683/*
drhbbd42a62004-05-22 17:41:58 +0000684** Attempt to open a file for both reading and writing. If that
685** fails, try opening it read-only. If the file does not exist,
686** try to create it.
687**
688** On success, a handle for the open file is written to *id
689** and *pReadonly is set to 0 if the file was opened for reading and
690** writing or 1 if the file was opened read-only. The function returns
691** SQLITE_OK.
692**
693** On failure, the function returns SQLITE_CANTOPEN and leaves
694** *id and *pReadonly unchanged.
695*/
drh66560ad2006-01-06 14:32:19 +0000696int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000697 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000698 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000699 int *pReadonly
700){
701 int rc;
drh054889e2005-11-30 03:20:31 +0000702 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000703
drh66560ad2006-01-06 14:32:19 +0000704 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000705 assert( 0==*pId );
drh9cbe6352005-11-29 03:13:21 +0000706 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000707 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000708 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000709#ifdef EISDIR
710 if( errno==EISDIR ){
711 return SQLITE_CANTOPEN;
712 }
713#endif
drh9cbe6352005-11-29 03:13:21 +0000714 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
715 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000716 return SQLITE_CANTOPEN;
717 }
718 *pReadonly = 1;
719 }else{
720 *pReadonly = 0;
721 }
drh66560ad2006-01-06 14:32:19 +0000722 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000723 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000724 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000725 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000726 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000727 return SQLITE_NOMEM;
728 }
drh9cbe6352005-11-29 03:13:21 +0000729 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000730 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000731}
732
733
734/*
735** Attempt to open a new file for exclusive access by this process.
736** The file will be opened for both reading and writing. To avoid
737** a potential security problem, we do not allow the file to have
738** previously existed. Nor do we allow the file to be a symbolic
739** link.
740**
741** If delFlag is true, then make arrangements to automatically delete
742** the file when it is closed.
743**
744** On success, write the file handle into *id and return SQLITE_OK.
745**
746** On failure, return SQLITE_CANTOPEN.
747*/
drh66560ad2006-01-06 14:32:19 +0000748int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000749 int rc;
drh054889e2005-11-30 03:20:31 +0000750 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000751
drh66560ad2006-01-06 14:32:19 +0000752 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000753 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000754 if( access(zFilename, 0)==0 ){
755 return SQLITE_CANTOPEN;
756 }
drh9cbe6352005-11-29 03:13:21 +0000757 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000758 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
759 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000760 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000761 return SQLITE_CANTOPEN;
762 }
drh66560ad2006-01-06 14:32:19 +0000763 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000764 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000765 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000766 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000767 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000768 unlink(zFilename);
769 return SQLITE_NOMEM;
770 }
drhbbd42a62004-05-22 17:41:58 +0000771 if( delFlag ){
772 unlink(zFilename);
773 }
drh9cbe6352005-11-29 03:13:21 +0000774 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000775 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000776}
777
778/*
779** Attempt to open a new file for read-only access.
780**
781** On success, write the file handle into *id and return SQLITE_OK.
782**
783** On failure, return SQLITE_CANTOPEN.
784*/
drh66560ad2006-01-06 14:32:19 +0000785int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000786 int rc;
drh054889e2005-11-30 03:20:31 +0000787 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000788
drh66560ad2006-01-06 14:32:19 +0000789 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000790 assert( 0==*pId );
drh9cbe6352005-11-29 03:13:21 +0000791 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
792 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000793 return SQLITE_CANTOPEN;
794 }
drh66560ad2006-01-06 14:32:19 +0000795 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000796 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000797 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000798 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000799 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000800 return SQLITE_NOMEM;
801 }
drh9cbe6352005-11-29 03:13:21 +0000802 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000803 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000804}
805
806/*
807** Attempt to open a file descriptor for the directory that contains a
808** file. This file descriptor can be used to fsync() the directory
809** in order to make sure the creation of a new file is actually written
810** to disk.
811**
812** This routine is only meaningful for Unix. It is a no-op under
813** windows since windows does not support hard links.
814**
drh9cbe6352005-11-29 03:13:21 +0000815** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000816** updated with the new directory file descriptor and SQLITE_OK is
817** returned.
818**
819** On failure, the function returns SQLITE_CANTOPEN and leaves
820** *id unchanged.
821*/
drh9c06c952005-11-26 00:25:00 +0000822static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000823 OsFile *id,
824 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000825){
drh054889e2005-11-30 03:20:31 +0000826 unixFile *pFile = (unixFile*)id;
827 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000828 /* Do not open the directory if the corresponding file is not already
829 ** open. */
830 return SQLITE_CANTOPEN;
831 }
drh054889e2005-11-30 03:20:31 +0000832 SET_THREADID(pFile);
833 assert( pFile->dirfd<0 );
834 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
835 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000836 return SQLITE_CANTOPEN;
837 }
drh054889e2005-11-30 03:20:31 +0000838 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000839 return SQLITE_OK;
840}
841
842/*
drhab3f9fe2004-08-14 17:10:10 +0000843** If the following global variable points to a string which is the
844** name of a directory, then that directory will be used to store
845** temporary files.
drhf1a221e2006-01-15 17:27:17 +0000846**
847** See also the "PRAGMA temp_store_directory" SQL command.
drhab3f9fe2004-08-14 17:10:10 +0000848*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000849char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000850
851/*
drhbbd42a62004-05-22 17:41:58 +0000852** Create a temporary file name in zBuf. zBuf must be big enough to
853** hold at least SQLITE_TEMPNAME_SIZE characters.
854*/
drh66560ad2006-01-06 14:32:19 +0000855int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000856 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000857 0,
drhbbd42a62004-05-22 17:41:58 +0000858 "/var/tmp",
859 "/usr/tmp",
860 "/tmp",
861 ".",
862 };
drh57196282004-10-06 15:41:16 +0000863 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000864 "abcdefghijklmnopqrstuvwxyz"
865 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
866 "0123456789";
867 int i, j;
868 struct stat buf;
869 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000870 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000871 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000872 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000873 if( stat(azDirs[i], &buf) ) continue;
874 if( !S_ISDIR(buf.st_mode) ) continue;
875 if( access(azDirs[i], 07) ) continue;
876 zDir = azDirs[i];
877 break;
878 }
879 do{
880 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
881 j = strlen(zBuf);
882 sqlite3Randomness(15, &zBuf[j]);
883 for(i=0; i<15; i++, j++){
884 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
885 }
886 zBuf[j] = 0;
887 }while( access(zBuf,0)==0 );
888 return SQLITE_OK;
889}
890
891/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000892** Check that a given pathname is a directory and is writable
893**
894*/
drh66560ad2006-01-06 14:32:19 +0000895int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000896#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000897 struct stat buf;
898 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000899 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000900 if( stat(zBuf, &buf) ) return 0;
901 if( !S_ISDIR(buf.st_mode) ) return 0;
902 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000903#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000904 return 1;
905}
906
907/*
drhbbd42a62004-05-22 17:41:58 +0000908** Read data from a file into a buffer. Return SQLITE_OK if all
909** bytes were read successfully and SQLITE_IOERR if anything goes
910** wrong.
911*/
drh9c06c952005-11-26 00:25:00 +0000912static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000913 int got;
drh9cbe6352005-11-29 03:13:21 +0000914 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000915 SimulateIOError(SQLITE_IOERR);
916 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000917 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000918 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000919 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
920 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000921 SEEK(0);
922 /* if( got<0 ) got = 0; */
923 if( got==amt ){
924 return SQLITE_OK;
925 }else{
926 return SQLITE_IOERR;
927 }
928}
929
930/*
931** Write data from a buffer into a file. Return SQLITE_OK on success
932** or some other error code on failure.
933*/
drh9c06c952005-11-26 00:25:00 +0000934static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000935 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000936 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000937 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000938 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000939 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000940 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000941 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000942 amt -= wrote;
943 pBuf = &((char*)pBuf)[wrote];
944 }
945 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000946 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
947 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000948 SEEK(0);
949 if( amt>0 ){
950 return SQLITE_FULL;
951 }
952 return SQLITE_OK;
953}
954
955/*
956** Move the read/write pointer in a file.
957*/
drh9c06c952005-11-26 00:25:00 +0000958static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000959 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000960 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000961#ifdef SQLITE_TEST
962 if( offset ) SimulateDiskfullError
963#endif
drh054889e2005-11-30 03:20:31 +0000964 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000965 return SQLITE_OK;
966}
967
drhb851b2c2005-03-10 14:11:12 +0000968#ifdef SQLITE_TEST
969/*
970** Count the number of fullsyncs and normal syncs. This is used to test
971** that syncs and fullsyncs are occuring at the right times.
972*/
973int sqlite3_sync_count = 0;
974int sqlite3_fullsync_count = 0;
975#endif
976
drhf2f23912005-10-05 10:29:36 +0000977/*
978** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
979** Otherwise use fsync() in its place.
980*/
981#ifndef HAVE_FDATASYNC
982# define fdatasync fsync
983#endif
984
drhac530b12006-02-11 01:25:50 +0000985/*
986** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
987** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
988** only available on Mac OS X. But that could change.
989*/
990#ifdef F_FULLFSYNC
991# define HAVE_FULLFSYNC 1
992#else
993# define HAVE_FULLFSYNC 0
994#endif
995
drhb851b2c2005-03-10 14:11:12 +0000996
drhbbd42a62004-05-22 17:41:58 +0000997/*
drhdd809b02004-07-17 21:44:57 +0000998** The fsync() system call does not work as advertised on many
999** unix systems. The following procedure is an attempt to make
1000** it work better.
drh1398ad32005-01-19 23:24:50 +00001001**
1002** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
1003** for testing when we want to run through the test suite quickly.
1004** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
1005** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
1006** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +00001007*/
drheb796a72005-09-08 12:38:41 +00001008static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +00001009 int rc;
drhb851b2c2005-03-10 14:11:12 +00001010
1011 /* Record the number of times that we do a normal fsync() and
1012 ** FULLSYNC. This is used during testing to verify that this procedure
1013 ** gets called with the correct arguments.
1014 */
1015#ifdef SQLITE_TEST
1016 if( fullSync ) sqlite3_fullsync_count++;
1017 sqlite3_sync_count++;
1018#endif
1019
1020 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
1021 ** no-op
1022 */
1023#ifdef SQLITE_NO_SYNC
1024 rc = SQLITE_OK;
1025#else
1026
drhac530b12006-02-11 01:25:50 +00001027#if HAVE_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +00001028 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +00001029 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +00001030 }else{
1031 rc = 1;
1032 }
1033 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +00001034 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +00001035
drhc035e6e2005-09-22 15:45:04 +00001036#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +00001037 if( dataOnly ){
1038 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +00001039 }else{
drheb796a72005-09-08 12:38:41 +00001040 rc = fsync(fd);
1041 }
drhf30cc942005-03-11 17:52:34 +00001042#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +00001043#endif /* defined(SQLITE_NO_SYNC) */
1044
drhdd809b02004-07-17 21:44:57 +00001045 return rc;
1046}
1047
1048/*
drhbbd42a62004-05-22 17:41:58 +00001049** Make sure all writes to a particular file are committed to disk.
1050**
drheb796a72005-09-08 12:38:41 +00001051** If dataOnly==0 then both the file itself and its metadata (file
1052** size, access time, etc) are synced. If dataOnly!=0 then only the
1053** file data is synced.
1054**
drhbbd42a62004-05-22 17:41:58 +00001055** Under Unix, also make sure that the directory entry for the file
1056** has been created by fsync-ing the directory that contains the file.
1057** If we do not do this and we encounter a power failure, the directory
1058** entry for the journal might not exist after we reboot. The next
1059** SQLite to access the file will not know that the journal exists (because
1060** the directory entry for the journal was never created) and the transaction
1061** will not roll back - possibly leading to database corruption.
1062*/
drh9c06c952005-11-26 00:25:00 +00001063static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +00001064 unixFile *pFile = (unixFile*)id;
1065 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +00001066 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001067 TRACE2("SYNC %-3d\n", pFile->h);
1068 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +00001069 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001070 }
drh054889e2005-11-30 03:20:31 +00001071 if( pFile->dirfd>=0 ){
drhac530b12006-02-11 01:25:50 +00001072 TRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
1073 HAVE_FULLFSYNC, pFile->fullSync);
danielk1977d7c03f72005-11-25 10:38:22 +00001074#ifndef SQLITE_DISABLE_DIRSYNC
drhac530b12006-02-11 01:25:50 +00001075 /* The directory sync is only attempted if full_fsync is
1076 ** turned off or unavailable. If a full_fsync occurred above,
1077 ** then the directory sync is superfluous.
1078 */
1079 if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
1080 /*
1081 ** We have received multiple reports of fsync() returning
drh86631a52006-02-09 23:05:51 +00001082 ** errors when applied to directories on certain file systems.
1083 ** A failed directory sync is not a big deal. So it seems
1084 ** better to ignore the error. Ticket #1657
1085 */
1086 /* return SQLITE_IOERR; */
danielk19770964b232005-11-25 08:47:57 +00001087 }
danielk1977d7c03f72005-11-25 10:38:22 +00001088#endif
drh054889e2005-11-30 03:20:31 +00001089 close(pFile->dirfd); /* Only need to sync once, so close the directory */
1090 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +00001091 }
drha2854222004-06-17 19:04:17 +00001092 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +00001093}
1094
1095/*
danielk1977962398d2004-06-14 09:35:16 +00001096** Sync the directory zDirname. This is a no-op on operating systems other
1097** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001098**
1099** This is used to make sure the master journal file has truely been deleted
1100** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001101** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001102*/
drh66560ad2006-01-06 14:32:19 +00001103int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001104#ifdef SQLITE_DISABLE_DIRSYNC
1105 return SQLITE_OK;
1106#else
danielk1977962398d2004-06-14 09:35:16 +00001107 int fd;
1108 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001109 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001110 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001111 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001112 if( fd<0 ){
1113 return SQLITE_CANTOPEN;
1114 }
1115 r = fsync(fd);
1116 close(fd);
1117 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001118#endif
danielk1977962398d2004-06-14 09:35:16 +00001119}
1120
1121/*
drhbbd42a62004-05-22 17:41:58 +00001122** Truncate an open file to a specified size
1123*/
drh9c06c952005-11-26 00:25:00 +00001124static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001125 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001126 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001127 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001128}
1129
1130/*
1131** Determine the current size of a file in bytes
1132*/
drh9c06c952005-11-26 00:25:00 +00001133static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001134 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001135 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001136 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001137 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001138 return SQLITE_IOERR;
1139 }
1140 *pSize = buf.st_size;
1141 return SQLITE_OK;
1142}
1143
danielk19779a1d0ab2004-06-01 14:09:28 +00001144/*
danielk197713adf8a2004-06-03 16:08:41 +00001145** This routine checks if there is a RESERVED lock held on the specified
1146** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001147** non-zero. If the file is unlocked or holds only SHARED locks, then
1148** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001149*/
drh9c06c952005-11-26 00:25:00 +00001150static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001151 int r = 0;
drh054889e2005-11-30 03:20:31 +00001152 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001153
drh054889e2005-11-30 03:20:31 +00001154 assert( pFile );
drh66560ad2006-01-06 14:32:19 +00001155 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001156
1157 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001158 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001159 r = 1;
1160 }
1161
drh2ac3ee92004-06-07 16:27:46 +00001162 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001163 */
1164 if( !r ){
1165 struct flock lock;
1166 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001167 lock.l_start = RESERVED_BYTE;
1168 lock.l_len = 1;
1169 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001170 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001171 if( lock.l_type!=F_UNLCK ){
1172 r = 1;
1173 }
1174 }
1175
drh66560ad2006-01-06 14:32:19 +00001176 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001177 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001178
1179 return r;
1180}
1181
1182/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001183** Lock the file with the lock specified by parameter locktype - one
1184** of the following:
1185**
drh2ac3ee92004-06-07 16:27:46 +00001186** (1) SHARED_LOCK
1187** (2) RESERVED_LOCK
1188** (3) PENDING_LOCK
1189** (4) EXCLUSIVE_LOCK
1190**
drhb3e04342004-06-08 00:47:47 +00001191** Sometimes when requesting one lock state, additional lock states
1192** are inserted in between. The locking might fail on one of the later
1193** transitions leaving the lock state different from what it started but
1194** still short of its goal. The following chart shows the allowed
1195** transitions and the inserted intermediate states:
1196**
1197** UNLOCKED -> SHARED
1198** SHARED -> RESERVED
1199** SHARED -> (PENDING) -> EXCLUSIVE
1200** RESERVED -> (PENDING) -> EXCLUSIVE
1201** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001202**
drha6abd042004-06-09 17:37:22 +00001203** This routine will only increase a lock. Use the sqlite3OsUnlock()
1204** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001205*/
drh9c06c952005-11-26 00:25:00 +00001206static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001207 /* The following describes the implementation of the various locks and
1208 ** lock transitions in terms of the POSIX advisory shared and exclusive
1209 ** lock primitives (called read-locks and write-locks below, to avoid
1210 ** confusion with SQLite lock names). The algorithms are complicated
1211 ** slightly in order to be compatible with windows systems simultaneously
1212 ** accessing the same database file, in case that is ever required.
1213 **
1214 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1215 ** byte', each single bytes at well known offsets, and the 'shared byte
1216 ** range', a range of 510 bytes at a well known offset.
1217 **
1218 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1219 ** byte'. If this is successful, a random byte from the 'shared byte
1220 ** range' is read-locked and the lock on the 'pending byte' released.
1221 **
danielk197790ba3bd2004-06-25 08:32:25 +00001222 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1223 ** A RESERVED lock is implemented by grabbing a write-lock on the
1224 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001225 **
1226 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001227 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1228 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1229 ** obtained, but existing SHARED locks are allowed to persist. A process
1230 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1231 ** This property is used by the algorithm for rolling back a journal file
1232 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001233 **
danielk197790ba3bd2004-06-25 08:32:25 +00001234 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1235 ** implemented by obtaining a write-lock on the entire 'shared byte
1236 ** range'. Since all other locks require a read-lock on one of the bytes
1237 ** within this range, this ensures that no other locks are held on the
1238 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001239 **
1240 ** The reason a single byte cannot be used instead of the 'shared byte
1241 ** range' is that some versions of windows do not support read-locks. By
1242 ** locking a random byte from a range, concurrent SHARED locks may exist
1243 ** even if the locking primitive used is always a write-lock.
1244 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001245 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001246 unixFile *pFile = (unixFile*)id;
1247 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001248 struct flock lock;
1249 int s;
1250
drh054889e2005-11-30 03:20:31 +00001251 assert( pFile );
1252 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1253 locktypeName(locktype), locktypeName(pFile->locktype),
1254 locktypeName(pLock->locktype), pLock->cnt , getpid());
danielk19779a1d0ab2004-06-01 14:09:28 +00001255
1256 /* If there is already a lock of this type or more restrictive on the
1257 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001258 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001259 */
drh054889e2005-11-30 03:20:31 +00001260 if( pFile->locktype>=locktype ){
1261 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1262 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001263 return SQLITE_OK;
1264 }
1265
drhb3e04342004-06-08 00:47:47 +00001266 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001267 */
drh054889e2005-11-30 03:20:31 +00001268 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001269 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001270 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001271
drh054889e2005-11-30 03:20:31 +00001272 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001273 */
drh66560ad2006-01-06 14:32:19 +00001274 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001275
drh029b44b2006-01-15 00:13:15 +00001276 /* Make sure the current thread owns the pFile.
1277 */
1278 rc = transferOwnership(pFile);
1279 if( rc!=SQLITE_OK ){
1280 sqlite3OsLeaveMutex();
1281 return rc;
1282 }
drh64b1bea2006-01-15 02:30:57 +00001283 pLock = pFile->pLock;
drh029b44b2006-01-15 00:13:15 +00001284
danielk19779a1d0ab2004-06-01 14:09:28 +00001285 /* If some thread using this PID has a lock via a different OsFile*
1286 ** handle that precludes the requested lock, return BUSY.
1287 */
drh054889e2005-11-30 03:20:31 +00001288 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001289 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001290 ){
1291 rc = SQLITE_BUSY;
1292 goto end_lock;
1293 }
1294
1295 /* If a SHARED lock is requested, and some thread using this PID already
1296 ** has a SHARED or RESERVED lock, then increment reference counts and
1297 ** return SQLITE_OK.
1298 */
1299 if( locktype==SHARED_LOCK &&
1300 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1301 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001302 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001303 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001304 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001305 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001306 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001307 goto end_lock;
1308 }
1309
danielk197713adf8a2004-06-03 16:08:41 +00001310 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001311
danielk19779a1d0ab2004-06-01 14:09:28 +00001312 lock.l_whence = SEEK_SET;
1313
drh3cde3bb2004-06-12 02:17:14 +00001314 /* A PENDING lock is needed before acquiring a SHARED lock and before
1315 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1316 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001317 */
drh3cde3bb2004-06-12 02:17:14 +00001318 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001319 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001320 ){
danielk1977489468c2004-06-28 08:25:47 +00001321 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001322 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001323 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001324 if( s ){
1325 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1326 goto end_lock;
1327 }
drh3cde3bb2004-06-12 02:17:14 +00001328 }
1329
1330
1331 /* If control gets to this point, then actually go ahead and make
1332 ** operating system calls for the specified lock.
1333 */
1334 if( locktype==SHARED_LOCK ){
1335 assert( pLock->cnt==0 );
1336 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001337
drh2ac3ee92004-06-07 16:27:46 +00001338 /* Now get the read-lock */
1339 lock.l_start = SHARED_FIRST;
1340 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001341 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001342
1343 /* Drop the temporary PENDING lock */
1344 lock.l_start = PENDING_BYTE;
1345 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001346 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001347 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001348 rc = SQLITE_IOERR; /* This should never happen */
1349 goto end_lock;
1350 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001351 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001352 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1353 }else{
drh054889e2005-11-30 03:20:31 +00001354 pFile->locktype = SHARED_LOCK;
1355 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001356 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001357 }
drh3cde3bb2004-06-12 02:17:14 +00001358 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1359 /* We are trying for an exclusive lock but another thread in this
1360 ** same process is still holding a shared lock. */
1361 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001362 }else{
drh3cde3bb2004-06-12 02:17:14 +00001363 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001364 ** assumed that there is a SHARED or greater lock on the file
1365 ** already.
1366 */
drh054889e2005-11-30 03:20:31 +00001367 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001368 lock.l_type = F_WRLCK;
1369 switch( locktype ){
1370 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001371 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001372 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001374 lock.l_start = SHARED_FIRST;
1375 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001376 break;
1377 default:
1378 assert(0);
1379 }
drh054889e2005-11-30 03:20:31 +00001380 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001381 if( s ){
1382 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1383 }
drhbbd42a62004-05-22 17:41:58 +00001384 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001385
danielk1977ecb2a962004-06-02 06:30:16 +00001386 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001387 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001388 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001389 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001390 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001391 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001392 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001393
1394end_lock:
drh66560ad2006-01-06 14:32:19 +00001395 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001396 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001397 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001398 return rc;
1399}
1400
1401/*
drh054889e2005-11-30 03:20:31 +00001402** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001403** must be either NO_LOCK or SHARED_LOCK.
1404**
1405** If the locking level of the file descriptor is already at or below
1406** the requested locking level, this routine is a no-op.
drhbbd42a62004-05-22 17:41:58 +00001407*/
drh9c06c952005-11-26 00:25:00 +00001408static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001409 struct lockInfo *pLock;
1410 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001411 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001412 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001413
drh054889e2005-11-30 03:20:31 +00001414 assert( pFile );
1415 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1416 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
drha6abd042004-06-09 17:37:22 +00001417
1418 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001419 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001420 return SQLITE_OK;
1421 }
drhf1a221e2006-01-15 17:27:17 +00001422 if( CHECK_THREADID(pFile) ){
1423 return SQLITE_MISUSE;
1424 }
drh66560ad2006-01-06 14:32:19 +00001425 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001426 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001427 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001428 if( pFile->locktype>SHARED_LOCK ){
1429 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001430 if( locktype==SHARED_LOCK ){
1431 lock.l_type = F_RDLCK;
1432 lock.l_whence = SEEK_SET;
1433 lock.l_start = SHARED_FIRST;
1434 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001435 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001436 /* This should never happen */
1437 rc = SQLITE_IOERR;
1438 }
1439 }
drhbbd42a62004-05-22 17:41:58 +00001440 lock.l_type = F_UNLCK;
1441 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001442 lock.l_start = PENDING_BYTE;
1443 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001444 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001445 pLock->locktype = SHARED_LOCK;
1446 }else{
1447 rc = SQLITE_IOERR; /* This should never happen */
1448 }
drhbbd42a62004-05-22 17:41:58 +00001449 }
drha6abd042004-06-09 17:37:22 +00001450 if( locktype==NO_LOCK ){
1451 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001452
drha6abd042004-06-09 17:37:22 +00001453 /* Decrement the shared lock counter. Release the lock using an
1454 ** OS call only when all threads in this same process have released
1455 ** the lock.
1456 */
1457 pLock->cnt--;
1458 if( pLock->cnt==0 ){
1459 lock.l_type = F_UNLCK;
1460 lock.l_whence = SEEK_SET;
1461 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001462 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001463 pLock->locktype = NO_LOCK;
1464 }else{
1465 rc = SQLITE_IOERR; /* This should never happen */
1466 }
drha6abd042004-06-09 17:37:22 +00001467 }
1468
drhbbd42a62004-05-22 17:41:58 +00001469 /* Decrement the count of locks against this same file. When the
1470 ** count reaches zero, close any other file descriptors whose close
1471 ** was deferred because of outstanding locks.
1472 */
drh054889e2005-11-30 03:20:31 +00001473 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001474 pOpen->nLock--;
1475 assert( pOpen->nLock>=0 );
1476 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1477 int i;
1478 for(i=0; i<pOpen->nPending; i++){
1479 close(pOpen->aPending[i]);
1480 }
drh64b1bea2006-01-15 02:30:57 +00001481 free(pOpen->aPending);
drhbbd42a62004-05-22 17:41:58 +00001482 pOpen->nPending = 0;
1483 pOpen->aPending = 0;
1484 }
1485 }
drh66560ad2006-01-06 14:32:19 +00001486 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001487 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001488 return rc;
drhbbd42a62004-05-22 17:41:58 +00001489}
1490
1491/*
danielk1977e3026632004-06-22 11:29:02 +00001492** Close a file.
1493*/
drh9cbe6352005-11-29 03:13:21 +00001494static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001495 unixFile *id = (unixFile*)*pId;
drh029b44b2006-01-15 00:13:15 +00001496
drh9cbe6352005-11-29 03:13:21 +00001497 if( !id ) return SQLITE_OK;
drh38322302006-01-15 02:43:16 +00001498 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001499 if( id->dirfd>=0 ) close(id->dirfd);
1500 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001501 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001502
drh38322302006-01-15 02:43:16 +00001503 if( id->pOpen->nLock ){
danielk1977e3026632004-06-22 11:29:02 +00001504 /* If there are outstanding locks, do not actually close the file just
1505 ** yet because that would clear those locks. Instead, add the file
1506 ** descriptor to pOpen->aPending. It will be automatically closed when
1507 ** the last lock is cleared.
1508 */
1509 int *aNew;
1510 struct openCnt *pOpen = id->pOpen;
drh64b1bea2006-01-15 02:30:57 +00001511 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001512 if( aNew==0 ){
1513 /* If a malloc fails, just leak the file descriptor */
1514 }else{
1515 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001516 pOpen->aPending[pOpen->nPending] = id->h;
1517 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001518 }
1519 }else{
1520 /* There are no outstanding locks so we can close the file immediately */
1521 close(id->h);
1522 }
1523 releaseLockInfo(id->pLock);
1524 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001525
drh66560ad2006-01-06 14:32:19 +00001526 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001527 id->isOpen = 0;
1528 TRACE2("CLOSE %-3d\n", id->h);
1529 OpenCounter(-1);
danielk1977750b03e2006-02-14 10:48:39 +00001530 sqlite3ThreadSafeFree(id);
drh9cbe6352005-11-29 03:13:21 +00001531 *pId = 0;
drh02afc862006-01-20 18:10:57 +00001532 return SQLITE_OK;
danielk1977e3026632004-06-22 11:29:02 +00001533}
1534
1535/*
drh0ccebe72005-06-07 22:22:50 +00001536** Turn a relative pathname into a full pathname. Return a pointer
1537** to the full pathname stored in space obtained from sqliteMalloc().
1538** The calling function is responsible for freeing this space once it
1539** is no longer needed.
1540*/
drh66560ad2006-01-06 14:32:19 +00001541char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001542 char *zFull = 0;
1543 if( zRelative[0]=='/' ){
1544 sqlite3SetString(&zFull, zRelative, (char*)0);
1545 }else{
drh79158e12005-09-06 21:40:45 +00001546 char *zBuf = sqliteMalloc(5000);
1547 if( zBuf==0 ){
1548 return 0;
1549 }
drh0ccebe72005-06-07 22:22:50 +00001550 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001551 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001552 (char*)0);
drh79158e12005-09-06 21:40:45 +00001553 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001554 }
drh4eb9a972006-02-13 18:42:21 +00001555
1556#if 0
drh89ea9312006-02-13 17:03:47 +00001557 /*
1558 ** Remove "/./" path elements and convert "/A/./" path elements
1559 ** to just "/".
1560 */
1561 if( zFull ){
drh4eb9a972006-02-13 18:42:21 +00001562 int i, j;
drh89ea9312006-02-13 17:03:47 +00001563 for(i=j=0; zFull[i]; i++){
1564 if( zFull[i]=='/' ){
1565 if( zFull[i+1]=='/' ) continue;
1566 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
1567 i += 1;
1568 continue;
1569 }
1570 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
1571 while( j>0 && zFull[j-1]!='/' ){ j--; }
1572 i += 3;
1573 continue;
1574 }
1575 }
1576 zFull[j++] = zFull[i];
1577 }
1578 zFull[j] = 0;
1579 }
drh4eb9a972006-02-13 18:42:21 +00001580#endif
1581
drh0ccebe72005-06-07 22:22:50 +00001582 return zFull;
1583}
1584
drh18839212005-11-26 03:43:23 +00001585/*
drh9cbe6352005-11-29 03:13:21 +00001586** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001587*/
drh9cbe6352005-11-29 03:13:21 +00001588static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001589 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001590}
1591
1592/*
1593** Return the underlying file handle for an OsFile
1594*/
1595static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001596 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001597}
1598
1599/*
1600** Return an integer that indices the type of lock currently held
1601** by this handle. (Used for testing and analysis only.)
1602*/
1603static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001604 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001605}
drh0ccebe72005-06-07 22:22:50 +00001606
drh9c06c952005-11-26 00:25:00 +00001607/*
drh054889e2005-11-30 03:20:31 +00001608** This vector defines all the methods that can operate on an OsFile
1609** for unix.
drh9c06c952005-11-26 00:25:00 +00001610*/
drh054889e2005-11-30 03:20:31 +00001611static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001612 unixClose,
drh054889e2005-11-30 03:20:31 +00001613 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001614 unixRead,
1615 unixWrite,
1616 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001617 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001618 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001619 unixSetFullSync,
1620 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001621 unixFileSize,
1622 unixLock,
1623 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001624 unixLockState,
drh054889e2005-11-30 03:20:31 +00001625 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001626};
1627
drh054889e2005-11-30 03:20:31 +00001628/*
1629** Allocate memory for a unixFile. Initialize the new unixFile
1630** to the value given in pInit and return a pointer to the new
1631** OsFile. If we run out of memory, close the file and return NULL.
1632*/
1633static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1634 unixFile *pNew;
drh2f1a4d12006-01-23 16:24:54 +00001635 pInit->dirfd = -1;
1636 pInit->fullSync = 0;
1637 pInit->locktype = 0;
1638 SET_THREADID(pInit);
danielk1977750b03e2006-02-14 10:48:39 +00001639 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
drh054889e2005-11-30 03:20:31 +00001640 if( pNew==0 ){
1641 close(pInit->h);
drh029b44b2006-01-15 00:13:15 +00001642 sqlite3OsEnterMutex();
danielk19772e588c72005-12-09 14:25:08 +00001643 releaseLockInfo(pInit->pLock);
1644 releaseOpenCnt(pInit->pOpen);
drh029b44b2006-01-15 00:13:15 +00001645 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001646 *pId = 0;
1647 return SQLITE_NOMEM;
1648 }else{
1649 *pNew = *pInit;
1650 pNew->pMethod = &sqlite3UnixIoMethod;
1651 *pId = (OsFile*)pNew;
1652 OpenCounter(+1);
1653 return SQLITE_OK;
1654 }
1655}
1656
drh9c06c952005-11-26 00:25:00 +00001657
drh0ccebe72005-06-07 22:22:50 +00001658#endif /* SQLITE_OMIT_DISKIO */
1659/***************************************************************************
1660** Everything above deals with file I/O. Everything that follows deals
1661** with other miscellanous aspects of the operating system interface
1662****************************************************************************/
1663
1664
1665/*
drhbbd42a62004-05-22 17:41:58 +00001666** Get information to seed the random number generator. The seed
1667** is written into the buffer zBuf[256]. The calling function must
1668** supply a sufficiently large buffer.
1669*/
drh66560ad2006-01-06 14:32:19 +00001670int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001671 /* We have to initialize zBuf to prevent valgrind from reporting
1672 ** errors. The reports issued by valgrind are incorrect - we would
1673 ** prefer that the randomness be increased by making use of the
1674 ** uninitialized space in zBuf - but valgrind errors tend to worry
1675 ** some users. Rather than argue, it seems easier just to initialize
1676 ** the whole array and silence valgrind, even if that means less randomness
1677 ** in the random seed.
1678 **
1679 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00001680 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00001681 ** tests repeatable.
1682 */
1683 memset(zBuf, 0, 256);
1684#if !defined(SQLITE_TEST)
1685 {
drh842b8642005-01-21 17:53:17 +00001686 int pid, fd;
1687 fd = open("/dev/urandom", O_RDONLY);
1688 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001689 time_t t;
1690 time(&t);
1691 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001692 pid = getpid();
1693 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1694 }else{
1695 read(fd, zBuf, 256);
1696 close(fd);
1697 }
drhbbd42a62004-05-22 17:41:58 +00001698 }
1699#endif
1700 return SQLITE_OK;
1701}
1702
1703/*
1704** Sleep for a little while. Return the amount of time slept.
drhf1a221e2006-01-15 17:27:17 +00001705** The argument is the number of milliseconds we want to sleep.
drhbbd42a62004-05-22 17:41:58 +00001706*/
drh66560ad2006-01-06 14:32:19 +00001707int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001708#if defined(HAVE_USLEEP) && HAVE_USLEEP
1709 usleep(ms*1000);
1710 return ms;
1711#else
1712 sleep((ms+999)/1000);
1713 return 1000*((ms+999)/1000);
1714#endif
1715}
1716
1717/*
drh5c111232006-02-10 04:33:12 +00001718** Static variables used for thread synchronization.
1719**
1720** inMutex the nesting depth of the recursive mutex. The thread
1721** holding mutexMain can read this variable at any time.
1722** But is must hold mutexAux to change this variable. Other
drh6a3d6702006-02-10 13:11:32 +00001723** threads must hold mutexAux to read the variable and can
1724** never write.
drh5c111232006-02-10 04:33:12 +00001725**
1726** mutexOwner The thread id of the thread holding mutexMain. Same
1727** access rules as for inMutex.
1728**
drh6a3d6702006-02-10 13:11:32 +00001729** mutexOwnerValid True if the value in mutexOwner is valid. The same
1730** access rules apply as for inMutex.
drh5c111232006-02-10 04:33:12 +00001731**
1732** mutexMain The main mutex. Hold this mutex in order to get exclusive
1733** access to SQLite data structures.
1734**
1735** mutexAux An auxiliary mutex needed to access variables defined above.
1736**
drh6a3d6702006-02-10 13:11:32 +00001737** Mutexes are always acquired in this order: mutexMain mutexAux. It
1738** is not necessary to acquire mutexMain in order to get mutexAux - just
1739** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
1740** Either get the mutexes with mutexMain first or get mutexAux only.
1741**
1742** When running on a platform where the three variables inMutex, mutexOwner,
1743** and mutexOwnerValid can be set atomically, the mutexAux is not required.
1744** On many systems, all three are 32-bit integers and writing to a 32-bit
1745** integer is atomic. I think. But there are no guarantees. So it seems
1746** safer to protect them using mutexAux.
drhbbd42a62004-05-22 17:41:58 +00001747*/
1748static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001749#ifdef SQLITE_UNIX_THREADS
drh6a3d6702006-02-10 13:11:32 +00001750static pthread_t mutexOwner; /* Thread holding mutexMain */
drh5c111232006-02-10 04:33:12 +00001751static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
1752static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
1753static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
drh79069752004-05-22 21:30:40 +00001754#endif
drhbbd42a62004-05-22 17:41:58 +00001755
1756/*
1757** The following pair of routine implement mutual exclusion for
1758** multi-threaded processes. Only a single thread is allowed to
1759** executed code that is surrounded by EnterMutex() and LeaveMutex().
1760**
1761** SQLite uses only a single Mutex. There is not much critical
1762** code and what little there is executes quickly and without blocking.
drhf1a221e2006-01-15 17:27:17 +00001763**
drh757b04e2006-01-18 17:25:45 +00001764** As of version 3.3.2, this mutex must be recursive.
drhbbd42a62004-05-22 17:41:58 +00001765*/
drh66560ad2006-01-06 14:32:19 +00001766void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001767#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001768 pthread_mutex_lock(&mutexAux);
1769 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
1770 pthread_mutex_unlock(&mutexAux);
1771 pthread_mutex_lock(&mutexMain);
1772 assert( inMutex==0 );
1773 assert( !mutexOwnerValid );
1774 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001775 mutexOwner = pthread_self();
drh5c111232006-02-10 04:33:12 +00001776 mutexOwnerValid = 1;
drha3fad6f2006-01-18 14:06:37 +00001777 }
drha3fad6f2006-01-18 14:06:37 +00001778 inMutex++;
drh5c111232006-02-10 04:33:12 +00001779 pthread_mutex_unlock(&mutexAux);
1780#else
drhe9565a62006-02-11 02:03:52 +00001781 inMutex++;
drh5c111232006-02-10 04:33:12 +00001782#endif
drhbbd42a62004-05-22 17:41:58 +00001783}
drh66560ad2006-01-06 14:32:19 +00001784void sqlite3UnixLeaveMutex(){
drha3fad6f2006-01-18 14:06:37 +00001785 assert( inMutex>0 );
drhbbd42a62004-05-22 17:41:58 +00001786#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001787 pthread_mutex_lock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001788 inMutex--;
drh5c111232006-02-10 04:33:12 +00001789 assert( pthread_equal(mutexOwner, pthread_self()) );
drha3fad6f2006-01-18 14:06:37 +00001790 if( inMutex==0 ){
drh5c111232006-02-10 04:33:12 +00001791 assert( mutexOwnerValid );
1792 mutexOwnerValid = 0;
1793 pthread_mutex_unlock(&mutexMain);
drha3fad6f2006-01-18 14:06:37 +00001794 }
drh5c111232006-02-10 04:33:12 +00001795 pthread_mutex_unlock(&mutexAux);
drha3fad6f2006-01-18 14:06:37 +00001796#else
1797 inMutex--;
drhbbd42a62004-05-22 17:41:58 +00001798#endif
1799}
1800
1801/*
drh757b04e2006-01-18 17:25:45 +00001802** Return TRUE if the mutex is currently held.
1803**
drh5c111232006-02-10 04:33:12 +00001804** If the thisThrd parameter is true, return true only if the
drh757b04e2006-01-18 17:25:45 +00001805** calling thread holds the mutex. If the parameter is false, return
1806** true if any thread holds the mutex.
drh88f474a2006-01-02 20:00:12 +00001807*/
drh5c111232006-02-10 04:33:12 +00001808int sqlite3UnixInMutex(int thisThrd){
drha3fad6f2006-01-18 14:06:37 +00001809#ifdef SQLITE_UNIX_THREADS
drh5c111232006-02-10 04:33:12 +00001810 int rc;
1811 pthread_mutex_lock(&mutexAux);
1812 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
1813 pthread_mutex_unlock(&mutexAux);
1814 return rc;
drha3fad6f2006-01-18 14:06:37 +00001815#else
drh757b04e2006-01-18 17:25:45 +00001816 return inMutex>0;
drha3fad6f2006-01-18 14:06:37 +00001817#endif
drh88f474a2006-01-02 20:00:12 +00001818}
1819
1820/*
drhb4bc7052006-01-11 23:40:33 +00001821** Remember the number of thread-specific-data blocks allocated.
1822** Use this to verify that we are not leaking thread-specific-data.
1823** Ticket #1601
1824*/
1825#ifdef SQLITE_TEST
1826int sqlite3_tsd_count = 0;
1827# ifdef SQLITE_UNIX_THREADS
1828 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
1829# define TSD_COUNTER(N) \
1830 pthread_mutex_lock(&tsd_counter_mutex); \
1831 sqlite3_tsd_count += N; \
1832 pthread_mutex_unlock(&tsd_counter_mutex);
1833# else
1834# define TSD_COUNTER(N) sqlite3_tsd_count += N
1835# endif
1836#else
1837# define TSD_COUNTER(N) /* no-op */
1838#endif
1839
drhb4bc7052006-01-11 23:40:33 +00001840/*
drhf1a221e2006-01-15 17:27:17 +00001841** If called with allocateFlag>0, then return a pointer to thread
drh6f7adc82006-01-11 21:41:20 +00001842** specific data for the current thread. Allocate and zero the
drhf1a221e2006-01-15 17:27:17 +00001843** thread-specific data if it does not already exist.
danielk197713a68c32005-12-15 10:11:30 +00001844**
drh6f7adc82006-01-11 21:41:20 +00001845** If called with allocateFlag==0, then check the current thread
drh70ff98a2006-01-12 01:25:18 +00001846** specific data. Return it if it exists. If it does not exist,
1847** then return NULL.
1848**
1849** If called with allocateFlag<0, check to see if the thread specific
1850** data is allocated and is all zero. If it is then deallocate it.
drh6f7adc82006-01-11 21:41:20 +00001851** Return a pointer to the thread specific data or NULL if it is
drh70ff98a2006-01-12 01:25:18 +00001852** unallocated or gets deallocated.
danielk197713a68c32005-12-15 10:11:30 +00001853*/
drh6f7adc82006-01-11 21:41:20 +00001854ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
danielk19774d5238f2006-01-27 06:32:00 +00001855 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
1856 ** from broken compilers */
danielk197713a68c32005-12-15 10:11:30 +00001857#ifdef SQLITE_UNIX_THREADS
1858 static pthread_key_t key;
1859 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001860 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001861
1862 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001863 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001864 if( !keyInit ){
1865 int rc;
drh6f7adc82006-01-11 21:41:20 +00001866 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001867 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001868 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001869 return 0;
1870 }
1871 keyInit = 1;
1872 }
drh66560ad2006-01-06 14:32:19 +00001873 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001874 }
1875
drh3fbb0b12006-01-06 00:36:00 +00001876 pTsd = pthread_getspecific(key);
drh70ff98a2006-01-12 01:25:18 +00001877 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001878 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001879 if( !sqlite3TestMallocFail() ){
1880 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1881 }
1882#ifdef SQLITE_MEMDEBUG
1883 sqlite3_isFail = 0;
1884#endif
drh6f7adc82006-01-11 21:41:20 +00001885 if( pTsd ){
1886 *pTsd = zeroData;
1887 pthread_setspecific(key, pTsd);
drhb4bc7052006-01-11 23:40:33 +00001888 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001889 }
danielk197713a68c32005-12-15 10:11:30 +00001890 }
drh70ff98a2006-01-12 01:25:18 +00001891 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001892 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001893 sqlite3OsFree(pTsd);
1894 pthread_setspecific(key, 0);
drhb4bc7052006-01-11 23:40:33 +00001895 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001896 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001897 }
1898 return pTsd;
1899#else
drh6f7adc82006-01-11 21:41:20 +00001900 static ThreadData *pTsd = 0;
drh70ff98a2006-01-12 01:25:18 +00001901 if( allocateFlag>0 ){
drh6f7adc82006-01-11 21:41:20 +00001902 if( pTsd==0 ){
danielk197776e8d1a2006-01-18 18:22:43 +00001903 if( !sqlite3TestMallocFail() ){
1904 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1905 }
1906#ifdef SQLITE_MEMDEBUG
1907 sqlite3_isFail = 0;
1908#endif
drh6f7adc82006-01-11 21:41:20 +00001909 if( pTsd ){
1910 *pTsd = zeroData;
drhb4bc7052006-01-11 23:40:33 +00001911 TSD_COUNTER(+1);
drh6f7adc82006-01-11 21:41:20 +00001912 }
drh3fbb0b12006-01-06 00:36:00 +00001913 }
drh70ff98a2006-01-12 01:25:18 +00001914 }else if( pTsd!=0 && allocateFlag<0
danielk19779e128002006-01-18 16:51:35 +00001915 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
drh6f7adc82006-01-11 21:41:20 +00001916 sqlite3OsFree(pTsd);
drhb4bc7052006-01-11 23:40:33 +00001917 TSD_COUNTER(-1);
drh6f7adc82006-01-11 21:41:20 +00001918 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001919 }
drh3fbb0b12006-01-06 00:36:00 +00001920 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001921#endif
1922}
1923
1924/*
drhbbd42a62004-05-22 17:41:58 +00001925** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001926** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001927*/
1928#ifdef SQLITE_TEST
1929int sqlite3_current_time = 0;
1930#endif
1931
1932/*
1933** Find the current time (in Universal Coordinated Time). Write the
1934** current time and date as a Julian Day number into *prNow and
1935** return 0. Return 1 if the time and date cannot be found.
1936*/
drh66560ad2006-01-06 14:32:19 +00001937int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001938#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001939 time_t t;
1940 time(&t);
1941 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001942#else
1943 struct timeval sNow;
1944 struct timezone sTz; /* Not used */
1945 gettimeofday(&sNow, &sTz);
1946 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1947#endif
drhbbd42a62004-05-22 17:41:58 +00001948#ifdef SQLITE_TEST
1949 if( sqlite3_current_time ){
1950 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1951 }
1952#endif
1953 return 0;
1954}
1955
drhbbd42a62004-05-22 17:41:58 +00001956#endif /* OS_UNIX */