blob: e603151a953d648b52cb13ba8721339165b52975 [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;
505 rc = fstat(fd, &statbuf);
506 if( rc!=0 ) return 1;
danielk1977441b09a2006-01-05 13:48:29 +0000507
drhbbd42a62004-05-22 17:41:58 +0000508 memset(&key1, 0, sizeof(key1));
509 key1.dev = statbuf.st_dev;
510 key1.ino = statbuf.st_ino;
drh5fdae772004-06-29 03:29:00 +0000511#ifdef SQLITE_UNIX_THREADS
512 if( threadsOverrideEachOthersLocks<0 ){
513 testThreadLockingBehavior(fd);
514 }
515 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
516#endif
drhbbd42a62004-05-22 17:41:58 +0000517 memset(&key2, 0, sizeof(key2));
518 key2.dev = statbuf.st_dev;
519 key2.ino = statbuf.st_ino;
520 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
521 if( pLock==0 ){
522 struct lockInfo *pOld;
523 pLock = sqliteMallocRaw( sizeof(*pLock) );
danielk1977441b09a2006-01-05 13:48:29 +0000524 if( pLock==0 ){
525 rc = 1;
526 goto exit_findlockinfo;
527 }
drhbbd42a62004-05-22 17:41:58 +0000528 pLock->key = key1;
529 pLock->nRef = 1;
530 pLock->cnt = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +0000531 pLock->locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000532 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
533 if( pOld!=0 ){
534 assert( pOld==pLock );
535 sqliteFree(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000536 rc = 1;
537 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000538 }
539 }else{
540 pLock->nRef++;
541 }
542 *ppLock = pLock;
543 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
544 if( pOpen==0 ){
545 struct openCnt *pOld;
546 pOpen = sqliteMallocRaw( sizeof(*pOpen) );
547 if( pOpen==0 ){
548 releaseLockInfo(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000549 rc = 1;
550 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000551 }
552 pOpen->key = key2;
553 pOpen->nRef = 1;
554 pOpen->nLock = 0;
555 pOpen->nPending = 0;
556 pOpen->aPending = 0;
557 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
558 if( pOld!=0 ){
559 assert( pOld==pOpen );
560 sqliteFree(pOpen);
561 releaseLockInfo(pLock);
danielk1977441b09a2006-01-05 13:48:29 +0000562 rc = 1;
563 goto exit_findlockinfo;
drhbbd42a62004-05-22 17:41:58 +0000564 }
565 }else{
566 pOpen->nRef++;
567 }
568 *ppOpen = pOpen;
danielk1977441b09a2006-01-05 13:48:29 +0000569
570exit_findlockinfo:
danielk1977441b09a2006-01-05 13:48:29 +0000571 return rc;
drhbbd42a62004-05-22 17:41:58 +0000572}
573
574/*
575** Delete the named file
576*/
drh66560ad2006-01-06 14:32:19 +0000577int sqlite3UnixDelete(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000578 unlink(zFilename);
579 return SQLITE_OK;
580}
581
582/*
583** Return TRUE if the named file exists.
584*/
drh66560ad2006-01-06 14:32:19 +0000585int sqlite3UnixFileExists(const char *zFilename){
drhbbd42a62004-05-22 17:41:58 +0000586 return access(zFilename, 0)==0;
587}
588
drh054889e2005-11-30 03:20:31 +0000589/* Forward declaration */
590static int allocateUnixFile(unixFile *pInit, OsFile **pId);
drh9cbe6352005-11-29 03:13:21 +0000591
592/*
drhbbd42a62004-05-22 17:41:58 +0000593** Attempt to open a file for both reading and writing. If that
594** fails, try opening it read-only. If the file does not exist,
595** try to create it.
596**
597** On success, a handle for the open file is written to *id
598** and *pReadonly is set to 0 if the file was opened for reading and
599** writing or 1 if the file was opened read-only. The function returns
600** SQLITE_OK.
601**
602** On failure, the function returns SQLITE_CANTOPEN and leaves
603** *id and *pReadonly unchanged.
604*/
drh66560ad2006-01-06 14:32:19 +0000605int sqlite3UnixOpenReadWrite(
drhbbd42a62004-05-22 17:41:58 +0000606 const char *zFilename,
drh9cbe6352005-11-29 03:13:21 +0000607 OsFile **pId,
drhbbd42a62004-05-22 17:41:58 +0000608 int *pReadonly
609){
610 int rc;
drh054889e2005-11-30 03:20:31 +0000611 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000612
drh66560ad2006-01-06 14:32:19 +0000613 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
drh9cbe6352005-11-29 03:13:21 +0000614 assert( 0==*pId );
615 f.dirfd = -1;
616 SET_THREADID(&f);
617 f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
drh8e855772005-05-17 11:25:31 +0000618 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000619 if( f.h<0 ){
drh6458e392004-07-20 01:14:13 +0000620#ifdef EISDIR
621 if( errno==EISDIR ){
622 return SQLITE_CANTOPEN;
623 }
624#endif
drh9cbe6352005-11-29 03:13:21 +0000625 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
626 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000627 return SQLITE_CANTOPEN;
628 }
629 *pReadonly = 1;
630 }else{
631 *pReadonly = 0;
632 }
drh66560ad2006-01-06 14:32:19 +0000633 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000634 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000635 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000636 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000637 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000638 return SQLITE_NOMEM;
639 }
drh9cbe6352005-11-29 03:13:21 +0000640 f.locktype = 0;
641 TRACE3("OPEN %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000642 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000643}
644
645
646/*
647** Attempt to open a new file for exclusive access by this process.
648** The file will be opened for both reading and writing. To avoid
649** a potential security problem, we do not allow the file to have
650** previously existed. Nor do we allow the file to be a symbolic
651** link.
652**
653** If delFlag is true, then make arrangements to automatically delete
654** the file when it is closed.
655**
656** On success, write the file handle into *id and return SQLITE_OK.
657**
658** On failure, return SQLITE_CANTOPEN.
659*/
drh66560ad2006-01-06 14:32:19 +0000660int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
drhbbd42a62004-05-22 17:41:58 +0000661 int rc;
drh054889e2005-11-30 03:20:31 +0000662 unixFile f;
drh9cbe6352005-11-29 03:13:21 +0000663
drh66560ad2006-01-06 14:32:19 +0000664 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
drh9cbe6352005-11-29 03:13:21 +0000665 assert( 0==*pId );
drhbbd42a62004-05-22 17:41:58 +0000666 if( access(zFilename, 0)==0 ){
667 return SQLITE_CANTOPEN;
668 }
drh9cbe6352005-11-29 03:13:21 +0000669 SET_THREADID(&f);
670 f.dirfd = -1;
671 f.h = open(zFilename,
drhd6459672005-08-13 17:17:01 +0000672 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
673 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh9cbe6352005-11-29 03:13:21 +0000674 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000675 return SQLITE_CANTOPEN;
676 }
drh66560ad2006-01-06 14:32:19 +0000677 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000678 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000679 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000680 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000681 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000682 unlink(zFilename);
683 return SQLITE_NOMEM;
684 }
drh9cbe6352005-11-29 03:13:21 +0000685 f.locktype = 0;
drhbbd42a62004-05-22 17:41:58 +0000686 if( delFlag ){
687 unlink(zFilename);
688 }
drh9cbe6352005-11-29 03:13:21 +0000689 TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
drh054889e2005-11-30 03:20:31 +0000690 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000691}
692
693/*
694** Attempt to open a new file for read-only access.
695**
696** On success, write the file handle into *id and return SQLITE_OK.
697**
698** On failure, return SQLITE_CANTOPEN.
699*/
drh66560ad2006-01-06 14:32:19 +0000700int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
drhbbd42a62004-05-22 17:41:58 +0000701 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(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
drh9cbe6352005-11-29 03:13:21 +0000705 assert( 0==*pId );
706 SET_THREADID(&f);
707 f.dirfd = -1;
708 f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
709 if( f.h<0 ){
drhbbd42a62004-05-22 17:41:58 +0000710 return SQLITE_CANTOPEN;
711 }
drh66560ad2006-01-06 14:32:19 +0000712 sqlite3OsEnterMutex();
drh9cbe6352005-11-29 03:13:21 +0000713 rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
drh66560ad2006-01-06 14:32:19 +0000714 sqlite3OsLeaveMutex();
drhbbd42a62004-05-22 17:41:58 +0000715 if( rc ){
drh9cbe6352005-11-29 03:13:21 +0000716 close(f.h);
drhbbd42a62004-05-22 17:41:58 +0000717 return SQLITE_NOMEM;
718 }
drh9cbe6352005-11-29 03:13:21 +0000719 f.locktype = 0;
720 TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
danielk1977261919c2005-12-06 12:52:59 +0000721
drh054889e2005-11-30 03:20:31 +0000722 return allocateUnixFile(&f, pId);
drhbbd42a62004-05-22 17:41:58 +0000723}
724
725/*
726** Attempt to open a file descriptor for the directory that contains a
727** file. This file descriptor can be used to fsync() the directory
728** in order to make sure the creation of a new file is actually written
729** to disk.
730**
731** This routine is only meaningful for Unix. It is a no-op under
732** windows since windows does not support hard links.
733**
drh9cbe6352005-11-29 03:13:21 +0000734** On success, a handle for a previously open file at *id is
drhbbd42a62004-05-22 17:41:58 +0000735** updated with the new directory file descriptor and SQLITE_OK is
736** returned.
737**
738** On failure, the function returns SQLITE_CANTOPEN and leaves
739** *id unchanged.
740*/
drh9c06c952005-11-26 00:25:00 +0000741static int unixOpenDirectory(
drh054889e2005-11-30 03:20:31 +0000742 OsFile *id,
743 const char *zDirname
drhbbd42a62004-05-22 17:41:58 +0000744){
drh054889e2005-11-30 03:20:31 +0000745 unixFile *pFile = (unixFile*)id;
746 if( pFile==0 ){
drhbbd42a62004-05-22 17:41:58 +0000747 /* Do not open the directory if the corresponding file is not already
748 ** open. */
749 return SQLITE_CANTOPEN;
750 }
drh054889e2005-11-30 03:20:31 +0000751 SET_THREADID(pFile);
752 assert( pFile->dirfd<0 );
753 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
754 if( pFile->dirfd<0 ){
drhbbd42a62004-05-22 17:41:58 +0000755 return SQLITE_CANTOPEN;
756 }
drh054889e2005-11-30 03:20:31 +0000757 TRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
drhbbd42a62004-05-22 17:41:58 +0000758 return SQLITE_OK;
759}
760
761/*
drhab3f9fe2004-08-14 17:10:10 +0000762** If the following global variable points to a string which is the
763** name of a directory, then that directory will be used to store
764** temporary files.
765*/
tpoindex9a09a3c2004-12-20 19:01:32 +0000766char *sqlite3_temp_directory = 0;
drhab3f9fe2004-08-14 17:10:10 +0000767
768/*
drhbbd42a62004-05-22 17:41:58 +0000769** Create a temporary file name in zBuf. zBuf must be big enough to
770** hold at least SQLITE_TEMPNAME_SIZE characters.
771*/
drh66560ad2006-01-06 14:32:19 +0000772int sqlite3UnixTempFileName(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +0000773 static const char *azDirs[] = {
drhab3f9fe2004-08-14 17:10:10 +0000774 0,
drhbbd42a62004-05-22 17:41:58 +0000775 "/var/tmp",
776 "/usr/tmp",
777 "/tmp",
778 ".",
779 };
drh57196282004-10-06 15:41:16 +0000780 static const unsigned char zChars[] =
drhbbd42a62004-05-22 17:41:58 +0000781 "abcdefghijklmnopqrstuvwxyz"
782 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
783 "0123456789";
784 int i, j;
785 struct stat buf;
786 const char *zDir = ".";
drheffd02b2004-08-29 23:42:13 +0000787 azDirs[0] = sqlite3_temp_directory;
drhbbd42a62004-05-22 17:41:58 +0000788 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
drhab3f9fe2004-08-14 17:10:10 +0000789 if( azDirs[i]==0 ) continue;
drhbbd42a62004-05-22 17:41:58 +0000790 if( stat(azDirs[i], &buf) ) continue;
791 if( !S_ISDIR(buf.st_mode) ) continue;
792 if( access(azDirs[i], 07) ) continue;
793 zDir = azDirs[i];
794 break;
795 }
796 do{
797 sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
798 j = strlen(zBuf);
799 sqlite3Randomness(15, &zBuf[j]);
800 for(i=0; i<15; i++, j++){
801 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
802 }
803 zBuf[j] = 0;
804 }while( access(zBuf,0)==0 );
805 return SQLITE_OK;
806}
807
808/*
tpoindex9a09a3c2004-12-20 19:01:32 +0000809** Check that a given pathname is a directory and is writable
810**
811*/
drh66560ad2006-01-06 14:32:19 +0000812int sqlite3UnixIsDirWritable(char *zBuf){
drh9c06c952005-11-26 00:25:00 +0000813#ifndef SQLITE_OMIT_PAGER_PRAGMAS
tpoindex9a09a3c2004-12-20 19:01:32 +0000814 struct stat buf;
815 if( zBuf==0 ) return 0;
drh268283b2005-01-08 15:44:25 +0000816 if( zBuf[0]==0 ) return 0;
tpoindex9a09a3c2004-12-20 19:01:32 +0000817 if( stat(zBuf, &buf) ) return 0;
818 if( !S_ISDIR(buf.st_mode) ) return 0;
819 if( access(zBuf, 07) ) return 0;
drh9c06c952005-11-26 00:25:00 +0000820#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
tpoindex9a09a3c2004-12-20 19:01:32 +0000821 return 1;
822}
823
824/*
drhbbd42a62004-05-22 17:41:58 +0000825** Read data from a file into a buffer. Return SQLITE_OK if all
826** bytes were read successfully and SQLITE_IOERR if anything goes
827** wrong.
828*/
drh9c06c952005-11-26 00:25:00 +0000829static int unixRead(OsFile *id, void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000830 int got;
drh9cbe6352005-11-29 03:13:21 +0000831 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000832 SimulateIOError(SQLITE_IOERR);
833 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000834 got = read(((unixFile*)id)->h, pBuf, amt);
drhbbd42a62004-05-22 17:41:58 +0000835 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000836 TRACE5("READ %-3d %5d %7d %d\n", ((unixFile*)id)->h, got,
837 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000838 SEEK(0);
839 /* if( got<0 ) got = 0; */
840 if( got==amt ){
841 return SQLITE_OK;
842 }else{
843 return SQLITE_IOERR;
844 }
845}
846
847/*
848** Write data from a buffer into a file. Return SQLITE_OK on success
849** or some other error code on failure.
850*/
drh9c06c952005-11-26 00:25:00 +0000851static int unixWrite(OsFile *id, const void *pBuf, int amt){
drhbbd42a62004-05-22 17:41:58 +0000852 int wrote = 0;
drh9cbe6352005-11-29 03:13:21 +0000853 assert( id );
drh4c7f9412005-02-03 00:29:47 +0000854 assert( amt>0 );
drhbbd42a62004-05-22 17:41:58 +0000855 SimulateIOError(SQLITE_IOERR);
drh047d4832004-10-01 14:38:02 +0000856 SimulateDiskfullError;
drhbbd42a62004-05-22 17:41:58 +0000857 TIMER_START;
drh054889e2005-11-30 03:20:31 +0000858 while( amt>0 && (wrote = write(((unixFile*)id)->h, pBuf, amt))>0 ){
drhbbd42a62004-05-22 17:41:58 +0000859 amt -= wrote;
860 pBuf = &((char*)pBuf)[wrote];
861 }
862 TIMER_END;
drh054889e2005-11-30 03:20:31 +0000863 TRACE5("WRITE %-3d %5d %7d %d\n", ((unixFile*)id)->h, wrote,
864 last_page, TIMER_ELAPSED);
drhbbd42a62004-05-22 17:41:58 +0000865 SEEK(0);
866 if( amt>0 ){
867 return SQLITE_FULL;
868 }
869 return SQLITE_OK;
870}
871
872/*
873** Move the read/write pointer in a file.
874*/
drh9c06c952005-11-26 00:25:00 +0000875static int unixSeek(OsFile *id, i64 offset){
drh9cbe6352005-11-29 03:13:21 +0000876 assert( id );
drhbbd42a62004-05-22 17:41:58 +0000877 SEEK(offset/1024 + 1);
drhb4746b92005-09-09 01:32:06 +0000878#ifdef SQLITE_TEST
879 if( offset ) SimulateDiskfullError
880#endif
drh054889e2005-11-30 03:20:31 +0000881 lseek(((unixFile*)id)->h, offset, SEEK_SET);
drhbbd42a62004-05-22 17:41:58 +0000882 return SQLITE_OK;
883}
884
drhb851b2c2005-03-10 14:11:12 +0000885#ifdef SQLITE_TEST
886/*
887** Count the number of fullsyncs and normal syncs. This is used to test
888** that syncs and fullsyncs are occuring at the right times.
889*/
890int sqlite3_sync_count = 0;
891int sqlite3_fullsync_count = 0;
892#endif
893
drhf2f23912005-10-05 10:29:36 +0000894/*
895** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
896** Otherwise use fsync() in its place.
897*/
898#ifndef HAVE_FDATASYNC
899# define fdatasync fsync
900#endif
901
drhb851b2c2005-03-10 14:11:12 +0000902
drhbbd42a62004-05-22 17:41:58 +0000903/*
drhdd809b02004-07-17 21:44:57 +0000904** The fsync() system call does not work as advertised on many
905** unix systems. The following procedure is an attempt to make
906** it work better.
drh1398ad32005-01-19 23:24:50 +0000907**
908** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
909** for testing when we want to run through the test suite quickly.
910** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
911** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
912** or power failure will likely corrupt the database file.
drhdd809b02004-07-17 21:44:57 +0000913*/
drheb796a72005-09-08 12:38:41 +0000914static int full_fsync(int fd, int fullSync, int dataOnly){
drhdd809b02004-07-17 21:44:57 +0000915 int rc;
drhb851b2c2005-03-10 14:11:12 +0000916
917 /* Record the number of times that we do a normal fsync() and
918 ** FULLSYNC. This is used during testing to verify that this procedure
919 ** gets called with the correct arguments.
920 */
921#ifdef SQLITE_TEST
922 if( fullSync ) sqlite3_fullsync_count++;
923 sqlite3_sync_count++;
924#endif
925
926 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
927 ** no-op
928 */
929#ifdef SQLITE_NO_SYNC
930 rc = SQLITE_OK;
931#else
932
drhdd809b02004-07-17 21:44:57 +0000933#ifdef F_FULLFSYNC
drhb851b2c2005-03-10 14:11:12 +0000934 if( fullSync ){
drhf30cc942005-03-11 17:52:34 +0000935 rc = fcntl(fd, F_FULLFSYNC, 0);
drhb851b2c2005-03-10 14:11:12 +0000936 }else{
937 rc = 1;
938 }
939 /* If the FULLSYNC failed, try to do a normal fsync() */
drhdd809b02004-07-17 21:44:57 +0000940 if( rc ) rc = fsync(fd);
drhb851b2c2005-03-10 14:11:12 +0000941
drhc035e6e2005-09-22 15:45:04 +0000942#else /* if !defined(F_FULLSYNC) */
drheb796a72005-09-08 12:38:41 +0000943 if( dataOnly ){
944 rc = fdatasync(fd);
drhf2f23912005-10-05 10:29:36 +0000945 }else{
drheb796a72005-09-08 12:38:41 +0000946 rc = fsync(fd);
947 }
drhf30cc942005-03-11 17:52:34 +0000948#endif /* defined(F_FULLFSYNC) */
drhb851b2c2005-03-10 14:11:12 +0000949#endif /* defined(SQLITE_NO_SYNC) */
950
drhdd809b02004-07-17 21:44:57 +0000951 return rc;
952}
953
954/*
drhbbd42a62004-05-22 17:41:58 +0000955** Make sure all writes to a particular file are committed to disk.
956**
drheb796a72005-09-08 12:38:41 +0000957** If dataOnly==0 then both the file itself and its metadata (file
958** size, access time, etc) are synced. If dataOnly!=0 then only the
959** file data is synced.
960**
drhbbd42a62004-05-22 17:41:58 +0000961** Under Unix, also make sure that the directory entry for the file
962** has been created by fsync-ing the directory that contains the file.
963** If we do not do this and we encounter a power failure, the directory
964** entry for the journal might not exist after we reboot. The next
965** SQLite to access the file will not know that the journal exists (because
966** the directory entry for the journal was never created) and the transaction
967** will not roll back - possibly leading to database corruption.
968*/
drh9c06c952005-11-26 00:25:00 +0000969static int unixSync(OsFile *id, int dataOnly){
drh054889e2005-11-30 03:20:31 +0000970 unixFile *pFile = (unixFile*)id;
971 assert( pFile );
drhbbd42a62004-05-22 17:41:58 +0000972 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +0000973 TRACE2("SYNC %-3d\n", pFile->h);
974 if( full_fsync(pFile->h, pFile->fullSync, dataOnly) ){
drhbbd42a62004-05-22 17:41:58 +0000975 return SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +0000976 }
drh054889e2005-11-30 03:20:31 +0000977 if( pFile->dirfd>=0 ){
978 TRACE2("DIRSYNC %-3d\n", pFile->dirfd);
danielk1977d7c03f72005-11-25 10:38:22 +0000979#ifndef SQLITE_DISABLE_DIRSYNC
drh054889e2005-11-30 03:20:31 +0000980 if( full_fsync(pFile->dirfd, pFile->fullSync, 0) ){
danielk19770964b232005-11-25 08:47:57 +0000981 return SQLITE_IOERR;
982 }
danielk1977d7c03f72005-11-25 10:38:22 +0000983#endif
drh054889e2005-11-30 03:20:31 +0000984 close(pFile->dirfd); /* Only need to sync once, so close the directory */
985 pFile->dirfd = -1; /* when we are done. */
drha2854222004-06-17 19:04:17 +0000986 }
drha2854222004-06-17 19:04:17 +0000987 return SQLITE_OK;
drhbbd42a62004-05-22 17:41:58 +0000988}
989
990/*
danielk1977962398d2004-06-14 09:35:16 +0000991** Sync the directory zDirname. This is a no-op on operating systems other
992** than UNIX.
drhb851b2c2005-03-10 14:11:12 +0000993**
994** This is used to make sure the master journal file has truely been deleted
995** before making changes to individual journals on a multi-database commit.
drhf30cc942005-03-11 17:52:34 +0000996** The F_FULLFSYNC option is not needed here.
danielk1977962398d2004-06-14 09:35:16 +0000997*/
drh66560ad2006-01-06 14:32:19 +0000998int sqlite3UnixSyncDirectory(const char *zDirname){
danielk1977d7c03f72005-11-25 10:38:22 +0000999#ifdef SQLITE_DISABLE_DIRSYNC
1000 return SQLITE_OK;
1001#else
danielk1977962398d2004-06-14 09:35:16 +00001002 int fd;
1003 int r;
danielk1977369f27e2004-06-15 11:40:04 +00001004 SimulateIOError(SQLITE_IOERR);
drh8e855772005-05-17 11:25:31 +00001005 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
danielk1977369f27e2004-06-15 11:40:04 +00001006 TRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
danielk1977962398d2004-06-14 09:35:16 +00001007 if( fd<0 ){
1008 return SQLITE_CANTOPEN;
1009 }
1010 r = fsync(fd);
1011 close(fd);
1012 return ((r==0)?SQLITE_OK:SQLITE_IOERR);
danielk1977d7c03f72005-11-25 10:38:22 +00001013#endif
danielk1977962398d2004-06-14 09:35:16 +00001014}
1015
1016/*
drhbbd42a62004-05-22 17:41:58 +00001017** Truncate an open file to a specified size
1018*/
drh9c06c952005-11-26 00:25:00 +00001019static int unixTruncate(OsFile *id, i64 nByte){
drh9cbe6352005-11-29 03:13:21 +00001020 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001021 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001022 return ftruncate(((unixFile*)id)->h, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
drhbbd42a62004-05-22 17:41:58 +00001023}
1024
1025/*
1026** Determine the current size of a file in bytes
1027*/
drh9c06c952005-11-26 00:25:00 +00001028static int unixFileSize(OsFile *id, i64 *pSize){
drhbbd42a62004-05-22 17:41:58 +00001029 struct stat buf;
drh9cbe6352005-11-29 03:13:21 +00001030 assert( id );
drhbbd42a62004-05-22 17:41:58 +00001031 SimulateIOError(SQLITE_IOERR);
drh054889e2005-11-30 03:20:31 +00001032 if( fstat(((unixFile*)id)->h, &buf)!=0 ){
drhbbd42a62004-05-22 17:41:58 +00001033 return SQLITE_IOERR;
1034 }
1035 *pSize = buf.st_size;
1036 return SQLITE_OK;
1037}
1038
danielk19779a1d0ab2004-06-01 14:09:28 +00001039/*
danielk197713adf8a2004-06-03 16:08:41 +00001040** This routine checks if there is a RESERVED lock held on the specified
1041** file by this or any other process. If such a lock is held, return
drh2ac3ee92004-06-07 16:27:46 +00001042** non-zero. If the file is unlocked or holds only SHARED locks, then
1043** return zero.
danielk197713adf8a2004-06-03 16:08:41 +00001044*/
drh9c06c952005-11-26 00:25:00 +00001045static int unixCheckReservedLock(OsFile *id){
danielk197713adf8a2004-06-03 16:08:41 +00001046 int r = 0;
drh054889e2005-11-30 03:20:31 +00001047 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001048
drh054889e2005-11-30 03:20:31 +00001049 assert( pFile );
1050 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
drh66560ad2006-01-06 14:32:19 +00001051 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001052
1053 /* Check if a thread in this process holds such a lock */
drh054889e2005-11-30 03:20:31 +00001054 if( pFile->pLock->locktype>SHARED_LOCK ){
danielk197713adf8a2004-06-03 16:08:41 +00001055 r = 1;
1056 }
1057
drh2ac3ee92004-06-07 16:27:46 +00001058 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001059 */
1060 if( !r ){
1061 struct flock lock;
1062 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001063 lock.l_start = RESERVED_BYTE;
1064 lock.l_len = 1;
1065 lock.l_type = F_WRLCK;
drh054889e2005-11-30 03:20:31 +00001066 fcntl(pFile->h, F_GETLK, &lock);
danielk197713adf8a2004-06-03 16:08:41 +00001067 if( lock.l_type!=F_UNLCK ){
1068 r = 1;
1069 }
1070 }
1071
drh66560ad2006-01-06 14:32:19 +00001072 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001073 TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
danielk197713adf8a2004-06-03 16:08:41 +00001074
1075 return r;
1076}
1077
danielk19772b444852004-06-29 07:45:33 +00001078#ifdef SQLITE_DEBUG
1079/*
1080** Helper function for printing out trace information from debugging
1081** binaries. This returns the string represetation of the supplied
1082** integer lock-type.
1083*/
drh054889e2005-11-30 03:20:31 +00001084static const char *locktypeName(int locktype){
danielk19772b444852004-06-29 07:45:33 +00001085 switch( locktype ){
1086 case NO_LOCK: return "NONE";
1087 case SHARED_LOCK: return "SHARED";
1088 case RESERVED_LOCK: return "RESERVED";
1089 case PENDING_LOCK: return "PENDING";
1090 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
1091 }
1092 return "ERROR";
1093}
1094#endif
1095
danielk197713adf8a2004-06-03 16:08:41 +00001096/*
danielk19779a1d0ab2004-06-01 14:09:28 +00001097** Lock the file with the lock specified by parameter locktype - one
1098** of the following:
1099**
drh2ac3ee92004-06-07 16:27:46 +00001100** (1) SHARED_LOCK
1101** (2) RESERVED_LOCK
1102** (3) PENDING_LOCK
1103** (4) EXCLUSIVE_LOCK
1104**
drhb3e04342004-06-08 00:47:47 +00001105** Sometimes when requesting one lock state, additional lock states
1106** are inserted in between. The locking might fail on one of the later
1107** transitions leaving the lock state different from what it started but
1108** still short of its goal. The following chart shows the allowed
1109** transitions and the inserted intermediate states:
1110**
1111** UNLOCKED -> SHARED
1112** SHARED -> RESERVED
1113** SHARED -> (PENDING) -> EXCLUSIVE
1114** RESERVED -> (PENDING) -> EXCLUSIVE
1115** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001116**
drha6abd042004-06-09 17:37:22 +00001117** This routine will only increase a lock. Use the sqlite3OsUnlock()
1118** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001119*/
drh9c06c952005-11-26 00:25:00 +00001120static int unixLock(OsFile *id, int locktype){
danielk1977f42f25c2004-06-25 07:21:28 +00001121 /* The following describes the implementation of the various locks and
1122 ** lock transitions in terms of the POSIX advisory shared and exclusive
1123 ** lock primitives (called read-locks and write-locks below, to avoid
1124 ** confusion with SQLite lock names). The algorithms are complicated
1125 ** slightly in order to be compatible with windows systems simultaneously
1126 ** accessing the same database file, in case that is ever required.
1127 **
1128 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1129 ** byte', each single bytes at well known offsets, and the 'shared byte
1130 ** range', a range of 510 bytes at a well known offset.
1131 **
1132 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1133 ** byte'. If this is successful, a random byte from the 'shared byte
1134 ** range' is read-locked and the lock on the 'pending byte' released.
1135 **
danielk197790ba3bd2004-06-25 08:32:25 +00001136 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1137 ** A RESERVED lock is implemented by grabbing a write-lock on the
1138 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001139 **
1140 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001141 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1142 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1143 ** obtained, but existing SHARED locks are allowed to persist. A process
1144 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1145 ** This property is used by the algorithm for rolling back a journal file
1146 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001147 **
danielk197790ba3bd2004-06-25 08:32:25 +00001148 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1149 ** implemented by obtaining a write-lock on the entire 'shared byte
1150 ** range'. Since all other locks require a read-lock on one of the bytes
1151 ** within this range, this ensures that no other locks are held on the
1152 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001153 **
1154 ** The reason a single byte cannot be used instead of the 'shared byte
1155 ** range' is that some versions of windows do not support read-locks. By
1156 ** locking a random byte from a range, concurrent SHARED locks may exist
1157 ** even if the locking primitive used is always a write-lock.
1158 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001159 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001160 unixFile *pFile = (unixFile*)id;
1161 struct lockInfo *pLock = pFile->pLock;
danielk19779a1d0ab2004-06-01 14:09:28 +00001162 struct flock lock;
1163 int s;
1164
drh054889e2005-11-30 03:20:31 +00001165 assert( pFile );
1166 TRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
1167 locktypeName(locktype), locktypeName(pFile->locktype),
1168 locktypeName(pLock->locktype), pLock->cnt , getpid());
1169 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001170
1171 /* If there is already a lock of this type or more restrictive on the
1172 ** OsFile, do nothing. Don't use the end_lock: exit path, as
drh66560ad2006-01-06 14:32:19 +00001173 ** sqlite3OsEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001174 */
drh054889e2005-11-30 03:20:31 +00001175 if( pFile->locktype>=locktype ){
1176 TRACE3("LOCK %d %s ok (already held)\n", pFile->h,
1177 locktypeName(locktype));
danielk19779a1d0ab2004-06-01 14:09:28 +00001178 return SQLITE_OK;
1179 }
1180
drhb3e04342004-06-08 00:47:47 +00001181 /* Make sure the locking sequence is correct
drh2ac3ee92004-06-07 16:27:46 +00001182 */
drh054889e2005-11-30 03:20:31 +00001183 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
drhb3e04342004-06-08 00:47:47 +00001184 assert( locktype!=PENDING_LOCK );
drh054889e2005-11-30 03:20:31 +00001185 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001186
drh054889e2005-11-30 03:20:31 +00001187 /* This mutex is needed because pFile->pLock is shared across threads
drhb3e04342004-06-08 00:47:47 +00001188 */
drh66560ad2006-01-06 14:32:19 +00001189 sqlite3OsEnterMutex();
danielk19779a1d0ab2004-06-01 14:09:28 +00001190
1191 /* If some thread using this PID has a lock via a different OsFile*
1192 ** handle that precludes the requested lock, return BUSY.
1193 */
drh054889e2005-11-30 03:20:31 +00001194 if( (pFile->locktype!=pLock->locktype &&
drh2ac3ee92004-06-07 16:27:46 +00001195 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001196 ){
1197 rc = SQLITE_BUSY;
1198 goto end_lock;
1199 }
1200
1201 /* If a SHARED lock is requested, and some thread using this PID already
1202 ** has a SHARED or RESERVED lock, then increment reference counts and
1203 ** return SQLITE_OK.
1204 */
1205 if( locktype==SHARED_LOCK &&
1206 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
1207 assert( locktype==SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001208 assert( pFile->locktype==0 );
danielk1977ecb2a962004-06-02 06:30:16 +00001209 assert( pLock->cnt>0 );
drh054889e2005-11-30 03:20:31 +00001210 pFile->locktype = SHARED_LOCK;
danielk19779a1d0ab2004-06-01 14:09:28 +00001211 pLock->cnt++;
drh054889e2005-11-30 03:20:31 +00001212 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001213 goto end_lock;
1214 }
1215
danielk197713adf8a2004-06-03 16:08:41 +00001216 lock.l_len = 1L;
drh2b4b5962005-06-15 17:47:55 +00001217
danielk19779a1d0ab2004-06-01 14:09:28 +00001218 lock.l_whence = SEEK_SET;
1219
drh3cde3bb2004-06-12 02:17:14 +00001220 /* A PENDING lock is needed before acquiring a SHARED lock and before
1221 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1222 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001223 */
drh3cde3bb2004-06-12 02:17:14 +00001224 if( locktype==SHARED_LOCK
drh054889e2005-11-30 03:20:31 +00001225 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001226 ){
danielk1977489468c2004-06-28 08:25:47 +00001227 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001228 lock.l_start = PENDING_BYTE;
drh054889e2005-11-30 03:20:31 +00001229 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001230 if( s ){
1231 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1232 goto end_lock;
1233 }
drh3cde3bb2004-06-12 02:17:14 +00001234 }
1235
1236
1237 /* If control gets to this point, then actually go ahead and make
1238 ** operating system calls for the specified lock.
1239 */
1240 if( locktype==SHARED_LOCK ){
1241 assert( pLock->cnt==0 );
1242 assert( pLock->locktype==0 );
danielk19779a1d0ab2004-06-01 14:09:28 +00001243
drh2ac3ee92004-06-07 16:27:46 +00001244 /* Now get the read-lock */
1245 lock.l_start = SHARED_FIRST;
1246 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001247 s = fcntl(pFile->h, F_SETLK, &lock);
drh2ac3ee92004-06-07 16:27:46 +00001248
1249 /* Drop the temporary PENDING lock */
1250 lock.l_start = PENDING_BYTE;
1251 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001252 lock.l_type = F_UNLCK;
drh054889e2005-11-30 03:20:31 +00001253 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh2b4b5962005-06-15 17:47:55 +00001254 rc = SQLITE_IOERR; /* This should never happen */
1255 goto end_lock;
1256 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001257 if( s ){
drhbbd42a62004-05-22 17:41:58 +00001258 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1259 }else{
drh054889e2005-11-30 03:20:31 +00001260 pFile->locktype = SHARED_LOCK;
1261 pFile->pOpen->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001262 pLock->cnt = 1;
drhbbd42a62004-05-22 17:41:58 +00001263 }
drh3cde3bb2004-06-12 02:17:14 +00001264 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
1265 /* We are trying for an exclusive lock but another thread in this
1266 ** same process is still holding a shared lock. */
1267 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001268 }else{
drh3cde3bb2004-06-12 02:17:14 +00001269 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001270 ** assumed that there is a SHARED or greater lock on the file
1271 ** already.
1272 */
drh054889e2005-11-30 03:20:31 +00001273 assert( 0!=pFile->locktype );
danielk19779a1d0ab2004-06-01 14:09:28 +00001274 lock.l_type = F_WRLCK;
1275 switch( locktype ){
1276 case RESERVED_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001277 lock.l_start = RESERVED_BYTE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001278 break;
danielk19779a1d0ab2004-06-01 14:09:28 +00001279 case EXCLUSIVE_LOCK:
drh2ac3ee92004-06-07 16:27:46 +00001280 lock.l_start = SHARED_FIRST;
1281 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001282 break;
1283 default:
1284 assert(0);
1285 }
drh054889e2005-11-30 03:20:31 +00001286 s = fcntl(pFile->h, F_SETLK, &lock);
danielk19779a1d0ab2004-06-01 14:09:28 +00001287 if( s ){
1288 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
1289 }
drhbbd42a62004-05-22 17:41:58 +00001290 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001291
danielk1977ecb2a962004-06-02 06:30:16 +00001292 if( rc==SQLITE_OK ){
drh054889e2005-11-30 03:20:31 +00001293 pFile->locktype = locktype;
danielk1977ecb2a962004-06-02 06:30:16 +00001294 pLock->locktype = locktype;
drh3cde3bb2004-06-12 02:17:14 +00001295 }else if( locktype==EXCLUSIVE_LOCK ){
drh054889e2005-11-30 03:20:31 +00001296 pFile->locktype = PENDING_LOCK;
drh3cde3bb2004-06-12 02:17:14 +00001297 pLock->locktype = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001298 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001299
1300end_lock:
drh66560ad2006-01-06 14:32:19 +00001301 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001302 TRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
danielk19772b444852004-06-29 07:45:33 +00001303 rc==SQLITE_OK ? "ok" : "failed");
drhbbd42a62004-05-22 17:41:58 +00001304 return rc;
1305}
1306
1307/*
drh054889e2005-11-30 03:20:31 +00001308** Lower the locking level on file descriptor pFile to locktype. locktype
drha6abd042004-06-09 17:37:22 +00001309** must be either NO_LOCK or SHARED_LOCK.
1310**
1311** If the locking level of the file descriptor is already at or below
1312** the requested locking level, this routine is a no-op.
1313**
drh9c105bb2004-10-02 20:38:28 +00001314** It is not possible for this routine to fail if the second argument
1315** is NO_LOCK. If the second argument is SHARED_LOCK, this routine
1316** might return SQLITE_IOERR instead of SQLITE_OK.
drhbbd42a62004-05-22 17:41:58 +00001317*/
drh9c06c952005-11-26 00:25:00 +00001318static int unixUnlock(OsFile *id, int locktype){
drha6abd042004-06-09 17:37:22 +00001319 struct lockInfo *pLock;
1320 struct flock lock;
drh9c105bb2004-10-02 20:38:28 +00001321 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001322 unixFile *pFile = (unixFile*)id;
drha6abd042004-06-09 17:37:22 +00001323
drh054889e2005-11-30 03:20:31 +00001324 assert( pFile );
1325 TRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
1326 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
1327 if( CHECK_THREADID(pFile) ) return SQLITE_MISUSE;
drha6abd042004-06-09 17:37:22 +00001328
1329 assert( locktype<=SHARED_LOCK );
drh054889e2005-11-30 03:20:31 +00001330 if( pFile->locktype<=locktype ){
drha6abd042004-06-09 17:37:22 +00001331 return SQLITE_OK;
1332 }
drh66560ad2006-01-06 14:32:19 +00001333 sqlite3OsEnterMutex();
drh054889e2005-11-30 03:20:31 +00001334 pLock = pFile->pLock;
drha6abd042004-06-09 17:37:22 +00001335 assert( pLock->cnt!=0 );
drh054889e2005-11-30 03:20:31 +00001336 if( pFile->locktype>SHARED_LOCK ){
1337 assert( pLock->locktype==pFile->locktype );
drh9c105bb2004-10-02 20:38:28 +00001338 if( locktype==SHARED_LOCK ){
1339 lock.l_type = F_RDLCK;
1340 lock.l_whence = SEEK_SET;
1341 lock.l_start = SHARED_FIRST;
1342 lock.l_len = SHARED_SIZE;
drh054889e2005-11-30 03:20:31 +00001343 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
drh9c105bb2004-10-02 20:38:28 +00001344 /* This should never happen */
1345 rc = SQLITE_IOERR;
1346 }
1347 }
drhbbd42a62004-05-22 17:41:58 +00001348 lock.l_type = F_UNLCK;
1349 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001350 lock.l_start = PENDING_BYTE;
1351 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
drh054889e2005-11-30 03:20:31 +00001352 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001353 pLock->locktype = SHARED_LOCK;
1354 }else{
1355 rc = SQLITE_IOERR; /* This should never happen */
1356 }
drhbbd42a62004-05-22 17:41:58 +00001357 }
drha6abd042004-06-09 17:37:22 +00001358 if( locktype==NO_LOCK ){
1359 struct openCnt *pOpen;
danielk1977ecb2a962004-06-02 06:30:16 +00001360
drha6abd042004-06-09 17:37:22 +00001361 /* Decrement the shared lock counter. Release the lock using an
1362 ** OS call only when all threads in this same process have released
1363 ** the lock.
1364 */
1365 pLock->cnt--;
1366 if( pLock->cnt==0 ){
1367 lock.l_type = F_UNLCK;
1368 lock.l_whence = SEEK_SET;
1369 lock.l_start = lock.l_len = 0L;
drh054889e2005-11-30 03:20:31 +00001370 if( fcntl(pFile->h, F_SETLK, &lock)==0 ){
drh2b4b5962005-06-15 17:47:55 +00001371 pLock->locktype = NO_LOCK;
1372 }else{
1373 rc = SQLITE_IOERR; /* This should never happen */
1374 }
drha6abd042004-06-09 17:37:22 +00001375 }
1376
drhbbd42a62004-05-22 17:41:58 +00001377 /* Decrement the count of locks against this same file. When the
1378 ** count reaches zero, close any other file descriptors whose close
1379 ** was deferred because of outstanding locks.
1380 */
drh054889e2005-11-30 03:20:31 +00001381 pOpen = pFile->pOpen;
drhbbd42a62004-05-22 17:41:58 +00001382 pOpen->nLock--;
1383 assert( pOpen->nLock>=0 );
1384 if( pOpen->nLock==0 && pOpen->nPending>0 ){
1385 int i;
1386 for(i=0; i<pOpen->nPending; i++){
1387 close(pOpen->aPending[i]);
1388 }
1389 sqliteFree(pOpen->aPending);
1390 pOpen->nPending = 0;
1391 pOpen->aPending = 0;
1392 }
1393 }
drh66560ad2006-01-06 14:32:19 +00001394 sqlite3OsLeaveMutex();
drh054889e2005-11-30 03:20:31 +00001395 pFile->locktype = locktype;
drh9c105bb2004-10-02 20:38:28 +00001396 return rc;
drhbbd42a62004-05-22 17:41:58 +00001397}
1398
1399/*
danielk1977e3026632004-06-22 11:29:02 +00001400** Close a file.
1401*/
drh9cbe6352005-11-29 03:13:21 +00001402static int unixClose(OsFile **pId){
drh054889e2005-11-30 03:20:31 +00001403 unixFile *id = (unixFile*)*pId;
drh9cbe6352005-11-29 03:13:21 +00001404 if( !id ) return SQLITE_OK;
drh2b4b5962005-06-15 17:47:55 +00001405 if( CHECK_THREADID(id) ) return SQLITE_MISUSE;
drh054889e2005-11-30 03:20:31 +00001406 unixUnlock(*pId, NO_LOCK);
danielk1977e3026632004-06-22 11:29:02 +00001407 if( id->dirfd>=0 ) close(id->dirfd);
1408 id->dirfd = -1;
drh66560ad2006-01-06 14:32:19 +00001409 sqlite3OsEnterMutex();
danielk1977441b09a2006-01-05 13:48:29 +00001410
danielk1977e3026632004-06-22 11:29:02 +00001411 if( id->pOpen->nLock ){
1412 /* If there are outstanding locks, do not actually close the file just
1413 ** yet because that would clear those locks. Instead, add the file
1414 ** descriptor to pOpen->aPending. It will be automatically closed when
1415 ** the last lock is cleared.
1416 */
1417 int *aNew;
1418 struct openCnt *pOpen = id->pOpen;
drhad81e872005-08-21 21:45:01 +00001419 aNew = sqliteRealloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
danielk1977e3026632004-06-22 11:29:02 +00001420 if( aNew==0 ){
1421 /* If a malloc fails, just leak the file descriptor */
1422 }else{
1423 pOpen->aPending = aNew;
drhad81e872005-08-21 21:45:01 +00001424 pOpen->aPending[pOpen->nPending] = id->h;
1425 pOpen->nPending++;
danielk1977e3026632004-06-22 11:29:02 +00001426 }
1427 }else{
1428 /* There are no outstanding locks so we can close the file immediately */
1429 close(id->h);
1430 }
1431 releaseLockInfo(id->pLock);
1432 releaseOpenCnt(id->pOpen);
danielk1977441b09a2006-01-05 13:48:29 +00001433
drh66560ad2006-01-06 14:32:19 +00001434 sqlite3OsLeaveMutex();
danielk1977e3026632004-06-22 11:29:02 +00001435 id->isOpen = 0;
1436 TRACE2("CLOSE %-3d\n", id->h);
1437 OpenCounter(-1);
drh9cbe6352005-11-29 03:13:21 +00001438 sqliteFree(id);
1439 *pId = 0;
danielk1977e3026632004-06-22 11:29:02 +00001440 return SQLITE_OK;
1441}
1442
1443/*
drh0ccebe72005-06-07 22:22:50 +00001444** Turn a relative pathname into a full pathname. Return a pointer
1445** to the full pathname stored in space obtained from sqliteMalloc().
1446** The calling function is responsible for freeing this space once it
1447** is no longer needed.
1448*/
drh66560ad2006-01-06 14:32:19 +00001449char *sqlite3UnixFullPathname(const char *zRelative){
drh0ccebe72005-06-07 22:22:50 +00001450 char *zFull = 0;
1451 if( zRelative[0]=='/' ){
1452 sqlite3SetString(&zFull, zRelative, (char*)0);
1453 }else{
drh79158e12005-09-06 21:40:45 +00001454 char *zBuf = sqliteMalloc(5000);
1455 if( zBuf==0 ){
1456 return 0;
1457 }
drh0ccebe72005-06-07 22:22:50 +00001458 zBuf[0] = 0;
drh79158e12005-09-06 21:40:45 +00001459 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
drh0ccebe72005-06-07 22:22:50 +00001460 (char*)0);
drh79158e12005-09-06 21:40:45 +00001461 sqliteFree(zBuf);
drh0ccebe72005-06-07 22:22:50 +00001462 }
1463 return zFull;
1464}
1465
drh18839212005-11-26 03:43:23 +00001466/*
drh9cbe6352005-11-29 03:13:21 +00001467** Change the value of the fullsync flag in the given file descriptor.
drh18839212005-11-26 03:43:23 +00001468*/
drh9cbe6352005-11-29 03:13:21 +00001469static void unixSetFullSync(OsFile *id, int v){
drh054889e2005-11-30 03:20:31 +00001470 ((unixFile*)id)->fullSync = v;
drh9cbe6352005-11-29 03:13:21 +00001471}
1472
1473/*
1474** Return the underlying file handle for an OsFile
1475*/
1476static int unixFileHandle(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001477 return ((unixFile*)id)->h;
drh9cbe6352005-11-29 03:13:21 +00001478}
1479
1480/*
1481** Return an integer that indices the type of lock currently held
1482** by this handle. (Used for testing and analysis only.)
1483*/
1484static int unixLockState(OsFile *id){
drh054889e2005-11-30 03:20:31 +00001485 return ((unixFile*)id)->locktype;
drh18839212005-11-26 03:43:23 +00001486}
drh0ccebe72005-06-07 22:22:50 +00001487
drh9c06c952005-11-26 00:25:00 +00001488/*
drh054889e2005-11-30 03:20:31 +00001489** This vector defines all the methods that can operate on an OsFile
1490** for unix.
drh9c06c952005-11-26 00:25:00 +00001491*/
drh054889e2005-11-30 03:20:31 +00001492static const IoMethod sqlite3UnixIoMethod = {
drh9c06c952005-11-26 00:25:00 +00001493 unixClose,
drh054889e2005-11-30 03:20:31 +00001494 unixOpenDirectory,
drh9c06c952005-11-26 00:25:00 +00001495 unixRead,
1496 unixWrite,
1497 unixSeek,
drh9c06c952005-11-26 00:25:00 +00001498 unixTruncate,
drh054889e2005-11-30 03:20:31 +00001499 unixSync,
drh9cbe6352005-11-29 03:13:21 +00001500 unixSetFullSync,
1501 unixFileHandle,
drh054889e2005-11-30 03:20:31 +00001502 unixFileSize,
1503 unixLock,
1504 unixUnlock,
drh9cbe6352005-11-29 03:13:21 +00001505 unixLockState,
drh054889e2005-11-30 03:20:31 +00001506 unixCheckReservedLock,
drh9c06c952005-11-26 00:25:00 +00001507};
1508
drh054889e2005-11-30 03:20:31 +00001509/*
1510** Allocate memory for a unixFile. Initialize the new unixFile
1511** to the value given in pInit and return a pointer to the new
1512** OsFile. If we run out of memory, close the file and return NULL.
1513*/
1514static int allocateUnixFile(unixFile *pInit, OsFile **pId){
1515 unixFile *pNew;
1516 pNew = sqliteMalloc( sizeof(unixFile) );
1517 if( pNew==0 ){
1518 close(pInit->h);
danielk19772e588c72005-12-09 14:25:08 +00001519 releaseLockInfo(pInit->pLock);
1520 releaseOpenCnt(pInit->pOpen);
drh054889e2005-11-30 03:20:31 +00001521 *pId = 0;
1522 return SQLITE_NOMEM;
1523 }else{
1524 *pNew = *pInit;
1525 pNew->pMethod = &sqlite3UnixIoMethod;
1526 *pId = (OsFile*)pNew;
1527 OpenCounter(+1);
1528 return SQLITE_OK;
1529 }
1530}
1531
drh9c06c952005-11-26 00:25:00 +00001532
drh0ccebe72005-06-07 22:22:50 +00001533#endif /* SQLITE_OMIT_DISKIO */
1534/***************************************************************************
1535** Everything above deals with file I/O. Everything that follows deals
1536** with other miscellanous aspects of the operating system interface
1537****************************************************************************/
1538
1539
1540/*
drhbbd42a62004-05-22 17:41:58 +00001541** Get information to seed the random number generator. The seed
1542** is written into the buffer zBuf[256]. The calling function must
1543** supply a sufficiently large buffer.
1544*/
drh66560ad2006-01-06 14:32:19 +00001545int sqlite3UnixRandomSeed(char *zBuf){
drhbbd42a62004-05-22 17:41:58 +00001546 /* We have to initialize zBuf to prevent valgrind from reporting
1547 ** errors. The reports issued by valgrind are incorrect - we would
1548 ** prefer that the randomness be increased by making use of the
1549 ** uninitialized space in zBuf - but valgrind errors tend to worry
1550 ** some users. Rather than argue, it seems easier just to initialize
1551 ** the whole array and silence valgrind, even if that means less randomness
1552 ** in the random seed.
1553 **
1554 ** When testing, initializing zBuf[] to zero is all we do. That means
1555 ** that we always use the same random number sequence.* This makes the
1556 ** tests repeatable.
1557 */
1558 memset(zBuf, 0, 256);
1559#if !defined(SQLITE_TEST)
1560 {
drh842b8642005-01-21 17:53:17 +00001561 int pid, fd;
1562 fd = open("/dev/urandom", O_RDONLY);
1563 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00001564 time_t t;
1565 time(&t);
1566 memcpy(zBuf, &t, sizeof(t));
drh842b8642005-01-21 17:53:17 +00001567 pid = getpid();
1568 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
1569 }else{
1570 read(fd, zBuf, 256);
1571 close(fd);
1572 }
drhbbd42a62004-05-22 17:41:58 +00001573 }
1574#endif
1575 return SQLITE_OK;
1576}
1577
1578/*
1579** Sleep for a little while. Return the amount of time slept.
1580*/
drh66560ad2006-01-06 14:32:19 +00001581int sqlite3UnixSleep(int ms){
drhbbd42a62004-05-22 17:41:58 +00001582#if defined(HAVE_USLEEP) && HAVE_USLEEP
1583 usleep(ms*1000);
1584 return ms;
1585#else
1586 sleep((ms+999)/1000);
1587 return 1000*((ms+999)/1000);
1588#endif
1589}
1590
1591/*
1592** Static variables used for thread synchronization
1593*/
1594static int inMutex = 0;
drh79069752004-05-22 21:30:40 +00001595#ifdef SQLITE_UNIX_THREADS
drhbbd42a62004-05-22 17:41:58 +00001596static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
drh79069752004-05-22 21:30:40 +00001597#endif
drhbbd42a62004-05-22 17:41:58 +00001598
1599/*
1600** The following pair of routine implement mutual exclusion for
1601** multi-threaded processes. Only a single thread is allowed to
1602** executed code that is surrounded by EnterMutex() and LeaveMutex().
1603**
1604** SQLite uses only a single Mutex. There is not much critical
1605** code and what little there is executes quickly and without blocking.
1606*/
drh66560ad2006-01-06 14:32:19 +00001607void sqlite3UnixEnterMutex(){
drhbbd42a62004-05-22 17:41:58 +00001608#ifdef SQLITE_UNIX_THREADS
1609 pthread_mutex_lock(&mutex);
1610#endif
1611 assert( !inMutex );
1612 inMutex = 1;
1613}
drh66560ad2006-01-06 14:32:19 +00001614void sqlite3UnixLeaveMutex(){
drhbbd42a62004-05-22 17:41:58 +00001615 assert( inMutex );
1616 inMutex = 0;
1617#ifdef SQLITE_UNIX_THREADS
1618 pthread_mutex_unlock(&mutex);
1619#endif
1620}
1621
1622/*
drh88f474a2006-01-02 20:00:12 +00001623** Return TRUE if we are currently within the mutex and FALSE if not.
drh88f474a2006-01-02 20:00:12 +00001624*/
drh66560ad2006-01-06 14:32:19 +00001625int sqlite3UnixInMutex(){
drh88f474a2006-01-02 20:00:12 +00001626 return inMutex;
1627}
1628
1629/*
drh6f7adc82006-01-11 21:41:20 +00001630** If called with allocateFlag==1, then return a pointer to thread
1631** specific data for the current thread. Allocate and zero the
1632** thread-specific data if it does not already exist necessary.
danielk197713a68c32005-12-15 10:11:30 +00001633**
drh6f7adc82006-01-11 21:41:20 +00001634** If called with allocateFlag==0, then check the current thread
1635** specific data. If it exists and is all zeros, then deallocate it.
1636** Return a pointer to the thread specific data or NULL if it is
1637** unallocated.
danielk197713a68c32005-12-15 10:11:30 +00001638*/
drh6f7adc82006-01-11 21:41:20 +00001639ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
1640 static const ThreadData zeroData;
danielk197713a68c32005-12-15 10:11:30 +00001641#ifdef SQLITE_UNIX_THREADS
1642 static pthread_key_t key;
1643 static int keyInit = 0;
drh6f7adc82006-01-11 21:41:20 +00001644 ThreadData *pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001645
1646 if( !keyInit ){
drh66560ad2006-01-06 14:32:19 +00001647 sqlite3OsEnterMutex();
danielk197713a68c32005-12-15 10:11:30 +00001648 if( !keyInit ){
1649 int rc;
drh6f7adc82006-01-11 21:41:20 +00001650 rc = pthread_key_create(&key, 0);
danielk197713a68c32005-12-15 10:11:30 +00001651 if( rc ){
drh8c0ca7d2006-01-07 04:06:54 +00001652 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001653 return 0;
1654 }
1655 keyInit = 1;
1656 }
drh66560ad2006-01-06 14:32:19 +00001657 sqlite3OsLeaveMutex();
danielk197713a68c32005-12-15 10:11:30 +00001658 }
1659
drh3fbb0b12006-01-06 00:36:00 +00001660 pTsd = pthread_getspecific(key);
drh6f7adc82006-01-11 21:41:20 +00001661 if( allocateFlag ){
1662 if( pTsd==0 ){
1663 pTsd = sqlite3OsMalloc(sizeof(zeroData));
1664 if( pTsd ){
1665 *pTsd = zeroData;
1666 pthread_setspecific(key, pTsd);
1667 }
danielk197713a68c32005-12-15 10:11:30 +00001668 }
drh6f7adc82006-01-11 21:41:20 +00001669 }else if( pTsd!=0 && memcmp(pTsd, &zeroData, sizeof(zeroData))==0 ){
1670 sqlite3OsFree(pTsd);
1671 pthread_setspecific(key, 0);
1672 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001673 }
1674 return pTsd;
1675#else
drh6f7adc82006-01-11 21:41:20 +00001676 static ThreadData *pTsd = 0;
1677 if( allocateFlag ){
1678 if( pTsd==0 ){
1679 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
1680 if( pTsd ){
1681 *pTsd = zeroData;
1682 }
drh3fbb0b12006-01-06 00:36:00 +00001683 }
drh6f7adc82006-01-11 21:41:20 +00001684 }else if( pTsd!=0 && memcmp(pTsd, &zeroData, sizeof(zeroData))==0 ){
1685 sqlite3OsFree(pTsd);
1686 pTsd = 0;
danielk197713a68c32005-12-15 10:11:30 +00001687 }
drh3fbb0b12006-01-06 00:36:00 +00001688 return pTsd;
danielk197713a68c32005-12-15 10:11:30 +00001689#endif
1690}
1691
1692/*
drhbbd42a62004-05-22 17:41:58 +00001693** The following variable, if set to a non-zero value, becomes the result
drh66560ad2006-01-06 14:32:19 +00001694** returned from sqlite3OsCurrentTime(). This is used for testing.
drhbbd42a62004-05-22 17:41:58 +00001695*/
1696#ifdef SQLITE_TEST
1697int sqlite3_current_time = 0;
1698#endif
1699
1700/*
1701** Find the current time (in Universal Coordinated Time). Write the
1702** current time and date as a Julian Day number into *prNow and
1703** return 0. Return 1 if the time and date cannot be found.
1704*/
drh66560ad2006-01-06 14:32:19 +00001705int sqlite3UnixCurrentTime(double *prNow){
drh19e2d372005-08-29 23:00:03 +00001706#ifdef NO_GETTOD
drhbbd42a62004-05-22 17:41:58 +00001707 time_t t;
1708 time(&t);
1709 *prNow = t/86400.0 + 2440587.5;
drh19e2d372005-08-29 23:00:03 +00001710#else
1711 struct timeval sNow;
1712 struct timezone sTz; /* Not used */
1713 gettimeofday(&sNow, &sTz);
1714 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
1715#endif
drhbbd42a62004-05-22 17:41:58 +00001716#ifdef SQLITE_TEST
1717 if( sqlite3_current_time ){
1718 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
1719 }
1720#endif
1721 return 0;
1722}
1723
drhbbd42a62004-05-22 17:41:58 +00001724#endif /* OS_UNIX */