blob: 71125fa61ec8cab50dcc1241fb6c238e06931afc [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
22** large file support, or if the OS is windows, these should be no-ops.
23**
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.
31**
32** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
33*/
34#ifndef SQLITE_DISABLE_LFS
35# define _LARGE_FILE 1
36# ifndef _FILE_OFFSET_BITS
37# define _FILE_OFFSET_BITS 64
38# endif
39# define _LARGEFILE_SOURCE 1
40#endif
drhbbd42a62004-05-22 17:41:58 +000041
drh9cbe6352005-11-29 03:13:21 +000042/*
43** standard include files.
44*/
45#include <sys/types.h>
46#include <sys/stat.h>
47#include <fcntl.h>
48#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000049#include <time.h>
drh19e2d372005-08-29 23:00:03 +000050#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000051#include <errno.h>
drh9cbe6352005-11-29 03:13:21 +000052
53/*
54** Macros used to determine whether or not to use threads. The
55** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
56** Posix threads and SQLITE_W32_THREADS is defined if we are
57** synchronizing using Win32 threads.
58*/
59#if defined(THREADSAFE) && THREADSAFE
60# include <pthread.h>
61# define SQLITE_UNIX_THREADS 1
62#endif
63
64/*
65** Default permissions when creating a new file
66*/
67#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
68# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
69#endif
70
71
72
73/*
drh054889e2005-11-30 03:20:31 +000074** The unixFile structure is subclass of OsFile specific for the unix
75** protability layer.
drh9cbe6352005-11-29 03:13:21 +000076*/
drh054889e2005-11-30 03:20:31 +000077typedef struct unixFile unixFile;
78struct unixFile {
79 IoMethod const *pMethod; /* Always the first entry */
drh9cbe6352005-11-29 03:13:21 +000080 struct openCnt *pOpen; /* Info about all open fd's on this inode */
81 struct lockInfo *pLock; /* Info about locks on this inode */
82 int h; /* The file descriptor */
83 unsigned char locktype; /* The type of lock held on this fd */
84 unsigned char isOpen; /* True if needs to be closed */
85 unsigned char fullSync; /* Use F_FULLSYNC if available */
86 int dirfd; /* File descriptor for the directory */
87#ifdef SQLITE_UNIX_THREADS
88 pthread_t tid; /* The thread authorized to use this OsFile */
89#endif
90};
91
drh66560ad2006-01-06 14:32:19 +000092/*
93** Provide the ability to override some OS-layer functions during
94** testing. This is used to simulate OS crashes to verify that
95** commits are atomic even in the event of an OS crash.
96*/
97#ifdef SQLITE_CRASH_TEST
98 extern int sqlite3CrashTestEnable;
99 extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
100 extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
101 extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
102# define CRASH_TEST_OVERRIDE(X,A,B,C) \
103 if(sqlite3CrashTestEnable){ return X(A,B,C); }
104#else
105# define CRASH_TEST_OVERRIDE(X,A,B,C) /* no-op */
106#endif
107
drh0ccebe72005-06-07 22:22:50 +0000108
109/*
drh198bf392006-01-06 21:52:49 +0000110** Include code that is common to all os_*.c files
111*/
112#include "os_common.h"
113
114/*
drh0ccebe72005-06-07 22:22:50 +0000115** Do not include any of the File I/O interface procedures if the
116** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
117** will be in-memory only)
118*/
119#ifndef SQLITE_OMIT_DISKIO
120
121
122/*
123** Define various macros that are missing from some systems.
124*/
drhbbd42a62004-05-22 17:41:58 +0000125#ifndef O_LARGEFILE
126# define O_LARGEFILE 0
127#endif
128#ifdef SQLITE_DISABLE_LFS
129# undef O_LARGEFILE
130# define O_LARGEFILE 0
131#endif
132#ifndef O_NOFOLLOW
133# define O_NOFOLLOW 0
134#endif
135#ifndef O_BINARY
136# define O_BINARY 0
137#endif
138
139/*
140** The DJGPP compiler environment looks mostly like Unix, but it
141** lacks the fcntl() system call. So redefine fcntl() to be something
142** that always succeeds. This means that locking does not occur under
danielk197726c5d792005-11-25 09:01:23 +0000143** DJGPP. But it's DOS - what did you expect?
drhbbd42a62004-05-22 17:41:58 +0000144*/
145#ifdef __DJGPP__
146# define fcntl(A,B,C) 0
147#endif
148
149/*
drh2b4b5962005-06-15 17:47:55 +0000150** The threadid macro resolves to the thread-id or to 0. Used for
151** testing and debugging only.
152*/
153#ifdef SQLITE_UNIX_THREADS
154#define threadid pthread_self()
155#else
156#define threadid 0
157#endif
158
159/*
160** Set or check the OsFile.tid field. This field is set when an OsFile
161** is first opened. All subsequent uses of the OsFile verify that the
162** same thread is operating on the OsFile. Some operating systems do
163** not allow locks to be overridden by other threads and that restriction
164** means that sqlite3* database handles cannot be moved from one thread
165** to another. This logic makes sure a user does not try to do that
166** by mistake.
167*/
drh91636d52005-11-24 23:14:00 +0000168#if defined(SQLITE_UNIX_THREADS) && !defined(SQLITE_ALLOW_XTHREAD_CONNECTIONS)
drh9cbe6352005-11-29 03:13:21 +0000169# define SET_THREADID(X) (X)->tid = pthread_self()
170# define CHECK_THREADID(X) (!pthread_equal((X)->tid, pthread_self()))
drh2b4b5962005-06-15 17:47:55 +0000171#else
172# define SET_THREADID(X)
173# define CHECK_THREADID(X) 0
danielk197713adf8a2004-06-03 16:08:41 +0000174#endif
175
drhbbd42a62004-05-22 17:41:58 +0000176/*
177** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
178** section 6.5.2.2 lines 483 through 490 specify that when a process
179** sets or clears a lock, that operation overrides any prior locks set
180** by the same process. It does not explicitly say so, but this implies
181** that it overrides locks set by the same process using a different
182** file descriptor. Consider this test case:
183**
184** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
185** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
186**
187** Suppose ./file1 and ./file2 are really the same file (because
188** one is a hard or symbolic link to the other) then if you set
189** an exclusive lock on fd1, then try to get an exclusive lock
190** on fd2, it works. I would have expected the second lock to
191** fail since there was already a lock on the file due to fd1.
192** But not so. Since both locks came from the same process, the
193** second overrides the first, even though they were on different
194** file descriptors opened on different file names.
195**
196** Bummer. If you ask me, this is broken. Badly broken. It means
197** that we cannot use POSIX locks to synchronize file access among
198** competing threads of the same process. POSIX locks will work fine
199** to synchronize access for threads in separate processes, but not
200** threads within the same process.
201**
202** To work around the problem, SQLite has to manage file locks internally
203** on its own. Whenever a new database is opened, we have to find the
204** specific inode of the database file (the inode is determined by the
205** st_dev and st_ino fields of the stat structure that fstat() fills in)
206** and check for locks already existing on that inode. When locks are
207** created or removed, we have to look at our own internal record of the
208** locks to see if another thread has previously set a lock on that same
209** inode.
210**
211** The OsFile structure for POSIX is no longer just an integer file
212** descriptor. It is now a structure that holds the integer file
213** descriptor and a pointer to a structure that describes the internal
214** locks on the corresponding inode. There is one locking structure
215** per inode, so if the same inode is opened twice, both OsFile structures
216** point to the same locking structure. The locking structure keeps
217** a reference count (so we will know when to delete it) and a "cnt"
218** field that tells us its internal lock status. cnt==0 means the
219** file is unlocked. cnt==-1 means the file has an exclusive lock.
220** cnt>0 means there are cnt shared locks on the file.
221**
222** Any attempt to lock or unlock a file first checks the locking
223** structure. The fcntl() system call is only invoked to set a
224** POSIX lock if the internal lock structure transitions between
225** a locked and an unlocked state.
226**
227** 2004-Jan-11:
228** More recent discoveries about POSIX advisory locks. (The more
229** I discover, the more I realize the a POSIX advisory locks are
230** an abomination.)
231**
232** If you close a file descriptor that points to a file that has locks,
233** all locks on that file that are owned by the current process are
234** released. To work around this problem, each OsFile structure contains
235** a pointer to an openCnt structure. There is one openCnt structure
236** per open inode, which means that multiple OsFiles can point to a single
237** openCnt. When an attempt is made to close an OsFile, if there are
238** other OsFiles open on the same inode that are holding locks, the call
239** to close() the file descriptor is deferred until all of the locks clear.
240** The openCnt structure keeps a list of file descriptors that need to
241** be closed and that list is walked (and cleared) when the last lock
242** clears.
243**
244** First, under Linux threads, because each thread has a separate
245** process ID, lock operations in one thread do not override locks
246** to the same file in other threads. Linux threads behave like
247** separate processes in this respect. But, if you close a file
248** descriptor in linux threads, all locks are cleared, even locks
249** on other threads and even though the other threads have different
250** process IDs. Linux threads is inconsistent in this respect.
251** (I'm beginning to think that linux threads is an abomination too.)
252** The consequence of this all is that the hash table for the lockInfo
253** structure has to include the process id as part of its key because
254** locks in different threads are treated as distinct. But the
255** openCnt structure should not include the process id in its
256** key because close() clears lock on all threads, not just the current
257** thread. Were it not for this goofiness in linux threads, we could
258** combine the lockInfo and openCnt structures into a single structure.
drh5fdae772004-06-29 03:29:00 +0000259**
260** 2004-Jun-28:
261** On some versions of linux, threads can override each others locks.
262** On others not. Sometimes you can change the behavior on the same
263** system by setting the LD_ASSUME_KERNEL environment variable. The
264** POSIX standard is silent as to which behavior is correct, as far
265** as I can tell, so other versions of unix might show the same
266** inconsistency. There is no little doubt in my mind that posix
267** advisory locks and linux threads are profoundly broken.
268**
269** To work around the inconsistencies, we have to test at runtime
270** whether or not threads can override each others locks. This test
271** is run once, the first time any lock is attempted. A static
272** variable is set to record the results of this test for future
273** use.
drhbbd42a62004-05-22 17:41:58 +0000274*/
275
276/*
277** An instance of the following structure serves as the key used
drh5fdae772004-06-29 03:29:00 +0000278** to locate a particular lockInfo structure given its inode.
279**
280** If threads cannot override each others locks, then we set the
281** lockKey.tid field to the thread ID. If threads can override
282** each others locks then tid is always set to zero. tid is also
283** set to zero if we compile without threading support.
drhbbd42a62004-05-22 17:41:58 +0000284*/
285struct lockKey {
drh5fdae772004-06-29 03:29:00 +0000286 dev_t dev; /* Device number */
287 ino_t ino; /* Inode number */
288#ifdef SQLITE_UNIX_THREADS
drhd9cb6ac2005-10-20 07:28:17 +0000289 pthread_t tid; /* Thread ID or zero if threads can override each other */
drh5fdae772004-06-29 03:29:00 +0000290#endif
drhbbd42a62004-05-22 17:41:58 +0000291};
292
293/*
294** An instance of the following structure is allocated for each open
295** inode on each thread with a different process ID. (Threads have
296** different process IDs on linux, but not on most other unixes.)
297**
298** A single inode can have multiple file descriptors, so each OsFile
299** structure contains a pointer to an instance of this object and this
300** object keeps a count of the number of OsFiles pointing to it.
301*/
302struct lockInfo {
303 struct lockKey key; /* The lookup key */
drh2ac3ee92004-06-07 16:27:46 +0000304 int cnt; /* Number of SHARED locks held */
danielk19779a1d0ab2004-06-01 14:09:28 +0000305 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
drhbbd42a62004-05-22 17:41:58 +0000306 int nRef; /* Number of pointers to this structure */
307};
308
309/*
310** An instance of the following structure serves as the key used
311** to locate a particular openCnt structure given its inode. This
drh5fdae772004-06-29 03:29:00 +0000312** is the same as the lockKey except that the thread ID is omitted.
drhbbd42a62004-05-22 17:41:58 +0000313*/
314struct openKey {
315 dev_t dev; /* Device number */
316 ino_t ino; /* Inode number */
317};
318
319/*
320** An instance of the following structure is allocated for each open
321** inode. This structure keeps track of the number of locks on that
322** inode. If a close is attempted against an inode that is holding
323** locks, the close is deferred until all locks clear by adding the
324** file descriptor to be closed to the pending list.
325*/
326struct openCnt {
327 struct openKey key; /* The lookup key */
328 int nRef; /* Number of pointers to this structure */
329 int nLock; /* Number of outstanding locks */
330 int nPending; /* Number of pending close() operations */
331 int *aPending; /* Malloced space holding fd's awaiting a close() */
332};
333
334/*
335** These hash table maps inodes and process IDs into lockInfo and openCnt
336** structures. Access to these hash tables must be protected by a mutex.
337*/
338static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
339static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
340
drh5fdae772004-06-29 03:29:00 +0000341
342#ifdef SQLITE_UNIX_THREADS
343/*
344** This variable records whether or not threads can override each others
345** locks.
346**
347** 0: No. Threads cannot override each others locks.
348** 1: Yes. Threads can override each others locks.
349** -1: We don't know yet.
350*/
351static int threadsOverrideEachOthersLocks = -1;
352
353/*
354** This structure holds information passed into individual test
355** threads by the testThreadLockingBehavior() routine.
356*/
357struct threadTestData {
358 int fd; /* File to be locked */
359 struct flock lock; /* The locking operation */
360 int result; /* Result of the locking operation */
361};
362
drh2b4b5962005-06-15 17:47:55 +0000363#ifdef SQLITE_LOCK_TRACE
364/*
365** Print out information about all locking operations.
366**
367** This routine is used for troubleshooting locks on multithreaded
368** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
369** command-line option on the compiler. This code is normally
370** turnned off.
371*/
372static int lockTrace(int fd, int op, struct flock *p){
373 char *zOpName, *zType;
374 int s;
375 int savedErrno;
376 if( op==F_GETLK ){
377 zOpName = "GETLK";
378 }else if( op==F_SETLK ){
379 zOpName = "SETLK";
380 }else{
381 s = fcntl(fd, op, p);
382 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
383 return s;
384 }
385 if( p->l_type==F_RDLCK ){
386 zType = "RDLCK";
387 }else if( p->l_type==F_WRLCK ){
388 zType = "WRLCK";
389 }else if( p->l_type==F_UNLCK ){
390 zType = "UNLCK";
391 }else{
392 assert( 0 );
393 }
394 assert( p->l_whence==SEEK_SET );
395 s = fcntl(fd, op, p);
396 savedErrno = errno;
397 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
398 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
399 (int)p->l_pid, s);
400 if( s && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
401 struct flock l2;
402 l2 = *p;
403 fcntl(fd, F_GETLK, &l2);
404 if( l2.l_type==F_RDLCK ){
405 zType = "RDLCK";
406 }else if( l2.l_type==F_WRLCK ){
407 zType = "WRLCK";
408 }else if( l2.l_type==F_UNLCK ){
409 zType = "UNLCK";
410 }else{
411 assert( 0 );
412 }
413 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
414 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
415 }
416 errno = savedErrno;
417 return s;
418}
419#define fcntl lockTrace
420#endif /* SQLITE_LOCK_TRACE */
421
drh5fdae772004-06-29 03:29:00 +0000422/*
423** The testThreadLockingBehavior() routine launches two separate
424** threads on this routine. This routine attempts to lock a file
425** descriptor then returns. The success or failure of that attempt
426** allows the testThreadLockingBehavior() procedure to determine
427** whether or not threads can override each others locks.
428*/
429static void *threadLockingTest(void *pArg){
430 struct threadTestData *pData = (struct threadTestData*)pArg;
431 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
432 return pArg;
433}
434
435/*
436** This procedure attempts to determine whether or not threads
437** can override each others locks then sets the
438** threadsOverrideEachOthersLocks variable appropriately.
439*/
440static void testThreadLockingBehavior(fd_orig){
441 int fd;
442 struct threadTestData d[2];
443 pthread_t t[2];
444
445 fd = dup(fd_orig);
446 if( fd<0 ) return;
447 memset(d, 0, sizeof(d));
448 d[0].fd = fd;
449 d[0].lock.l_type = F_RDLCK;
450 d[0].lock.l_len = 1;
451 d[0].lock.l_start = 0;
452 d[0].lock.l_whence = SEEK_SET;
453 d[1] = d[0];
454 d[1].lock.l_type = F_WRLCK;
455 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
456 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
457 pthread_join(t[0], 0);
458 pthread_join(t[1], 0);
459 close(fd);
460 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
461}
462#endif /* SQLITE_UNIX_THREADS */
463
drhbbd42a62004-05-22 17:41:58 +0000464/*
465** Release a lockInfo structure previously allocated by findLockInfo().
466*/
467static void releaseLockInfo(struct lockInfo *pLock){
468 pLock->nRef--;
469 if( pLock->nRef==0 ){
470 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
471 sqliteFree(pLock);
472 }
473}
474
475/*
476** Release a openCnt structure previously allocated by findLockInfo().
477*/
478static void releaseOpenCnt(struct openCnt *pOpen){
479 pOpen->nRef--;
480 if( pOpen->nRef==0 ){
481 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
482 sqliteFree(pOpen->aPending);
483 sqliteFree(pOpen);
484 }
485}
486
487/*
488** Given a file descriptor, locate lockInfo and openCnt structures that
489** describes that file descriptor. Create a new ones if necessary. The
490** return values might be unset if an error occurs.
491**
492** Return the number of errors.
493*/
drh38f82712004-06-18 17:10:16 +0000494static int findLockInfo(
drhbbd42a62004-05-22 17:41:58 +0000495 int fd, /* The file descriptor used in the key */
496 struct lockInfo **ppLock, /* Return the lockInfo structure here */
drh5fdae772004-06-29 03:29:00 +0000497 struct openCnt **ppOpen /* Return the openCnt structure here */
drhbbd42a62004-05-22 17:41:58 +0000498){
499 int rc;
500 struct lockKey key1;
501 struct openKey key2;
502 struct stat statbuf;
503 struct lockInfo *pLock;
504 struct openCnt *pOpen;
danielk1977441b09a2006-01-05 13:48:29 +0000505 SqliteTsd *pTsd = sqlite3Tsd();
drhbbd42a62004-05-22 17:41:58 +0000506 rc = fstat(fd, &statbuf);
507 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000508
509 /* Disable the sqlite3_release_memory() function */
510 assert( !pTsd->disableReleaseMemory );
511 pTsd->disableReleaseMemory = 1;
512
drhbbd42a62004-05-22 17:41:58 +0000513 memset(&key1, 0, sizeof(key1));
514 key1.dev = statbuf.st_dev;
515 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000516#ifdef SQLITE_UNIX_THREADS
517 if( threadsOverrideEachOthersLocks<0 ){
518 testThreadLockingBehavior(fd);
519 }
520 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
521#endif
drhbbd42a62004-05-22 17:41:58 +0000522 memset(&key2, 0, sizeof(key2));
523 key2.dev = statbuf.st_dev;
524 key2.ino = statbuf.st_ino;
525 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
526 if( pLock==0 ){
527 struct lockInfo *pOld;
528 pLock = sqliteMallocRaw( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000529 if( pLock==0 ){
530 rc = 1;
531 goto exit_findlockinfo;
532 }
drhbbd42a62004-05-22 17:41:58 +0000533 pLock->key = key1;
534 pLock->nRef = 1;
535 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000536 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000537 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
538 if( pOld!=0 ){
539 assert( pOld==pLock );
540 sqliteFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000541 rc = 1;
542 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000543 }
544 }else{
545 pLock->nRef++;
546 }
547 *ppLock = pLock;
548 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
549 if( pOpen==0 ){
550 struct openCnt *pOld;
551 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
552 if( pOpen==0 ){
553 releaseLockInfo(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000554 rc = 1;
555 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000556 }
557 pOpen->key = key2;
558 pOpen->nRef = 1;
559 pOpen->nLock = 0;
560 pOpen->nPending = 0;
561 pOpen->aPending = 0;
562 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
563 if( pOld!=0 ){
564 assert( pOld==pOpen );
565 sqliteFree(pOpen);
566 releaseLockInfo(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000567 rc = 1;
568 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000569 }
570 }else{
571 pOpen->nRef++;
572 }
573 *ppOpen = pOpen;
danielk1977441b09a2006-01-05 13:48:29 +0000574
575exit_findlockinfo:
576 /* Re-enable sqlite3_release_memory() */
577 pTsd->disableReleaseMemory = 0;
578 return rc;
drhbbd42a62004-05-22 17:41:58 +0000579}
580
581/*
582** Delete the named file
583*/
drh66560ad2006-01-06 14:32:19 +0000584int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000585 unlink(zFilename);
586 return SQLITE_OK;
587}
588
589/*
590** Return TRUE if the named file exists.
591*/
drh66560ad2006-01-06 14:32:19 +0000592int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000593 return access(zFilename, 0)==0;
594}
595
drh054889e2005-11-30 03:20:31 +0000596/* Forward declaration */
597static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000598
599/*
drhbbd42a62004-05-22 17:41:58 +0000600** Attempt to open a file for both reading and writing. If that
601** fails, try opening it read-only. If the file does not exist,
602** try to create it.
603**
604** On success, a handle for the open file is written to *id
605** and *pReadonly is set to 0 if the file was opened for reading and
606** writing or 1 if the file was opened read-only. The function returns
607** SQLITE_OK.
608**
609** On failure, the function returns SQLITE_CANTOPEN and leaves
610** *id and *pReadonly unchanged.
611*/
drh66560ad2006-01-06 14:32:19 +0000612int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000613 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000614 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000615 int *pReadonly
616){
617 int rc;
drh054889e2005-11-30 03:20:31 +0000618 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000619
drh66560ad2006-01-06 14:32:19 +0000620 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000621 assert( 0==*pId );
622 f.dirfd = -1;
623 SET_THREADID(&f);
624 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000625 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000626 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000627#ifdef EISDIR
628 if( errno==EISDIR ){
629 return SQLITE_CANTOPEN;
630 }
631#endif
drh9cbe6352005-11-29 03:13:21 +0000632 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
633 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000634 return SQLITE_CANTOPEN;
635 }
636 *pReadonly = 1;
637 }else{
638 *pReadonly = 0;
639 }
drh66560ad2006-01-06 14:32:19 +0000640 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000641 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000642 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000643 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000644 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000645 return SQLITE_NOMEM;
646 }
drh9cbe6352005-11-29 03:13:21 +0000647 f.locktype = 0;
648 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000649 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000650}
651
652
653/*
654** Attempt to open a new file for exclusive access by this process.
655** The file will be opened for both reading and writing. To avoid
656** a potential security problem, we do not allow the file to have
657** previously existed. Nor do we allow the file to be a symbolic
658** link.
659**
660** If delFlag is true, then make arrangements to automatically delete
661** the file when it is closed.
662**
663** On success, write the file handle into *id and return SQLITE_OK.
664**
665** On failure, return SQLITE_CANTOPEN.
666*/
drh66560ad2006-01-06 14:32:19 +0000667int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000668 int rc;
drh054889e2005-11-30 03:20:31 +0000669 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000670
drh66560ad2006-01-06 14:32:19 +0000671 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000672 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000673 if( access(zFilename, 0)==0 ){
674 return SQLITE_CANTOPEN;
675 }
drh9cbe6352005-11-29 03:13:21 +0000676 SET_THREADID(&f);
677 f.dirfd = -1;
678 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000679 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
680 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000681 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000682 return SQLITE_CANTOPEN;
683 }
drh66560ad2006-01-06 14:32:19 +0000684 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000685 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000686 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000687 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000688 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000689 unlink(zFilename);
690 return SQLITE_NOMEM;
691 }
drh9cbe6352005-11-29 03:13:21 +0000692 f.locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000693 if( delFlag ){
694 unlink(zFilename);
695 }
drh9cbe6352005-11-29 03:13:21 +0000696 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000697 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000698}
699
700/*
701** Attempt to open a new file for read-only access.
702**
703** On success, write the file handle into *id and return SQLITE_OK.
704**
705** On failure, return SQLITE_CANTOPEN.
706*/
drh66560ad2006-01-06 14:32:19 +0000707int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000708 int rc;
drh054889e2005-11-30 03:20:31 +0000709 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000710
drh66560ad2006-01-06 14:32:19 +0000711 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000712 assert( 0==*pId );
713 SET_THREADID(&f);
714 f.dirfd = -1;
715 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 }
drh66560ad2006-01-06 14:32:19 +0000719 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000720 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000721 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000722 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000723 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000724 return SQLITE_NOMEM;
725 }
drh9cbe6352005-11-29 03:13:21 +0000726 f.locktype = 0;
727 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
danielk1977261919c2005-12-06 12:52:59 +0000728
drh054889e2005-11-30 03:20:31 +0000729 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000730}
731
732/*
733** Attempt to open a file descriptor for the directory that contains a
734** file. This file descriptor can be used to fsync() the directory
735** in order to make sure the creation of a new file is actually written
736** to disk.
737**
738** This routine is only meaningful for Unix. It is a no-op under
739** windows since windows does not support hard links.
740**
drh9cbe6352005-11-29 03:13:21 +0000741** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000742** updated with the new directory file descriptor and SQLITE_OK is
743** returned.
744**
745** On failure, the function returns SQLITE_CANTOPEN and leaves
746** *id unchanged.
747*/
drh9c06c952005-11-26 00:25:00 +0000748static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000749 OsFile *id,
750 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000751){
drh054889e2005-11-30 03:20:31 +0000752 unixFile *pFile = (unixFile*)id;
753 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000754 /* Do not open the directory if the corresponding file is not already
755 ** open. */
756 return SQLITE_CANTOPEN;
757 }
drh054889e2005-11-30 03:20:31 +0000758 SET_THREADID(pFile);
759 assert( pFile->dirfd<0 );
760 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
761 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000762 return SQLITE_CANTOPEN;
763 }
drh054889e2005-11-30 03:20:31 +0000764 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000765 return SQLITE_OK;
766}
767
768/*
drhab3f9fe2004-08-14 17:10:10 +0000769** If the following global variable points to a string which is the
770** name of a directory, then that directory will be used to store
771** temporary files.
772*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000773char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000774
775/*
drhbbd42a62004-05-22 17:41:58 +0000776** Create a temporary file name in zBuf. zBuf must be big enough to
777** hold at least SQLITE_TEMPNAME_SIZE characters.
778*/
drh66560ad2006-01-06 14:32:19 +0000779int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000780 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000781 0,
drhbbd42a62004-05-22 17:41:58 +0000782 "/var/tmp",
783 "/usr/tmp",
784 "/tmp",
785 ".",
786 };
drh57196282004-10-06 15:41:16 +0000787 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000788 "abcdefghijklmnopqrstuvwxyz"
789 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
790 "0123456789";
791 int i, j;
792 struct stat buf;
793 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000794 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000795 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000796 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000797 if( stat(azDirs[i], &buf) ) continue;
798 if( !S_ISDIR(buf.st_mode) ) continue;
799 if( access(azDirs[i], 07) ) continue;
800 zDir = azDirs[i];
801 break;
802 }
803 do{
804 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
805 j = strlen(zBuf);
806 sqlite3Randomness(15, &zBuf[j]);
807 for(i=0; i<15; i++, j++){
808 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
809 }
810 zBuf[j] = 0;
811 }while( access(zBuf,0)==0 );
812 return SQLITE_OK;
813}
814
815/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000816** Check that a given pathname is a directory and is writable
817**
818*/
drh66560ad2006-01-06 14:32:19 +0000819int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000820#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000821 struct stat buf;
822 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000823 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000824 if( stat(zBuf, &buf) ) return 0;
825 if( !S_ISDIR(buf.st_mode) ) return 0;
826 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000827#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000828 return 1;
829}
830
831/*
drhbbd42a62004-05-22 17:41:58 +0000832** Read data from a file into a buffer. Return SQLITE_OK if all
833** bytes were read successfully and SQLITE_IOERR if anything goes
834** wrong.
835*/
drh9c06c952005-11-26 00:25:00 +0000836static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000837 int got;
drh9cbe6352005-11-29 03:13:21 +0000838 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000839 SimulateIOError(SQLITE_IOERR);
840 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000841 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000842 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000843 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
844 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000845 SEEK(0);
846 /* if( got<0 ) got = 0; */
847 if( got==amt ){
848 return SQLITE_OK;
849 }else{
850 return SQLITE_IOERR;
851 }
852}
853
854/*
855** Write data from a buffer into a file. Return SQLITE_OK on success
856** or some other error code on failure.
857*/
drh9c06c952005-11-26 00:25:00 +0000858static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000859 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000860 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000861 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000862 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000863 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000864 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000865 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000866 amt -= wrote;
867 pBuf = &((char*)pBuf)[wrote];
868 }
869 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000870 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
871 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000872 SEEK(0);
873 if( amt>0 ){
874 return SQLITE_FULL;
875 }
876 return SQLITE_OK;
877}
878
879/*
880** Move the read/write pointer in a file.
881*/
drh9c06c952005-11-26 00:25:00 +0000882static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000883 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000884 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000885#ifdef SQLITE_TEST
886 if( offset ) SimulateDiskfullError
887#endif
drh054889e2005-11-30 03:20:31 +0000888 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000889 return SQLITE_OK;
890}
891
drhb851b2c2005-03-10 14:11:12 +0000892#ifdef SQLITE_TEST
893/*
894** Count the number of fullsyncs and normal syncs. This is used to test
895** that syncs and fullsyncs are occuring at the right times.
896*/
897int sqlite3_sync_count = 0;
898int sqlite3_fullsync_count = 0;
899#endif
900
drhf2f23912005-10-05 10:29:36 +0000901/*
902** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
903** Otherwise use fsync() in its place.
904*/
905#ifndef HAVE_FDATASYNC
906# define fdatasync fsync
907#endif
908
drhb851b2c2005-03-10 14:11:12 +0000909
drhbbd42a62004-05-22 17:41:58 +0000910/*
drhdd809b02004-07-17 21:44:57 +0000911** The fsync() system call does not work as advertised on many
912** unix systems. The following procedure is an attempt to make
913** it work better.
drh1398ad32005-01-19 23:24:50 +0000914**
915** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
916** for testing when we want to run through the test suite quickly.
917** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
918** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
919** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000920*/
drheb796a72005-09-08 12:38:41 +0000921static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000922 int rc;
drhb851b2c2005-03-10 14:11:12 +0000923
924 /* Record the number of times that we do a normal fsync() and
925 ** FULLSYNC. This is used during testing to verify that this procedure
926 ** gets called with the correct arguments.
927 */
928#ifdef SQLITE_TEST
929 if( fullSync ) sqlite3_fullsync_count++;
930 sqlite3_sync_count++;
931#endif
932
933 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
934 ** no-op
935 */
936#ifdef SQLITE_NO_SYNC
937 rc = SQLITE_OK;
938#else
939
drhdd809b02004-07-17 21:44:57 +0000940#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000941 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000942 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +0000943 }else{
944 rc = 1;
945 }
946 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +0000947 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +0000948
drhc035e6e2005-09-22 15:45:04 +0000949#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +0000950 if( dataOnly ){
951 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +0000952 }else{
drheb796a72005-09-08 12:38:41 +0000953 rc = fsync(fd);
954 }
drhf30cc942005-03-11 17:52:34 +0000955#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +0000956#endif /* defined(SQLITE_NO_SYNC) */
957
drhdd809b02004-07-17 21:44:57 +0000958 return rc;
959}
960
961/*
drhbbd42a62004-05-22 17:41:58 +0000962** Make sure all writes to a particular file are committed to disk.
963**
drheb796a72005-09-08 12:38:41 +0000964** If dataOnly==0 then both the file itself and its metadata (file
965** size, access time, etc) are synced. If dataOnly!=0 then only the
966** file data is synced.
967**
drhbbd42a62004-05-22 17:41:58 +0000968** Under Unix, also make sure that the directory entry for the file
969** has been created by fsync-ing the directory that contains the file.
970** If we do not do this and we encounter a power failure, the directory
971** entry for the journal might not exist after we reboot. The next
972** SQLite to access the file will not know that the journal exists (because
973** the directory entry for the journal was never created) and the transaction
974** will not roll back - possibly leading to database corruption.
975*/
drh9c06c952005-11-26 00:25:00 +0000976static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +0000977 unixFile *pFile = (unixFile*)id;
978 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +0000979 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +0000980 TRACE2("SYNC %-3d\n", pFile->h);
981 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +0000982 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000983 }
drh054889e2005-11-30 03:20:31 +0000984 if( pFile->dirfd>=0 ){
985 TRACE2("DIRSYNC %-3d\n", pFile->dirfd);
danielk1977d7c03f72005-11-25 10:38:22 +0000986#ifndef SQLITE_DISABLE_DIRSYNC
drh054889e2005-11-30 03:20:31 +0000987 if( full_fsync(pFile->dirfd, pFile->fullSync, 0) ){
danielk19770964b232005-11-25 08:47:57 +0000988 return SQLITE_IOERR;
989 }
danielk1977d7c03f72005-11-25 10:38:22 +0000990#endif
drh054889e2005-11-30 03:20:31 +0000991 close(pFile->dirfd); /* Only need to sync once, so close the directory */
992 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +0000993 }
drha2854222004-06-17 19:04:17 +0000994 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000995}
996
997/*
danielk1977962398d2004-06-14 09:35:16 +0000998** Sync the directory zDirname. This is a no-op on operating systems other
999** than UNIX.
drhb851b2c2005-03-10 14:11:12 +00001000**
1001** This is used to make sure the master journal file has truely been deleted
1002** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +00001003** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +00001004*/
drh66560ad2006-01-06 14:32:19 +00001005int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +00001006#ifdef SQLITE_DISABLE_DIRSYNC
1007 return SQLITE_OK;
1008#else
danielk1977962398d2004-06-14 09:35:16 +00001009 int fd;
1010 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001011 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001012 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001013 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001014 if( fd<0 ){
1015 return SQLITE_CANTOPEN;
1016 }
1017 r = fsync(fd);
1018 close(fd);
1019 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001020#endif
danielk1977962398d2004-06-14 09:35:16 +00001021}
1022
1023/*
drhbbd42a62004-05-22 17:41:58 +00001024** Truncate an open file to a specified size
1025*/
drh9c06c952005-11-26 00:25:00 +00001026static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001027 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001028 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001029 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001030}
1031
1032/*
1033** Determine the current size of a file in bytes
1034*/
drh9c06c952005-11-26 00:25:00 +00001035static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001036 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001037 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001038 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001039 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001040 return SQLITE_IOERR;
1041 }
1042 *pSize = buf.st_size;
1043 return SQLITE_OK;
1044}
1045
danielk19779a1d0ab2004-06-01 14:09:28 +00001046/*
danielk197713adf8a2004-06-03 16:08:41 +00001047** This routine checks if there is a RESERVED lock held on the specified
1048** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001049** non-zero. If the file is unlocked or holds only SHARED locks, then
1050** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001051*/
drh9c06c952005-11-26 00:25:00 +00001052static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001053 int r = 0;
drh054889e2005-11-30 03:20:31 +00001054 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001055
drh054889e2005-11-30 03:20:31 +00001056 assert( pFile );
1057 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
drh66560ad2006-01-06 14:32:19 +00001058 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001059
1060 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001061 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001062 r = 1;
1063 }
1064
drh2ac3ee92004-06-07 16:27:46 +00001065 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001066 */
1067 if( !r ){
1068 struct flock lock;
1069 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001070 lock.l_start = RESERVED_BYTE;
1071 lock.l_len = 1;
1072 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001073 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001074 if( lock.l_type!=F_UNLCK ){
1075 r = 1;
1076 }
1077 }
1078
drh66560ad2006-01-06 14:32:19 +00001079 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001080 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001081
1082 return r;
1083}
1084
danielk19772b444852004-06-29 07:45:33 +00001085#ifdef SQLITE_DEBUG
1086/*
1087** Helper function for printing out trace information from debugging
1088** binaries. This returns the string represetation of the supplied
1089** integer lock-type.
1090*/
drh054889e2005-11-30 03:20:31 +00001091static const char *locktypeName(int locktype){
danielk19772b444852004-06-29 07:45:33 +00001092 switch( locktype ){
1093 case NO_LOCK: return "NONE";
1094 case SHARED_LOCK: return "SHARED";
1095 case RESERVED_LOCK: return "RESERVED";
1096 case PENDING_LOCK: return "PENDING";
1097 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
1098 }
1099 return "ERROR";
1100}
1101#endif
1102
danielk197713adf8a2004-06-03 16:08:41 +00001103/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001104** Lock the file with the lock specified by parameter locktype - one
1105** of the following:
1106**
drh2ac3ee92004-06-07 16:27:46 +00001107** (1) SHARED_LOCK
1108** (2) RESERVED_LOCK
1109** (3) PENDING_LOCK
1110** (4) EXCLUSIVE_LOCK
1111**
drhb3e04342004-06-08 00:47:47 +00001112** Sometimes when requesting one lock state, additional lock states
1113** are inserted in between. The locking might fail on one of the later
1114** transitions leaving the lock state different from what it started but
1115** still short of its goal. The following chart shows the allowed
1116** transitions and the inserted intermediate states:
1117**
1118** UNLOCKED -> SHARED
1119** SHARED -> RESERVED
1120** SHARED -> (PENDING) -> EXCLUSIVE
1121** RESERVED -> (PENDING) -> EXCLUSIVE
1122** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001123**
drha6abd042004-06-09 17:37:22 +00001124** This routine will only increase a lock. Use the sqlite3OsUnlock()
1125** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001126*/
drh9c06c952005-11-26 00:25:00 +00001127static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001128 /* The following describes the implementation of the various locks and
1129 ** lock transitions in terms of the POSIX advisory shared and exclusive
1130 ** lock primitives (called read-locks and write-locks below, to avoid
1131 ** confusion with SQLite lock names). The algorithms are complicated
1132 ** slightly in order to be compatible with windows systems simultaneously
1133 ** accessing the same database file, in case that is ever required.
1134 **
1135 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1136 ** byte', each single bytes at well known offsets, and the 'shared byte
1137 ** range', a range of 510 bytes at a well known offset.
1138 **
1139 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1140 ** byte'. If this is successful, a random byte from the 'shared byte
1141 ** range' is read-locked and the lock on the 'pending byte' released.
1142 **
danielk197790ba3bd2004-06-25 08:32:25 +00001143 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1144 ** A RESERVED lock is implemented by grabbing a write-lock on the
1145 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001146 **
1147 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001148 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1149 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1150 ** obtained, but existing SHARED locks are allowed to persist. A process
1151 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1152 ** This property is used by the algorithm for rolling back a journal file
1153 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001154 **
danielk197790ba3bd2004-06-25 08:32:25 +00001155 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1156 ** implemented by obtaining a write-lock on the entire 'shared byte
1157 ** range'. Since all other locks require a read-lock on one of the bytes
1158 ** within this range, this ensures that no other locks are held on the
1159 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001160 **
1161 ** The reason a single byte cannot be used instead of the 'shared byte
1162 ** range' is that some versions of windows do not support read-locks. By
1163 ** locking a random byte from a range, concurrent SHARED locks may exist
1164 ** even if the locking primitive used is always a write-lock.
1165 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001166 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001167 unixFile *pFile = (unixFile*)id;
1168 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001169 struct flock lock;
1170 int s;
1171
drh054889e2005-11-30 03:20:31 +00001172 assert( pFile );
1173 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1174 locktypeName(locktype), locktypeName(pFile->locktype),
1175 locktypeName(pLock->locktype), pLock->cnt , getpid());
1176 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001177
1178 /* If there is already a lock of this type or more restrictive on the
1179 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001180 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001181 */
drh054889e2005-11-30 03:20:31 +00001182 if( pFile->locktype>=locktype ){
1183 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1184 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001185 return SQLITE_OK;
1186 }
1187
drhb3e04342004-06-08 00:47:47 +00001188 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001189 */
drh054889e2005-11-30 03:20:31 +00001190 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001191 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001192 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001193
drh054889e2005-11-30 03:20:31 +00001194 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001195 */
drh66560ad2006-01-06 14:32:19 +00001196 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001197
1198 /* If some thread using this PID has a lock via a different OsFile*
1199 ** handle that precludes the requested lock, return BUSY.
1200 */
drh054889e2005-11-30 03:20:31 +00001201 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001202 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001203 ){
1204 rc = SQLITE_BUSY;
1205 goto end_lock;
1206 }
1207
1208 /* If a SHARED lock is requested, and some thread using this PID already
1209 ** has a SHARED or RESERVED lock, then increment reference counts and
1210 ** return SQLITE_OK.
1211 */
1212 if( locktype==SHARED_LOCK &&
1213 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1214 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001215 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001216 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001217 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001218 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001219 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001220 goto end_lock;
1221 }
1222
danielk197713adf8a2004-06-03 16:08:41 +00001223 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001224
danielk19779a1d0ab2004-06-01 14:09:28 +00001225 lock.l_whence = SEEK_SET;
1226
drh3cde3bb2004-06-12 02:17:14 +00001227 /* A PENDING lock is needed before acquiring a SHARED lock and before
1228 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1229 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001230 */
drh3cde3bb2004-06-12 02:17:14 +00001231 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001232 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001233 ){
danielk1977489468c2004-06-28 08:25:47 +00001234 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001235 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001236 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001237 if( s ){
1238 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1239 goto end_lock;
1240 }
drh3cde3bb2004-06-12 02:17:14 +00001241 }
1242
1243
1244 /* If control gets to this point, then actually go ahead and make
1245 ** operating system calls for the specified lock.
1246 */
1247 if( locktype==SHARED_LOCK ){
1248 assert( pLock->cnt==0 );
1249 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001250
drh2ac3ee92004-06-07 16:27:46 +00001251 /* Now get the read-lock */
1252 lock.l_start = SHARED_FIRST;
1253 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001254 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001255
1256 /* Drop the temporary PENDING lock */
1257 lock.l_start = PENDING_BYTE;
1258 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001259 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001260 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001261 rc = SQLITE_IOERR; /* This should never happen */
1262 goto end_lock;
1263 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001264 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001265 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1266 }else{
drh054889e2005-11-30 03:20:31 +00001267 pFile->locktype = SHARED_LOCK;
1268 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001269 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001270 }
drh3cde3bb2004-06-12 02:17:14 +00001271 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1272 /* We are trying for an exclusive lock but another thread in this
1273 ** same process is still holding a shared lock. */
1274 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001275 }else{
drh3cde3bb2004-06-12 02:17:14 +00001276 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001277 ** assumed that there is a SHARED or greater lock on the file
1278 ** already.
1279 */
drh054889e2005-11-30 03:20:31 +00001280 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001281 lock.l_type = F_WRLCK;
1282 switch( locktype ){
1283 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001284 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001285 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001286 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001287 lock.l_start = SHARED_FIRST;
1288 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001289 break;
1290 default:
1291 assert(0);
1292 }
drh054889e2005-11-30 03:20:31 +00001293 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001294 if( s ){
1295 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1296 }
drhbbd42a62004-05-22 17:41:58 +00001297 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001298
danielk1977ecb2a962004-06-02 06:30:16 +00001299 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001300 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001301 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001302 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001303 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001304 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001305 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001306
1307end_lock:
drh66560ad2006-01-06 14:32:19 +00001308 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001309 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001310 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001311 return rc;
1312}
1313
1314/*
drh054889e2005-11-30 03:20:31 +00001315** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001316** must be either NO_LOCK or SHARED_LOCK.
1317**
1318** If the locking level of the file descriptor is already at or below
1319** the requested locking level, this routine is a no-op.
1320**
drh9c105bb2004-10-02 20:38:28 +00001321** It is not possible for this routine to fail if the second argument
1322** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1323** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001324*/
drh9c06c952005-11-26 00:25:00 +00001325static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001326 struct lockInfo *pLock;
1327 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001328 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001329 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001330
drh054889e2005-11-30 03:20:31 +00001331 assert( pFile );
1332 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1333 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
1334 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
drha6abd042004-06-09 17:37:22 +00001335
1336 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001337 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001338 return SQLITE_OK;
1339 }
drh66560ad2006-01-06 14:32:19 +00001340 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001341 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001342 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001343 if( pFile->locktype>SHARED_LOCK ){
1344 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001345 if( locktype==SHARED_LOCK ){
1346 lock.l_type = F_RDLCK;
1347 lock.l_whence = SEEK_SET;
1348 lock.l_start = SHARED_FIRST;
1349 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001350 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001351 /* This should never happen */
1352 rc = SQLITE_IOERR;
1353 }
1354 }
drhbbd42a62004-05-22 17:41:58 +00001355 lock.l_type = F_UNLCK;
1356 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001357 lock.l_start = PENDING_BYTE;
1358 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001359 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001360 pLock->locktype = SHARED_LOCK;
1361 }else{
1362 rc = SQLITE_IOERR; /* This should never happen */
1363 }
drhbbd42a62004-05-22 17:41:58 +00001364 }
drha6abd042004-06-09 17:37:22 +00001365 if( locktype==NO_LOCK ){
1366 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001367
drha6abd042004-06-09 17:37:22 +00001368 /* Decrement the shared lock counter. Release the lock using an
1369 ** OS call only when all threads in this same process have released
1370 ** the lock.
1371 */
1372 pLock->cnt--;
1373 if( pLock->cnt==0 ){
1374 lock.l_type = F_UNLCK;
1375 lock.l_whence = SEEK_SET;
1376 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001377 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001378 pLock->locktype = NO_LOCK;
1379 }else{
1380 rc = SQLITE_IOERR; /* This should never happen */
1381 }
drha6abd042004-06-09 17:37:22 +00001382 }
1383
drhbbd42a62004-05-22 17:41:58 +00001384 /* Decrement the count of locks against this same file. When the
1385 ** count reaches zero, close any other file descriptors whose close
1386 ** was deferred because of outstanding locks.
1387 */
drh054889e2005-11-30 03:20:31 +00001388 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001389 pOpen->nLock--;
1390 assert( pOpen->nLock>=0 );
1391 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1392 int i;
1393 for(i=0; i<pOpen->nPending; i++){
1394 close(pOpen->aPending[i]);
1395 }
1396 sqliteFree(pOpen->aPending);
1397 pOpen->nPending = 0;
1398 pOpen->aPending = 0;
1399 }
1400 }
drh66560ad2006-01-06 14:32:19 +00001401 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001402 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001403 return rc;
drhbbd42a62004-05-22 17:41:58 +00001404}
1405
1406/*
danielk1977e3026632004-06-22 11:29:02 +00001407** Close a file.
1408*/
drh9cbe6352005-11-29 03:13:21 +00001409static int unixClose(OsFile **pId){
danielk1977441b09a2006-01-05 13:48:29 +00001410 SqliteTsd *pTsd = sqlite3Tsd();
drh054889e2005-11-30 03:20:31 +00001411 unixFile *id = (unixFile*)*pId;
drh9cbe6352005-11-29 03:13:21 +00001412 if( !id ) return SQLITE_OK;
drh2b4b5962005-06-15 17:47:55 +00001413 if( CHECK_THREADID(id) ) return SQLITE_MISUSE;
drh054889e2005-11-30 03:20:31 +00001414 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001415 if( id->dirfd>=0 ) close(id->dirfd);
1416 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001417 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001418
1419 /* Disable the sqlite3_release_memory() function */
1420 assert( !pTsd->disableReleaseMemory );
1421 pTsd->disableReleaseMemory = 1;
1422
danielk1977e3026632004-06-22 11:29:02 +00001423 if( id->pOpen->nLock ){
1424 /* If there are outstanding locks, do not actually close the file just
1425 ** yet because that would clear those locks. Instead, add the file
1426 ** descriptor to pOpen->aPending. It will be automatically closed when
1427 ** the last lock is cleared.
1428 */
1429 int *aNew;
1430 struct openCnt *pOpen = id->pOpen;
drhad81e872005-08-21 21:45:01 +00001431 aNew = sqliteRealloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001432 if( aNew==0 ){
1433 /* If a malloc fails, just leak the file descriptor */
1434 }else{
1435 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001436 pOpen->aPending[pOpen->nPending] = id->h;
1437 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001438 }
1439 }else{
1440 /* There are no outstanding locks so we can close the file immediately */
1441 close(id->h);
1442 }
1443 releaseLockInfo(id->pLock);
1444 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001445
1446 /* Disable the sqlite3_release_memory() function */
1447 pTsd->disableReleaseMemory = 0;
1448
drh66560ad2006-01-06 14:32:19 +00001449 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001450 id->isOpen = 0;
1451 TRACE2("CLOSE %-3d\n", id->h);
1452 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001453 sqliteFree(id);
1454 *pId = 0;
danielk1977e3026632004-06-22 11:29:02 +00001455 return SQLITE_OK;
1456}
1457
1458/*
drh0ccebe72005-06-07 22:22:50 +00001459** Turn a relative pathname into a full pathname. Return a pointer
1460** to the full pathname stored in space obtained from sqliteMalloc().
1461** The calling function is responsible for freeing this space once it
1462** is no longer needed.
1463*/
drh66560ad2006-01-06 14:32:19 +00001464char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001465 char *zFull = 0;
1466 if( zRelative[0]=='/' ){
1467 sqlite3SetString(&zFull, zRelative, (char*)0);
1468 }else{
drh79158e12005-09-06 21:40:45 +00001469 char *zBuf = sqliteMalloc(5000);
1470 if( zBuf==0 ){
1471 return 0;
1472 }
drh0ccebe72005-06-07 22:22:50 +00001473 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001474 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001475 (char*)0);
drh79158e12005-09-06 21:40:45 +00001476 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001477 }
1478 return zFull;
1479}
1480
drh18839212005-11-26 03:43:23 +00001481/*
drh9cbe6352005-11-29 03:13:21 +00001482** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001483*/
drh9cbe6352005-11-29 03:13:21 +00001484static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001485 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001486}
1487
1488/*
1489** Return the underlying file handle for an OsFile
1490*/
1491static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001492 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001493}
1494
1495/*
1496** Return an integer that indices the type of lock currently held
1497** by this handle. (Used for testing and analysis only.)
1498*/
1499static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001500 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001501}
drh0ccebe72005-06-07 22:22:50 +00001502
drh9c06c952005-11-26 00:25:00 +00001503/*
drh054889e2005-11-30 03:20:31 +00001504** This vector defines all the methods that can operate on an OsFile
1505** for unix.
drh9c06c952005-11-26 00:25:00 +00001506*/
drh054889e2005-11-30 03:20:31 +00001507static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001508 unixClose,
drh054889e2005-11-30 03:20:31 +00001509 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001510 unixRead,
1511 unixWrite,
1512 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001513 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001514 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001515 unixSetFullSync,
1516 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001517 unixFileSize,
1518 unixLock,
1519 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001520 unixLockState,
drh054889e2005-11-30 03:20:31 +00001521 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001522};
1523
drh054889e2005-11-30 03:20:31 +00001524/*
1525** Allocate memory for a unixFile. Initialize the new unixFile
1526** to the value given in pInit and return a pointer to the new
1527** OsFile. If we run out of memory, close the file and return NULL.
1528*/
1529static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1530 unixFile *pNew;
1531 pNew = sqliteMalloc( sizeof(unixFile) );
1532 if( pNew==0 ){
1533 close(pInit->h);
danielk19772e588c72005-12-09 14:25:08 +00001534 releaseLockInfo(pInit->pLock);
1535 releaseOpenCnt(pInit->pOpen);
drh054889e2005-11-30 03:20:31 +00001536 *pId = 0;
1537 return SQLITE_NOMEM;
1538 }else{
1539 *pNew = *pInit;
1540 pNew->pMethod = &sqlite3UnixIoMethod;
1541 *pId = (OsFile*)pNew;
1542 OpenCounter(+1);
1543 return SQLITE_OK;
1544 }
1545}
1546
drh9c06c952005-11-26 00:25:00 +00001547
drh0ccebe72005-06-07 22:22:50 +00001548#endif /* SQLITE_OMIT_DISKIO */
1549/***************************************************************************
1550** Everything above deals with file I/O. Everything that follows deals
1551** with other miscellanous aspects of the operating system interface
1552****************************************************************************/
1553
1554
1555/*
drhbbd42a62004-05-22 17:41:58 +00001556** Get information to seed the random number generator. The seed
1557** is written into the buffer zBuf[256]. The calling function must
1558** supply a sufficiently large buffer.
1559*/
drh66560ad2006-01-06 14:32:19 +00001560int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001561 /* We have to initialize zBuf to prevent valgrind from reporting
1562 ** errors. The reports issued by valgrind are incorrect - we would
1563 ** prefer that the randomness be increased by making use of the
1564 ** uninitialized space in zBuf - but valgrind errors tend to worry
1565 ** some users. Rather than argue, it seems easier just to initialize
1566 ** the whole array and silence valgrind, even if that means less randomness
1567 ** in the random seed.
1568 **
1569 ** When testing, initializing zBuf[] to zero is all we do. That means
1570 ** that we always use the same random number sequence.* This makes the
1571 ** tests repeatable.
1572 */
1573 memset(zBuf, 0, 256);
1574#if !defined(SQLITE_TEST)
1575 {
drh842b8642005-01-21 17:53:17 +00001576 int pid, fd;
1577 fd = open("/dev/urandom", O_RDONLY);
1578 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001579 time_t t;
1580 time(&t);
1581 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001582 pid = getpid();
1583 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1584 }else{
1585 read(fd, zBuf, 256);
1586 close(fd);
1587 }
drhbbd42a62004-05-22 17:41:58 +00001588 }
1589#endif
1590 return SQLITE_OK;
1591}
1592
1593/*
1594** Sleep for a little while. Return the amount of time slept.
1595*/
drh66560ad2006-01-06 14:32:19 +00001596int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001597#if defined(HAVE_USLEEP) && HAVE_USLEEP
1598 usleep(ms*1000);
1599 return ms;
1600#else
1601 sleep((ms+999)/1000);
1602 return 1000*((ms+999)/1000);
1603#endif
1604}
1605
1606/*
1607** Static variables used for thread synchronization
1608*/
1609static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001610#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001611static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001612#endif
drhbbd42a62004-05-22 17:41:58 +00001613
1614/*
1615** The following pair of routine implement mutual exclusion for
1616** multi-threaded processes. Only a single thread is allowed to
1617** executed code that is surrounded by EnterMutex() and LeaveMutex().
1618**
1619** SQLite uses only a single Mutex. There is not much critical
1620** code and what little there is executes quickly and without blocking.
1621*/
drh66560ad2006-01-06 14:32:19 +00001622void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001623#ifdef SQLITE_UNIX_THREADS
1624 pthread_mutex_lock(&mutex);
1625#endif
1626 assert( !inMutex );
1627 inMutex = 1;
1628}
drh66560ad2006-01-06 14:32:19 +00001629void sqlite3UnixLeaveMutex(){
drhbbd42a62004-05-22 17:41:58 +00001630 assert( inMutex );
1631 inMutex = 0;
1632#ifdef SQLITE_UNIX_THREADS
1633 pthread_mutex_unlock(&mutex);
1634#endif
1635}
1636
1637/*
drh88f474a2006-01-02 20:00:12 +00001638** Return TRUE if we are currently within the mutex and FALSE if not.
1639** This routine is intended for sanity checking only. It is designed
1640** for use in an assert() to verify that the mutex is held or not held
1641** in certain routines.
1642*/
drh66560ad2006-01-06 14:32:19 +00001643int sqlite3UnixInMutex(){
drh88f474a2006-01-02 20:00:12 +00001644 return inMutex;
1645}
1646
1647/*
danielk197713a68c32005-12-15 10:11:30 +00001648** This function is called automatically when a thread exists to delete
1649** the threads SqliteTsd structure.
1650**
1651** Because the SqliteTsd structure is required by higher level routines
1652** such as sqliteMalloc() we use OsFree() and OsMalloc() directly to
1653** allocate the thread specific data.
1654*/
danielk1977c529f522005-12-15 10:50:53 +00001655#ifdef SQLITE_UNIX_THREADS
danielk197713a68c32005-12-15 10:11:30 +00001656static void deleteTsd(void *pTsd){
drh66560ad2006-01-06 14:32:19 +00001657 sqlite3OsFree(pTsd);
danielk197713a68c32005-12-15 10:11:30 +00001658}
danielk1977c529f522005-12-15 10:50:53 +00001659#endif
danielk197713a68c32005-12-15 10:11:30 +00001660
1661/*
1662** The first time this function is called from a specific thread, nByte
1663** bytes of data area are allocated and zeroed. A pointer to the new
1664** allocation is returned to the caller.
1665**
1666** Each subsequent call to this function from the thread returns the same
1667** pointer. The argument is ignored in this case.
1668*/
drh66560ad2006-01-06 14:32:19 +00001669void *sqlite3UnixThreadSpecificData(int nByte){
danielk197713a68c32005-12-15 10:11:30 +00001670#ifdef SQLITE_UNIX_THREADS
1671 static pthread_key_t key;
1672 static int keyInit = 0;
1673 void *pTsd;
1674
1675 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001676 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001677 if( !keyInit ){
1678 int rc;
1679 rc = pthread_key_create(&key, deleteTsd);
1680 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001681 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001682 return 0;
1683 }
1684 keyInit = 1;
1685 }
drh66560ad2006-01-06 14:32:19 +00001686 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001687 }
1688
drh3fbb0b12006-01-06 00:36:00 +00001689 pTsd = pthread_getspecific(key);
danielk197713a68c32005-12-15 10:11:30 +00001690 if( !pTsd ){
drh66560ad2006-01-06 14:32:19 +00001691 pTsd = sqlite3OsMalloc(nByte);
danielk197713a68c32005-12-15 10:11:30 +00001692 if( pTsd ){
drh3fbb0b12006-01-06 00:36:00 +00001693 memset(pTsd, 0, nByte);
danielk197713a68c32005-12-15 10:11:30 +00001694 pthread_setspecific(key, pTsd);
1695 }
1696 }
1697 return pTsd;
1698#else
drh3fbb0b12006-01-06 00:36:00 +00001699 static void *pTsd = 0;
1700 if( !pTsd ){
drh66560ad2006-01-06 14:32:19 +00001701 pTsd = sqlite3OsMalloc(nByte);
drh3fbb0b12006-01-06 00:36:00 +00001702 if( pTsd ){
1703 memset(pTsd, 0, nByte);
1704 }
danielk197713a68c32005-12-15 10:11:30 +00001705 }
drh3fbb0b12006-01-06 00:36:00 +00001706 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001707#endif
1708}
1709
1710/*
drhbbd42a62004-05-22 17:41:58 +00001711** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001712** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001713*/
1714#ifdef SQLITE_TEST
1715int sqlite3_current_time = 0;
1716#endif
1717
1718/*
1719** Find the current time (in Universal Coordinated Time). Write the
1720** current time and date as a Julian Day number into *prNow and
1721** return 0. Return 1 if the time and date cannot be found.
1722*/
drh66560ad2006-01-06 14:32:19 +00001723int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001724#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001725 time_t t;
1726 time(&t);
1727 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001728#else
1729 struct timeval sNow;
1730 struct timezone sTz; /* Not used */
1731 gettimeofday(&sNow, &sTz);
1732 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1733#endif
drhbbd42a62004-05-22 17:41:58 +00001734#ifdef SQLITE_TEST
1735 if( sqlite3_current_time ){
1736 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1737 }
1738#endif
1739 return 0;
1740}
1741
drhbbd42a62004-05-22 17:41:58 +00001742#endif /* OS_UNIX */